about summary refs log tree commit diff
diff options
context:
space:
mode:
-rw-r--r--GNUmakefile15
-rw-r--r--analyzer/pamfile.c36
-rw-r--r--analyzer/pamfind.c4
-rw-r--r--analyzer/pamgetcolor.c10
-rw-r--r--analyzer/pamsharpmap.c26
-rw-r--r--analyzer/pamsharpness.c26
-rw-r--r--analyzer/pamslice.c24
-rw-r--r--analyzer/pamsumm.c4
-rw-r--r--analyzer/pamtable.c89
-rw-r--r--analyzer/pamtilt.c2
-rw-r--r--analyzer/pbmminkowski.c62
-rw-r--r--analyzer/pgmhist.c8
-rw-r--r--analyzer/pgmminkowski.c100
-rw-r--r--analyzer/pgmtexture.c846
-rw-r--r--analyzer/pnmhistmap.c32
-rw-r--r--analyzer/pnmpsnr.c6
-rw-r--r--analyzer/ppmhist.c66
-rwxr-xr-xbuildtools/configure.pl250
-rwxr-xr-xbuildtools/debian/mkdeb8
-rw-r--r--buildtools/endiangen.c9
-rw-r--r--buildtools/genfontc.c19
-rw-r--r--buildtools/libopt.c104
-rwxr-xr-xbuildtools/makeman59
-rwxr-xr-xbuildtools/stamp-date25
-rw-r--r--buildtools/typegen.c7
-rw-r--r--common.mk6
-rw-r--r--converter/other/Makefile7
-rw-r--r--converter/other/avstopam.c3
-rw-r--r--converter/other/bmptopnm.c10
-rw-r--r--converter/other/cameratopam/camera.c87
-rw-r--r--converter/other/cameratopam/camera.h2
-rw-r--r--converter/other/cameratopam/cameratopam.c46
-rw-r--r--converter/other/cameratopam/canon.c3
-rw-r--r--converter/other/cameratopam/decode.c12
-rw-r--r--converter/other/cameratopam/decode.h14
-rw-r--r--converter/other/cameratopam/dng.c2
-rw-r--r--converter/other/cameratopam/dng.h2
-rw-r--r--converter/other/cameratopam/foveon.c13
-rw-r--r--converter/other/cameratopam/foveon.h6
-rw-r--r--converter/other/cameratopam/identify.c4
-rw-r--r--converter/other/cameratopam/ljpeg.c3
-rw-r--r--converter/other/cameratopam/ljpeg.h4
-rw-r--r--converter/other/cameratopam/util.c11
-rw-r--r--converter/other/exif.c1414
-rw-r--r--converter/other/exif.h95
-rw-r--r--converter/other/fiasco/Makefile2
-rw-r--r--converter/other/fiasco/binerror.c136
-rw-r--r--converter/other/fiasco/binerror.h50
-rw-r--r--converter/other/fiasco/buttons.c510
-rw-r--r--converter/other/fiasco/buttons.h50
-rw-r--r--converter/other/fiasco/codec/approx.c140
-rw-r--r--converter/other/fiasco/codec/approx.h10
-rw-r--r--converter/other/fiasco/codec/bintree.c26
-rw-r--r--converter/other/fiasco/codec/bintree.h8
-rw-r--r--converter/other/fiasco/codec/coder.h4
-rw-r--r--converter/other/fiasco/codec/coeff.c194
-rw-r--r--converter/other/fiasco/codec/coeff.h20
-rw-r--r--converter/other/fiasco/codec/control.c204
-rw-r--r--converter/other/fiasco/codec/control.h14
-rw-r--r--converter/other/fiasco/codec/cwfa.h102
-rw-r--r--converter/other/fiasco/codec/decoder.h52
-rw-r--r--converter/other/fiasco/codec/dfiasco.c178
-rw-r--r--converter/other/fiasco/codec/dfiasco.h8
-rw-r--r--converter/other/fiasco/codec/domain-pool.c148
-rw-r--r--converter/other/fiasco/codec/domain-pool.h28
-rw-r--r--converter/other/fiasco/codec/ip.c266
-rw-r--r--converter/other/fiasco/codec/ip.h22
-rw-r--r--converter/other/fiasco/codec/motion.c428
-rw-r--r--converter/other/fiasco/codec/motion.h14
-rw-r--r--converter/other/fiasco/codec/mwfa.c888
-rw-r--r--converter/other/fiasco/codec/mwfa.h14
-rw-r--r--converter/other/fiasco/codec/options.c414
-rw-r--r--converter/other/fiasco/codec/options.h80
-rw-r--r--converter/other/fiasco/codec/prediction.c406
-rw-r--r--converter/other/fiasco/codec/prediction.h14
-rw-r--r--converter/other/fiasco/codec/subdivide.c426
-rw-r--r--converter/other/fiasco/codec/subdivide.h12
-rw-r--r--converter/other/fiasco/codec/tiling.c166
-rw-r--r--converter/other/fiasco/codec/tiling.h14
-rw-r--r--converter/other/fiasco/codec/wfa.h144
-rw-r--r--converter/other/fiasco/codec/wfalib.c462
-rw-r--r--converter/other/fiasco/codec/wfalib.h18
-rw-r--r--converter/other/fiasco/display.c415
-rw-r--r--converter/other/fiasco/display.h49
-rw-r--r--converter/other/fiasco/fiasco.h242
-rw-r--r--converter/other/fiasco/fiascotopnm.c548
-rw-r--r--converter/other/fiasco/getopt.c824
-rw-r--r--converter/other/fiasco/getopt.h28
-rw-r--r--converter/other/fiasco/getopt1.c116
-rw-r--r--converter/other/fiasco/input/basis.c88
-rw-r--r--converter/other/fiasco/input/basis.h4
-rw-r--r--converter/other/fiasco/input/matrices.c636
-rw-r--r--converter/other/fiasco/input/matrices.h4
-rw-r--r--converter/other/fiasco/input/mc.c226
-rw-r--r--converter/other/fiasco/input/mc.h4
-rw-r--r--converter/other/fiasco/input/nd.c194
-rw-r--r--converter/other/fiasco/input/nd.h4
-rw-r--r--converter/other/fiasco/input/read.c354
-rw-r--r--converter/other/fiasco/input/read.h4
-rw-r--r--converter/other/fiasco/input/tree.c224
-rw-r--r--converter/other/fiasco/input/tree.h4
-rw-r--r--converter/other/fiasco/input/weights.c16
-rw-r--r--converter/other/fiasco/input/weights.h4
-rw-r--r--converter/other/fiasco/lib/arith.c440
-rw-r--r--converter/other/fiasco/lib/arith.h40
-rw-r--r--converter/other/fiasco/lib/bit-io.h20
-rw-r--r--converter/other/fiasco/lib/dither.c2258
-rw-r--r--converter/other/fiasco/lib/dither.h8
-rw-r--r--converter/other/fiasco/lib/error.c20
-rw-r--r--converter/other/fiasco/lib/error.h6
-rw-r--r--converter/other/fiasco/lib/image.h16
-rw-r--r--converter/other/fiasco/lib/list.c108
-rw-r--r--converter/other/fiasco/lib/list.h32
-rw-r--r--converter/other/fiasco/lib/macros.h36
-rw-r--r--converter/other/fiasco/lib/misc.c198
-rw-r--r--converter/other/fiasco/lib/misc.h26
-rw-r--r--converter/other/fiasco/lib/mvcode.c2
-rw-r--r--converter/other/fiasco/lib/rpf.c34
-rw-r--r--converter/other/fiasco/lib/rpf.h14
-rw-r--r--converter/other/fiasco/lib/types.h2
-rw-r--r--converter/other/fiasco/output/matrices.c560
-rw-r--r--converter/other/fiasco/output/matrices.h6
-rw-r--r--converter/other/fiasco/output/mc.c200
-rw-r--r--converter/other/fiasco/output/mc.h6
-rw-r--r--converter/other/fiasco/output/nd.c180
-rw-r--r--converter/other/fiasco/output/nd.h4
-rw-r--r--converter/other/fiasco/output/tree.c98
-rw-r--r--converter/other/fiasco/output/tree.h4
-rw-r--r--converter/other/fiasco/output/weights.c76
-rw-r--r--converter/other/fiasco/output/weights.h4
-rw-r--r--converter/other/fiasco/output/write.c58
-rw-r--r--converter/other/fiasco/output/write.h4
-rw-r--r--converter/other/fiasco/params.c1157
-rw-r--r--converter/other/fiasco/params.h16
-rw-r--r--converter/other/fiasco/pnmtofiasco.c356
-rw-r--r--converter/other/fitstopnm.c223
-rw-r--r--converter/other/gemtopnm.c388
-rw-r--r--converter/other/giftopnm.c20
-rw-r--r--converter/other/hdifftopam.c54
-rw-r--r--converter/other/infotopam.c633
-rw-r--r--converter/other/ipdb.c222
-rw-r--r--converter/other/ipdb.h23
-rw-r--r--converter/other/jbig/jbigtopnm.c1
-rw-r--r--converter/other/jbig/libjbig/include/jbig.h54
-rw-r--r--converter/other/jbig/libjbig/include/jbig_ar.h6
-rw-r--r--converter/other/jbig/libjbig/jbig.c1812
-rw-r--r--converter/other/jbig/libjbig/jbig_ar.c138
-rw-r--r--converter/other/jbig/pnmtojbig.c46
-rw-r--r--converter/other/jpeg2000/libjasper/base/jas_debug.c82
-rw-r--r--converter/other/jpeg2000/libjasper/base/jas_getopt.c164
-rw-r--r--converter/other/jpeg2000/libjasper/base/jas_image.c1315
-rw-r--r--converter/other/jpeg2000/libjasper/base/jas_init.c128
-rw-r--r--converter/other/jpeg2000/libjasper/base/jas_malloc.c48
-rw-r--r--converter/other/jpeg2000/libjasper/base/jas_seq.c544
-rw-r--r--converter/other/jpeg2000/libjasper/base/jas_stream.c1484
-rw-r--r--converter/other/jpeg2000/libjasper/base/jas_string.c42
-rw-r--r--converter/other/jpeg2000/libjasper/base/jas_tvp.c204
-rw-r--r--converter/other/jpeg2000/libjasper/base/jas_version.c28
-rw-r--r--converter/other/jpeg2000/libjasper/common.mk3
-rw-r--r--converter/other/jpeg2000/libjasper/include/jasper/jas_debug.h32
-rw-r--r--converter/other/jpeg2000/libjasper/include/jasper/jas_fix.h206
-rw-r--r--converter/other/jpeg2000/libjasper/include/jasper/jas_getopt.h44
-rw-r--r--converter/other/jpeg2000/libjasper/include/jasper/jas_image.h326
-rw-r--r--converter/other/jpeg2000/libjasper/include/jasper/jas_init.h26
-rw-r--r--converter/other/jpeg2000/libjasper/include/jasper/jas_malloc.h34
-rw-r--r--converter/other/jpeg2000/libjasper/include/jasper/jas_math.h54
-rw-r--r--converter/other/jpeg2000/libjasper/include/jasper/jas_seq.h182
-rw-r--r--converter/other/jpeg2000/libjasper/include/jasper/jas_stream.h222
-rw-r--r--converter/other/jpeg2000/libjasper/include/jasper/jas_string.h30
-rw-r--r--converter/other/jpeg2000/libjasper/include/jasper/jas_tvp.h50
-rw-r--r--converter/other/jpeg2000/libjasper/include/jasper/jas_types.h4
-rw-r--r--converter/other/jpeg2000/libjasper/include/jasper/jas_version.h64
-rw-r--r--converter/other/jpeg2000/libjasper/include/jasper/jasper.h26
-rw-r--r--converter/other/jpeg2000/libjasper/jp2/jp2_cod.c28
-rw-r--r--converter/other/jpeg2000/libjasper/jp2/jp2_cod.h256
-rw-r--r--converter/other/jpeg2000/libjasper/jp2/jp2_dec.c30
-rw-r--r--converter/other/jpeg2000/libjasper/jp2/jp2_dec.h44
-rw-r--r--converter/other/jpeg2000/libjasper/jp2/jp2_enc.c558
-rw-r--r--converter/other/jpeg2000/libjasper/jpc/jpc_bs.c528
-rw-r--r--converter/other/jpeg2000/libjasper/jpc/jpc_bs.h100
-rw-r--r--converter/other/jpeg2000/libjasper/jpc/jpc_cod.h28
-rw-r--r--converter/other/jpeg2000/libjasper/jpc/jpc_cs.c26
-rw-r--r--converter/other/jpeg2000/libjasper/jpc/jpc_cs.h544
-rw-r--r--converter/other/jpeg2000/libjasper/jpc/jpc_dec.c28
-rw-r--r--converter/other/jpeg2000/libjasper/jpc/jpc_dec.h694
-rw-r--r--converter/other/jpeg2000/libjasper/jpc/jpc_enc.c1404
-rw-r--r--converter/other/jpeg2000/libjasper/jpc/jpc_enc.h684
-rw-r--r--converter/other/jpeg2000/libjasper/jpc/jpc_fix.h94
-rw-r--r--converter/other/jpeg2000/libjasper/jpc/jpc_flt.h26
-rw-r--r--converter/other/jpeg2000/libjasper/jpc/jpc_math.c74
-rw-r--r--converter/other/jpeg2000/libjasper/jpc/jpc_math.h46
-rw-r--r--converter/other/jpeg2000/libjasper/jpc/jpc_mct.c368
-rw-r--r--converter/other/jpeg2000/libjasper/jpc/jpc_mct.h32
-rw-r--r--converter/other/jpeg2000/libjasper/jpc/jpc_mqcod.c214
-rw-r--r--converter/other/jpeg2000/libjasper/jpc/jpc_mqcod.h50
-rw-r--r--converter/other/jpeg2000/libjasper/jpc/jpc_mqdec.c266
-rw-r--r--converter/other/jpeg2000/libjasper/jpc/jpc_mqdec.h214
-rw-r--r--converter/other/jpeg2000/libjasper/jpc/jpc_mqenc.h110
-rw-r--r--converter/other/jpeg2000/libjasper/jpc/jpc_qmfb.c1579
-rw-r--r--converter/other/jpeg2000/libjasper/jpc/jpc_qmfb.h76
-rw-r--r--converter/other/jpeg2000/libjasper/jpc/jpc_t1cod.c636
-rw-r--r--converter/other/jpeg2000/libjasper/jpc/jpc_t1cod.h204
-rw-r--r--converter/other/jpeg2000/libjasper/jpc/jpc_t1dec.c27
-rw-r--r--converter/other/jpeg2000/libjasper/jpc/jpc_t1dec.h26
-rw-r--r--converter/other/jpeg2000/libjasper/jpc/jpc_t1enc.c189
-rw-r--r--converter/other/jpeg2000/libjasper/jpc/jpc_t1enc.h26
-rw-r--r--converter/other/jpeg2000/libjasper/jpc/jpc_t2cod.c1052
-rw-r--r--converter/other/jpeg2000/libjasper/jpc/jpc_t2cod.h200
-rw-r--r--converter/other/jpeg2000/libjasper/jpc/jpc_t2dec.c887
-rw-r--r--converter/other/jpeg2000/libjasper/jpc/jpc_t2dec.h26
-rw-r--r--converter/other/jpeg2000/libjasper/jpc/jpc_t2enc.c1071
-rw-r--r--converter/other/jpeg2000/libjasper/jpc/jpc_t2enc.h26
-rw-r--r--converter/other/jpeg2000/libjasper/jpc/jpc_tagtree.c466
-rw-r--r--converter/other/jpeg2000/libjasper/jpc/jpc_tagtree.h60
-rw-r--r--converter/other/jpeg2000/libjasper/jpc/jpc_tsfb.c852
-rw-r--r--converter/other/jpeg2000/libjasper/jpc/jpc_tsfb.h100
-rw-r--r--converter/other/jpeg2000/libjasper/jpc/jpc_util.c207
-rw-r--r--converter/other/jpeg2000/libjasper/jpc/jpc_util.h26
-rw-r--r--converter/other/jpeg2000/libjasper_compat.h2
-rw-r--r--converter/other/jpeg2000/pamtojpeg2k.c37
-rw-r--r--converter/other/jpegdatasource.c25
-rw-r--r--converter/other/jpegdatasource.h2
-rw-r--r--converter/other/jpegtopnm.c632
-rw-r--r--converter/other/pamtoavs.c3
-rw-r--r--converter/other/pamtodjvurle.c59
-rw-r--r--converter/other/pamtofits.c19
-rw-r--r--converter/other/pamtogif.c505
-rw-r--r--converter/other/pamtohdiff.c10
-rw-r--r--converter/other/pamtohtmltbl.c45
-rw-r--r--converter/other/pamtompfont.c9
-rw-r--r--converter/other/pamtooctaveimg.c6
-rw-r--r--converter/other/pamtopam.c3
-rw-r--r--converter/other/pamtopdbimg.c99
-rw-r--r--converter/other/pamtopfm.c52
-rw-r--r--converter/other/pamtopng.c40
-rw-r--r--converter/other/pamtopnm.c35
-rw-r--r--converter/other/pamtoqoi.c440
-rw-r--r--converter/other/pamtosrf.c8
-rw-r--r--converter/other/pamtosvg/Makefile3
-rw-r--r--converter/other/pamtosvg/autotrace.c39
-rw-r--r--converter/other/pamtosvg/autotrace.h48
-rw-r--r--converter/other/pamtosvg/bitmap.c29
-rw-r--r--converter/other/pamtosvg/bitmap.h26
-rw-r--r--converter/other/pamtosvg/curve.c325
-rw-r--r--converter/other/pamtosvg/curve.h136
-rw-r--r--converter/other/pamtosvg/epsilon.c (renamed from converter/other/pamtosvg/epsilon-equal.c)8
-rw-r--r--converter/other/pamtosvg/epsilon.h (renamed from converter/other/pamtosvg/epsilon-equal.h)6
-rw-r--r--converter/other/pamtosvg/exception.c10
-rw-r--r--converter/other/pamtosvg/exception.h6
-rw-r--r--converter/other/pamtosvg/fit.c1278
-rw-r--r--converter/other/pamtosvg/fit.h4
-rw-r--r--converter/other/pamtosvg/image-header.h8
-rw-r--r--converter/other/pamtosvg/image-proc.c315
-rw-r--r--converter/other/pamtosvg/image-proc.h2
-rw-r--r--converter/other/pamtosvg/logreport.c2
-rw-r--r--converter/other/pamtosvg/logreport.h12
-rw-r--r--converter/other/pamtosvg/message.h8
-rw-r--r--converter/other/pamtosvg/output-svg.c25
-rw-r--r--converter/other/pamtosvg/output-svg.h4
-rw-r--r--converter/other/pamtosvg/pamtosvg.c49
-rw-r--r--converter/other/pamtosvg/pamtosvg.test8
-rw-r--r--converter/other/pamtosvg/point.c90
-rw-r--r--converter/other/pamtosvg/point.h25
-rw-r--r--converter/other/pamtosvg/pxl-outline.c141
-rw-r--r--converter/other/pamtosvg/pxl-outline.h8
-rw-r--r--converter/other/pamtosvg/spline.c34
-rw-r--r--converter/other/pamtosvg/spline.h7
-rw-r--r--converter/other/pamtosvg/thin-image.c567
-rw-r--r--converter/other/pamtosvg/vector.c295
-rw-r--r--converter/other/pamtosvg/vector.h112
-rw-r--r--converter/other/pamtotga.c8
-rw-r--r--converter/other/pamtotiff.c3
-rw-r--r--converter/other/pamtouil.c74
-rw-r--r--converter/other/pamtowinicon.c8
-rw-r--r--converter/other/pamtoxvmini.c77
-rw-r--r--converter/other/pbmtopgm.c150
-rw-r--r--converter/other/pdbimgtopam.c134
-rw-r--r--converter/other/pfmtopam.c61
-rw-r--r--converter/other/pgmtopbm.c16
-rw-r--r--converter/other/pgmtoppm.c161
-rw-r--r--converter/other/pm_tiff.h2
-rw-r--r--converter/other/pngtopam.c40
-rw-r--r--converter/other/pngtxt.c55
-rw-r--r--converter/other/pngtxt.h4
-rw-r--r--converter/other/pngx.c19
-rw-r--r--converter/other/pnmtoddif.c39
-rw-r--r--converter/other/pnmtojpeg.c1036
-rw-r--r--converter/other/pnmtopalm/gen_palm_colormap.c4
-rw-r--r--converter/other/pnmtopalm/palm.h2
-rw-r--r--converter/other/pnmtopalm/palmcolormap.c35
-rw-r--r--converter/other/pnmtopalm/palmtopnm.c59
-rw-r--r--converter/other/pnmtopalm/pnmtopalm.c4
-rw-r--r--converter/other/pnmtopclxl.c4
-rw-r--r--converter/other/pnmtopng.c131
-rw-r--r--converter/other/pnmtops.c30
-rw-r--r--converter/other/pnmtorast.c11
-rw-r--r--converter/other/pnmtorle.c293
-rw-r--r--converter/other/pnmtosgi.c15
-rw-r--r--converter/other/pnmtosir.c35
-rw-r--r--converter/other/pnmtotiffcmyk.c116
-rw-r--r--converter/other/pnmtoxwd.c50
-rw-r--r--converter/other/ppmtopgm.c15
-rw-r--r--converter/other/pstopnm.c5
-rw-r--r--converter/other/qoi.h105
-rw-r--r--converter/other/qoitopam.c323
-rw-r--r--converter/other/rast.c15
-rw-r--r--converter/other/rast.h52
-rw-r--r--converter/other/rasttopnm.c27
-rw-r--r--converter/other/rla.h6
-rw-r--r--converter/other/rletopnm.c3
-rw-r--r--converter/other/sgitopnm.c7
-rw-r--r--converter/other/sirtopnm.c205
-rw-r--r--converter/other/srf.c16
-rw-r--r--converter/other/srftopam.c13
-rw-r--r--converter/other/sunicontopnm.c35
-rw-r--r--converter/other/svgtopam.c62
-rw-r--r--converter/other/tiff.c11
-rw-r--r--converter/other/tifftopnm.c26
-rw-r--r--converter/other/winicontopam.c4
-rw-r--r--converter/other/x10wd.h26
-rw-r--r--converter/other/x11wd.h4
-rw-r--r--converter/other/xwdtopnm.c337
-rw-r--r--converter/other/yuy2topam.c16
-rw-r--r--converter/other/zeisstopnm.c95
-rw-r--r--converter/pbm/atktopbm.c37
-rw-r--r--converter/pbm/brushtopbm.c10
-rw-r--r--converter/pbm/cistopbm.c7
-rw-r--r--converter/pbm/cmuwmtopbm.c11
-rw-r--r--converter/pbm/ddbugtopbm.c19
-rw-r--r--converter/pbm/escp2topbm.c37
-rw-r--r--converter/pbm/g3topbm.c196
-rw-r--r--converter/pbm/macp.h12
-rw-r--r--converter/pbm/macptopbm.c6
-rw-r--r--converter/pbm/mdatopbm.c267
-rw-r--r--converter/pbm/mgrtopbm.c80
-rw-r--r--converter/pbm/mrftopbm.c29
-rw-r--r--converter/pbm/pbmto10x.c8
-rw-r--r--converter/pbm/pbmto4425.c219
-rw-r--r--converter/pbm/pbmtoascii.c5
-rw-r--r--converter/pbm/pbmtoatk.c34
-rw-r--r--converter/pbm/pbmtobbnbg.c50
-rw-r--r--converter/pbm/pbmtocis.c15
-rw-r--r--converter/pbm/pbmtocmuwm.c13
-rw-r--r--converter/pbm/pbmtodjvurle.c14
-rw-r--r--converter/pbm/pbmtoepsi.c62
-rw-r--r--converter/pbm/pbmtoepson.c42
-rw-r--r--converter/pbm/pbmtoescp2.c35
-rw-r--r--converter/pbm/pbmtog3.c9
-rw-r--r--converter/pbm/pbmtogem.c12
-rw-r--r--converter/pbm/pbmtoibm23xx.c9
-rw-r--r--converter/pbm/pbmtolj.c38
-rw-r--r--converter/pbm/pbmtoln03.c1
-rw-r--r--converter/pbm/pbmtolps.c7
-rw-r--r--converter/pbm/pbmtomacp.c5
-rw-r--r--converter/pbm/pbmtomatrixorbital.c12
-rw-r--r--converter/pbm/pbmtomda.c217
-rw-r--r--converter/pbm/pbmtomgr.c14
-rw-r--r--converter/pbm/pbmtomrf.c52
-rw-r--r--converter/pbm/pbmtonokia.c3
-rw-r--r--converter/pbm/pbmtopi3.c5
-rw-r--r--converter/pbm/pbmtoplot.c49
-rw-r--r--converter/pbm/pbmtoppa/cutswath.c619
-rw-r--r--converter/pbm/pbmtoppa/cutswath.h2
-rw-r--r--converter/pbm/pbmtoppa/pbm.c12
-rw-r--r--converter/pbm/pbmtoppa/pbmtoppa.c209
-rw-r--r--converter/pbm/pbmtoppa/ppa.c179
-rw-r--r--converter/pbm/pbmtoppa/ppa.h2
-rw-r--r--converter/pbm/pbmtoppa/ppapbm.h2
-rw-r--r--converter/pbm/pbmtopsg3.c149
-rw-r--r--converter/pbm/pbmtoptx.c1
-rw-r--r--converter/pbm/pbmtosunicon.c18
-rw-r--r--converter/pbm/pbmtowbmp.c18
-rw-r--r--converter/pbm/pbmtox10bm15
-rw-r--r--converter/pbm/pbmtoxbm.c153
-rw-r--r--converter/pbm/pbmtoybm.c3
-rw-r--r--converter/pbm/pbmtozinc.c3
-rw-r--r--converter/pbm/pi3topbm.c20
-rw-r--r--converter/pbm/pktopbm.c828
-rw-r--r--converter/pbm/thinkjettopbm.l8
-rw-r--r--converter/pbm/wbmptopbm.c18
-rw-r--r--converter/pbm/xbmtopbm.c2
-rw-r--r--converter/pbm/ybmtopbm.c45
-rw-r--r--converter/pgm/asciitopgm.c7
-rw-r--r--converter/pgm/bioradtopgm.c133
-rw-r--r--converter/pgm/fstopgm.c6
-rw-r--r--converter/pgm/hipstopgm.c50
-rw-r--r--converter/pgm/lispmtopgm.c258
-rw-r--r--converter/pgm/pgmtofs.c30
-rw-r--r--converter/pgm/pgmtolispm.c9
-rw-r--r--converter/pgm/pgmtopgm.c7
-rw-r--r--converter/pgm/pgmtosbig.c3
-rw-r--r--converter/pgm/pgmtost4.c5
-rw-r--r--converter/pgm/psidtopgm.c25
-rw-r--r--converter/pgm/rawtopgm.c4
-rw-r--r--converter/pgm/sbigtopgm.c12
-rw-r--r--converter/pgm/spottopgm.c20
-rw-r--r--converter/pgm/st4topgm.c20
-rw-r--r--converter/ppm/411toppm.c10
-rw-r--r--converter/ppm/autocad.h2
-rw-r--r--converter/ppm/eyuvtoppm.c41
-rw-r--r--converter/ppm/gouldtoppm.c149
-rw-r--r--converter/ppm/hpcdtoppm/Makefile24
-rw-r--r--converter/ppm/hpcdtoppm/README37
-rwxr-xr-xconverter/ppm/hpcdtoppm/hpcdtoppm16
-rwxr-xr-xconverter/ppm/hpcdtoppm/pcdovtoppm25
-rw-r--r--converter/ppm/ilbm.h12
-rw-r--r--converter/ppm/ilbmtoppm.c394
-rw-r--r--converter/ppm/imgtoppm.c172
-rw-r--r--converter/ppm/leaftoppm.c53
-rw-r--r--converter/ppm/mitsu.h27
-rw-r--r--converter/ppm/mtvtoppm.c33
-rw-r--r--converter/ppm/neotoppm.c5
-rw-r--r--converter/ppm/pc1toppm.c23
-rw-r--r--converter/ppm/pcxtoppm.c532
-rw-r--r--converter/ppm/pi1toppm.c3
-rw-r--r--converter/ppm/picttoppm.c1690
-rw-r--r--converter/ppm/pjtoppm.c205
-rw-r--r--converter/ppm/ppmtoacad.c23
-rw-r--r--converter/ppm/ppmtoapplevol.c11
-rw-r--r--converter/ppm/ppmtoarbtxt.c63
-rw-r--r--converter/ppm/ppmtoascii.c12
-rw-r--r--converter/ppm/ppmtobmp.c10
-rw-r--r--converter/ppm/ppmtoeyuv.c231
-rw-r--r--converter/ppm/ppmtogif.c82
-rw-r--r--converter/ppm/ppmtoicr.c231
-rw-r--r--converter/ppm/ppmtoilbm.c230
-rw-r--r--converter/ppm/ppmtoleaf.c70
-rw-r--r--converter/ppm/ppmtolj.c415
-rw-r--r--converter/ppm/ppmtomitsu.c175
-rw-r--r--converter/ppm/ppmtomitsu.test12
-rw-r--r--converter/ppm/ppmtompeg/bframe.c128
-rw-r--r--converter/ppm/ppmtompeg/bitio.c31
-rw-r--r--converter/ppm/ppmtompeg/block.c41
-rw-r--r--converter/ppm/ppmtompeg/bsearch.c7
-rw-r--r--converter/ppm/ppmtompeg/combine.c28
-rw-r--r--converter/ppm/ppmtompeg/file.c9
-rw-r--r--converter/ppm/ppmtompeg/frame.c72
-rw-r--r--converter/ppm/ppmtompeg/frametype.c67
-rw-r--r--converter/ppm/ppmtompeg/fsize.c54
-rw-r--r--converter/ppm/ppmtompeg/gethostname.c3
-rw-r--r--converter/ppm/ppmtompeg/gethostname_win32.c24
-rw-r--r--converter/ppm/ppmtompeg/headers/all.h10
-rw-r--r--converter/ppm/ppmtompeg/headers/bitio.h32
-rw-r--r--converter/ppm/ppmtompeg/headers/byteorder.h20
-rw-r--r--converter/ppm/ppmtompeg/headers/combine.h4
-rw-r--r--converter/ppm/ppmtompeg/headers/dct.h10
-rw-r--r--converter/ppm/ppmtompeg/headers/frame.h28
-rw-r--r--converter/ppm/ppmtompeg/headers/frames.h23
-rw-r--r--converter/ppm/ppmtompeg/headers/frametype.h2
-rw-r--r--converter/ppm/ppmtompeg/headers/fsize.h8
-rw-r--r--converter/ppm/ppmtompeg/headers/general.h20
-rw-r--r--converter/ppm/ppmtompeg/headers/huff.h8
-rw-r--r--converter/ppm/ppmtompeg/headers/iframe.h6
-rw-r--r--converter/ppm/ppmtompeg/headers/mheaders.h52
-rw-r--r--converter/ppm/ppmtompeg/headers/motion_search.h12
-rw-r--r--converter/ppm/ppmtompeg/headers/mpeg.h48
-rw-r--r--converter/ppm/ppmtompeg/headers/mproto.h26
-rw-r--r--converter/ppm/ppmtompeg/headers/mtypes.h18
-rw-r--r--converter/ppm/ppmtompeg/headers/opts.h10
-rw-r--r--converter/ppm/ppmtompeg/headers/parallel.h40
-rw-r--r--converter/ppm/ppmtompeg/headers/param.h2
-rw-r--r--converter/ppm/ppmtompeg/headers/postdct.h14
-rw-r--r--converter/ppm/ppmtompeg/headers/psocket.h4
-rw-r--r--converter/ppm/ppmtompeg/headers/rate.h30
-rw-r--r--converter/ppm/ppmtompeg/headers/readframe.h34
-rw-r--r--converter/ppm/ppmtompeg/headers/rgbtoycc.h8
-rw-r--r--converter/ppm/ppmtompeg/headers/specifics.h8
-rw-r--r--converter/ppm/ppmtompeg/huff.c45
-rw-r--r--converter/ppm/ppmtompeg/iframe.c109
-rw-r--r--converter/ppm/ppmtompeg/input.c93
-rw-r--r--converter/ppm/ppmtompeg/jpeg.c1
-rw-r--r--converter/ppm/ppmtompeg/jrevdct.c1778
-rw-r--r--converter/ppm/ppmtompeg/memory.c19
-rw-r--r--converter/ppm/ppmtompeg/mfwddct.c174
-rw-r--r--converter/ppm/ppmtompeg/mheaders.c301
-rw-r--r--converter/ppm/ppmtompeg/moutput.c405
-rw-r--r--converter/ppm/ppmtompeg/mpeg.c5
-rw-r--r--converter/ppm/ppmtompeg/mquant.c27
-rw-r--r--converter/ppm/ppmtompeg/nojpeg.c20
-rw-r--r--converter/ppm/ppmtompeg/noparallel.c26
-rw-r--r--converter/ppm/ppmtompeg/opts.c14
-rw-r--r--converter/ppm/ppmtompeg/parallel.c69
-rw-r--r--converter/ppm/ppmtompeg/param.c2
-rw-r--r--converter/ppm/ppmtompeg/pframe.c173
-rw-r--r--converter/ppm/ppmtompeg/postdct.c508
-rw-r--r--converter/ppm/ppmtompeg/ppmtompeg.c95
-rw-r--r--converter/ppm/ppmtompeg/psearch.c119
-rw-r--r--converter/ppm/ppmtompeg/qtest.c13
-rw-r--r--converter/ppm/ppmtompeg/rate.c116
-rw-r--r--converter/ppm/ppmtompeg/readframe.c113
-rw-r--r--converter/ppm/ppmtompeg/rgbtoycc.c26
-rw-r--r--converter/ppm/ppmtompeg/specifics.c198
-rw-r--r--converter/ppm/ppmtompeg/subsample.c13
-rw-r--r--converter/ppm/ppmtoneo.c3
-rw-r--r--converter/ppm/ppmtopcx.c9
-rw-r--r--converter/ppm/ppmtopi1.c3
-rw-r--r--converter/ppm/ppmtopict.c220
-rw-r--r--converter/ppm/ppmtopj.c480
-rw-r--r--converter/ppm/ppmtopjxl.c552
-rw-r--r--converter/ppm/ppmtoppm.c5
-rw-r--r--converter/ppm/ppmtopuzz.c67
-rw-r--r--converter/ppm/ppmtosixel.c440
-rw-r--r--converter/ppm/ppmtospu.c29
-rw-r--r--converter/ppm/ppmtoterm.c27
-rw-r--r--converter/ppm/ppmtowinicon.c1092
-rw-r--r--converter/ppm/ppmtoxpm.c388
-rw-r--r--converter/ppm/ppmtoyuv.c9
-rw-r--r--converter/ppm/ppmtoyuvsplit.c3
-rw-r--r--converter/ppm/qrttoppm.c104
-rw-r--r--converter/ppm/rawtoppm.c5
-rw-r--r--converter/ppm/rgb3toppm.c41
-rw-r--r--converter/ppm/sldtoppm.c289
-rw-r--r--converter/ppm/spctoppm.c155
-rw-r--r--converter/ppm/tgatoppm.c1
-rw-r--r--converter/ppm/vidtoppm.c65
-rw-r--r--converter/ppm/winico.h20
-rw-r--r--converter/ppm/winicontoppm.c107
-rw-r--r--converter/ppm/ximtoppm.c406
-rw-r--r--converter/ppm/yuvsplittoppm.c31
-rw-r--r--converter/ppm/yuvtoppm.c12
-rw-r--r--doc/COPYRIGHT.PATENT7
-rw-r--r--doc/HISTORY522
-rw-r--r--doc/INSTALL17
-rw-r--r--doc/Netpbm.programming425
-rw-r--r--doc/copyright_summary2
-rw-r--r--editor/Makefile29
-rw-r--r--editor/pamaddnoise.c236
-rw-r--r--editor/pambackground.c54
-rw-r--r--editor/pamcat.c1461
-rw-r--r--editor/pamcut.c263
-rw-r--r--editor/pamdice.c6
-rw-r--r--editor/pamditherbw.c140
-rw-r--r--editor/pamedge.c8
-rw-r--r--editor/pamenlarge.c1
-rw-r--r--editor/pamhomography.c799
-rw-r--r--editor/pamlevels.c1
-rw-r--r--editor/pammasksharpen.c26
-rw-r--r--editor/pammixmulti.c151
-rw-r--r--editor/pamperspective.c44
-rw-r--r--editor/pamrecolor.c49
-rw-r--r--editor/pamrestack.c472
-rw-r--r--editor/pamrubber.c542
-rw-r--r--editor/pamscale.c31
-rw-r--r--editor/pamshuffle.c155
-rw-r--r--editor/pamsistoaglyph.c10
-rw-r--r--editor/pamwipeout.c28
-rw-r--r--editor/pbmclean.c8
-rw-r--r--editor/pbmpscale.c36
-rw-r--r--editor/pbmreduce.c49
-rw-r--r--editor/pgmdeshadow.c22
-rw-r--r--editor/pgmenhance.c4
-rw-r--r--editor/pgmmedian.c287
-rw-r--r--editor/pnmalias.c58
-rw-r--r--editor/pnmcat.c874
-rw-r--r--editor/pnmconvol.c62
-rwxr-xr-xeditor/pnmflip10
-rw-r--r--editor/pnmgamma.c74
-rw-r--r--editor/pnmhisteq.c25
-rwxr-xr-xeditor/pnmindex.csh189
-rwxr-xr-xeditor/pnmindex.sh214
-rw-r--r--editor/pnminvert.c20
-rwxr-xr-xeditor/pnmmargin38
-rw-r--r--editor/pnmmontage.c44
-rw-r--r--editor/pnmnlfilt.c2
-rw-r--r--editor/pnmpad.c834
-rwxr-xr-xeditor/pnmquant48
-rwxr-xr-xeditor/pnmquantall24
-rw-r--r--editor/pnmremap.c60
-rw-r--r--editor/pnmrotate.c202
-rw-r--r--editor/pnmscalefixed.c113
-rw-r--r--editor/pnmsmooth.c12
-rw-r--r--editor/pnmstitch.c152
-rw-r--r--editor/pnmtile.c2
-rw-r--r--editor/ppmchange.c40
-rw-r--r--editor/ppmdim.c159
-rw-r--r--editor/ppmdither.c142
-rwxr-xr-xeditor/ppmfade631
-rw-r--r--editor/ppmflash.c9
-rw-r--r--editor/ppmlabel.c6
-rwxr-xr-xeditor/ppmshadow2
-rw-r--r--editor/specialty/pamdeinterlace.c35
-rw-r--r--editor/specialty/pamoil.c235
-rw-r--r--editor/specialty/pampaintspill.c168
-rw-r--r--editor/specialty/pampop9.c4
-rw-r--r--editor/specialty/pbmlife.c114
-rw-r--r--editor/specialty/pgmabel.c13
-rw-r--r--editor/specialty/pgmbentley.c6
-rw-r--r--editor/specialty/pgmmorphconv.c56
-rw-r--r--editor/specialty/pnmindex.c494
-rw-r--r--editor/specialty/pnmmercator.c54
-rw-r--r--editor/specialty/ppm3d.c30
-rw-r--r--editor/specialty/ppmglobe.c14
-rw-r--r--editor/specialty/ppmntsc.c124
-rw-r--r--editor/specialty/ppmrelief.c2
-rw-r--r--editor/specialty/ppmshift.c125
-rw-r--r--editor/specialty/ppmspread.c206
-rw-r--r--editor/specialty/ppmtv.c167
-rw-r--r--generator/Makefile2
-rw-r--r--generator/pamcrater.c61
-rw-r--r--generator/pamgauss.c39
-rw-r--r--generator/pamgradient.c11
-rw-r--r--generator/pamseq.c346
-rw-r--r--generator/pamshadedrelief.c12
-rw-r--r--generator/pamstereogram.c134
-rw-r--r--generator/pamstereogram.test70
-rw-r--r--generator/pamtris/framebuffer.c2
-rw-r--r--generator/pamtris/pamtris.c2
-rw-r--r--generator/pamtris/triangle.c4
-rw-r--r--generator/pamtris/utils.c4
-rw-r--r--generator/pbmnoise.c485
-rw-r--r--generator/pbmtext.c30
-rw-r--r--generator/pbmtextps.c448
-rw-r--r--generator/pbmupc.c481
-rwxr-xr-xgenerator/pgmcrater12
-rw-r--r--generator/pgmkernel.c37
-rw-r--r--generator/pgmmake.c4
-rw-r--r--generator/pgmnoise.c118
-rw-r--r--generator/ppmcie.c21
-rw-r--r--generator/ppmcolors.c10
-rw-r--r--generator/ppmforge.c258
-rw-r--r--generator/ppmmake.c4
-rw-r--r--generator/ppmpat.c654
-rwxr-xr-xgenerator/ppmrainbow37
-rw-r--r--generator/ppmrough.c526
-rw-r--r--lib/Makefile48
-rw-r--r--lib/colorname.c80
-rw-r--r--lib/dithers.h2
-rw-r--r--lib/fileio.c16
-rw-r--r--lib/libpam.c145
-rw-r--r--lib/libpamcolor.c53
-rw-r--r--lib/libpammap.c7
-rw-r--r--lib/libpamread.c38
-rw-r--r--lib/libpamwrite.c205
-rw-r--r--lib/libpbm.h6
-rw-r--r--lib/libpbm1.c34
-rw-r--r--lib/libpbm2.c64
-rw-r--r--lib/libpbm3.c25
-rw-r--r--lib/libpbmfont1.c63
-rw-r--r--lib/libpbmfont2.c51
-rw-r--r--lib/libpgm.h7
-rw-r--r--lib/libpgm1.c126
-rw-r--r--lib/libpgm2.c40
-rw-r--r--lib/libpm.c55
-rw-r--r--lib/libpnm1.c30
-rw-r--r--lib/libpnm2.c61
-rw-r--r--lib/libpnm3.c19
-rw-r--r--lib/libppm.h10
-rw-r--r--lib/libppm1.c33
-rw-r--r--lib/libppm2.c57
-rw-r--r--lib/libppmcmap.c13
-rw-r--r--lib/libppmcolor.c553
-rw-r--r--lib/libppmfloyd.c312
-rw-r--r--lib/libppmfuzzy.c6
-rw-r--r--lib/libsystem.c204
-rw-r--r--lib/libsystem_dummy.c30
-rw-r--r--lib/lum.h192
-rw-r--r--lib/pam.h37
-rw-r--r--lib/pamdraw.h132
-rw-r--r--lib/path.c24
-rw-r--r--lib/pbm.h13
-rw-r--r--lib/pm.h38
-rw-r--r--lib/pm_system.h12
-rw-r--r--lib/pmfileio.c184
-rw-r--r--lib/pnm.h3
-rw-r--r--lib/ppm.h36
-rw-r--r--lib/ppmdfont.c4
-rw-r--r--lib/ppmdfont.h4
-rw-r--r--lib/ppmdraw.h218
-rw-r--r--lib/ppmfloyd.h69
-rw-r--r--lib/rgb.txt1422
-rw-r--r--lib/util/LICENSE.txt40
-rw-r--r--lib/util/Makefile4
-rw-r--r--lib/util/bitio.c14
-rw-r--r--lib/util/bitio.h12
-rw-r--r--lib/util/bitreverse.h2
-rw-r--r--lib/util/floatcode.h12
-rw-r--r--lib/util/intcode.h18
-rw-r--r--lib/util/io.c4
-rw-r--r--lib/util/mallocvar.h13
-rw-r--r--lib/util/matrix.c4
-rw-r--r--lib/util/nstring.c757
-rw-r--r--lib/util/nstring.h35
-rw-r--r--lib/util/pm_c_util.h6
-rw-r--r--lib/util/rand.c320
-rw-r--r--lib/util/rand.h118
-rw-r--r--lib/util/randmersenne.c192
-rw-r--r--lib/util/randsysrand.c39
-rw-r--r--lib/util/randsysrandom.c45
-rw-r--r--lib/util/runlength.h4
-rw-r--r--lib/util/shhopt.README18
-rw-r--r--lib/util/shhopt.c732
-rw-r--r--lib/util/shhopt.h48
-rw-r--r--lib/util/testnstring.c4
-rw-r--r--lib/util/token.c2
-rw-r--r--lib/util/vasprintf.c13
-rw-r--r--other/Makefile6
-rw-r--r--other/pamarith.c2
-rw-r--r--other/pambayer.c231
-rw-r--r--other/pamchannel.c40
-rw-r--r--other/pamdepth.c6
-rw-r--r--other/pamendian.c49
-rw-r--r--other/pamexec.c83
-rw-r--r--other/pamlookup.c62
-rw-r--r--other/pampick.c6
-rw-r--r--other/pamsplit.c20
-rw-r--r--other/pamstack.c198
-rw-r--r--other/pamsummcol.c48
-rw-r--r--other/pamunlookup.c3
-rw-r--r--other/pamvalidate.c2
-rw-r--r--other/pamx/fill.c8
-rw-r--r--other/pamx/image.c10
-rw-r--r--other/pamx/pamx.c26
-rw-r--r--other/pamx/send.c118
-rw-r--r--other/pamx/window.c87
-rw-r--r--other/pnmcolormap.c457
-rw-r--r--other/ppmdcfont.c14
-rw-r--r--other/ppmddumpfont.c10
-rw-r--r--other/ppmdmkfont.c56
-rw-r--r--other/ppmsvgalib.c49
-rw-r--r--pm_config.in.h10
-rwxr-xr-xtest/411toppm.test2
-rwxr-xr-xtest/Execute-Tests24
-rw-r--r--test/Makefile21
-rw-r--r--test/Test-Order65
-rw-r--r--test/all-in-place.ok8
-rwxr-xr-xtest/all-in-place.test10
-rwxr-xr-xtest/atari-roundtrip.test2
-rw-r--r--test/atk-roundtrip.ok8
-rwxr-xr-xtest/atk-roundtrip.test24
-rwxr-xr-xtest/avs-roundtrip.test2
-rw-r--r--test/bmp-roundtrip.ok14
-rwxr-xr-xtest/bmp-roundtrip.test16
-rwxr-xr-xtest/channel-stack-roundtrip.test6
-rw-r--r--test/cis-roundtrip.ok8
-rwxr-xr-xtest/cis-roundtrip.test21
-rw-r--r--test/cmuw-roundtrip.ok3
-rwxr-xr-xtest/cmuw-roundtrip.test7
-rw-r--r--test/cut-cat-roundtrip.ok146
-rwxr-xr-xtest/cut-cat-roundtrip.test181
-rwxr-xr-xtest/cut-paste-roundtrip.test3
-rwxr-xr-xtest/enlarge-reduce-roundtrip.test2
-rwxr-xr-xtest/eyuvtoppm.test2
-rwxr-xr-xtest/facesaver-roundtrip.test2
-rwxr-xr-xtest/fiasco-roundtrip.test2
-rwxr-xr-xtest/fits-roundtrip.test2
-rw-r--r--test/g3-roundtrip.ok9
-rwxr-xr-xtest/g3-roundtrip.test43
-rw-r--r--test/gem-roundtrip.ok2
-rwxr-xr-xtest/gem-roundtrip.test6
-rw-r--r--test/gif-roundtrip.ok24
-rwxr-xr-xtest/gif-roundtrip.test90
-rw-r--r--test/gif-transparent1.ok99
-rwxr-xr-xtest/gif-transparent1.test224
-rwxr-xr-xtest/hdiff-roundtrip.test2
-rw-r--r--test/ilbm-roundtrip.ok16
-rwxr-xr-xtest/ilbm-roundtrip.test62
-rw-r--r--test/jbig-roundtrip.ok2
-rwxr-xr-xtest/jbig-roundtrip.test6
-rwxr-xr-xtest/jpeg-roundtrip.test2
-rwxr-xr-xtest/jpeg2k-roundtrip.test2
-rwxr-xr-xtest/leaf-roundtrip.test2
-rw-r--r--test/legacy-names.ok1
-rwxr-xr-xtest/legacy-names.test1
-rwxr-xr-xtest/lookup-roundtrip.test4
-rw-r--r--test/lps-roundtrip.ok3
-rwxr-xr-xtest/lps-roundtrip.test27
-rw-r--r--test/macp-roundtrip.ok13
-rwxr-xr-xtest/macp-roundtrip.test46
-rw-r--r--test/maze.pbmbin0 -> 481 bytes
-rw-r--r--test/mda-roundtrip.ok5
-rwxr-xr-xtest/mda-roundtrip.test14
-rw-r--r--test/mgr-roundtrip.ok8
-rwxr-xr-xtest/mgr-roundtrip.test16
-rw-r--r--test/mrf-roundtrip.ok2
-rwxr-xr-xtest/mrf-roundtrip.test6
-rw-r--r--test/pad-crop-roundtrip.ok4
-rwxr-xr-xtest/pad-crop-roundtrip.test14
-rw-r--r--test/palm-roundtrip.ok14
-rwxr-xr-xtest/palm-roundtrip.test10
-rwxr-xr-xtest/palm-roundtrip2.test2
-rw-r--r--test/pamaddnoise-parameters.ok62
-rwxr-xr-xtest/pamaddnoise-parameters.test337
-rw-r--r--test/pamarith-compare-equal.ok32
-rwxr-xr-xtest/pamarith-compare-equal.test47
-rwxr-xr-xtest/pamarith-multiple-input.test6
-rw-r--r--test/pamarith.ok110
-rwxr-xr-xtest/pamarith.test217
-rwxr-xr-xtest/pambackground.test2
-rw-r--r--test/pambrighten.ok24
-rwxr-xr-xtest/pambrighten.test58
-rw-r--r--test/pamcat1.ok150
-rwxr-xr-xtest/pamcat1.test215
-rw-r--r--test/pamcat2.ok93
-rwxr-xr-xtest/pamcat2.test64
-rw-r--r--test/pamcat3.ok19
-rwxr-xr-xtest/pamcat3.test97
-rw-r--r--test/pamchannel.ok14
-rwxr-xr-xtest/pamchannel.test33
-rw-r--r--test/pamcrater.ok8
-rwxr-xr-xtest/pamcrater.test26
-rw-r--r--test/pamcut.ok132
-rwxr-xr-xtest/pamcut.test263
-rw-r--r--test/pamdepth-roundtrip.ok2
-rwxr-xr-xtest/pamdepth-roundtrip.test4
-rw-r--r--test/pamdepth.ok4
-rwxr-xr-xtest/pamdepth.test14
-rw-r--r--test/pamdice-roundtrip.ok22
-rwxr-xr-xtest/pamdice-roundtrip.test54
-rw-r--r--test/pamdice.ok7
-rwxr-xr-xtest/pamdice.test27
-rw-r--r--test/pamditherbw-random.ok6
-rwxr-xr-xtest/pamditherbw-random.test23
-rw-r--r--test/pamditherbw.ok24
-rwxr-xr-xtest/pamditherbw.test51
-rwxr-xr-xtest/pamedge.test2
-rw-r--r--test/pamendian-roundtrip.ok5
-rwxr-xr-xtest/pamendian-roundtrip.test8
-rwxr-xr-xtest/pamenlarge-pamscale-point.test4
-rwxr-xr-xtest/pamenlarge-pbm.test32
-rw-r--r--test/pamenlarge.ok8
-rwxr-xr-xtest/pamenlarge.test15
-rwxr-xr-xtest/pamexec.test14
-rw-r--r--test/pamfile.ok6
-rwxr-xr-xtest/pamfile.test22
-rw-r--r--test/pamfind.ok8
-rwxr-xr-xtest/pamfind.test30
-rw-r--r--test/pamfix.ok8
-rwxr-xr-xtest/pamfix.test51
-rw-r--r--test/pamflip-pbm-roundtrip.ok122
-rwxr-xr-xtest/pamflip-pbm-roundtrip.test74
-rw-r--r--test/pamflip-roundtrip.ok77
-rwxr-xr-xtest/pamflip-roundtrip.test142
-rw-r--r--test/pamflip1.ok13
-rwxr-xr-xtest/pamflip1.test26
-rw-r--r--test/pamflip2.ok9
-rwxr-xr-xtest/pamflip2.test16
-rw-r--r--test/pamfunc.ok62
-rwxr-xr-xtest/pamfunc.test121
-rw-r--r--test/pamgauss.ok13
-rwxr-xr-xtest/pamgauss.test46
-rwxr-xr-xtest/pamhue-roundtrip.test2
-rw-r--r--test/pamhue.ok2
-rwxr-xr-xtest/pamhue.test19
-rwxr-xr-xtest/pammixmulti-identity.test2
-rw-r--r--test/pamrecolor.ok11
-rwxr-xr-xtest/pamrecolor.test31
-rw-r--r--test/pamrestack.ok68
-rwxr-xr-xtest/pamrestack.test67
-rwxr-xr-xtest/pamscale-filters1.test6
-rwxr-xr-xtest/pamscale-filters2.test6
-rwxr-xr-xtest/pamscale-filters3.test6
-rw-r--r--test/pamscale-reportonly.ok12
-rwxr-xr-xtest/pamscale-reportonly.test36
-rw-r--r--test/pamseq.ok8
-rwxr-xr-xtest/pamseq.test27
-rw-r--r--test/pamshuffle.ok19
-rwxr-xr-xtest/pamshuffle.test53
-rw-r--r--test/pamslice-roundtrip.ok13
-rwxr-xr-xtest/pamslice-roundtrip.test80
-rw-r--r--test/pamstack.ok38
-rwxr-xr-xtest/pamstack.test108
-rw-r--r--test/pamstereogram.ok32
-rwxr-xr-xtest/pamstereogram.test80
-rwxr-xr-xtest/pamstretch.test9
-rw-r--r--test/pamsumm.ok17
-rwxr-xr-xtest/pamsumm.test35
-rw-r--r--test/pamtable.ok59
-rwxr-xr-xtest/pamtable.test55
-rw-r--r--test/pamtopam.ok40
-rwxr-xr-xtest/pamtopam.test23
-rwxr-xr-xtest/pamtopdbimg.test6
-rw-r--r--test/pamtosvg.ok4
-rwxr-xr-xtest/pamtosvg.test45
-rw-r--r--test/pamundice.ok40
-rwxr-xr-xtest/pamundice.test129
-rwxr-xr-xtest/pamvalidate.test12
-rw-r--r--test/pbm-misc-converters.ok83
-rwxr-xr-xtest/pbm-misc-converters.test120
-rw-r--r--test/pbm-ppm-roundtrip.ok39
-rwxr-xr-xtest/pbm-ppm-roundtrip.test34
-rw-r--r--test/pbmclean.ok2
-rwxr-xr-xtest/pbmclean.test15
-rw-r--r--test/pbmlife.ok63
-rwxr-xr-xtest/pbmlife.test13
-rw-r--r--test/pbmmake.ok16
-rwxr-xr-xtest/pbmmake.test61
-rw-r--r--test/pbmminkowski.ok8
-rwxr-xr-xtest/pbmminkowski.test9
-rw-r--r--test/pbmnoise-parameters.ok28
-rwxr-xr-xtest/pbmnoise-parameters.test43
-rw-r--r--test/pbmnoise1.ok50
-rwxr-xr-xtest/pbmnoise1.test38
-rw-r--r--test/pbmnoise2.ok19
-rwxr-xr-xtest/pbmnoise2.test85
-rw-r--r--test/pbmpage.ok6
-rwxr-xr-xtest/pbmpage.test20
-rw-r--r--test/pbmpscale.ok229
-rwxr-xr-xtest/pbmpscale.test62
-rwxr-xr-xtest/pbmtext-bdf.test4
-rwxr-xr-xtest/pbmtext-iso88591.test29
-rw-r--r--test/pbmtext-utf8.ok16
-rwxr-xr-xtest/pbmtext-utf8.test93
-rw-r--r--test/pbmtext.ok22
-rwxr-xr-xtest/pbmtext.test76
-rw-r--r--test/pbmtextps-dump.ok88
-rwxr-xr-xtest/pbmtextps-dump.test136
-rw-r--r--test/pbmtextps.ok18
-rwxr-xr-xtest/pbmtextps.test55
-rw-r--r--test/pbmtog3.ok18
-rwxr-xr-xtest/pbmtog3.test39
-rw-r--r--test/pbmtopgm.ok8
-rwxr-xr-xtest/pbmtopgm.test27
-rw-r--r--test/pbmupc.ok18
-rwxr-xr-xtest/pbmupc.test48
-rw-r--r--test/pcx-roundtrip.ok6
-rwxr-xr-xtest/pcx-roundtrip.test16
-rw-r--r--test/pdb-roundtrip.ok8
-rwxr-xr-xtest/pdb-roundtrip.test30
-rwxr-xr-xtest/pfm-roundtrip.test2
-rwxr-xr-xtest/pgmbentley.test2
-rw-r--r--test/pgmhist.ok8
-rwxr-xr-xtest/pgmhist.test24
-rw-r--r--test/pgmmake.ok29
-rwxr-xr-xtest/pgmmake.test43
-rwxr-xr-xtest/pgmminkowski.test6
-rw-r--r--test/pgmnoise-parameters.ok12
-rwxr-xr-xtest/pgmnoise-parameters.test30
-rw-r--r--test/pgmnoise.ok102
-rw-r--r--test/pgmnoise.rand-ok3
-rwxr-xr-xtest/pgmnoise.test127
-rw-r--r--test/pgmramp.ok12
-rwxr-xr-xtest/pgmramp.test26
-rw-r--r--test/pgmtopgm.ok12
-rwxr-xr-xtest/pgmtopgm.test12
-rw-r--r--test/pgmtoppm.ok36
-rwxr-xr-xtest/pgmtoppm.test139
-rw-r--r--test/pi3-roundtrip.ok5
-rwxr-xr-xtest/pi3-roundtrip.test17
-rwxr-xr-xtest/pict-roundtrip.test2
-rwxr-xr-xtest/pj-roundtrip.test4
-rw-r--r--test/png-roundtrip.ok36
-rwxr-xr-xtest/png-roundtrip.test6
-rw-r--r--test/png-roundtrip2.ok4
-rwxr-xr-xtest/png-roundtrip2.test6
-rw-r--r--test/pnm-pam-roundtrip.ok2
-rwxr-xr-xtest/pnm-pam-roundtrip.test4
-rw-r--r--test/pnm-plain-roundtrip.ok2
-rwxr-xr-xtest/pnm-plain-roundtrip.test4
-rw-r--r--test/pnmcat.ok116
-rwxr-xr-xtest/pnmcat.test165
-rw-r--r--test/pnmcolormap.ok38
-rwxr-xr-xtest/pnmcolormap.test72
-rw-r--r--test/pnmcolormap2.ok37
-rwxr-xr-xtest/pnmcolormap2.test147
-rwxr-xr-xtest/pnmcrop-blank.test2
-rw-r--r--test/pnmcrop1.ok153
-rwxr-xr-xtest/pnmcrop1.test35
-rwxr-xr-xtest/pnmcrop2.test4
-rw-r--r--test/pnmcrop3.ok4
-rwxr-xr-xtest/pnmcrop3.test23
-rw-r--r--test/pnmindex.ok34
-rwxr-xr-xtest/pnmindex.test60
-rw-r--r--test/pnminvert-roundtrip.ok2
-rwxr-xr-xtest/pnminvert-roundtrip.test4
-rw-r--r--test/pnminvert.ok7
-rwxr-xr-xtest/pnminvert.test19
-rw-r--r--test/pnmpad-color.ok222
-rwxr-xr-xtest/pnmpad-color.test446
-rw-r--r--test/pnmpad-extend-enlarge.ok163
-rwxr-xr-xtest/pnmpad-extend-enlarge.test177
-rw-r--r--test/pnmpad-flip.ok64
-rwxr-xr-xtest/pnmpad-flip.test62
-rw-r--r--test/pnmpad-format.ok135
-rwxr-xr-xtest/pnmpad-format.test245
-rw-r--r--test/pnmpad-pnmmargin.ok15
-rwxr-xr-xtest/pnmpad-pnmmargin.test79
-rw-r--r--test/pnmpad-reportonly.ok75
-rwxr-xr-xtest/pnmpad-reportonly.test158
-rwxr-xr-xtest/pnmpaste-pbm.test2
-rw-r--r--test/pnmpsnr.ok8
-rwxr-xr-xtest/pnmpsnr.test28
-rw-r--r--test/pnmquant.ok16
-rwxr-xr-xtest/pnmquant.test61
-rw-r--r--test/pnmquantall.ok9
-rwxr-xr-xtest/pnmquantall.test66
-rw-r--r--test/pnmremap1.ok12
-rwxr-xr-xtest/pnmremap1.test33
-rwxr-xr-xtest/pnmremap2.test2
-rwxr-xr-xtest/pnmshear.test2
-rw-r--r--test/pnmtile.ok10
-rwxr-xr-xtest/pnmtile.test32
-rw-r--r--test/pnmtojpeg-scans.ok20
-rwxr-xr-xtest/pnmtojpeg-scans.test32
-rw-r--r--test/pnmtopnm-plain.ok89
-rwxr-xr-xtest/pnmtopnm-plain.test16
-rw-r--r--test/ppmbrighten.ok8
-rwxr-xr-xtest/ppmbrighten.test22
-rw-r--r--test/ppmchange-roundtrip.ok4
-rwxr-xr-xtest/ppmchange-roundtrip.test6
-rwxr-xr-xtest/ppmchange.test2
-rwxr-xr-xtest/ppmcie.test2
-rwxr-xr-xtest/ppmdfont.test2
-rwxr-xr-xtest/ppmdim.test2
-rwxr-xr-xtest/ppmdither.test2
-rw-r--r--test/ppmforge-parameters.ok18
-rwxr-xr-xtest/ppmforge-parameters.test46
-rw-r--r--test/ppmforge.ok10
-rw-r--r--test/ppmforge.rand-ok3
-rwxr-xr-xtest/ppmforge.test53
-rw-r--r--test/ppmhist.ok6
-rwxr-xr-xtest/ppmhist.test21
-rw-r--r--test/ppmmake.ok30
-rwxr-xr-xtest/ppmmake.test49
-rwxr-xr-xtest/ppmmix.test2
-rw-r--r--test/ppmpat-random.ok6
-rw-r--r--test/ppmpat-random.rand-ok7
-rwxr-xr-xtest/ppmpat-random.test14
-rw-r--r--test/ppmpat.ok72
-rwxr-xr-xtest/ppmpat.test149
-rwxr-xr-xtest/ppmrelief.test2
-rw-r--r--test/ppmrough-parameters.ok25
-rwxr-xr-xtest/ppmrough-parameters.test145
-rw-r--r--test/ppmrough.ok24
-rw-r--r--test/ppmrough.rand-ok3
-rwxr-xr-xtest/ppmrough.test48
-rw-r--r--test/ppmshift.ok23
-rwxr-xr-xtest/ppmshift.test42
-rw-r--r--test/ppmspread.ok12
-rwxr-xr-xtest/ppmspread.test28
-rw-r--r--test/ppmtoapplevol.ok6
-rwxr-xr-xtest/ppmtoapplevol.test30
-rwxr-xr-xtest/ppmtoarbtxt-roundtrip.test5
-rw-r--r--test/ppmtomitsu.ok14
-rwxr-xr-xtest/ppmtomitsu.test31
-rwxr-xr-xtest/ppmtopgm.test2
-rw-r--r--test/ppmtoppm.ok24
-rwxr-xr-xtest/ppmtoppm.test15
-rw-r--r--test/ppmwheel.ok9
-rwxr-xr-xtest/ppmwheel.test25
-rw-r--r--test/ps-alt-roundtrip.ok4
-rwxr-xr-xtest/ps-alt-roundtrip.test13
-rw-r--r--test/ps-flate-roundtrip.ok4
-rwxr-xr-xtest/ps-flate-roundtrip.test15
-rw-r--r--test/ps-roundtrip.ok9
-rwxr-xr-xtest/ps-roundtrip.test24
-rw-r--r--test/qoi-roundtrip.ok34
-rwxr-xr-xtest/qoi-roundtrip.test254
-rw-r--r--test/random-generator.ok219
-rwxr-xr-xtest/random-generator.test83
-rw-r--r--test/rgb3-roundtrip.ok8
-rwxr-xr-xtest/rgb3-roundtrip.test62
-rwxr-xr-xtest/sbig-roundtrip.test2
-rw-r--r--test/sgi-roundtrip.ok13
-rwxr-xr-xtest/sgi-roundtrip.test31
-rwxr-xr-xtest/st4-roundtrip.test2
-rw-r--r--test/stdin-pam1.ok44
-rwxr-xr-xtest/stdin-pam1.test75
-rw-r--r--test/stdin-pam2.ok5
-rwxr-xr-xtest/stdin-pam2.test70
-rw-r--r--test/stdin-pam3.ok34
-rwxr-xr-xtest/stdin-pam3.test75
-rw-r--r--test/stdin-pbm1.ok9
-rwxr-xr-xtest/stdin-pbm1.test45
-rw-r--r--test/stdin-pbm2.ok28
-rwxr-xr-xtest/stdin-pbm2.test78
-rw-r--r--test/stdin-pgm1.ok11
-rwxr-xr-xtest/stdin-pgm1.test47
-rw-r--r--test/stdin-pgm2.ok6
-rwxr-xr-xtest/stdin-pgm2.test49
-rw-r--r--test/stdin-pnm1.ok22
-rwxr-xr-xtest/stdin-pnm1.test59
-rw-r--r--test/stdin-pnm2.ok28
-rwxr-xr-xtest/stdin-pnm2.test91
-rw-r--r--test/stdin-ppm1.ok15
-rwxr-xr-xtest/stdin-ppm1.test58
-rw-r--r--test/stdin-ppm2.ok11
-rwxr-xr-xtest/stdin-ppm2.test58
-rw-r--r--test/stdin-ppm3.ok20
-rwxr-xr-xtest/stdin-ppm3.test75
-rw-r--r--test/sunicon-roundtrip.ok5
-rwxr-xr-xtest/sunicon-roundtrip.test28
-rwxr-xr-xtest/sunrast-roundtrip.test2
-rw-r--r--test/symmetry.ok6
-rwxr-xr-xtest/symmetry.test25
-rw-r--r--test/targa-roundtrip.ok30
-rwxr-xr-xtest/targa-roundtrip.test26
-rw-r--r--test/test-invalid.inc16
-rw-r--r--test/test1.infobin0 -> 989 bytes
-rw-r--r--test/test2.infobin0 -> 16230 bytes
-rw-r--r--test/tiff-flate-lzw-roundtrip.ok4
-rwxr-xr-xtest/tiff-flate-lzw-roundtrip.test14
-rw-r--r--test/tiff-roundtrip.ok20
-rwxr-xr-xtest/tiff-roundtrip.test32
-rwxr-xr-xtest/tiffcmyk-roundtrip.test2
-rwxr-xr-xtest/utahrle-roundtrip.test2
-rw-r--r--test/wbmp-roundtrip.ok2
-rwxr-xr-xtest/wbmp-roundtrip.test6
-rw-r--r--test/winicon-roundtrip.ok14
-rwxr-xr-xtest/winicon-roundtrip.test12
-rw-r--r--test/winicon-roundtrip2.ok2
-rwxr-xr-xtest/winicon-roundtrip2.test16
-rw-r--r--test/xbm-roundtrip.ok5
-rwxr-xr-xtest/xbm-roundtrip.test7
-rw-r--r--test/xpm-roundtrip.ok5
-rwxr-xr-xtest/xpm-roundtrip.test10
-rwxr-xr-xtest/xv-roundtrip.test2
-rw-r--r--test/xwd-roundtrip.ok8
-rwxr-xr-xtest/xwd-roundtrip.test24
-rw-r--r--test/ybm-roundtrip.ok2
-rwxr-xr-xtest/ybm-roundtrip.test7
-rwxr-xr-xtest/yuv-roundtrip.test2
-rw-r--r--urt/Makefile6
-rw-r--r--urt/README5
-rw-r--r--urt/Runput.c535
-rw-r--r--urt/Runput.h34
-rw-r--r--urt/cmd_name.c33
-rw-r--r--urt/rle.h155
-rw-r--r--urt/rle_addhist.c177
-rw-r--r--urt/rle_code.h74
-rw-r--r--urt/rle_config.h10
-rw-r--r--urt/rle_error.c89
-rw-r--r--urt/rle_getcom.c46
-rw-r--r--urt/rle_getrow.c422
-rw-r--r--urt/rle_getskip.c201
-rw-r--r--urt/rle_global.c78
-rw-r--r--urt/rle_hdr.c2
-rw-r--r--urt/rle_open_f.c27
-rw-r--r--urt/rle_put.h72
-rw-r--r--urt/rle_putcom.c156
-rw-r--r--urt/rle_putrow.c760
-rw-r--r--urt/rle_row_alc.c104
-rw-r--r--urt/scanargs.c918
-rw-r--r--urt/vaxshort.c46
-rw-r--r--urt/vaxshort.h6
-rw-r--r--version.mk6
1135 files changed, 66103 insertions, 48560 deletions
diff --git a/GNUmakefile b/GNUmakefile
index 7389c16a..9d02c6ba 100644
--- a/GNUmakefile
+++ b/GNUmakefile
@@ -24,6 +24,21 @@
 #   The default target is either "merge" or "nonmerge", as determined by
 #   the DEFAULT_TARGET variable set by config.mk.
 
+# Debugging techniques:
+#
+#   When a test (make check ...) fails, the incorrect output is in the file
+#   TESTNAME.out in /tmp/netpbm-test/ .
+#
+#   To build so you can easily debug with a debugger such as Gdb:
+#
+#     make CFLAGS="-g -O0"
+#
+#   To debug libnetpbm, link it statically into the using program:
+#
+#     make NETPBMLIBTYPE=unixstatic pamcut
+#
+#     (Then 'ldd ./pamcut' to make sure it worked)
+#
 # About the "merge" target: Normally the Makefiles build separate
 # executables for each program.  However, on some systems (especially
 # those without shared libraries) this can mean a lot of space.  In
diff --git a/analyzer/pamfile.c b/analyzer/pamfile.c
index 7b61f6fd..80674710 100644
--- a/analyzer/pamfile.c
+++ b/analyzer/pamfile.c
@@ -1,4 +1,4 @@
-/* pamfile.c - describe a portable anymap
+/* pamfile.c - describe a Netpbm image
 **
 ** Copyright (C) 1991 by Jef Poskanzer.
 **
@@ -40,7 +40,7 @@ parseCommandLine(int argc, const char ** argv,
    was passed to as as the argv array.
 -----------------------------------------------------------------------------*/
     optEntry * option_def;
-        /* Instructions to pm_optParseOptions3 on how to parse our options.
+        /* Instructions to pm_optParseOptions4 on how to parse our options.
          */
     optStruct3 opt;
 
@@ -60,7 +60,7 @@ parseCommandLine(int argc, const char ** argv,
     opt.short_allowed = false; /* We have no short (old-fashioned) options */
     opt.allowNegNum   = false; /* We have no parms that are negative numbers */
 
-    pm_optParseOptions3(&argc, (char **)argv, opt, sizeof(opt), 0);
+    pm_optParseOptions4(&argc, argv, opt, sizeof(opt), 0);
         /* Uses and sets argc, argv, and some of *cmdlineP and others */
 
     cmdlineP->inputFilespec = (const char **)&argv[1];
@@ -92,30 +92,30 @@ dumpHeaderHuman(struct pam const pam) {
         printf("    Tuple type: %s\n", pam.tuple_type);
         break;
 
-	case PBM_FORMAT:
+        case PBM_FORMAT:
         printf("PBM plain, %d by %d\n", pam.width, pam.height );
         break;
 
-	case RPBM_FORMAT:
+        case RPBM_FORMAT:
         printf("PBM raw, %d by %d\n", pam.width, pam.height);
         break;
 
-	case PGM_FORMAT:
+        case PGM_FORMAT:
         printf("PGM plain, %d by %d  maxval %ld\n",
                pam.width, pam.height, pam.maxval);
         break;
 
-	case RPGM_FORMAT:
+        case RPGM_FORMAT:
         printf("PGM raw, %d by %d  maxval %ld\n",
                pam.width, pam.height, pam.maxval);
         break;
 
-	case PPM_FORMAT:
+        case PPM_FORMAT:
         printf("PPM plain, %d by %d  maxval %ld\n",
                pam.width, pam.height, pam.maxval);
         break;
 
-	case RPPM_FORMAT:
+        case RPPM_FORMAT:
         printf("PPM raw, %d by %d  maxval %ld\n",
                pam.width, pam.height, pam.maxval);
         break;
@@ -136,32 +136,32 @@ dumpHeaderMachine(struct pam const pam) {
         plain = false;
         break;
 
-	case PBM_FORMAT:
+        case PBM_FORMAT:
         formatString = "PBM";
         plain = TRUE;
         break;
 
-	case RPBM_FORMAT:
+        case RPBM_FORMAT:
         formatString = "PBM";
         plain = false;
         break;
 
-	case PGM_FORMAT:
+        case PGM_FORMAT:
         formatString = "PGM";
         plain = TRUE;
         break;
 
-	case RPGM_FORMAT:
+        case RPGM_FORMAT:
         formatString = "PGM";
         plain = false;
         break;
 
-	case PPM_FORMAT:
+        case PPM_FORMAT:
         formatString = "PPM";
         plain = TRUE;
         break;
 
-	case RPPM_FORMAT:
+        case RPPM_FORMAT:
         formatString = "PPM";
         plain = false;        break;
     }
@@ -227,6 +227,7 @@ readToNextImage(const struct pam * const pamP,
 }
 
 
+
 static void
 doOneImage(const char *      const name,
            unsigned int      const imageDoneCt,
@@ -340,11 +341,10 @@ main(int argc, const char *argv[]) {
                             cmdline.comments);
 
             pm_close(ifP);
-	    }
-	}
+            }
+        }
 
     return 0;
 }
 
 
-
diff --git a/analyzer/pamfind.c b/analyzer/pamfind.c
index 15ca9e85..fb98aea3 100644
--- a/analyzer/pamfind.c
+++ b/analyzer/pamfind.c
@@ -23,7 +23,7 @@ parsedCommandLine(int                 argc,
                   const char ** const argv) {
 
     optEntry * option_def;
-        /* Instructions to OptParseOptions3 on how to parse our options.
+        /* Instructions to OptParseOptions4 on how to parse our options.
          */
     optStruct3 opt;
 
@@ -46,7 +46,7 @@ parsedCommandLine(int                 argc,
     opt.short_allowed = FALSE;  /* We have no short (old-fashioned) options */
     opt.allowNegNum = FALSE;  /* We have no parms that are negative numbers */
 
-    pm_optParseOptions3(&argc, (char **)argv, opt, sizeof(opt), 0);
+    pm_optParseOptions4(&argc, argv, opt, sizeof(opt), 0);
 
     if (targetSpec + colorSpec > 1)
         pm_error("You cannot specify both -target and -color");
diff --git a/analyzer/pamgetcolor.c b/analyzer/pamgetcolor.c
index d1ea3799..e7e9160d 100644
--- a/analyzer/pamgetcolor.c
+++ b/analyzer/pamgetcolor.c
@@ -1,4 +1,8 @@
+#define _C99_SOURCE  /* Make sure snprintf() is in stdio.h */
+
 #include <string.h>
+#include <stdio.h>
+
 #include <nstring.h>
 #include <pm_gamma.h>
 #include <pam.h>
@@ -246,7 +250,7 @@ parsedCommandLine(int                 argc,
                   const char ** const argv) {
 
     optEntry * option_def;
-        /* Instructions to OptParseOptions3 on how to parse our options.
+        /* Instructions to OptParseOptions4 on how to parse our options.
          */
     optStruct3 opt;
 
@@ -269,7 +273,7 @@ parsedCommandLine(int                 argc,
     opt.short_allowed = FALSE;  /* We have no short (old-fashioned) options */
     opt.allowNegNum = FALSE;  /* We have no parms that are negative numbers */
 
-    pm_optParseOptions3(&argc, (char **)argv, opt, sizeof(opt), 0);
+    pm_optParseOptions4(&argc, argv, opt, sizeof(opt), 0);
 
     if (!infileSpec)
         cmdLine.infile = "-";
@@ -526,7 +530,7 @@ printColors(struct pam *    const pamP,
 
     tup = pnm_allocpamtuple(pamP);
 
-    pm_snprintf(fmt, sizeof(fmt), "%%%is: %%s\n", cmdLine.maxLbLen);
+    snprintf(fmt, sizeof(fmt), "%%%is: %%s\n", cmdLine.maxLbLen);
 
     for (r = 0; r < cmdLine.regN; ++r) {
         RegSpec      spec;
diff --git a/analyzer/pamsharpmap.c b/analyzer/pamsharpmap.c
index 2f31835b..f63760fe 100644
--- a/analyzer/pamsharpmap.c
+++ b/analyzer/pamsharpmap.c
@@ -14,7 +14,7 @@
    No warranty. See file 'artistic.license' for more details.
 
    boris@13thmonkey.org
-   www.13thmonkey.org/~boris/photopnmtools/ 
+   www.13thmonkey.org/~boris/photopnmtools/
 -----------------------------------------------------------------------------*/
 
 #include <stdio.h>
@@ -40,7 +40,7 @@ parseCommandLine ( int argc, char ** argv,
                    struct cmdlineInfo *cmdlineP ) {
 /*----------------------------------------------------------------------------
    parse program command line described in Unix standard form by argc
-   and argv.  Return the information in the options as *cmdlineP.  
+   and argv.  Return the information in the options as *cmdlineP.
 
    If command line is internally inconsistent (invalid options, etc.),
    issue error message to stderr and abort program.
@@ -58,7 +58,7 @@ parseCommandLine ( int argc, char ** argv,
     unsigned int contextSpec;
 
     option_def_index = 0;   /* incremented by OPTENT3 */
-    OPTENT3(0, "context",       OPT_UINT,   &cmdlineP->context,       
+    OPTENT3(0, "context",       OPT_UINT,   &cmdlineP->context,
             &contextSpec,         0 );
 
     opt.opt_table = option_def;
@@ -92,7 +92,7 @@ makeSharpnessPixel(struct pam * const pamP,
 
     unsigned int plane;
     for (plane = 0; plane < pamP->depth; ++plane)
-        sharpnessTuple[plane] = 
+        sharpnessTuple[plane] =
             (sample)(sharpness[plane] * pamP->maxval + 0.5);
 }
 
@@ -132,20 +132,20 @@ main(int argc, char **argv) {
     int row;
     float * sharpness;
 
-	pnm_init(&argc, argv);
+        pnm_init(&argc, argv);
 
     parseCommandLine(argc, argv, &cmdline);
 
     ifP = pm_openr(cmdline.inputFilespec);
 
-	tuplenarray = pnm_readpamn(ifP, &inpam, PAM_STRUCT_SIZE(tuple_type));
+        tuplenarray = pnm_readpamn(ifP, &inpam, PAM_STRUCT_SIZE(tuple_type));
 
     mappam = inpam;
     mappam.file = stdout;
     mappam.maxval = 255;
 
     MALLOCARRAY_NOFAIL(sharpness, inpam.depth);
-            
+
     map = pnm_allocpamarray(&mappam);
     makeBlackRown(&inpam, tuplenarray[0]);
     for (row = 1; row < inpam.height-1; ++row) {
@@ -154,7 +154,7 @@ main(int argc, char **argv) {
         for (col = 1; col < inpam.width-1; ++col) {
             int dy;
             unsigned int plane;
-            
+
             for (plane = 0; plane < inpam.depth; ++plane)
                 sharpness[plane] = 0.0;
 
@@ -164,9 +164,9 @@ main(int argc, char **argv) {
                     if (dx != 0 || dy != 0) {
                         unsigned int plane;
                         for (plane = 0; plane < inpam.depth; ++plane) {
-                            samplen const sampleval = 
+                            samplen const sampleval =
                                 tuplenarray[row][col][plane];
-                            samplen const sampleval2 = 
+                            samplen const sampleval2 =
                                 tuplenarray[row+dy][col+dx][plane];
                             sharpness[plane] += fabs(sampleval - sampleval2);
                         }
@@ -179,11 +179,11 @@ main(int argc, char **argv) {
     }
     makeBlackRown(&inpam, tuplenarray[inpam.height-1]);
     free(sharpness);
-    
+
     pnm_writepam(&mappam, map);
 
     pnm_freepamarray(map, &mappam);
-	pnm_freepamarrayn(tuplenarray, &inpam);
+        pnm_freepamarrayn(tuplenarray, &inpam);
 
-	return 0;
+        return 0;
 }
diff --git a/analyzer/pamsharpness.c b/analyzer/pamsharpness.c
index 5943416f..f9140bcf 100644
--- a/analyzer/pamsharpness.c
+++ b/analyzer/pamsharpness.c
@@ -14,7 +14,7 @@
    No warranty. See file 'artistic.license' for more details.
 
    boris@13thmonkey.org
-   www.13thmonkey.org/~boris/photopnmtools/ 
+   www.13thmonkey.org/~boris/photopnmtools/
 -----------------------------------------------------------------------------*/
 
 #include <stdio.h>
@@ -40,7 +40,7 @@ parseCommandLine(int argc, char ** argv,
                  struct cmdlineInfo *cmdlineP) {
 /*----------------------------------------------------------------------------
    parse program command line described in Unix standard form by argc
-   and argv.  Return the information in the options as *cmdlineP.  
+   and argv.  Return the information in the options as *cmdlineP.
 
    If command line is internally inconsistent (invalid options, etc.),
    issue error message to stderr and abort program.
@@ -60,7 +60,7 @@ parseCommandLine(int argc, char ** argv,
     MALLOCARRAY_NOFAIL(option_def, 100);
 
     option_def_index = 0;   /* incremented by OPTENT3 */
-    OPTENT3(0, "context",       OPT_UINT,   &cmdlineP->context,       
+    OPTENT3(0, "context",       OPT_UINT,   &cmdlineP->context,
             &contextSpec,         0 );
 
     opt.opt_table = option_def;
@@ -96,7 +96,7 @@ computeSharpness(struct pam * const inpamP,
 
     unsigned int row;
     double totsharp;
-    
+
     totsharp = 0.0;
 
     for (row = 1; row < inpamP->height-1; ++row) {
@@ -109,18 +109,18 @@ computeSharpness(struct pam * const inpamP,
                     if (dx != 0 || dy != 0) {
                         unsigned int plane;
                         for (plane = 0; plane < inpamP->depth; ++plane) {
-                            samplen const sampleval = 
+                            samplen const sampleval =
                                 tuplenarray[row][col][plane];
-                            samplen const sampleval2 = 
+                            samplen const sampleval2 =
                                 tuplenarray[row+dy][col+dx][plane];
                             totsharp += fabs(sampleval - sampleval2);
                         }
                     }
                 }
             }
-		}
-	}
-    *sharpnessP = 
+                }
+        }
+    *sharpnessP =
         totsharp / (inpamP->width * inpamP->height * inpamP->depth * 8);
         /* The 8 above is for the 8 neighbors to which we compare each pixel */
 }
@@ -136,13 +136,13 @@ main(int argc, char **argv) {
     struct pam inpam;
     double sharpness;
 
-	pnm_init(&argc, argv);
+        pnm_init(&argc, argv);
 
     parseCommandLine(argc, argv, &cmdline);
 
     ifP = pm_openr(cmdline.inputFilespec);
 
-	tuplenarray = pnm_readpamn(ifP, &inpam, PAM_STRUCT_SIZE(tuple_type));
+        tuplenarray = pnm_readpamn(ifP, &inpam, PAM_STRUCT_SIZE(tuple_type));
 
     if (inpam.height < 3 || inpam.width < 3)
         pm_error("sharpness is undefined for an image less than 3 pixels "
@@ -153,8 +153,8 @@ main(int argc, char **argv) {
 
     printf("Sharpness = %f\n", sharpness);
 
-	pnm_freepamarrayn(tuplenarray, &inpam);
+        pnm_freepamarrayn(tuplenarray, &inpam);
     pm_close(ifP);
 
-	return 0;
+        return 0;
 }
diff --git a/analyzer/pamslice.c b/analyzer/pamslice.c
index db0ab9c0..9d236441 100644
--- a/analyzer/pamslice.c
+++ b/analyzer/pamslice.c
@@ -1,4 +1,4 @@
-/* 
+/*
  *
  * This program (Pamslice) was derived by Bryan Henderson in July 2002
  * from Pgmslice by Jos Dingjan.  Pgmslice did the same thing, but
@@ -10,10 +10,10 @@
  * modify it under the terms of the GNU General Public License
  * as published by the Free Software Foundation; either version 2
  * of the License, or (at your option) any later version.
- * 
+ *
  * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of 
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  * GNU General Public License for more details.
  *
  * You should have received a copy of the GNU General Public License
@@ -50,7 +50,7 @@ parseCommandLine(int argc, char ** const argv,
    was passed to us as the argv array.
 -----------------------------------------------------------------------------*/
     optEntry *option_def = malloc(100*sizeof(optEntry));
-        /* Instructions to OptParseOptions2 on how to parse our options.
+        /* Instructions to OptParseOptions3 on how to parse our options.
          */
     optStruct3 opt;
 
@@ -77,12 +77,12 @@ parseCommandLine(int argc, char ** const argv,
     if (argc-1 > 1)
         pm_error("Too many arguments (%d).  Only argument is filename.",
                  argc-1);
-    else if (argc-1 == 1) 
+    else if (argc-1 == 1)
         cmdlineP->inputFilespec = argv[1];
     else
         cmdlineP->inputFilespec = "-";
 
-    if (rowSpec) 
+    if (rowSpec)
         cmdlineP->orientation = ROW;
     else if (colSpec)
         cmdlineP->orientation = COLUMN;
@@ -121,7 +121,7 @@ printSlice(FILE *       const outfile,
         else
             fprintf(stdout,"@    type  nxy\n");
     }
-    
+
     count = 0;
     for (row = rowstart; row < rowend; ++row) {
         unsigned int col;
@@ -137,7 +137,7 @@ printSlice(FILE *       const outfile,
 
 
 
-int 
+int
 main(int argc, char *argv[]) {
 
     struct cmdlineInfo cmdline;
@@ -177,7 +177,7 @@ main(int argc, char *argv[]) {
 
         break;
     }
-    
+
     if (cmdline.onePlane) {
         if (cmdline.plane >= inpam.depth)
             pm_error("You specified plane %u, but there are only %u planes "
@@ -189,12 +189,12 @@ main(int argc, char *argv[]) {
         planeend = inpam.depth;
     }
 
-    printSlice(stdout, tuples, 
+    printSlice(stdout, tuples,
                rowstart, rowend, colstart, colend, planestart, planeend,
                cmdline.xmgr);
 
     pm_close(ifP);
     pm_close(stdout);
-        
+
     exit(0);
 }
diff --git a/analyzer/pamsumm.c b/analyzer/pamsumm.c
index 03ff6749..e6c5aca8 100644
--- a/analyzer/pamsumm.c
+++ b/analyzer/pamsumm.c
@@ -32,7 +32,7 @@ parseCommandLine(int argc, const char ** const argv,
                  struct CmdlineInfo * const cmdlineP) {
 
     optEntry * option_def;
-        /* Instructions to OptParseOptions3 on how to parse our options.
+        /* Instructions to OptParseOptions4 on how to parse our options.
          */
     optStruct3 opt;
 
@@ -55,7 +55,7 @@ parseCommandLine(int argc, const char ** const argv,
     opt.short_allowed = FALSE;  /* We have no short (old-fashioned) options */
     opt.allowNegNum = FALSE;  /* We have no parms that are negative numbers */
 
-    pm_optParseOptions3(&argc, (char **)argv, opt, sizeof(opt), 0);
+    pm_optParseOptions4(&argc, argv, opt, sizeof(opt), 0);
         /* Uses and sets argc, argv, and some of *cmdlineP and others. */
 
     if (sumSpec + minSpec + maxSpec + meanSpec > 1)
diff --git a/analyzer/pamtable.c b/analyzer/pamtable.c
index 2835469a..333eff69 100644
--- a/analyzer/pamtable.c
+++ b/analyzer/pamtable.c
@@ -15,12 +15,16 @@
 #include "mallocvar.h"
 #include "nstring.h"
 
+enum Style {STYLE_BASIC, STYLE_TUPLE};
+
 struct CmdlineInfo {
     /* All the information the user supplied in the command line,
        in a form easy for the program to use.
     */
     const char * inputFileName;  /* Name of input file */
-    unsigned int  verbose;
+    enum Style   outputStyle;
+    unsigned int hex;
+    unsigned int verbose;
 };
 
 
@@ -29,16 +33,19 @@ parseCommandLine(int argc, const char ** const argv,
                  struct CmdlineInfo * const cmdlineP) {
 
     optEntry * option_def;
-        /* Instructions to OptParseOptions3 on how to parse our options.
+        /* Instructions to OptParseOptions4 on how to parse our options.
          */
     optStruct3 opt;
 
     unsigned int option_def_index;
+    unsigned int tuple;
 
     MALLOCARRAY(option_def, 100);
 
     option_def_index = 0;   /* incremented by OPTENT3 */
 
+    OPTENT3(0,   "tuple",     OPT_FLAG,  NULL, &tuple,               0);
+    OPTENT3(0,   "hex",       OPT_FLAG,  NULL, &cmdlineP->hex,       0);
     OPTENT3(0,   "verbose",   OPT_FLAG,  NULL, &cmdlineP->verbose,   0);
         /* For future expansion */
 
@@ -46,9 +53,17 @@ parseCommandLine(int argc, const char ** const argv,
     opt.short_allowed = FALSE;  /* We have no short (old-fashioned) options */
     opt.allowNegNum = FALSE;  /* We have no parms that are negative numbers */
 
-    pm_optParseOptions3(&argc, (char **)argv, opt, sizeof(opt), 0);
+    pm_optParseOptions4(&argc, argv, opt, sizeof(opt), 0);
         /* Uses and sets argc, argv, and some of *cmdlineP and others. */
 
+    if (tuple && cmdlineP->hex)
+        pm_error("-hex is invalid with -tuple");
+
+    if (tuple)
+        cmdlineP->outputStyle = STYLE_TUPLE;
+    else
+        cmdlineP->outputStyle = STYLE_BASIC;
+
     if (argc-1 > 1)
         pm_error("Too many arguments (%d).  File name is the only argument.",
                  argc-1);
@@ -74,12 +89,27 @@ typedef struct {
     const char * interTupleGutter;
        /* What we print between tuples within a row */
 
+    const char * rowStartString;
+       /* What we print at the beginning of each row */
+
+    const char * rowEndString;
+       /* What we print at the end of each row */
+
 } Format;
 
 
 
+static double const
+log16(double const arg) {
+
+    return log(arg)/log(16);
+}
+
+
+
 static const char *
-sampleFormat(const struct pam * const pamP) {
+basicSampleFormat(const struct pam * const pamP,
+                  bool               const wantHex) {
 /*----------------------------------------------------------------------------
    The printf format string for a single sample in the output table.
 
@@ -87,11 +117,21 @@ sampleFormat(const struct pam * const pamP) {
 
    This format does not include any spacing between samples.
 -----------------------------------------------------------------------------*/
-    unsigned int const decimalWidth = ROUNDU(ceil(log10(pamP->maxval + 1)));
-
+    unsigned int cipherWidth;
+    char         formatSpecifier;
+    const char * flag;
     const char * retval;
 
-    pm_asprintf(&retval, "%%%uu", decimalWidth);
+    if (wantHex) {
+        formatSpecifier = 'x';
+        cipherWidth     = ROUNDU(ceil(log16(pamP->maxval + 1)));
+        flag            = "0";
+    } else {
+        formatSpecifier = 'u';
+        cipherWidth     = ROUNDU(ceil(log10(pamP->maxval + 1)));
+        flag            = "";
+    }
+    pm_asprintf(&retval, "%%%s%u%c", flag, cipherWidth, formatSpecifier);
 
     return retval;
 }
@@ -100,13 +140,26 @@ sampleFormat(const struct pam * const pamP) {
 
 static void
 makeFormat(const struct pam * const pamP,
+           enum Style         const outputStyle,
+           bool               const wantHex,
            Format *           const formatP) {
 
-    formatP->sampleFmt = sampleFormat(pamP);
-
-    formatP->interSampleGutter = " ";
-
-    formatP->interTupleGutter = pamP->depth > 1 ? "|" : " ";
+    switch (outputStyle) {
+      case STYLE_BASIC:
+          formatP->sampleFmt         = basicSampleFormat(pamP, wantHex);
+          formatP->interSampleGutter = " ";
+          formatP->interTupleGutter  = pamP->depth > 1 ? "|" : " ";
+          formatP->rowStartString    = "";
+          formatP->rowEndString      = "\n";
+          break;
+      case STYLE_TUPLE:
+          formatP->sampleFmt         = pm_strdup("%u");
+          formatP->interSampleGutter = ",";
+          formatP->interTupleGutter  = ") (";
+          formatP->rowStartString    = "(";
+          formatP->rowEndString      = ")\n";
+          break;
+    }
 }
 
 
@@ -127,6 +180,8 @@ printRow(const struct pam * const pamP,
 
     unsigned int col;
 
+    fputs (format.rowStartString, ofP);
+
     for (col = 0; col < pamP->width; ++col) {
         unsigned int plane;
 
@@ -142,7 +197,7 @@ printRow(const struct pam * const pamP,
         }
     }
 
-    fputs("\n", ofP);
+    fputs (format.rowEndString, ofP);
 }
 
 
@@ -150,14 +205,16 @@ printRow(const struct pam * const pamP,
 static void
 printRaster(FILE *             const ifP,
             const struct pam * const pamP,
-            FILE *             const ofP) {
+            FILE *             const ofP,
+            enum Style         const outputStyle,
+            bool               const wantHex) {
 
     Format format;
 
     tuple * inputRow;   /* Row from input image */
     unsigned int row;
 
-    makeFormat(pamP, &format);
+    makeFormat(pamP, outputStyle, wantHex, &format);
 
     inputRow = pnm_allocpamrow(pamP);
 
@@ -189,7 +246,7 @@ main(int argc, const char *argv[]) {
 
     pnm_readpaminit(ifP, &inpam, PAM_STRUCT_SIZE(tuple_type));
 
-    printRaster(ifP, &inpam, stdout);
+    printRaster(ifP, &inpam, stdout, cmdline.outputStyle, cmdline.hex);
 
     pm_close(inpam.file);
 
diff --git a/analyzer/pamtilt.c b/analyzer/pamtilt.c
index 2898d30f..031c4206 100644
--- a/analyzer/pamtilt.c
+++ b/analyzer/pamtilt.c
@@ -76,7 +76,7 @@ parseCommandLine(int argc, const char ** const argv,
     opt.opt_table = option_def;
     opt.short_allowed = FALSE;          /* no short options used */
     opt.allowNegNum = FALSE;            /* don't allow negative values */
-    pm_optParseOptions3(&argc, (char **)argv, opt, sizeof(opt), 0);
+    pm_optParseOptions4(&argc, argv, opt, sizeof(opt), 0);
 
     if (cmdlineP->hstep < 1)
         pm_error("-hstep must be at least 1 column.");
diff --git a/analyzer/pbmminkowski.c b/analyzer/pbmminkowski.c
index 0f7b47a9..368ff34e 100644
--- a/analyzer/pbmminkowski.c
+++ b/analyzer/pbmminkowski.c
@@ -25,15 +25,15 @@ int main(int argc, const char ** argv) {
     bit * prevrow;
     bit * thisrow;
     bit * tmprow;
-  
+
     int row;
-    int col; 
+    int col;
 
     int countTile;
     int countEdgeX;
     int countEdgeY;
     int countVertex;
-  
+
     int rows;
     int cols;
     int format;
@@ -42,15 +42,15 @@ int main(int argc, const char ** argv) {
 
 
     pm_proginit(&argc, argv);
-  
+
     if (argc > 2)
         pm_usage("[pbmfile]");
-  
+
     if (argc == 2)
         ifP = pm_openr(argv[1]);
     else
         ifP = stdin;
-  
+
     pbm_readpbminit(ifP, &cols, &rows, &format);
 
     prevrow = pbm_allocrow(cols);
@@ -68,10 +68,10 @@ int main(int argc, const char ** argv) {
 
     /* tiles */
 
-    for (col = 0; col < cols; ++col) 
+    for (col = 0; col < cols; ++col)
         if (ISWHITE(thisrow[col]))
             ++countTile;
-  
+
     /* shortcut: for the first row, edgeY == countTile */
     countEdgeY = countTile;
 
@@ -80,7 +80,7 @@ int main(int argc, const char ** argv) {
     if (ISWHITE(thisrow[0]))
         ++countEdgeX;
 
-    for (col = 0; col < cols-1; ++col) 
+    for (col = 0; col < cols-1; ++col)
         if (ISWHITE(thisrow[col]) || ISWHITE(thisrow[col+1]))
             ++countEdgeX;
 
@@ -88,56 +88,56 @@ int main(int argc, const char ** argv) {
         ++countEdgeX;
 
     /* shortcut: for the first row, countVertex == countEdgeX */
-  
+
     countVertex = countEdgeX;
-  
 
-    for (row = 1; row < rows; ++row) {  
-    
-        tmprow  = prevrow; 
+
+    for (row = 1; row < rows; ++row) {
+
+        tmprow  = prevrow;
         prevrow = thisrow;
         thisrow = tmprow;
- 
+
         pbm_readpbmrow(ifP, thisrow, cols, format);
-  
+
         /* tiles */
 
-        for (col = 0; col < cols; ++col) 
+        for (col = 0; col < cols; ++col)
             if (ISWHITE(thisrow[col]))
                 ++countTile;
-    
+
         /* y-edges */
 
-        for (col = 0; col < cols; ++col) 
+        for (col = 0; col < cols; ++col)
             if (ISWHITE(thisrow[col]) || ISWHITE(prevrow[col]))
                 ++countEdgeY;
-    
+
         /* x-edges */
 
         if (ISWHITE(thisrow[0]))
             ++countEdgeX;
 
-        for (col = 0; col < cols-1; ++col) 
+        for (col = 0; col < cols-1; ++col)
             if (ISWHITE(thisrow[col]) || ISWHITE(thisrow[col+1]))
                 ++countEdgeX;
-    
+
         if (ISWHITE(thisrow[cols-1]))
             ++countEdgeX;
-    
+
         /* vertices */
 
         if (ISWHITE(thisrow[0]) || ISWHITE(prevrow[0]))
             ++countVertex;
 
-        for (col = 0; col < cols-1; ++col) 
-            if (ISWHITE(thisrow[col]) || ISWHITE(thisrow[col+1]) 
+        for (col = 0; col < cols-1; ++col)
+            if (ISWHITE(thisrow[col]) || ISWHITE(thisrow[col+1])
                 || ISWHITE(prevrow[col]) || ISWHITE(prevrow[col+1]))
                 ++countVertex;
 
         if (ISWHITE(thisrow[cols-1]) || ISWHITE(prevrow[cols-1]))
             ++countVertex;
 
-	  
+
     } /* for row */
 
     /* now thisrow contains the top row*/
@@ -145,19 +145,19 @@ int main(int argc, const char ** argv) {
        vertices remain
     */
 
-  
+
     /* y-edges */
 
-    for (col = 0; col < cols; ++col) 
+    for (col = 0; col < cols; ++col)
         if (ISWHITE(thisrow[col]))
             ++countEdgeY;
 
     /* vertices */
-  
+
     if (ISWHITE(thisrow[0]))
         ++countVertex;
 
-    for (col = 0; col < cols-1; ++col) 
+    for (col = 0; col < cols-1; ++col)
         if (ISWHITE(thisrow[col]) || ISWHITE(thisrow[col+1]))
             ++countVertex;
 
@@ -179,7 +179,7 @@ int main(int argc, const char ** argv) {
 
     printf("    area:\t%d\nperimeter:\t%d\n eulerchi:\t%d\n",
            area, perimeter, eulerchi );
-  
+
     return 0;
 }
 
diff --git a/analyzer/pgmhist.c b/analyzer/pgmhist.c
index 1e779655..3b0b9b95 100644
--- a/analyzer/pgmhist.c
+++ b/analyzer/pgmhist.c
@@ -64,7 +64,7 @@ parseCommandLine(int argc, const char ** argv,
     opt.short_allowed = FALSE;  /* We have no short (old-fashioned) options */
     opt.allowNegNum = FALSE;  /* We have no parms that are negative numbers */
 
-    pm_optParseOptions3(&argc, (char **)argv, opt, sizeof(opt), 0);
+    pm_optParseOptions4(&argc, argv, opt, sizeof(opt), 0);
         /* Uses and sets argc, argv, and some of *cmdlineP and others. */
 
     if (cmdlineP->median + cmdlineP->quartile + cmdlineP->decile > 1)
@@ -211,8 +211,8 @@ findQuantiles(unsigned int      const n,
     cumCt = hist[0];  /* initial value */
 
     for (quantSeq = 1; quantSeq <= n; ++quantSeq) {
-        unsigned long int const q = totalCt / n; 
-        unsigned long int const r = totalCt % n;  
+        unsigned long int const q = totalCt / n;
+        unsigned long int const r = totalCt % n;
         unsigned long int const quantCt = q*quantSeq + (r*quantSeq + n - 1)/n;
        /* This is how many pixels are (ignoring quantization) in the
           quantile.  E.g. for the 3rd quartile, it is 3/4 of the pixels
@@ -419,7 +419,7 @@ summarizeInvalidPixels(unsigned long int const hist[],
   Print total count of valid and invalid pixels, if there are any
   invalid ones.
 -----------------------------------------------------------------------------*/
-    unsigned long int const invalidPixelCt = 
+    unsigned long int const invalidPixelCt =
         mmaxval > maxval ? rcount[maxval+1] : 0;
 
     if (invalidPixelCt > 0) {
diff --git a/analyzer/pgmminkowski.c b/analyzer/pgmminkowski.c
index dfb08429..676dd567 100644
--- a/analyzer/pgmminkowski.c
+++ b/analyzer/pgmminkowski.c
@@ -1,9 +1,9 @@
-/* pgmminkowsky.c - read a portable graymap and calculate the Minkowski 
+/* pgmminkowsky.c - read a portable graymap and calculate the Minkowski
 ** Integrals as a function of the threshold.
 **
 ** Copyright (C) 2000 by Luuk van Dijk/Mind over Matter
 **
-** Based on pgmhist.c, 
+** Based on pgmhist.c,
 ** Copyright (C) 1989 by Jef Poskanzer.
 **
 ** Permission to use, copy, modify, and distribute this software and its
@@ -22,7 +22,7 @@
 #define MAX4(a,b,c,d) MAX2( MAX2((a),(b)), MAX2((c),(d)) )
 
 int main( int argc, char** argv ){
-  
+
   FILE *ifp;
 
   gray maxval;
@@ -31,11 +31,11 @@ int main( int argc, char** argv ){
   gray* prevrow;
   gray* thisrow;
   gray* tmprow;
-  
-  int* countTile;   
-  int* countEdgeX;  
-  int* countEdgeY; 
-  int* countVertex; 
+
+  int* countTile;
+  int* countEdgeX;
+  int* countEdgeY;
+  int* countVertex;
 
   int i, col, row;
 
@@ -46,12 +46,12 @@ int main( int argc, char** argv ){
 
   /*
    * parse arg and initialize
-   */ 
+   */
 
   pgm_init( &argc, argv );
 
   if ( argc > 2 ) pm_usage( "[pgmfile]" );
-  
+
   if ( argc == 2 )
     ifp = pm_openr( argv[1] );
   else
@@ -62,19 +62,19 @@ int main( int argc, char** argv ){
    */
 
   pgm_readpgminit( ifp, &cols, &rows, &maxval, &format );
-  
+
   prevrow = pgm_allocrow( cols );
   thisrow = pgm_allocrow( cols );
-  
+
   MALLOCARRAY(countTile   , maxval + 1 );
   MALLOCARRAY(countEdgeX  , maxval + 1 );
   MALLOCARRAY(countEdgeY  , maxval + 1 );
   MALLOCARRAY(countVertex , maxval + 1 );
- 
+
   if (countTile == NULL || countEdgeX == NULL || countEdgeY == NULL ||
       countVertex == NULL)
       pm_error( "out of memory" );
-  
+
   for ( i = 0; i <= maxval; i++ ) countTile[i]   = 0;
   for ( i = 0; i <= maxval; i++ ) countEdgeX[i]  = 0;
   for ( i = 0; i <= maxval; i++ ) countEdgeY[i]  = 0;
@@ -89,84 +89,84 @@ int main( int argc, char** argv ){
 
   /* tiles */
 
-  for ( col = 0; col < cols; ++col ) ++countTile[thisrow[col]]; 
-  
+  for ( col = 0; col < cols; ++col ) ++countTile[thisrow[col]];
+
   /* y-edges */
 
-  for ( col = 0; col < cols; ++col ) ++countEdgeY[thisrow[col]]; 
+  for ( col = 0; col < cols; ++col ) ++countEdgeY[thisrow[col]];
 
   /* x-edges */
 
   ++countEdgeX[thisrow[0]];
 
-  for ( col = 0; col < cols-1; ++col ) 
+  for ( col = 0; col < cols-1; ++col )
     ++countEdgeX[ MAX2(thisrow[col], thisrow[col+1]) ];
-  
+
   ++countEdgeX[thisrow[cols-1]];
-  
+
   /* shortcut: for the first row, countVertex == countEdgeX */
-  
+
   ++countVertex[thisrow[0]];
 
-  for ( col = 0; col < cols-1; ++col ) 
+  for ( col = 0; col < cols-1; ++col )
     ++countVertex[ MAX2(thisrow[col], thisrow[col+1]) ];
 
   ++countVertex[thisrow[cols-1]];
 
-  
 
-  for ( row = 1; row < rows; ++row ){  
-    
-    tmprow = prevrow; 
+
+  for ( row = 1; row < rows; ++row ){
+
+    tmprow = prevrow;
     prevrow = thisrow;
     thisrow = tmprow;
- 
+
     pgm_readpgmrow( ifp, thisrow, cols, maxval, format );
-  
+
     /* tiles */
 
-    for ( col = 0; col < cols; ++col ) ++countTile[thisrow[col]]; 
-    
+    for ( col = 0; col < cols; ++col ) ++countTile[thisrow[col]];
+
     /* y-edges */
-    
-    for ( col = 0; col < cols; ++col ) 
+
+    for ( col = 0; col < cols; ++col )
       ++countEdgeY[ MAX2(thisrow[col], prevrow[col]) ];
     /* x-edges */
-    
+
     ++countEdgeX[thisrow[0]];
-    
-    for ( col = 0; col < cols-1; ++col ) 
+
+    for ( col = 0; col < cols-1; ++col )
       ++countEdgeX[ MAX2(thisrow[col], thisrow[col+1]) ];
-    
+
     ++countEdgeX[thisrow[cols-1]];
-    
+
     /* vertices */
 
     ++countVertex[ MAX2(thisrow[0],prevrow[0]) ];
 
-    for ( col = 0; col < cols-1; ++col ) 
+    for ( col = 0; col < cols-1; ++col )
       ++countVertex[
         MAX4(thisrow[col], thisrow[col+1], prevrow[col], prevrow[col+1])
       ];
-    
+
     ++countVertex[ MAX2(thisrow[cols-1],prevrow[cols-1]) ];
-    
+
   } /* for row */
-  
+
   /* now thisrow contains the top row*/
 
   /* tiles and x-edges have been counted, now upper
      y-edges and top vertices remain */
-  
+
   /* y-edges */
 
   for ( col = 0; col < cols; ++col ) ++countEdgeY[ thisrow[col] ];
 
   /* vertices */
-  
+
   ++countVertex[thisrow[0]];
 
-  for ( col = 0; col < cols-1; ++col ) 
+  for ( col = 0; col < cols-1; ++col )
     ++countVertex[ MAX2(thisrow[col],thisrow[col+1]) ];
 
   ++countVertex[ thisrow[cols-1] ];
@@ -178,7 +178,7 @@ int main( int argc, char** argv ){
   maxedgex =  rows    * (cols+1);
   maxedgey = (rows+1) *  cols;
   maxvertex= (rows+1) * (cols+1);
-  
+
   l2inv = 1.0/maxtiles;
   linv  = 0.5/(rows+cols);
 
@@ -187,14 +187,14 @@ int main( int argc, char** argv ){
   printf( "#---------\t -----\t-------\t-------\t--------\n" );
   for ( i = 0; i <= maxval; i++ ){
 
-    if( !(countTile[i] || countEdgeX[i] || countEdgeY[i] || countVertex[i] ) ) 
+    if( !(countTile[i] || countEdgeX[i] || countEdgeY[i] || countVertex[i] ) )
       continue; /* skip empty slots */
 
     area      = maxtiles;
     perimeter = 2*maxedgex + 2*maxedgey - 4*maxtiles;
     eulerchi  = maxtiles - maxedgex - maxedgey + maxvertex;
 
-    printf( "%f\t%6d\t%7d\t%7d\t%8d\t%g\t%g\t%6d\n", (float) i/(1.0*maxval), 
+    printf( "%f\t%6d\t%7d\t%7d\t%8d\t%g\t%g\t%6d\n", (float) i/(1.0*maxval),
         maxtiles, maxedgex, maxedgey, maxvertex,
         area*l2inv, perimeter*linv, eulerchi
         );
@@ -210,13 +210,13 @@ int main( int argc, char** argv ){
   }
 
   /* these should be zero: */
-  printf( "#  check:\t%6d\t%7d\t%7d\t%8d\n", 
+  printf( "#  check:\t%6d\t%7d\t%7d\t%8d\n",
           maxtiles, maxedgex, maxedgey, maxvertex );
 
   pm_close( ifp );
-  
+
   exit( 0 );
-  
+
 } /*main*/
 
 
diff --git a/analyzer/pgmtexture.c b/analyzer/pgmtexture.c
index c69643e7..938f9ef8 100644
--- a/analyzer/pgmtexture.c
+++ b/analyzer/pgmtexture.c
@@ -9,25 +9,62 @@
 
 #include "pm_c_util.h"
 #include "mallocvar.h"
+#include "shhopt.h"
 #include "pgm.h"
 
+
+struct CmdlineInfo {
+    /* All the information the user supplied in the command line,
+     * in a form easy for the program to use.
+     */
+    const char * inputFileName;  /* Filespec of input file */
+    unsigned int d;
+};
+
+
+
+static void
+parseCommandLine(int argc, const char ** const argv,
+                 struct CmdlineInfo * const cmdlineP) {
+/*----------------------------------------------------------------------------
+   Note that the file spec array we return is stored in the storage that
+   was passed to us as the argv array.
+-----------------------------------------------------------------------------*/
+    optEntry * option_def;
+    optStruct3 opt;
+    unsigned int option_def_index;
+
+    unsigned int dSpec;
+
+    MALLOCARRAY_NOFAIL(option_def, 100);
+
+    option_def_index = 0;   /* incremented by OPTENT3 */
+    OPTENT3(0,   "d",          OPT_UINT,   &cmdlineP->d,  &dSpec,      0);
+
+    opt.opt_table = option_def;
+    opt.short_allowed = FALSE;  /* We have no short (old-fashioned) options */
+    opt.allowNegNum = TRUE;  /* We may have parms that are negative numbers */
+
+    pm_optParseOptions4(&argc, argv, opt, sizeof(opt), 0);
+        /* Uses and sets argc, argv, and some of *cmdlineP and others. */
+
+    if (!dSpec)
+        cmdlineP->d = 1;
+
+    if (argc-1 < 1)
+        cmdlineP->inputFileName = "-";
+    else if (argc-1 == 1)
+        cmdlineP->inputFileName = argv[1];
+    else
+        pm_error("Program takes at most 1 parameter: the file name.  "
+                 "You specified %u", argc-1);
+}
+
+
+
 #define RADIX 2.0
 #define EPSILON 0.000000001
 #define BL  "Angle                 "
-#define F1  "Angular Second Moment "
-#define F2  "Contrast              "
-#define F3  "Correlation           "
-#define F4  "Variance              "
-#define F5  "Inverse Diff Moment   "
-#define F6  "Sum Average           "
-#define F7  "Sum Variance          "
-#define F8  "Sum Entropy           "
-#define F9  "Entropy               "
-#define F10 "Difference Variance   "
-#define F11 "Difference Entropy    "
-#define F12 "Meas of Correlation-1 "
-#define F13 "Meas of Correlation-2 "
-#define F14 "Max Correlation Coeff "
 
 #define SWAP(a,b) do {float const y=(a);(a)=(b);(b)=y;} while (0)
 
@@ -42,23 +79,31 @@ sign(float const x,
 
 
 
-static bool const sortit = FALSE;
-
-
-
 static float *
 vector(unsigned int const nl,
        unsigned int const nh) {
+/*----------------------------------------------------------------------------
+  Allocate a float vector with range [nl..nh]
 
+  We do some seedy C here, subtracting an arbitrary integer from a pointer and
+  calling the result a pointer.  It normally works because the only way we'll
+  use that pointer is by adding that same integer or something greater to it.
+
+  The point of this is not to allocate memory for vector elements that will
+  never be referenced (component < nl).
+-----------------------------------------------------------------------------*/
     float * v;
+    unsigned int i;
 
-    assert(nh >= nl);
+    assert(nh >= nl); assert(nh <= UINT_MAX-1);
 
     MALLOCARRAY(v, (unsigned) (nh - nl + 1));
 
     if (v == NULL)
         pm_error("Unable to allocate memory for a vector.");
 
+    for (i = 0; i < nh - nl +1; ++i)
+        v[i] = 0;
     return v - nl;
 }
 
@@ -72,48 +117,61 @@ matrix (unsigned int const nrl,
 /*----------------------------------------------------------------------------
   Allocate a float matrix with range [nrl..nrh][ncl..nch]
 
-  We do some seedy C here, subtracting an arbitrary integer from a pointer and
-  calling the result a pointer.  It normally works because the only way we'll
-  use that pointer is by adding that same integer or something greater to it.
-
-  The point of this is not to allocate memory for matrix elements that will
-  never be referenced (row < nrl or column < ncl).
+  Return value is a pointer to array of pointers to rows
 -----------------------------------------------------------------------------*/
+    /* We do some seedy C here, subtracting an arbitrary integer from a
+       pointer and calling the result a pointer.  It normally works because
+       the only way we'll use that pointer is by adding that same integer or
+       something greater to it.
+
+       The point of this is not to allocate memory for matrix elements that
+       will never be referenced (row < nrl or column < ncl).
+    */
+
     unsigned int i;
-    float ** m;
+    float ** matrix;  /* What we are creating */
 
-    assert(nrh >= nrl);
+    assert(nrh >= nrl); assert(nrh <= UINT_MAX-1);
 
     /* allocate pointers to rows */
-    MALLOCARRAY(m, (unsigned) (nrh - nrl + 1));
-    if (m == NULL)
+    MALLOCARRAY(matrix, (unsigned) (nrh - nrl + 1));
+    if (matrix == NULL)
         pm_error("Unable to allocate memory for a matrix.");
 
-    m -= ncl;
+    matrix -= ncl;
 
-    assert (nch >= ncl);
+    assert (nch >= ncl); assert(nch <= UINT_MAX-1);
 
     /* allocate rows and set pointers to them */
     for (i = nrl; i <= nrh; ++i) {
-        MALLOCARRAY(m[i], (unsigned) (nch - ncl + 1));
-        if (m[i] == NULL)
+        MALLOCARRAY(matrix[i], (unsigned) (nch - ncl + 1));
+        if (!matrix[i])
             pm_error("Unable to allocate memory for a matrix row.");
-        m[i] -= ncl;
+        matrix[i] -= ncl;
     }
 
-    /* return pointer to array of pointers to rows */
-    return m;
+    return matrix;
 }
 
 
 
 static void
-results (const char *  const name,
-         const float * const a) {
+printHeader() {
+
+    fprintf(stdout,
+            "%-22.22s %10.10s %10.10s %10.10s %10.10s %10.10s\n",
+            "Angle", "0", "45", "90", "135", "Avg");
+}
+
+
+
+static void
+printResults(const char *  const name,
+             const float * const a) {
 
     unsigned int i;
 
-    fprintf(stdout, "%s", name);
+    fprintf(stdout, "%-22.22s ", name);
 
     for (i = 0; i < 4; ++i)
         fprintf(stdout, "% 1.3e ", a[i]);
@@ -124,24 +182,105 @@ results (const char *  const name,
 
 
 static void
-simplesrt (unsigned int  const n,
-           float *       const arr) {
+makeGrayToneSpatialDependenceMatrix(gray **        const grays,
+                                    unsigned int   const rows,
+                                    unsigned int   const cols,
+                                    unsigned int   const d,
+                                    unsigned int * const tone,
+                                    unsigned int   const toneCt,
+                                    float *** const pmatrix0P,
+                                    float *** const pmatrix45P,
+                                    float *** const pmatrix90P,
+                                    float *** const pmatrix135P) {
+
+    float ** pmatrix0, ** pmatrix45, ** pmatrix90, ** pmatrix135;
+    unsigned int row;
 
-    unsigned int j;
-    float a;
+    pm_message("Computing spatial dependence matrix...");
 
-    for (j = 2; j <= n; ++j) {
-        unsigned int i;
+    /* Allocate memory */
+    pmatrix0   = matrix(0, toneCt, 0, toneCt);
+    pmatrix45  = matrix(0, toneCt, 0, toneCt);
+    pmatrix90  = matrix(0, toneCt, 0, toneCt);
+    pmatrix135 = matrix(0, toneCt, 0, toneCt);
 
-        a = arr[j];
-        i = j;
+    for (row = 0; row < toneCt; ++row) {
+        unsigned int col;
+        for (col = 0; col < toneCt; ++col) {
+            pmatrix0 [row][col] = pmatrix45 [row][col] = 0;
+            pmatrix90[row][col] = pmatrix135[row][col] = 0;
+        }
+    }
+    for (row = 0; row < rows; ++row) {
+        unsigned int col;
+        for (col = 0; col < cols; ++col) {
+            unsigned int angle;
+            unsigned int x;
+            for (angle = 0, x = 0; angle <= 135; angle += 45) {
+                while (tone[x] != grays[row][col])
+                    ++x;
+                if (angle == 0 && col + d < cols) {
+                    unsigned int y;
+                    y = 0;
+                    while (tone[y] != grays[row][col + d])
+                        ++y;
+                    ++pmatrix0[x][y];
+                    ++pmatrix0[y][x];
+                }
+                if (angle == 90 && row + d < rows) {
+                    unsigned int y;
+                    y = 0;
+                    while (tone[y] != grays[row + d][col])
+                        ++y;
+                    ++pmatrix90[x][y];
+                    ++pmatrix90[y][x];
+                }
+                if (angle == 45 && row + d < rows && col >= d) {
+                    unsigned int y;
+                    y = 0;
+                    while (tone[y] != grays[row + d][col - d])
+                        ++y;
+                    ++pmatrix45[x][y];
+                    ++pmatrix45[y][x];
+                }
+                if (angle == 135 && row + d < rows && col + d < cols) {
+                    unsigned int y;
+                    y = 0;
+                    while (tone[y] != grays[row + d][col + d])
+                        ++y;
+                    ++pmatrix135[x][y];
+                    ++pmatrix135[y][x];
+                }
+            }
+        }
+    }
+    /* Gray-tone spatial dependence matrices are complete */
+
+    {
+    /* Find normalizing constants */
+    unsigned int const r0  = 2 * rows * (cols - d);
+    unsigned int const r45 = 2 * (rows - d) * (cols - d);
+    unsigned int const r90 = 2 * (rows - d) * cols;
+
+    unsigned int i;
 
-        while (i > 1 && arr[i-1] > a) {
-            arr[i] = arr[i-1];
-            --i;
+    /* Normalize gray-tone spatial dependence matrix */
+    for (i = 0; i < toneCt; ++i) {
+        unsigned int j;
+        for (j = 0; j < toneCt; ++j) {
+            pmatrix0  [i][j] /= r0;
+            pmatrix45 [i][j] /= r45;
+            pmatrix90 [i][j] /= r90;
+            pmatrix135[i][j] /= r45;
         }
-        arr[i] = a;
     }
+    }
+    pm_message(" ...done.");
+
+    *pmatrix0P   = pmatrix0;
+    *pmatrix45P  = pmatrix45;
+    *pmatrix90P  = pmatrix90;
+    *pmatrix135P = pmatrix135;
 }
 
 
@@ -197,8 +336,8 @@ mkbalanced (float **     const a,
 
 
 static void
-reduction (float **     const a,
-           unsigned int const n) {
+reduction(float **     const a,
+          unsigned int const n) {
 
     unsigned int m;
 
@@ -315,7 +454,7 @@ hessenberg(float **     const a,
                     float p, q, r;
                     if (its == 30)
                         pm_error("Too many iterations to required "
-                                 "to find %s.  Giving up", F14);
+                                 "to find max correlation coefficient");
                     if (its == 10 || its == 20) {
                         int i;
                         float s;
@@ -558,6 +697,43 @@ f5_idm (float **     const p,
 }
 
 
+static double *
+newPxpy2(unsigned int const ng) {
+
+    double * pxpy;
+
+    if (ng > UINT_MAX-1)
+        pm_error("Too many gray levels (%u) to do computations", ng);
+
+    MALLOCARRAY(pxpy, ng+1);
+
+    if (!pxpy)
+        pm_error("Unable to allocate %u entries for the pxpy table",
+                 ng+1);
+
+    return pxpy;
+}
+
+
+
+static float *
+newPxpy(unsigned int const ng) {
+
+    float * pxpy;
+
+    if (ng > (UINT_MAX-1)/2 -1)
+        pm_error("Too many gray levels (%u) to do computations", ng);
+
+    MALLOCARRAY(pxpy, 2 * (ng+1) + 1);
+
+    if (!pxpy)
+        pm_error("Unable to allocate %u entries for the pxpy table",
+                 2* (ng+1) + 1);
+
+    return pxpy;
+}
+
+
 
 static float
 f6_savg (float **     const p,
@@ -565,12 +741,11 @@ f6_savg (float **     const p,
 /*----------------------------------------------------------------------------
    Sum Average
 -----------------------------------------------------------------------------*/
-    float pxpy[2 * (PGM_MAXMAXVAL+1) + 1];
+    float * const pxpy = newPxpy(ng);
+
     unsigned int i;
     float savg;
 
-    assert(2*ng < ARRAY_SIZE(pxpy));
-
     for (i = 0; i <= 2 * ng; ++i)
         pxpy[i] = 0.0;
 
@@ -582,6 +757,8 @@ f6_savg (float **     const p,
     for (i = 2, savg = 0.0; i <= 2 * ng; ++i)
         savg += i * pxpy[i];
 
+    free(pxpy);
+
     return savg;
 }
 
@@ -594,12 +771,11 @@ f7_svar (float **     const p,
 /*----------------------------------------------------------------------------
    Sum Variance
 -----------------------------------------------------------------------------*/
-    float pxpy[2 * (PGM_MAXMAXVAL+1) + 1];
+    float * const pxpy = newPxpy(ng);
+
     unsigned int i;
     float var;
 
-    assert(2*ng < ARRAY_SIZE(pxpy));
-
     for (i = 0; i <= 2 * ng; ++i)
         pxpy[i] = 0;
 
@@ -611,6 +787,8 @@ f7_svar (float **     const p,
     for (i = 2, var = 0.0; i <= 2 * ng; ++i)
         var += (i - s) * (i - s) * pxpy[i];
 
+    free(pxpy);
+
     return var;
 }
 
@@ -622,12 +800,11 @@ f8_sentropy (float **     const p,
 /*----------------------------------------------------------------------------
    Sum Entropy
 -----------------------------------------------------------------------------*/
-    float pxpy[2 * (PGM_MAXMAXVAL+1) + 1];
+    float * const pxpy = newPxpy(ng);
+
     unsigned int i;
     float sentropy;
 
-    assert(2*ng < ARRAY_SIZE(pxpy));
-
     for (i = 0; i <= 2 * ng; ++i)
         pxpy[i] = 0;
 
@@ -639,6 +816,8 @@ f8_sentropy (float **     const p,
     for (i = 2, sentropy = 0.0; i <= 2 * ng; ++i)
         sentropy -= pxpy[i] * log10(pxpy[i] + EPSILON);
 
+    free(pxpy);
+
     return sentropy;
 }
 
@@ -669,15 +848,14 @@ f10_dvar(float **     const p,
 /*----------------------------------------------------------------------------
    Difference Variance
 -----------------------------------------------------------------------------*/
-    double pxpy[PGM_MAXMAXVAL + 1];
+    double * const pxpy = newPxpy2(ng);
+
     unsigned int i;
     double sqrNg;  /* Square of 'ng' */
     double sum;
     double sumSqr;
     double var;
 
-    assert(ng <= ARRAY_SIZE(pxpy));
-
     for (i = 0; i < ng; ++i)
         pxpy[i] = 0;
 
@@ -694,6 +872,8 @@ f10_dvar(float **     const p,
     sqrNg = SQR(ng);
     var = (sqrNg * sumSqr - SQR(sum)) / SQR(sqrNg);
 
+    free(pxpy);
+
     return var;
 }
 
@@ -705,12 +885,11 @@ f11_dentropy (float **     const p,
 /*----------------------------------------------------------------------------
    Difference Entropy
 -----------------------------------------------------------------------------*/
-    float pxpy[2 * (PGM_MAXMAXVAL+1) + 1];
+    float * const pxpy = newPxpy(ng);
+
     unsigned int i;
     float sum;
 
-    assert(2*ng < ARRAY_SIZE(pxpy));
-
     for (i = 0; i <= 2 * ng; ++i)
         pxpy[i] = 0;
 
@@ -722,6 +901,8 @@ f11_dentropy (float **     const p,
     for (i = 0, sum = 0.0; i < ng; ++i)
         sum += pxpy[i] * log10(pxpy[i] + EPSILON);
 
+    free(pxpy);
+
     return -sum;
 }
 
@@ -867,8 +1048,6 @@ f14_maxcorr (float **     const p,
     reduction(q, ng);
     /* Finding eigenvalue for nonsymetric matrix using QR algorithm */
     hessenberg(q, ng, x, iy);
-    if (sortit)
-        simplesrt(ng, x);
 
     /* Return the sqrt of the second largest eigenvalue of q */
     for (i = 2, tmp = x[1]; i <= ng; ++i)
@@ -879,253 +1058,370 @@ f14_maxcorr (float **     const p,
 
 
 
+static void
+printAngularSecondMom(float **     const pmatrix0,
+                      float **     const pmatrix45,
+                      float **     const pmatrix90,
+                      float **     const pmatrix135,
+                      unsigned int const toneCt) {
+
+    float res[4];
+
+    res[0] = f1_a2m(pmatrix0,   toneCt);
+    res[1] = f1_a2m(pmatrix45,  toneCt);
+    res[2] = f1_a2m(pmatrix90,  toneCt);
+    res[3] = f1_a2m(pmatrix135, toneCt);
+
+    printResults("Angular Second Moment", res);
+}
+
+
+
+static void
+printContrast(float **     const pmatrix0,
+              float **     const pmatrix45,
+              float **     const pmatrix90,
+              float **     const pmatrix135,
+              unsigned int const toneCt) {
+
+    float res[4];
+
+    res[0] = f2_contrast(pmatrix0,   toneCt);
+    res[1] = f2_contrast(pmatrix45,  toneCt);
+    res[2] = f2_contrast(pmatrix90,  toneCt);
+    res[3] = f2_contrast(pmatrix135, toneCt);
+
+    printResults("Contrast", res);
+}
+
+
+
+static void
+printCorrelation(float **     const pmatrix0,
+                 float **     const pmatrix45,
+                 float **     const pmatrix90,
+                 float **     const pmatrix135,
+                 unsigned int const toneCt) {
+
+    float res[4];
+
+    res[0] = f3_corr(pmatrix0,   toneCt);
+    res[1] = f3_corr(pmatrix45,  toneCt);
+    res[2] = f3_corr(pmatrix90,  toneCt);
+    res[3] = f3_corr(pmatrix135, toneCt);
+
+    printResults("Correlation", res);
+}
+
+
+
+static void
+printVariance(float **     const pmatrix0,
+              float **     const pmatrix45,
+              float **     const pmatrix90,
+              float **     const pmatrix135,
+              unsigned int const toneCt) {
+
+    float res[4];
+
+    res[0] = f4_var(pmatrix0,   toneCt);
+    res[1] = f4_var(pmatrix45,  toneCt);
+    res[2] = f4_var(pmatrix90,  toneCt);
+    res[3] = f4_var(pmatrix135, toneCt);
+
+    printResults("Variance", res);
+}
+
+
+
+static void
+printInverseDiffMoment(float **     const pmatrix0,
+                       float **     const pmatrix45,
+                       float **     const pmatrix90,
+                       float **     const pmatrix135,
+                       unsigned int const toneCt) {
+
+    float res[4];
+
+    res[0] = f5_idm(pmatrix0,   toneCt);
+    res[1] = f5_idm(pmatrix45,  toneCt);
+    res[2] = f5_idm(pmatrix90,  toneCt);
+    res[3] = f5_idm(pmatrix135, toneCt);
+
+    printResults("Inverse Diff Moment", res);
+}
+
+
+
+static void
+printSumAverage(float **     const pmatrix0,
+                float **     const pmatrix45,
+                float **     const pmatrix90,
+                float **     const pmatrix135,
+                unsigned int const toneCt) {
+
+    float res[4];
+
+    res[0] = f6_savg(pmatrix0,  toneCt);
+    res[1] = f6_savg(pmatrix45,  toneCt);
+    res[2] = f6_savg(pmatrix90,  toneCt);
+    res[3] = f6_savg(pmatrix135, toneCt);
+
+    printResults("Sum Average", res);
+}
+
+
+
+static void
+printSumVariance(float **     const pmatrix0,
+                 float **     const pmatrix45,
+                 float **     const pmatrix90,
+                 float **     const pmatrix135,
+                 unsigned int const toneCt) {
+
+    float res[4];
+    float savg[4];
+
+    savg[0] = f6_savg(pmatrix0,   toneCt);
+    savg[1] = f6_savg(pmatrix45,  toneCt);
+    savg[2] = f6_savg(pmatrix90,  toneCt);
+    savg[3] = f6_savg(pmatrix135, toneCt);
+
+    res[0] = f7_svar(pmatrix0,   toneCt, savg[0]);
+    res[1] = f7_svar(pmatrix45,  toneCt, savg[1]);
+    res[2] = f7_svar(pmatrix90,  toneCt, savg[2]);
+    res[3] = f7_svar(pmatrix135, toneCt, savg[3]);
+
+    printResults("Sum Variance", res);
+}
+
+
+
+static void
+printSumVarianceEnt(float **     const pmatrix0,
+                    float **     const pmatrix45,
+                    float **     const pmatrix90,
+                    float **     const pmatrix135,
+                    unsigned int const toneCt) {
+
+    float res[4];
+
+    res[0] = f8_sentropy(pmatrix0,   toneCt);
+    res[1] = f8_sentropy(pmatrix45,  toneCt);
+    res[2] = f8_sentropy(pmatrix90,  toneCt);
+    res[3] = f8_sentropy(pmatrix135, toneCt);
+
+    printResults("Sum Entropy", res);
+}
+
+
+
+static void
+printEntropy(float **     const pmatrix0,
+             float **     const pmatrix45,
+             float **     const pmatrix90,
+             float **     const pmatrix135,
+             unsigned int const toneCt) {
+
+    float res[4];
+
+
+    res[0] = f9_entropy(pmatrix0,   toneCt);
+    res[1] = f9_entropy(pmatrix45,  toneCt);
+    res[2] = f9_entropy(pmatrix90,  toneCt);
+    res[3] = f9_entropy(pmatrix135, toneCt);
+
+    printResults("Entropy", res);
+}
+
+
+
+static void
+printDiffVariance(float **     const pmatrix0,
+                  float **     const pmatrix45,
+                  float **     const pmatrix90,
+                  float **     const pmatrix135,
+                  unsigned int const toneCt) {
+
+    float res[4];
+
+    res[0] = f10_dvar(pmatrix0,   toneCt);
+    res[1] = f10_dvar(pmatrix45,  toneCt);
+    res[2] = f10_dvar(pmatrix90,  toneCt);
+    res[3] = f10_dvar(pmatrix135, toneCt);
+
+    printResults("Difference Variance", res);
+}
+
+
+
+static void
+printDiffEntropy(float **     const pmatrix0,
+                 float **     const pmatrix45,
+                 float **     const pmatrix90,
+                 float **     const pmatrix135,
+                 unsigned int const toneCt) {
+
+    float res[4];
+
+    res[0] = f11_dentropy(pmatrix0,   toneCt);
+    res[1] = f11_dentropy(pmatrix45,  toneCt);
+    res[2] = f11_dentropy(pmatrix90,  toneCt);
+    res[3] = f11_dentropy(pmatrix135, toneCt);
+
+    printResults ("Difference Entropy", res);
+}
+
+
+
+static void
+printCorrelation1(float **     const pmatrix0,
+                  float **     const pmatrix45,
+                  float **     const pmatrix90,
+                  float **     const pmatrix135,
+                  unsigned int const toneCt) {
+
+    float res[4];
+
+    res[0] = f12_icorr(pmatrix0,   toneCt);
+    res[1] = f12_icorr(pmatrix45,  toneCt);
+    res[2] = f12_icorr(pmatrix90,  toneCt);
+    res[3] = f12_icorr(pmatrix135, toneCt);
+
+    printResults("Meas of Correlation-1", res);
+}
+
+
+
+static void
+printCorrelation2(float **     const pmatrix0,
+                  float **     const pmatrix45,
+                  float **     const pmatrix90,
+                  float **     const pmatrix135,
+                  unsigned int const toneCt) {
+
+    float res[4];
+
+    res[0] = f13_icorr(pmatrix0,   toneCt);
+    res[1] = f13_icorr(pmatrix45,  toneCt);
+    res[2] = f13_icorr(pmatrix90,  toneCt);
+    res[3] = f13_icorr(pmatrix135, toneCt);
+
+    printResults("Meas of Correlation2", res);
+}
+
+
+
+static void
+printCorrelationMax(float **     const pmatrix0,
+                    float **     const pmatrix45,
+                    float **     const pmatrix90,
+                    float **     const pmatrix135,
+                    unsigned int const toneCt) {
+
+    float res[4];
+
+    res[0] = f14_maxcorr(pmatrix0,   toneCt);
+    res[1] = f14_maxcorr(pmatrix45,  toneCt);
+    res[2] = f14_maxcorr(pmatrix90,  toneCt);
+    res[3] = f14_maxcorr(pmatrix135, toneCt);
+
+    printResults("Max Correlation Coeff", res);
+}
+
+
+
 int
 main (int argc, const char ** argv) {
 
+    struct CmdlineInfo cmdline;
     FILE * ifP;
     gray ** grays;
-    unsigned int tone[PGM_MAXMAXVAL+1];
-    unsigned int r0, r45, r90;
-    unsigned int d;
-    unsigned int x, y;
+    unsigned int * tone;  /* malloced array */
+    unsigned int toneCt;
     unsigned int row;
     int rows, cols;
-    int argn;
     unsigned int itone;
-    unsigned int toneCt;
-    float ** p_matrix0, ** p_matrix45, ** p_matrix90, ** p_matrix135;
-    float a2m[4], contrast[4], corr[4], var[4], idm[4], savg[4];
-    float sentropy[4], svar[4], entropy[4], dvar[4], dentropy[4];
-    float icorr[4], maxcorr[4];
+    float ** pmatrix0, ** pmatrix45, ** pmatrix90, ** pmatrix135;
     gray maxval;
     unsigned int i;
-    const char * const usage = "[-d <d>] [pgmfile]";
 
     pm_proginit(&argc, argv);
 
-    argn = 1;
-
-    /* Check for flags. */
-    if ( argn < argc && argv[argn][0] == '-' )
-    {
-        if ( argv[argn][1] == 'd' )
-        {
-            ++argn;
-            if ( argn == argc || sscanf( argv[argn], "%u", &d ) != 1 )
-                pm_usage( usage );
-        }
-        else
-            pm_usage( usage );
-        ++argn;
-    }
-
-    if ( argn < argc )
-    {
-        ifP = pm_openr( argv[argn] );
-        ++argn;
-    }
-    else
-        ifP = stdin;
-
-    if ( argn != argc )
-        pm_usage( usage );
+    parseCommandLine(argc, argv, &cmdline);
 
-    d = 1;
+    ifP = pm_openr(cmdline.inputFileName);
 
     grays = pgm_readpgm(ifP, &cols, &rows, &maxval);
-    pm_close (ifP);
+
+    MALLOCARRAY(tone, maxval+1);
 
     /* Determine the number of different gray scales (not maxval) */
-    for (i = 0; i <= PGM_MAXMAXVAL; ++i)
+    for (i = 0; i <= maxval; ++i)
         tone[i] = -1;
     for (row = 0; row < rows; ++row) {
         unsigned int col;
         for (col = 0; col < cols; ++col)
             tone[grays[row][col]] = grays[row][col];
     }
-    for (i = 0, toneCt = 0; i <= PGM_MAXMAXVAL; ++i) {
+    for (i = 0, toneCt = 0; i <= maxval; ++i) {
         if (tone[i] != -1)
             ++toneCt;
     }
     pm_message("(Image has %u gray levels.)", toneCt);
 
     /* Collapse array, taking out all zero values */
-    for (row = 0, itone = 0; row <= PGM_MAXMAXVAL; ++row)
+    for (row = 0, itone = 0; row <= maxval; ++row)
         if (tone[row] != -1)
             tone[itone++] = tone[row];
     /* Now array contains only the gray levels present (in ascending order) */
 
-    /* Allocate memory for gray-tone spatial dependence matrix */
-    p_matrix0   = matrix (0, toneCt, 0, toneCt);
-    p_matrix45  = matrix (0, toneCt, 0, toneCt);
-    p_matrix90  = matrix (0, toneCt, 0, toneCt);
-    p_matrix135 = matrix (0, toneCt, 0, toneCt);
-
-    for (row = 0; row < toneCt; ++row) {
-        unsigned int col;
-        for (col = 0; col < toneCt; ++col) {
-            p_matrix0 [row][col] = p_matrix45 [row][col] = 0;
-            p_matrix90[row][col] = p_matrix135[row][col] = 0;
-        }
-    }
-    if (d > cols)
+    if (cmdline.d > cols)
         pm_error("Image is narrower (%u columns) "
-                 "than specified distance (%u)", cols, d);
-
-    /* Find gray-tone spatial dependence matrix */
-    pm_message("Computing spatial dependence matrix...");
-    for (row = 0; row < rows; ++row) {
-        unsigned int col;
-        for (col = 0; col < cols; ++col) {
-            unsigned int angle;
-            for (angle = 0, x = 0; angle <= 135; angle += 45) {
-                while (tone[x] != grays[row][col])
-                    ++x;
-                if (angle == 0 && col + d < cols) {
-                    y = 0;
-                    while (tone[y] != grays[row][col + d])
-                        ++y;
-                    ++p_matrix0[x][y];
-                    ++p_matrix0[y][x];
-                }
-                if (angle == 90 && row + d < rows) {
-                    y = 0;
-                    while (tone[y] != grays[row + d][col])
-                        ++y;
-                    ++p_matrix90[x][y];
-                    ++p_matrix90[y][x];
-                }
-                if (angle == 45 && row + d < rows && col >= d) {
-                    y = 0;
-                    while (tone[y] != grays[row + d][col - d])
-                        ++y;
-                    ++p_matrix45[x][y];
-                    ++p_matrix45[y][x];
-                }
-                if (angle == 135 && row + d < rows && col + d < cols) {
-                    y = 0;
-                    while (tone[y] != grays[row + d][col + d])
-                        ++y;
-                    ++p_matrix135[x][y];
-                    ++p_matrix135[y][x];
-                }
-            }
-        }
-    }
-    /* Gray-tone spatial dependence matrices are complete */
+                 "than specified distance (%u)", cols, cmdline.d);
 
-    /* Find normalizing constants */
-    r0  = 2 * rows * (cols - d);
-    r45 = 2 * (rows - d) * (cols - d);
-    r90 = 2 * (rows - d) * cols;
-
-    /* Normalize gray-tone spatial dependence matrix */
-    for (itone = 0; itone < toneCt; ++itone) {
-        unsigned int jtone;
-        for (jtone = 0; jtone < toneCt; ++jtone) {
-            p_matrix0[itone][jtone]   /= r0;
-            p_matrix45[itone][jtone]  /= r45;
-            p_matrix90[itone][jtone]  /= r90;
-            p_matrix135[itone][jtone] /= r45;
-        }
-    }
-    pm_message(" ...done.");
+    makeGrayToneSpatialDependenceMatrix(
+        grays, rows, cols, cmdline.d, tone, toneCt,
+        &pmatrix0, &pmatrix45, &pmatrix90, &pmatrix135);
 
     pm_message("Computing textural features ...");
 
     fprintf(stdout, "\n");
-    fprintf(stdout,
-            "%s         0         45         90        135        Avg\n",
-            BL);
-
-    a2m[0] = f1_a2m(p_matrix0,   toneCt);
-    a2m[1] = f1_a2m(p_matrix45,  toneCt);
-    a2m[2] = f1_a2m(p_matrix90,  toneCt);
-    a2m[3] = f1_a2m(p_matrix135, toneCt);
-    results(F1, a2m);
-
-    contrast[0] = f2_contrast(p_matrix0,   toneCt);
-    contrast[1] = f2_contrast(p_matrix45,  toneCt);
-    contrast[2] = f2_contrast(p_matrix90,  toneCt);
-    contrast[3] = f2_contrast(p_matrix135, toneCt);
-    results(F2, contrast);
-
-
-    corr[0] = f3_corr(p_matrix0,   toneCt);
-    corr[1] = f3_corr(p_matrix45,  toneCt);
-    corr[2] = f3_corr(p_matrix90,  toneCt);
-    corr[3] = f3_corr(p_matrix135, toneCt);
-    results(F3, corr);
-
-    var[0] = f4_var(p_matrix0,   toneCt);
-    var[1] = f4_var(p_matrix45,  toneCt);
-    var[2] = f4_var(p_matrix90,  toneCt);
-    var[3] = f4_var(p_matrix135, toneCt);
-    results(F4, var);
-
-
-    idm[0] = f5_idm(p_matrix0,   toneCt);
-    idm[1] = f5_idm(p_matrix45,  toneCt);
-    idm[2] = f5_idm(p_matrix90,  toneCt);
-    idm[3] = f5_idm(p_matrix135, toneCt);
-    results(F5, idm);
-
-    savg[0] = f6_savg(p_matrix0,  toneCt);
-    savg[1] = f6_savg(p_matrix45,  toneCt);
-    savg[2] = f6_savg(p_matrix90,  toneCt);
-    savg[3] = f6_savg(p_matrix135, toneCt);
-    results(F6, savg);
-
-    svar[0] = f7_svar(p_matrix0,   toneCt, savg[0]);
-    svar[1] = f7_svar(p_matrix45,  toneCt, savg[1]);
-    svar[2] = f7_svar(p_matrix90,  toneCt, savg[2]);
-    svar[3] = f7_svar(p_matrix135, toneCt, savg[3]);
-    results(F7, svar);
-
-    sentropy[0] = f8_sentropy(p_matrix0,   toneCt);
-    sentropy[1] = f8_sentropy(p_matrix45,  toneCt);
-    sentropy[2] = f8_sentropy(p_matrix90,  toneCt);
-    sentropy[3] = f8_sentropy(p_matrix135, toneCt);
-    results(F8, sentropy);
-
-    entropy[0] = f9_entropy(p_matrix0,   toneCt);
-    entropy[1] = f9_entropy(p_matrix45,  toneCt);
-    entropy[2] = f9_entropy(p_matrix90,  toneCt);
-    entropy[3] = f9_entropy(p_matrix135, toneCt);
-    results(F9, entropy);
-
-    dvar[0] = f10_dvar(p_matrix0,   toneCt);
-    dvar[1] = f10_dvar(p_matrix45,  toneCt);
-    dvar[2] = f10_dvar(p_matrix90,  toneCt);
-    dvar[3] = f10_dvar(p_matrix135, toneCt);
-    results(F10, dvar);
-
-    dentropy[0] = f11_dentropy(p_matrix0,   toneCt);
-    dentropy[1] = f11_dentropy(p_matrix45,  toneCt);
-    dentropy[2] = f11_dentropy(p_matrix90,  toneCt);
-    dentropy[3] = f11_dentropy(p_matrix135, toneCt);
-    results (F11, dentropy);
-
-    icorr[0] = f12_icorr(p_matrix0,   toneCt);
-    icorr[1] = f12_icorr(p_matrix45,  toneCt);
-    icorr[2] = f12_icorr(p_matrix90,  toneCt);
-    icorr[3] = f12_icorr(p_matrix135, toneCt);
-    results(F12, icorr);
-
-    icorr[0] = f13_icorr(p_matrix0,   toneCt);
-    icorr[1] = f13_icorr(p_matrix45,  toneCt);
-    icorr[2] = f13_icorr(p_matrix90,  toneCt);
-    icorr[3] = f13_icorr(p_matrix135, toneCt);
-    results(F13, icorr);
-
-    maxcorr[0] = f14_maxcorr(p_matrix0,   toneCt);
-    maxcorr[1] = f14_maxcorr(p_matrix45,  toneCt);
-    maxcorr[2] = f14_maxcorr(p_matrix90,  toneCt);
-    maxcorr[3] = f14_maxcorr(p_matrix135, toneCt);
-    results(F14, maxcorr);
+
+    printHeader();
+
+    printAngularSecondMom (pmatrix0, pmatrix45, pmatrix90, pmatrix135, toneCt);
+
+    printContrast         (pmatrix0, pmatrix45, pmatrix90, pmatrix135, toneCt);
+
+    printCorrelation      (pmatrix0, pmatrix45, pmatrix90, pmatrix135, toneCt);
+
+    printVariance         (pmatrix0, pmatrix45, pmatrix90, pmatrix135, toneCt);
+
+    printInverseDiffMoment(pmatrix0, pmatrix45, pmatrix90, pmatrix135, toneCt);
+
+    printSumAverage       (pmatrix0, pmatrix45, pmatrix90, pmatrix135, toneCt);
+
+    printSumVariance      (pmatrix0, pmatrix45, pmatrix90, pmatrix135, toneCt);
+
+    printSumVarianceEnt   (pmatrix0, pmatrix45, pmatrix90, pmatrix135, toneCt);
+
+    printEntropy          (pmatrix0, pmatrix45, pmatrix90, pmatrix135, toneCt);
+
+    printDiffVariance     (pmatrix0, pmatrix45, pmatrix90, pmatrix135, toneCt);
+
+    printDiffEntropy      (pmatrix0, pmatrix45, pmatrix90, pmatrix135, toneCt);
+
+    printCorrelation1     (pmatrix0, pmatrix45, pmatrix90, pmatrix135, toneCt);
+
+    printCorrelation2     (pmatrix0, pmatrix45, pmatrix90, pmatrix135, toneCt);
+
+    printCorrelationMax   (pmatrix0, pmatrix45, pmatrix90, pmatrix135, toneCt);
 
     pm_message(" ...done.");
 
+    pm_close (ifP);
+
     return 0;
 }
 
diff --git a/analyzer/pnmhistmap.c b/analyzer/pnmhistmap.c
index fc1bbbde..3c943db9 100644
--- a/analyzer/pnmhistmap.c
+++ b/analyzer/pnmhistmap.c
@@ -59,7 +59,7 @@ parseCommandLine(int argc, const char ** argv,
    was passed to us as the argv array.
 -----------------------------------------------------------------------------*/
     optEntry *option_def;
-        /* Instructions to pm_optParseOptions3 on how to parse our options.
+        /* Instructions to pm_optParseOptions4 on how to parse our options.
          */
     optStruct3 opt;
 
@@ -92,7 +92,7 @@ parseCommandLine(int argc, const char ** argv,
     opt.short_allowed = FALSE;  /* We have no short (old-fashioned) options */
     opt.allowNegNum = FALSE;  /* We may have parms that are negative numbers */
 
-    pm_optParseOptions3(&argc, (char **)argv, opt, sizeof(opt), 0);
+    pm_optParseOptions4(&argc, argv, opt, sizeof(opt), 0);
         /* Uses and sets argc, argv, and some of *cmdlineP and others. */
 
     if (!lvalSpec)
@@ -113,7 +113,7 @@ parseCommandLine(int argc, const char ** argv,
     if (!heightSpec)
         cmdlineP->height = 200;
 
-    if (argc-1 == 0) 
+    if (argc-1 == 0)
         cmdlineP->inputFilespec = "-";
     else if (argc-1 != 1)
         pm_error("Program takes zero or one argument (filename).  You "
@@ -202,7 +202,7 @@ pgmHist(FILE *       const ifP,
     unsigned int * ghist;
     double vscale;
     unsigned int hmax;
-    
+
     MALLOCARRAY(ghist, histWidth);
     if (ghist == NULL)
         pm_error("Not enough memory for histogram array (%u bytes)",
@@ -231,7 +231,7 @@ pgmHist(FILE *       const ifP,
         pm_message("finding max. slot height...");
     if (clipSpec)
         hmax = clipCount;
-    else 
+    else
         hmax = maxSlotCount(ghist, histWidth, no_white, no_black);
 
     assert(hmax > 0);
@@ -275,10 +275,10 @@ maxSlotCountAll(unsigned int *       const hist[3],
 
     for (color = 0; color < 3; ++color)
         if (hist[color])
-            hmax = MAX(hmax, 
-                       maxSlotCount(hist[color], 
+            hmax = MAX(hmax,
+                       maxSlotCount(hist[color],
                                     histWidth, no_white, no_black));
-    
+
     return hmax;
 }
 
@@ -418,7 +418,7 @@ ppmHist(FILE *       const ifP,
         pm_message("finding max. slot height...");
     if (clipSpec)
         hmax = clipCount;
-    else 
+    else
         hmax = maxSlotCountAll(hist, histWidth, no_white, no_black);
 
     assert(hmax > 0);
@@ -427,7 +427,7 @@ ppmHist(FILE *       const ifP,
 
     vscale = (double) histHeight / hmax;
     if (verbose && pm_have_float_format())
-        pm_message("Done: height = %u, vertical scale factor = %g", 
+        pm_message("Done: height = %u, vertical scale factor = %g",
                    hmax, vscale);
 
     for (i = 0; i < histWidth; ++i) {
@@ -435,8 +435,8 @@ ppmHist(FILE *       const ifP,
             unsigned int j;
             bool plotted;
             plotted = FALSE;
-            for (j = histHeight - (int)(vscale * hist[WANT_RED][i]); 
-                 j < histHeight && !plotted; 
+            for (j = histHeight - (int)(vscale * hist[WANT_RED][i]);
+                 j < histHeight && !plotted;
                  ++j) {
                 PPM_PUTR(pixels[j][i], maxval);
                 plotted = dots;
@@ -446,8 +446,8 @@ ppmHist(FILE *       const ifP,
             unsigned int j;
             bool plotted;
             plotted = FALSE;
-            for (j = histHeight - (int)(vscale * hist[WANT_GRN][i]); 
-                 j < histHeight && !plotted; 
+            for (j = histHeight - (int)(vscale * hist[WANT_GRN][i]);
+                 j < histHeight && !plotted;
                  ++j) {
                 PPM_PUTG(pixels[j][i], maxval);
                 plotted = dots;
@@ -457,8 +457,8 @@ ppmHist(FILE *       const ifP,
             unsigned int j;
             bool plotted;
             plotted = FALSE;
-            for (j = histHeight - (int)(vscale * hist[WANT_BLU][i]); 
-                 j < histHeight && !plotted; 
+            for (j = histHeight - (int)(vscale * hist[WANT_BLU][i]);
+                 j < histHeight && !plotted;
                  ++j) {
                 PPM_PUTB(pixels[j][i], maxval);
                 plotted = dots;
diff --git a/analyzer/pnmpsnr.c b/analyzer/pnmpsnr.c
index 2363e8c3..031b714e 100644
--- a/analyzer/pnmpsnr.c
+++ b/analyzer/pnmpsnr.c
@@ -95,7 +95,7 @@ parseCommandLine(int argc, const char ** argv,
    was passed to as as the argv array.
 -----------------------------------------------------------------------------*/
     optEntry * option_def;
-        /* Instructions to pm_optParseOptions3 on how to parse our options.
+        /* Instructions to pm_optParseOptions4 on how to parse our options.
          */
     optStruct3 opt;
 
@@ -123,7 +123,7 @@ parseCommandLine(int argc, const char ** argv,
     opt.short_allowed = FALSE; /* We have no short (old-fashioned) options */
     opt.allowNegNum   = FALSE; /* We have no parms that are negative numbers */
 
-    pm_optParseOptions3(&argc, (char **)argv, opt, sizeof(opt), 0);
+    pm_optParseOptions4(&argc, argv, opt, sizeof(opt), 0);
         /* Uses and sets argc, argv, and some of *cmdlineP and others */
 
     if (argc-1 < 2)
@@ -179,7 +179,7 @@ validateInput(struct pam const pam1,
                  pam1.height, pam2.height);
 
     if (pam1.maxval != pam2.maxval)
-        pm_error("images do not have the same maxval.  This programs works "
+        pm_error("images do not have the same maxval.  This program works "
                  "only on like maxvals.  "
                  "The first image has maxval %u, "
                  "while the second has %u.  Use Pamdepth to change the "
diff --git a/analyzer/ppmhist.c b/analyzer/ppmhist.c
index 62345fa1..c2024018 100644
--- a/analyzer/ppmhist.c
+++ b/analyzer/ppmhist.c
@@ -69,7 +69,7 @@ parseCommandLine(int argc, const char ** argv,
     /* Set defaults */
     sort_type = "frequency";
 
-    pm_optParseOptions3(&argc, (char **)argv, opt, sizeof(opt), 0);
+    pm_optParseOptions4(&argc, argv, opt, sizeof(opt), 0);
         /* Uses and sets argc, argv, and some of *cmdlineP and others. */
     free(option_def);
 
@@ -374,31 +374,16 @@ printColorSummary(ColorSummary const colorSummary,
 
 
 
-typedef struct {
-/*----------------------------------------------------------------------------
-   A map of color name to color.
-
-   The actual information is outside of this structure; we just point to it.
------------------------------------------------------------------------------*/
-    unsigned int  n;
-
-    pixel *       color;
-
-    const char ** name;
-} ColorDict;
-
-
-
 static const char *
-colornameLabel(pixel     const color,
-               pixval    const maxval,
-               ColorDict const colorDict) {
+colornameLabel(pixel                 const color,
+               pixval                const maxval,
+               const ppm_ColorDict * const colorDictP) {
 /*----------------------------------------------------------------------------
    Return the name of the color 'color' or the closest color in the
    dictionary to it.  If the name returned is not the exact color,
    prefix it with "*".  Otherwise, prefix it with " ".
 
-   'colorDict' is the color dictionary.
+   *colorDictP is the color dictionary.
 
    Return the name in static storage within this subroutine.
 -----------------------------------------------------------------------------*/
@@ -412,16 +397,17 @@ colornameLabel(pixel     const color,
 
     PPM_DEPTH(color255, color, maxval, 255);
 
-    colorIndex = ppm_findclosestcolor(colorDict.color, colorDict.n, &color255);
+    colorIndex = ppm_findclosestcolor(colorDictP->color, colorDictP->count,
+                                      &color255);
 
-    assert(colorIndex >= 0 && colorIndex < colorDict.n);
+    assert(colorIndex >= 0 && colorIndex < colorDictP->count);
 
-    if (PPM_EQUAL(colorDict.color[colorIndex], color))
+    if (PPM_EQUAL(colorDictP->color[colorIndex], color))
         STRSCPY(retval, " ");
     else
         STRSCPY(retval, "*");
 
-    STRSCAT(retval, colorDict.name[colorIndex]);
+    STRSCAT(retval, colorDictP->name[colorIndex]);
 
     return retval;
 }
@@ -429,12 +415,12 @@ colornameLabel(pixel     const color,
 
 
 static void
-printColors(colorhist_vector const chv,
-            int              const colorCt,
-            pixval           const maxval,
-            enum ColorFmt    const colorFmt,
-            bool             const withColorName,
-            ColorDict        const colorDict) {
+printColors(colorhist_vector      const chv,
+            int                   const colorCt,
+            pixval                const maxval,
+            enum ColorFmt         const colorFmt,
+            bool                  const withColorName,
+            const ppm_ColorDict * const colorDictP) {
 /*----------------------------------------------------------------------------
    Print to Standard Output the list of colors, one per line in 'chv',
    of which there are 'colorCt'.
@@ -460,7 +446,7 @@ printColors(colorhist_vector const chv,
         const char * colornameValue;
 
         if (withColorName)
-            colornameValue = colornameLabel(chv[i].color, maxval, colorDict);
+            colornameValue = colornameLabel(chv[i].color, maxval, colorDictP);
         else
             colornameValue = "";
 
@@ -498,7 +484,7 @@ printHistogram(colorhist_vector const chv,
                bool             const wantHeader,
                bool             const wantColorName) {
 
-    ColorDict colorDict;
+    ppm_ColorDict * colorDictP;
 
     if (colorFmt == FMT_PPMPLAIN)
         printf("P3\n# color map\n%d 1\n%d\n", colorCt, maxval);
@@ -515,18 +501,16 @@ printHistogram(colorhist_vector const chv,
     }
     if (wantColorName) {
         bool const mustOpenTrue = TRUE;
-        ppm_readcolordict(NULL, mustOpenTrue,
-                          &colorDict.n, &colorDict.name, &colorDict.color,
-                          NULL);
-    }
+
+        colorDictP = ppm_colorDict_new(NULL, mustOpenTrue);
+    } else
+        colorDictP = NULL;
 
     printColors(chv, colorCt, maxval,
-                colorFmt, wantColorName, colorDict);
+                colorFmt, wantColorName, colorDictP);
 
-    if (wantColorName) {
-        free(colorDict.color);
-        free(colorDict.name);
-    }
+    if (colorDictP)
+        ppm_colorDict_destroy(colorDictP);
 }
 
 
diff --git a/buildtools/configure.pl b/buildtools/configure.pl
index 6a152a10..aa94a6bb 100755
--- a/buildtools/configure.pl
+++ b/buildtools/configure.pl
@@ -9,15 +9,15 @@ use Cwd 'abs_path';
 use Fcntl;
 use Config;
 #use File::Temp "tempfile";   Not available before Perl 5.6.1
-    
+
 
 my ($TRUE, $FALSE) = (1,0);
 
 # This program generates config.mk, which is included by all of the
-# Netpbm makefiles.  You run this program as the first step in building 
+# Netpbm makefiles.  You run this program as the first step in building
 # Netpbm.  (The second step is 'make').
 
-# This program is only a convenience.  It is supported to create 
+# This program is only a convenience.  It is supported to create
 # config.mk any way you want.  In fact, an easy way is to copy
 # config.mk.in and follow the instructions in the comments therein
 # to uncomment certain lines and make other changes.
@@ -28,7 +28,7 @@ my ($TRUE, $FALSE) = (1,0);
 # user, but it isn't the normal build process.
 
 # The argument to this program is the filepath of the config.mk.in
-# file.  If unspecified, the default is 'config.mk.in' in the 
+# file.  If unspecified, the default is 'config.mk.in' in the
 # Netpbm source directory.
 
 # For explanations of the stuff we put in the make files, see the comments
@@ -105,7 +105,7 @@ sub promptYesNo($) {
 
     while (!defined($retval)) {
         my $response = prompt("(y)es or (n)o", $default);
-        
+
         if (uc($response) =~ m{ ^ (Y|YES) $ }x)  {
             $retval = $TRUE;
         } elsif (uc($response) =~ m{ ^ (N|NO) $ }x)  {
@@ -131,11 +131,11 @@ sub flow($) {
     my $retval;
 
     my @words = split(m{\s+}, $unflowed);
-    
+
     my $currentLine;
-    
+
     $currentLine = "";
-    
+
     foreach my $word (@words) {
         my $mustSpill;
         if (length($currentLine) == 0) {
@@ -148,7 +148,7 @@ sub flow($) {
             } else {
                 $separator = " ";
             }
-                
+
             if (length($currentLine) + length($separator) + length($word)
                 <= 72) {
                 $currentLine .= $separator;
@@ -194,7 +194,7 @@ sub tmpdir() {
 # basic Perl some time after Perl 5.005_03.
 
     my $retval;
-    
+
     if ($ENV{'TMPDIR'}) {
         $retval = $ENV{'TMPDIR'};
     } elsif ($ENV{'TEMP'}) {
@@ -217,8 +217,8 @@ sub tempFile($) {
 
 # Here's what we'd do if we could expect Perl 5.6.1 or later, instead
 # of calling this subroutine:
-#    my ($cFile, $cFileName) = tempfile("netpbmXXXX", 
-#                                       SUFFIX=>".c", 
+#    my ($cFile, $cFileName) = tempfile("netpbmXXXX",
+#                                       SUFFIX=>".c",
 #                                       DIR=>File::Spec->tmpdir(),
 #                                       UNLINK=>0);
     my ($suffix) = @_;
@@ -275,7 +275,7 @@ sub commandExists($) {
 # from system() a lot different than if system() were to try to
 # execute the program directly.
 
-    return(system("$command 1</dev/null 1>/dev/null 2>/dev/null")/256 != 127); 
+    return(system("$command 1</dev/null 1>/dev/null 2>/dev/null")/256 != 127);
 }
 
 
@@ -304,20 +304,20 @@ sub testCflags() {
 
     my $cflags;
 
-    $cflags = "";  # initial value 
-    
+    $cflags = "";  # initial value
+
     if ($ENV{"CPPFLAGS"}) {
         $cflags = $ENV{"CPPFLAGS"};
     } else {
         $cflags = "";
     }
-    
+
     if ($ENV{"CFLAGS"}) {
         $cflags .= " " . $ENV{"CFLAGS"};
     }
-    
+
     return $cflags;
-}    
+}
 
 
 
@@ -325,21 +325,21 @@ sub testCompile($$$) {
     my ($cflags, $cSourceCodeR, $successR) = @_;
 #-----------------------------------------------------------------------------
 #  Do a test compile of the program in @{$cSourceCodeR}.
-#  
+#
 #  Return $$successR == $TRUE iff the compile succeeds (exit code 0).
 #-----------------------------------------------------------------------------
     my ($cFile, $cFileName) = tempFile(".c");
 
     print $cFile @{$cSourceCodeR};
-    
+
     my ($oFile, $oFileName) = tempFile(".o");
     # Note: we tried using /dev/null for the output file and got complaints
     # from the Sun compiler that it has the wrong suffix.  2002.08.09.
-    
+
     my $compileCommand = "$testCc -c -o $oFileName $cflags $cFileName";
     print ("Doing test compile: $compileCommand\n");
     my $rc = system($compileCommand);
-    
+
     unlink($oFileName);
     close($oFile);
     unlink($cFileName);
@@ -354,22 +354,22 @@ sub testCompileLink($$$) {
     my ($flags, $cSourceCodeR, $successR) = @_;
 #-----------------------------------------------------------------------------
 #  Do a test compile and link of the program in @{$cSourceCodeR}.
-#  
+#
 #  Return $$successR == $TRUE iff the compile succeeds (exit code 0).
 #-----------------------------------------------------------------------------
     my ($cFile, $cFileName) = tempFile('.c');
 
     print $cFile @{$cSourceCodeR};
-    
+
     my ($oFile, $oFileName) = tempFile('');
 
     # Note that $flags may contain -l options, which where static linking
     # is involved have to go _after_ the base object file ($oFileName).
-    
+
     my $compileCommand = "$testCc -o $oFileName $cFileName $flags";
     print ("Doing test compile/link: $compileCommand\n");
     my $rc = system($compileCommand);
-    
+
     unlink($oFileName);
     close($oFile);
     unlink($cFileName);
@@ -410,14 +410,14 @@ sub askAboutCygwin() {
 
     print("Are you building in/for the Cygwin environment?\n");
     print("\n");
-    
+
     my $default;
     if ($OSNAME eq "cygwin") {
         $default = "y";
     } else {
         $default = "n";
     }
-    
+
     my $retval = promptYesNo($default);
 
     return $retval;
@@ -429,14 +429,14 @@ sub askAboutDjgpp() {
 
     print("Are you building in/for the DJGPP environment?\n");
     print("\n");
-    
+
     my $default;
     if ($OSNAME eq "dos") {
         $default = "y";
     } else {
         $default = "n";
     }
-    
+
     my $retval = promptYesNo($default);
 }
 
@@ -446,7 +446,7 @@ sub askAboutMingw() {
 
     print("Are you building for the MinGW environment?\n");
     print("\n");
-    
+
     my $retval = promptYesNo("n");
 
     return $retval;
@@ -488,7 +488,7 @@ sub getPlatform() {
     computePlatformDefault(\$default);
 
     print("Which of the following best describes your platform?\n");
- 
+
     print("gnu      GNU/Linux\n");
     print("win      Windows/DOS (Cygwin, DJGPP, Mingw32)\n");
     print("sun      Solaris or SunOS\n");
@@ -658,7 +658,7 @@ sub getCompiler($$$) {
 #    make variable (e.g. make CC=gcc2).
 #
 #  - Configure needs to do test compiles.  The test is best if it uses
-#    the same compiler that the build eventually will use, but it's 
+#    the same compiler that the build eventually will use, but it's
 #    useful even if not.
 #
 # The value this subroutine returns is NOT the command name to invoke the
@@ -714,11 +714,11 @@ sub gccLinker() {
     # First, we assume that the compiler calls 'collect2' as the linker
     # front end.  The specs file might specify some other program, but
     # it usually says 'collect2'.
-    
+
     my $retval;
 
     my $collect2 = qx{gcc --print-prog-name=collect2};
-    
+
     if (defined($collect2)) {
         chomp($collect2);
         my $linker = qx{$collect2 -v 2>&1};
@@ -749,14 +749,14 @@ sub getLinker($$$$) {
             print("\n");
 
             my $default;
-            
+
             if ($compiler eq "gcc") {
                 $default = gccLinker();
             } else {
                 $default = "sun";
             }
             my $response = prompt("sun or gnu", $default);
-            
+
             if ($response eq "gnu") {
                 $$baseLinkerR = "GNU";
             } elsif ($response eq "sun") {
@@ -811,11 +811,11 @@ sub getLibTypes($$$$$$$$) {
 
     my $default = ($default_target eq "merge") ? "static" : "shared";
 
-    my ($netpbmlibtype, $netpbmlibsuffix, $shlibprefixlist, 
+    my ($netpbmlibtype, $netpbmlibsuffix, $shlibprefixlist,
         $willBuildShared, $staticlib_too);
-    
+
     my $response = prompt("static or shared", $default);
-    
+
     if ($response eq "shared") {
         $willBuildShared = $TRUE;
         if ($platform eq "WINDOWS") {
@@ -823,7 +823,7 @@ sub getLibTypes($$$$$$$$) {
             $netpbmlibsuffix = "dll";
             if ($subplatform eq "cygwin") {
                 $shlibprefixlist = "cyg lib";
-            } 
+            }
         } elsif ($platform eq "DARWIN") {
             $netpbmlibtype = "dylib";
             $netpbmlibsuffix = "dylib";
@@ -846,7 +846,7 @@ sub getLibTypes($$$$$$$$) {
         $netpbmlibtype = "unixstatic";
         $netpbmlibsuffix = "a";
         # targets, but needed for building
-        # libopt 
+        # libopt
     } else {
         print("'$response' isn't one of the choices.  \n" .
               "You must choose 'static' or 'shared'.\n");
@@ -857,18 +857,18 @@ sub getLibTypes($$$$$$$$) {
 
     # Note that we can't do both a static and shared library for AIX, because
     # they both have the same name: libnetpbm.a.
-    
-    if (($netpbmlibtype eq "unixshared" or 
-         $netpbmlibtype eq "irixshared" or 
+
+    if (($netpbmlibtype eq "unixshared" or
+         $netpbmlibtype eq "irixshared" or
          $netpbmlibtype eq "dll") and $netpbmlibsuffix ne "a") {
         print("Do you want to build static libraries too (for linking to \n");
         print("programs not in the Netpbm package?\n");
         print("\n");
-        
+
         my $default = "y";
-        
+
         my $response = prompt("(y)es or (n)o", $default);
-        
+
         if (uc($response) =~ /^(Y|YES)$/)  {
             $staticlib_too = "Y";
         } elsif (uc($response) =~ /^(N|NO)$/)  {
@@ -919,16 +919,16 @@ sub inttypesDefault() {
 
         my @candidateList = ("<inttypes.h>", "<sys/inttypes.h>",
                              "<types.h>", "<sys/types.h>");
-        
+
         for (my $i = 0; $i < @candidateList && !$works; ++$i) {
             my $candidate = $candidateList[$i];
             my @cSourceCode = (
                                "#include $candidate\n",
                                "int_fast32_t testvar;\n"
                                );
-            
+
             testCompile($cflags, \@cSourceCode, \my $success);
-            
+
             if ($success) {
                 $works = $candidate;
             }
@@ -961,7 +961,7 @@ sub getInttypes($) {
     print("\n");
 
     my $default = inttypesDefault();
-    
+
     while (!$gotit) {
         my $response = prompt("'#include' argument or NONE", $default);
 
@@ -1000,9 +1000,9 @@ sub getInt64($$) {
                            "#include $inttypes_h\n",
                            "int64_t testvar;\n"
                            );
-            
+
         testCompile($cflags, \@cSourceCode, \my $success);
-            
+
         if ($success) {
             print("You do.\n");
             $$haveInt64R = 'Y';
@@ -1034,9 +1034,9 @@ sub determineSseCapability($) {
         my @cSourceCode = (
                            "#include <emmintrin.h>\n",
                            );
-            
+
         testCompile($cflags, \@cSourceCode, \my $success);
-            
+
         if ($success) {
             print("It does.\n");
             $$haveEmmintrinR = $TRUE;
@@ -1115,9 +1115,9 @@ sub getTiffLibrary($@) {
         my $default = "libtiff" . libSuffix($platform);
 
         print("What is your TIFF (graphics format) library?\n");
-        
+
         my $response = prompt("library filename or 'none'", $default);
-        
+
         if ($response ne "none") {
             $tifflib = $response;
         }
@@ -1137,9 +1137,9 @@ sub getTiffLibrary($@) {
             $default = "default";
         }
         print("Where are the interface headers for it?\n");
-        
+
         my $response = prompt("TIFF header directory", $default);
-        
+
         if ($response ne "default") {
             $tiffhdr_dir = $response;
         }
@@ -1161,9 +1161,9 @@ sub getJpegLibrary($@) {
         my $default = "libjpeg" . libSuffix($platform);
 
         print("What is your JPEG (graphics format) library?\n");
-        
+
         my $response = prompt("library filename or 'none'", $default);
-        
+
         if ($response ne "none") {
             $jpeglib = $response;
         }
@@ -1178,9 +1178,9 @@ sub getJpegLibrary($@) {
             $default = "default";
         }
         print("Where are the interface headers for it?\n");
-        
+
         my $response = prompt("JPEG header directory", $default);
-        
+
         if ($response ne "default") {
             $jpeghdr_dir = $response;
         }
@@ -1218,9 +1218,9 @@ sub getPngLibrary($@) {
             my $default = "libpng" . libSuffix($platform);
 
             print("What is your PNG (graphics format) library?\n");
-            
+
             my $response = prompt("library filename or 'none'", $default);
-            
+
             if ($response ne "none") {
                 $pnglib = $response;
             }
@@ -1233,9 +1233,9 @@ sub getPngLibrary($@) {
             } else {
                 $default = "default";
             }
-            
+
             print("Where are the interface headers for it?\n");
-            
+
             my $response = prompt("PNG header directory", $default);
 
             if ($response ne "default") {
@@ -1258,9 +1258,9 @@ sub getZLibrary($@) {
         my $default = "libz" . libSuffix($platform);
 
         print("What is your Z (compression) library?\n");
-        
+
         my $response = prompt("library filename or 'none'", $default);
-        
+
         if ($response ne "none") {
             $zlib = $response;
         }
@@ -1273,11 +1273,11 @@ sub getZLibrary($@) {
         } else {
             $default = "default";
         }
-        
+
         print("Where are the interface headers for it?\n");
-        
+
         my $response = prompt("Z header directory", $default);
-        
+
         if ($response ne "default") {
             $zhdr_dir = $response;
         }
@@ -1315,9 +1315,9 @@ sub getX11Library($@) {
                 $default = "libX11" . libSuffix($platform);
             }
             print("What is your X11 (X client) library?\n");
-            
+
             my $response = prompt("library filename or 'none'", $default);
-            
+
             if ($response ne "none") {
                 $x11lib = $response;
             }
@@ -1328,9 +1328,9 @@ sub getX11Library($@) {
             $default = "default";
 
             print("Where are the interface headers for it?\n");
-            
+
             my $response = prompt("X11 header directory", $default);
-            
+
             if ($response ne "default") {
                 $x11hdr_dir = $response;
             }
@@ -1371,27 +1371,27 @@ sub getLinuxsvgaLibrary($@) {
         } else {
             $default = 'none';
         }
-            
+
         print("What is your Svgalib library?\n");
-        
+
         my $response = prompt("library filename or 'none'", $default);
-            
+
         if ($response ne 'none') {
             $svgalib = $response;
         }
     }
     if (defined($svgalib) && $svgalib ne 'none') {
         my $default;
-        
+
         if (-d('/usr/include/svgalib')) {
             $default = '/usr/include/svgalib';
         } else {
             $default = "default";
         }
         print("Where are the interface headers for it?\n");
-        
+
         my $response = prompt("Svgalib header directory", $default);
-        
+
         if ($response ne "default") {
             $svgalibhdr_dir = $response;
         }
@@ -1414,13 +1414,13 @@ sub symlink_command() {
     # simulation via a "ln" command, but have a "cp" command which works
     # in a pinch.  Some Windows environments have "ln", but it won't do
     # symbolic links.
-    
+
     if (commandExists("ln")) {
         # We assume if Perl can do symbolic links, so can Ln, and vice
         # versa.
 
         my $symlink_exists = eval { symlink("",""); 1 };
-        
+
         if ($symlink_exists) {
             $retval = "ln -s";
         } else {
@@ -1459,7 +1459,7 @@ sub gnuOptimizeOpt($) {
 #  that causes -O3 to generate incorrect code (symptom: pnmtojpeg --quality=95
 #  generates a syntax error message from shhopt).
 #-----------------------------------------------------------------------------
-# I don't know what are exactly the cases that Gcc is broken.  I know 
+# I don't know what are exactly the cases that Gcc is broken.  I know
 # Red Hat 7.1 and 7.2 and Mandrake 8.2, running gcc 2.96.1, commonly have
 # the problem.  But it may be limited to a certain subrelease level or
 # CPU type or other environment.  People who have reported the problem have
@@ -1472,7 +1472,7 @@ sub gnuOptimizeOpt($) {
     my @gccVerboseResp = `$gccCommandName --verbose 2>&1`;
 
     my $brokenCompiler;
-    
+
     if (@gccVerboseResp ==2) {
         if ($gccVerboseResp[1] =~ m{gcc version 2.96}) {
             $brokenCompiler = $TRUE;
@@ -1513,13 +1513,13 @@ sub wnostrictoverflowWorks($) {
     my ($cFile, $cFileName) = tempFile(".c");
 
     print $cFile "int x;";
-    
+
     my $compileCommand =
         "$gccCommandName -c -o /dev/null -Wno-strict-overflow $cFileName";
     print("Doing test compile to see if -Wno-strict-overflow works: "
           . "$compileCommand\n");
     my $rc = system($compileCommand);
-    
+
     unlink($cFileName);
     close($cFile);
 
@@ -1534,7 +1534,7 @@ sub gnuCflags($) {
     my $flags;
 
     $flags = gnuOptimizeOpt($gccCommandName) . " -ffast-math " .
-        " -pedantic -fno-common " . 
+        " -pedantic -fno-common " .
         "-Wall -Wno-uninitialized -Wmissing-declarations -Wimplicit " .
         "-Wwrite-strings -Wmissing-prototypes -Wundef " .
         "-Wno-unknown-pragmas ";
@@ -1577,7 +1577,7 @@ sub findProcessManagement($) {
     my @cSourceCode = (
                        "#include <sys/wait.h>\n",
                        );
-    
+
     testCompile($cflags, \@cSourceCode, \my $success);
 
     if (!$success) {
@@ -1637,7 +1637,7 @@ sub testCompileJpeglibH($$) {
                        "#include <stdio.h>\n",
                        "#include <jpeglib.h>\n",
                        );
-    
+
     testCompile($cflags, \@cSourceCode, $successR);
 }
 
@@ -1646,7 +1646,7 @@ sub testCompileJpeglibH($$) {
 sub testCompileJpegMarkerStruct($$) {
     my ($cflags, $successR) = @_;
 #-----------------------------------------------------------------------------
-#  Do a test compile to see if struct jpeg_marker_struct is defined in 
+#  Do a test compile to see if struct jpeg_marker_struct is defined in
 #  jpeglib.h.  Assume it is already established that the compiler works
 #  and can find jpeglib.h.
 #-----------------------------------------------------------------------------
@@ -1668,7 +1668,7 @@ sub printMissingHdrWarning($$) {
 
     warnUser("You said the compile-time part of the $name library " .
              "(the header files) is in " .
-             
+
              (defined($hdr_dir) ?
               "directory '$hdr_dir', " :
               "the compiler's default search path, ") .
@@ -1719,7 +1719,7 @@ sub testJpegHdr($) {
         } else {
             # We can get to something named jpeglib.h, but maybe it's an old
             # version we can't use.  Check it out.
-            testCompileJpegMarkerStruct("$generalCflags $jpegIOpt", 
+            testCompileJpegMarkerStruct("$generalCflags $jpegIOpt",
                                         \my $success);
             if (!$success) {
                 print("\n");
@@ -1789,7 +1789,7 @@ sub testCompileZlibH($$) {
     my @cSourceCode = (
                        "#include <zlib.h>\n",
                        );
-    
+
     testCompile($cflags, \@cSourceCode, $successR);
 }
 
@@ -1804,7 +1804,7 @@ sub testCompilePngH($$) {
     my @cSourceCode = (
                        "#include <png.h>\n",
                        );
-    
+
     testCompile($cflags, \@cSourceCode, $successR);
 }
 
@@ -1829,7 +1829,7 @@ sub testPngHdr($$) {
         } else {
             my $pngIOpt = $pnghdr_dir ? "-I$pnghdr_dir" : "";
 
-            testCompilePngH("$generalCflags $zlibIOpt $pngIOpt", 
+            testCompilePngH("$generalCflags $zlibIOpt $pngIOpt",
                             \my $success);
 
             if (!$success) {
@@ -1903,10 +1903,10 @@ sub testLinkPnglib($$) {
     } else {
         my $pngLdflags = qx{libpng-config --ldflags};
         chomp($pngLdflags);
-        
+
         testCompileLink("$generalCflags $pngCflags $pngLdflags",
                         \@cSourceCode, \my $success);
-        
+
         if (!$success) {
             testCompileLink("$generalCflags $pngCflags $pngLdflags -lz -lm",
                         \@cSourceCode, \my $lzLmSuccess);
@@ -1947,7 +1947,7 @@ sub testCompileXmlreaderH($$) {
     my @cSourceCode = (
                        "#include <libxml/xmlreader.h>\n",
                        );
-    
+
     testCompile($cflags, \@cSourceCode, $successR);
 }
 
@@ -1979,7 +1979,7 @@ sub testCompileXmlReaderTypes($$) {
                        "#include <libxml/xmlreader.h>\n",
                        "xmlReaderTypes dummy;\n",
                        );
-    
+
     testCompile($cflags, \@cSourceCode, $successR);
 }
 
@@ -2083,7 +2083,7 @@ if (@ARGV > 0) {
         } else {
             die("Unrecognized option: $ARGV[0]");
         }
-    } 
+    }
     $configInPathArg = $ARGV[0];
 }
 
@@ -2161,7 +2161,7 @@ print("\n");
 {
     my $default = "regular";
     my $response = prompt("regular or merge", $default);
-    
+
     if ($response eq "regular") {
         $default_target = "nonmerge";
     } elsif ($response eq "merge") {
@@ -2220,18 +2220,18 @@ my ($jpeglib, $jpeghdr_dir) = getJpegLibrary($platform);
 print("\n");
 my ($tifflib, $tiffhdr_dir) = getTiffLibrary($platform, $jpeghdr_dir);
 print("\n");
-my ($pnglib, $pnghdr_dir)   = getPngLibrary($platform, 
+my ($pnglib, $pnghdr_dir)   = getPngLibrary($platform,
                                             $tiffhdr_dir, $jpeghdr_dir);
 print("\n");
-my ($zlib, $zhdr_dir)       = getZLibrary($platform, 
+my ($zlib, $zhdr_dir)       = getZLibrary($platform,
                                           $pnghdr_dir,
                                           $tiffhdr_dir,
                                           $jpeghdr_dir);
 print("\n");
-my ($x11lib, $x11hdr_dir) = getX11Library($platform); 
+my ($x11lib, $x11hdr_dir) = getX11Library($platform);
 
 print("\n");
-my ($linuxsvgalib, $linuxsvgahdr_dir) = getLinuxsvgaLibrary($platform); 
+my ($linuxsvgalib, $linuxsvgahdr_dir) = getLinuxsvgaLibrary($platform);
 
 print("\n");
 
@@ -2274,7 +2274,7 @@ if (-f("GNUmakefile")) {
     while (!$done) {
         print("Where is the Netpbm source code?\n");
 
-        $srcdir = prompt("Netpbm source directory", 
+        $srcdir = prompt("Netpbm source directory",
                          abs_path(dirname($0) . "/.."));
 
         if (-f("$srcdir/GNUmakefile")) {
@@ -2283,7 +2283,7 @@ if (-f("GNUmakefile")) {
             print("That doesn't appear to contain Netpbm source code.\n");
             print("There is no file named 'GNUmakefile' in it.\n");
             print("\n");
-        }    
+        }
     }
     unlink("GNUmakefile");
     symlink("$srcdir/GNUmakefile", "GNUmakefile");
@@ -2293,7 +2293,7 @@ if (-f("GNUmakefile")) {
     open(SRCDIR, ">srcdir.mk");
     print(SRCDIR "SRCDIR = $srcdir\n");
     close(SRCDIR);
-    
+
     $defaultConfigInPath = "$srcdir/config.mk.in";
 }
 
@@ -2320,7 +2320,7 @@ open (CONFIG_IN,"<$configInPath") or
 
 @config_mk = <CONFIG_IN>;
 
-unshift(@config_mk, 
+unshift(@config_mk,
         "####This file was automatically created by 'configure.'\n",
         "####Many variables are set twice -- a generic setting, then \n",
         "####a system-specific override at the bottom of the file.\n",
@@ -2360,7 +2360,7 @@ if ($platform eq "GNU") {
         push(@config_mk, gnuCflags('cc'));
     }
 # The merged programs have a main_XXX subroutine instead of main(),
-# which would cause a warning with -Wmissing-declarations or 
+# which would cause a warning with -Wmissing-declarations or
 # -Wmissing-prototypes.
     push(@config_mk, "CFLAGS_MERGE = " .
          "-Wno-missing-declarations -Wno-missing-prototypes\n");
@@ -2376,7 +2376,7 @@ if ($platform eq "GNU") {
     } else {
         makeCompilerGcc(\@config_mk);
     }
-    # Before Netpbm 10.20 (January 2004), we set this to -R for 
+    # Before Netpbm 10.20 (January 2004), we set this to -R for
     # $compiler == cc and -rpath otherwise.  But now we know that the GNU
     # compiler can also invoke a linker that needs -R, so we're more flexible.
     if ($baseLinker eq "GNU") {
@@ -2416,7 +2416,7 @@ if ($platform eq "GNU") {
              "-L/usr/local/lib\n");
         push(@config_mk, "LDSHLIB = -shared -expect_unresolved \"*\"\n");
     } else {
-        # We've never tested this.  This is just here to give a user a 
+        # We've never tested this.  This is just here to give a user a
         # headstart on submitting to us the necessary information.  2002.07.04.
         push(@config_mk, "CC = gcc\n");
         push(@config_mk, 'CFLAGS = -O3', "\n");
@@ -2452,7 +2452,7 @@ if ($platform eq "GNU") {
 #    }
     push(@config_mk, 'SYMLINK = ', symlink_command(), "\n");
     push(@config_mk, 'DLLVER=$(NETPBM_MAJOR_RELEASE)', "\n");
-    push(@config_mk, "LDSHLIB = " . 
+    push(@config_mk, "LDSHLIB = " .
          '-shared -Wl,--image-base=0x10000000 -Wl,--enable-auto-import', "\n");
     if ($subplatform ne "cygwin") {
         push(@config_mk, "MSVCRT = Y\n");
@@ -2463,7 +2463,7 @@ if ($platform eq "GNU") {
 } elsif ($platform eq "BEOS") {
     push(@config_mk, "LDSHLIB = -nostart\n");
 } elsif ($platform eq "OPENBSD") {
-    # vedge@vedge.com.ar says on 2001.04.29 that there are a ton of 
+    # vedge@vedge.com.ar says on 2001.04.29 that there are a ton of
     # undefined symbols in the Fiasco stuff on OpenBSD.  So we'll just
     # cut it out of the build until someone feels like fixing it.
     push(@config_mk, "BUILD_FIASCO = N\n");
@@ -2482,13 +2482,21 @@ if ($platform eq "GNU") {
         push(@config_mk, "SHLIB_CLIB =\n");
     } else {
         makeCompilerGcc(\@config_mk);
-        push(@config_mk, "LDSHLIB = -shared\n"); 
+        push(@config_mk, "LDSHLIB = -shared\n");
     }
     push(@config_mk, "NETWORKLD = -lsocket -lresolve\n");
 } elsif ($platform eq "DARWIN") {
     push(@config_mk, "CC = cc -no-cpp-precomp\n");
     push(@config_mk, gnuCflags('cc'));
     push(@config_mk, 'CFLAGS_SHLIB = -fno-common', "\n");
+    # -D_DARWIN_SOURCE is a hack.  We've seen build fail on MacOS because the
+    # C library erroneously neglects to include 'sprintf' and 'vasprintf' in
+    # <stdio.h> under the conditions under which Netpbm includes it.
+    # -D_DARWIN_SOURCE makes it include them.  *_SOURCE macros are supposed to
+    # be defined in the source code to which they apply, but since this is
+    # just a hack, we prefer to do it with a compiler option and leave the
+    # source code unsullied.
+    push(@config_mk, "CFLAGS += -D_DARWIN_SOURCE\n");
 
     my $installNameOpt;
     if ($netpbmlib_runtime_path eq '') {
@@ -2520,7 +2528,7 @@ if (!$flex_result) {
         print("You do not appear to have the 'flex' or 'lex' pattern \n");
         print("matcher generator on your system, so we will not build \n");
         print("programs that need it (Thinkjettopbm)\n");
-        
+
         print("\n");
         print("Press ENTER to continue.\n");
         my $key = <STDIN>;
@@ -2534,7 +2542,7 @@ if (!$flex_result) {
         print("find 'flex' on your system.\n");
         print("\n");
 
-        push(@config_mk, "LEX = lex\n"); 
+        push(@config_mk, "LEX = lex\n");
     }
 }
 
@@ -2628,4 +2636,4 @@ if ($warned) {
 print("\n");
 
 
-exit 0;          
+exit 0;
diff --git a/buildtools/debian/mkdeb b/buildtools/debian/mkdeb
index b152a78d..6c475530 100755
--- a/buildtools/debian/mkdeb
+++ b/buildtools/debian/mkdeb
@@ -89,13 +89,7 @@ sub netpbmVersion($) {
     } else {
         my $version = <VERSION>;
         chomp($version);
-
-        if ($version =~ m{^Netpbm (\S*)}) {
-            my ($versionNumber) = ($1);
-            $retval = $versionNumber;
-        } else {
-            die("Can't understand format of '$versionFileName': '$version'");
-        }
+        $retval = $version;
         close(VERSION);
     }
 
diff --git a/buildtools/endiangen.c b/buildtools/endiangen.c
index 6b88b896..c770747b 100644
--- a/buildtools/endiangen.c
+++ b/buildtools/endiangen.c
@@ -13,7 +13,7 @@
     #ifndef BIG_ENDIAN
     #define BIG_ENDIAN 4321
     #endif
-       
+
     #ifndef BYTE_ORDER
     #define BYTE_ORDER LITTLE_ENDIAN
     #endif
@@ -21,7 +21,7 @@
     #define BITS_PER_WORD 32
     #endif
 
-    
+
   Really good code usually is not sensitive to endianness.  But fast,
   not-so-good code often is.  The best way for code to determine
   endianness is for it to do a runtime cast of an integer to an array
@@ -38,7 +38,7 @@ enum endianness {ENDIAN_LITTLE, ENDIAN_BIG};
 
 static enum endianness
 byteOrder(void) {
-    
+
     enum endianness retval;
 
     union {
@@ -83,7 +83,7 @@ main(int argc, char **argv) {
     printf("#endif\n");
     printf("\n");
     printf("#ifndef BYTE_ORDER\n");
-    printf("#define BYTE_ORDER %s\n", 
+    printf("#define BYTE_ORDER %s\n",
            byteOrder() == ENDIAN_LITTLE ? "LITTLE_ENDIAN" : "BIG_ENDIAN");
     printf("#endif\n");
     printf("\n");
@@ -94,4 +94,3 @@ main(int argc, char **argv) {
 
 
 
-
diff --git a/buildtools/genfontc.c b/buildtools/genfontc.c
index ce6b8c9c..b087026d 100644
--- a/buildtools/genfontc.c
+++ b/buildtools/genfontc.c
@@ -10,10 +10,10 @@ struct CmdlineInfo {
     /* All the information the user supplied in the command line,
        in a form easy for the program to use.
     */
-    const char * font;    
-    const char * builtin; 
-    const char * header; 
-    const char * varname; 
+    const char * font;
+    const char * builtin;
+    const char * header;
+    const char * varname;
     unsigned int verbose;
 };
 
@@ -108,7 +108,6 @@ computeFont(const char *   const fontName,
 
 
 
-
 static void
 dumpfont(struct font * const fontP,
          const char *  const header,
@@ -126,7 +125,7 @@ dumpfont(struct font * const fontP,
     }
 
     if (header != NULL)
-        printf("#include \"%s\"\n\n", header);    
+        printf("#include \"%s\"\n\n", header);
 
     printf("static struct glyph _g[%d] = {\n", ng);
 
@@ -139,13 +138,13 @@ dumpfont(struct font * const fontP,
             printf(" { %d, %d, %d, %d, %d, \"",
                    glyphP->width, glyphP->height,
                    glyphP->x, glyphP->y, glyphP->xadd);
-            
+
             for (j = 0; j < glyphP->width * glyphP->height; ++j) {
                 if (glyphP->bmap[j])
                     printf("\\1");
                 else
                     printf("\\0");
-            }    
+            }
             --ng;
             printf("\" }%s\n", ng ? "," : "");
         }
@@ -164,7 +163,7 @@ dumpfont(struct font * const fontP,
                 printf(" _g + %d", ng++);
             else
                 printf(" NULL");
-        
+
             if (i != 255)
                 printf(",");
 
@@ -186,7 +185,7 @@ main(int argc, const char *argv[]) {
     pm_proginit(&argc, argv);
 
     parseCommandLine(argc, argv, &cmdline);
-    
+
     computeFont(cmdline.font, cmdline.builtin, &fontP);
 
     if (cmdline.verbose)
diff --git a/buildtools/libopt.c b/buildtools/libopt.c
index f62194e5..c714f416 100644
--- a/buildtools/libopt.c
+++ b/buildtools/libopt.c
@@ -17,7 +17,7 @@
   The "lib" part of the library name, which we call the prefix, may be
   other than "lib".  The list of recognized values is compiled in as
   the macro SHLIBPREFIXLIST (see below).
-  
+
   There is no newline or null character or anything after the output.
 
   If you specify the option "-runtime", the output includes a -R
@@ -78,7 +78,7 @@
    have.  "lib" is traditionally the only prefix, as in libc or
    libnetpbm.  However, on Windows there is a convention of using
    different prefixes to distinguish different co-existent versions of
-   the same library (kind of like a major number in some unices). 
+   the same library (kind of like a major number in some unices).
    E.g. the value "cyg lib" is appropriate for a Cygwin system.
 */
 #ifndef SHLIBPREFIXLIST
@@ -103,7 +103,7 @@ static const char * dllverstr = DLLVERSTR;
 static const char * dllverstr = "";
 #endif
 
-bool const explicit = 
+bool const explicit =
 #ifdef EXPLICIT
 TRUE
 #else
@@ -117,8 +117,9 @@ strfree(const char * const arg) {
 }
 
 
+
 static void
-parse_prefixlist(const char * const prefixlist, 
+parse_prefixlist(const char * const prefixlist,
                  char * parsed_prefixes[MAX_PREFIXES+1],
                  bool * const errorP) {
 /*----------------------------------------------------------------------------
@@ -140,7 +141,7 @@ parse_prefixlist(const char * const prefixlist,
     if (prlist == NULL)
         *errorP = TRUE;
     else {
-        if (strlen(prlist) <= 0) 
+        if (strlen(prlist) <= 0)
             *errorP = TRUE;
         else {
             /* NOTE: Mac OS X, at least, does not have strtok_r().
@@ -149,7 +150,7 @@ parse_prefixlist(const char * const prefixlist,
             char * token;
             int num_tokens;
             int i;
-            
+
             for (i=0; i < MAX_PREFIXES + 1; i++) {
                 parsed_prefixes[i] = NULL;
             }
@@ -158,14 +159,14 @@ parse_prefixlist(const char * const prefixlist,
             *errorP = FALSE;  /* initial value */
             while (token != NULL && num_tokens < MAX_PREFIXES && !*errorP) {
                 parsed_prefixes[num_tokens] = strdup (token);
-                if (parsed_prefixes[num_tokens] == NULL) 
+                if (parsed_prefixes[num_tokens] == NULL)
                     *errorP = TRUE;
                 num_tokens++;
                 token = strtok(NULL, " ");
             }
             for (i = num_tokens; i < MAX_PREFIXES + 1 && !*errorP;  i++) {
                 parsed_prefixes[i] = strdup("");
-                if (parsed_prefixes[i] == NULL) 
+                if (parsed_prefixes[i] == NULL)
                     *errorP = TRUE;
             }
         }
@@ -183,31 +184,31 @@ parse_prefixlist(const char * const prefixlist,
 
 
 static void
-parse_prefix(const char * const filename, 
+parse_prefix(const char * const filename,
              bool * const prefix_good_p, unsigned int * const prefix_length_p,
              bool * const error_p) {
 /*----------------------------------------------------------------------------
    Find the library name prefix (e.g. "lib") in the library filename
    'filename'.
-   
+
    Return the length of the prefix, in characters, as *prefix_length_p.
    (The prefix always starts at the beginning of the filename).
 
    Iff we don't find a valid library name prefix, return *prefix_good_p
-   == FALSE.  
+   == FALSE.
 
    The list of valid prefixes is compiled in as the blank-delimited
    string which is the value of the SHLIBPREFIXLIST macro.
 -----------------------------------------------------------------------------*/
     char * shlibprefixlist[MAX_PREFIXES+1];
-        /* An argv-style array of prefix strings in the first entries, 
+        /* An argv-style array of prefix strings in the first entries,
            null strings in the later entries.  At most MAX_PREFIXES prefixes,
            so at least one null string.
         */
     char * prefix;
         /* The prefix that the filename actually
            uses.  e.g. if shlibprefixlist = { "lib", "cyg", "", ... } and the
-           filename is "path/to/cyg<something>.<extension>", then 
+           filename is "path/to/cyg<something>.<extension>", then
            prefix = "cyg".  String is in the same storage as pointed to by
            shlibprefixlist (shlibprefixlist[1] in this example).
         */
@@ -223,7 +224,7 @@ parse_prefix(const char * const filename,
         if (strcmp(shlibprefixlist[0], "") == 0) {
             fprintf(stderr, "libopt was compiled with an invalid value "
                     "of the SHLIBPREFIX macro.  It seems to have no "
-                    "tokens.  SHLIBPREFIX = '%s'", 
+                    "tokens.  SHLIBPREFIX = '%s'",
                     SHLIBPREFIXLIST);
             exit(100);
         }
@@ -236,9 +237,9 @@ parse_prefix(const char * const filename,
             /* stop condition: shlibprefixlist has MAX_PREFIXES+1 entries.
              * we only ever put tokens in the 0..MAX_PREFIXES-1 positions.
              * Then, we fill DOWN from the MAX_PREFIXES position with '\0'
-             * so we insure that the shlibprefixlist array contains at 
-             * least one final '\0' string, but probably many '\0' 
-             * strings (depending on how many tokens there were).               
+             * so we insure that the shlibprefixlist array contains at
+             * least one final '\0' string, but probably many '\0'
+             * strings (depending on how many tokens there were).
              */
             prefix_length = strlen(prefix);
             if (strncmp(filename, prefix, prefix_length) == 0) {
@@ -246,8 +247,8 @@ parse_prefix(const char * const filename,
                 /* at this point, prefix is pointing to the correct
                  * entry, and prefix_length has the correct value.
                  * When we bail out of the while loop because of the
-                 * !prefix_good clause, we can then use these 
-                 * vars (prefix, prefix_length) 
+                 * !prefix_good clause, we can then use these
+                 * vars (prefix, prefix_length)
                  */
             } else {
                 prefix = shlibprefixlist[++i];
@@ -255,9 +256,9 @@ parse_prefix(const char * const filename,
         }
         *prefix_length_p = prefix_length;
         *prefix_good_p = prefix_good;
-        { 
+        {
             int i;
-            for (i=0; i < MAX_PREFIXES + 1; i++) 
+            for (i=0; i < MAX_PREFIXES + 1; i++)
                 free (shlibprefixlist[i]);
         }
     }
@@ -276,7 +277,7 @@ parse_filename(const char *  const filename,
    is just a filename, not a whole pathname.
 
    Return it in newly malloc'ed storage pointed to by '*libname_p'.
-   
+
    E.g. for "libxyz.so", return "xyz".
 
    return *valid_library_p == TRUE iff 'filename' validly names a library
@@ -290,13 +291,13 @@ parse_filename(const char *  const filename,
 
    Do not allocate any memory if *error_p == TRUE or *valid_library_p == FALSE.
 -----------------------------------------------------------------------------*/
-    char *lastdot;  
+    char *lastdot;
     /* Pointer to last period in 'filename'.  Null if none */
-    
+
     /* We accept any period-delimited suffix as a library type suffix.
        It's probably .so or .a, but is could be .kalamazoo for all we
-       care. (HOWEVER, the double-suffixed import lib used on 
-       cygwin (.dll.a) is NOT understood). 
+       care. (HOWEVER, the double-suffixed import lib used on
+       cygwin (.dll.a) is NOT understood).
     */
     char *p;
 
@@ -321,8 +322,8 @@ parse_filename(const char *  const filename,
             if (!prefix_good) {
                 *valid_library_p = FALSE;
             } else {
-                /* Extract everything between <prefix> and "." as 
-                   the library name root. 
+                /* Extract everything between <prefix> and "." as
+                   the library name root.
                 */
                 char * libname;
 
@@ -334,7 +335,7 @@ parse_filename(const char *  const filename,
                     if (strlen(dllverstr) > 0) {
                         p = strstr(libname, dllverstr);
                         if (p) {
-                            if (libname + strlen(libname) 
+                            if (libname + strlen(libname)
                                 - strlen(dllverstr) == p) {
                                 *p = '\0';
                             }
@@ -350,17 +351,17 @@ parse_filename(const char *  const filename,
             }
         }
     }
-}   
+}
 
 
 
 static void
 parse_filepath(const char *  const filepath,
-               const char ** const directory_p, 
+               const char ** const directory_p,
                const char ** const filename_p,
                bool *        const error_p) {
 /*----------------------------------------------------------------------------
-   Extract the directory and filename components of the filepath 
+   Extract the directory and filename components of the filepath
    'filepath' and return them in newly malloc'ed storage pointed to by
    '*directory_p' and '*filename_p'.
 
@@ -373,7 +374,7 @@ parse_filepath(const char *  const filepath,
 
     if (lastslash == NULL) {
         /* There's no directory component; the filename starts at the
-           beginning of the filepath 
+           beginning of the filepath
         */
         *filename_p = strdup(filepath);
         if (*filename_p == NULL)
@@ -387,8 +388,8 @@ parse_filepath(const char *  const filepath,
                 *error_p = FALSE;
         }
     } else {
-        /* Split the string at the slash we just found, into filename and 
-           directory 
+        /* Split the string at the slash we just found, into filename and
+           directory
            */
         *filename_p = strdup(lastslash+1);
         if (*filename_p == NULL)
@@ -410,7 +411,7 @@ parse_filepath(const char *  const filepath,
 
 
 static void
-doOptions(const char *  const filepath, 
+doOptions(const char *  const filepath,
           const char *  const directory,
           const char *  const libname,
           bool          const runtime,
@@ -434,20 +435,20 @@ doOptions(const char *  const filepath,
     }
     if (runtime && !staticlib && strlen(directory) > 0) {
         options = malloc(strlen(linkopt) + strlen(directory) + 10);
-        sprintf(options, "%s -R%s", linkopt, directory); 
+        sprintf(options, "%s -R%s", linkopt, directory);
     } else
         options = strdup(linkopt);
-    
+
     strfree(linkopt);
-    
+
     *optionsP = options;
 }
 
 
 
 static void
-processOneLibrary(const char *  const filepath, 
-                  bool          const runtime, 
+processOneLibrary(const char *  const filepath,
+                  bool          const runtime,
                   bool          const explicit,
                   const char ** const optionsP,
                   bool *        const errorP) {
@@ -465,28 +466,28 @@ processOneLibrary(const char *  const filepath,
     if (!*errorP) {
         const char *libname;
             /* Library name component of 'filename'.  e.g. xyz in
-               libxyz.so 
+               libxyz.so
             */
-        bool valid_library;  
+        bool valid_library;
             /* Our argument is a valid library filepath that can be
-               converted to -l/-L notation.  
+               converted to -l/-L notation.
             */
         bool staticlib;
             /* Our argument appears to name a static library. */
 
-        parse_filename(filename, 
+        parse_filename(filename,
                        &libname, &valid_library, &staticlib, errorP);
-        
+
         if (!*errorP) {
             if (valid_library) {
-                doOptions(filepath, directory, libname, 
+                doOptions(filepath, directory, libname,
                           runtime, explicit, staticlib, optionsP);
 
                 strfree(libname);
             } else
                 *optionsP = strdup(filepath);
         }
-        strfree(directory); 
+        strfree(directory);
         strfree(filename);
     }
 }
@@ -513,10 +514,10 @@ main(int argc, char **argv) {
             /* Doesn't do anything today */
         } else {
             const char * options;
-            processOneLibrary(argv[arg], runtime, explicit, 
+            processOneLibrary(argv[arg], runtime, explicit,
                               &options, &error);
             if (!error) {
-                if (strlen(outputLine) + strlen(options) + 1 + 1 > 
+                if (strlen(outputLine) + strlen(options) + 1 + 1 >
                     sizeof(outputLine))
                     error = TRUE;
                 else {
@@ -537,3 +538,6 @@ main(int argc, char **argv) {
     }
     return retval;
 }
+
+
+
diff --git a/buildtools/makeman b/buildtools/makeman
index 196dbd0a..6e4bb52b 100755
--- a/buildtools/makeman
+++ b/buildtools/makeman
@@ -2,17 +2,24 @@
 #
 # makeman -- compile netpbm's stereotyped HTML to troff markup
 #
-# This approach works because we control the entire document universe 
+# Example:
+#
+#    $ makeman pamcut.html pamcomp.html
+#
+#    $ makeman -v -d /tmp/inputdir pamcut.html
+#
+# The output troff file is in the same directory as the input HTML file, named
+# the same except with .1 extension.
+
+# This approach works because we control the entire document universe
 # this is going to convert and can reinforce useful stereotypes.
 #
 # The output of this tool uses cliches parseable by doclifter,
 # which should thus be able to recover all the semantic information
 # it looks like this thing is losing.
 #
-# Known bugs:
-#  * Ordered lists are smashed into unordered lists
-#
 # Limitations:
+#  * Ordered lists are smashed into unordered lists
 #  * IMG tags are issued as .IMG preceded by a bolded caption containing
 #    the alt content.  This will only work if the page is formatted with
 #    mwww macros.
@@ -29,7 +36,7 @@
 # Version 1.1, February 11 2016
 #
 #   Added ability to process &mdash; &minus;
-#   Added footer message to clarify original source. 
+#   Added footer message to clarify original source.
 #
 
 import os, sys, re
@@ -110,7 +117,7 @@ def makeman(name, file, indoc):
     indoc = ('.TH "%s" %d "%s" "%s"\n' % (title,section,date,source)) + indoc
     # Literal layout
     indoc = re.sub("(?i)\n *<PRE>", "\n.nf", indoc)
-    indoc = re.sub("(?i)\n *</PRE>", "\n.fi", indoc)
+    indoc = re.sub("(?i) *</PRE>\n", "\n.fi\n", indoc)
     indoc = re.sub("(?i)\n *<BLOCKQUOTE>", "\n.RS", indoc)
     indoc = re.sub("(?i)\n *</BLOCKQUOTE>", "\n.RE", indoc)
     # Highlight processing
@@ -151,7 +158,7 @@ def makeman(name, file, indoc):
     indoc = "\n".join(lines)
     indoc = re.sub(r"\s*\.sp", "\n.sp", indoc)
     # Format email addresses as italic
-    indoc = re.sub('(?i)<A[ \n]+HREF="mailto:[^>]+">([^<]+)</A>', r'\\fI\1\\fP', indoc)    
+    indoc = re.sub('(?i)<A[ \n]+HREF="mailto:[^>]+">([^<]+)</A>', r'\\fI\1\\fP', indoc)
     # Format manual cross-references
     def xrefmatch(match):
         xrefto = match.group(2)
@@ -176,7 +183,7 @@ def makeman(name, file, indoc):
     indoc = indoc.replace("&#174;", r"\*R")
     indoc = indoc.replace("&copy;", r"\(co")
     # Turn anchors into .UN tags
-    indoc = re.sub('(?i)<A NAME *= *"#?([a-zA-Z_][a-zA-Z_0-9.-]+)">(?:&nbsp;)*</A>\s*', ".UN \\1\n", indoc)
+    indoc = re.sub(r'(?i)<A NAME *= *"#?([a-zA-Z_][a-zA-Z_0-9.-]+)">(?:&nbsp;)*</A>\s*', ".UN \\1\n", indoc)
     # Strip off the index trailer
     trailer = re.compile('<HR */*>.*', re.DOTALL | re.IGNORECASE)
     indoc = re.sub(trailer, "", indoc)
@@ -200,7 +207,8 @@ def makeman(name, file, indoc):
     indoc = re.sub('(?i)<H2>([^><]*)</H2>', ".SH \\1", indoc)
     indoc = re.sub('(?i)<H3>([^><]*)</H3>', ".SS \\1", indoc)
     indoc = re.sub('(?i)<H4>([^><]*)</H4>', ".B \\1", indoc)
-    # 
+    indoc = re.sub('(?i)<H5>([^><]*)</H5>', ".B \\1", indoc)
+    #
     # Process definition lists -- just turn them into .TPs
     indoc = re.sub("(?i) *<DL *(COMPACT)?>", "", indoc)
     indoc = re.sub("(?i) *</DL>", "", indoc)
@@ -210,7 +218,7 @@ def makeman(name, file, indoc):
     indoc = re.sub("(?i) *</DD>", "", indoc)
     # Process unordered lists -- just turn them into .TPs
     indoc = re.sub("(?i)</?[UO]L *(COMPACT)?>", "", indoc)
-    indoc = re.sub("(?i) *<LI>", ".IP \(bu\n", indoc)
+    indoc = re.sub("(?i) *<LI>", r".IP \(bu\n", indoc)
     indoc = re.sub("(?i) *</LI>", "", indoc)
     # No-print tags
     indoc = re.sub("<!--no_print-->.*", "", indoc)
@@ -221,6 +229,15 @@ def makeman(name, file, indoc):
     # Acronyms
     indoc = re.sub('<acronym [a-zA-Z0-9:= \n"]*>', "", indoc)
     indoc = re.sub("</acronym>", "", indoc)
+    # Abbreviation - just erase tags
+    indoc = re.sub('<abbr [^>]+>', '', indoc)
+    indoc = re.sub('</abbr>', '', indoc)
+    # Subscript - just erase tags
+    indoc = re.sub('(?i)<sub [^>]+>', '', indoc)
+    indoc = re.sub('(?i)</sub>', '', indoc)
+    # Span - just erase tags
+    indoc = re.sub('(?i)<span [^>]+>', '', indoc)
+    indoc = re.sub('(?i)</span>', '', indoc)
     # Image tags
     indoc = re.sub(' *<img src="([^"]*)" alt="([^"]*)"( *[a-z]*="?[0-9]*"?)*>', ".B \\2\n.IMG -C \\1", indoc)
     # Special characters
@@ -230,13 +247,14 @@ def makeman(name, file, indoc):
     indoc = indoc.replace("&mdash;", "-")
     indoc = indoc.replace("&mu;", "mu")
     indoc = indoc.replace("&sigma;", "sigma")
+    indoc = indoc.replace("&apos;", "'")
     # Tables
     # This will not handle rowspan
     indoc = re.sub('(?i) *<table[^>]*>.*', ".TS", indoc)
     indoc = re.sub("(?i) *</table>.*", ".TE", indoc)
     # First the single-line case
     indoc = re.sub("(?i)</td> *<td>", "\t", indoc)
-    indoc = re.sub("(?i)<tr> *<td>", "", indoc)
+    indoc = re.sub("(?i)<tr> *<td( [^>]*)?>", "", indoc)
     indoc = re.sub("(?i)</td> *</tr>", "", indoc)
     # Then the multiline case
     indoc = re.sub(r'(?i)\s*<t[hd][^>]*>([^<\n]*)</t[dh]>\s*', '\t\\1', indoc)
@@ -248,6 +266,9 @@ def makeman(name, file, indoc):
     # Debugging
     #sys.stderr.write("Name: %s, Title: %s, Date: %s\n" % (name, title, date))
     # Time for error checking now
+    # We replaced every HTML tag we could above, so any remaining in
+    #   'indoc' represent material we don't know how to convert, which we call
+    #   bad lines.
     badlines = []
     for line in indoc.split("\n"):
         if "<" in line or ">" in line.replace(" >", "") or re.search(r'(?<!^\\)&.*;', line):
@@ -282,10 +303,12 @@ def main(args, mainout=sys.stdout, mainerr=sys.stderr):
         # First pass: gather locations for cross-references:
         sectmap = {}
         for file in arguments:
-            try: 
-                infp = open(os.path.join(dirprefix, file))
+            fullfilenm = os.path.join(dirprefix, file)
+            try:
+                infp = open(fullfilenm)
             except:
-                sys.stderr.write("makeman: can't open %s\n" % file)
+                sys.stderr.write(
+                    "makeman: can't open input file '%s'\n" % fullfilenm)
                 continue
             indoc = infp.read()
             infp.close()
@@ -313,10 +336,12 @@ def main(args, mainout=sys.stdout, mainerr=sys.stderr):
                 LiftException("%s has two <HR> tags!" % file)
         # Second pass: do formatting
         for file in arguments:
-            try: 
-                infp = open(os.path.join(dirprefix, file))
+            fullfilenm = os.path.join(dirprefix, file)
+            try:
+                infp = open(fullfilenm)
             except:
-                sys.stderr.write("makeman: can't open %s\n" % file)
+                sys.stderr.write(
+                    "makeman: can't open output file '%s'\n" % fullfilenm)
                 continue
             indoc = infp.read()
             infp.close()
diff --git a/buildtools/stamp-date b/buildtools/stamp-date
index 902c82e4..baeec3fd 100755
--- a/buildtools/stamp-date
+++ b/buildtools/stamp-date
@@ -12,14 +12,29 @@
 # SOURCE_DATE_EPOCH is an environment variable as described here:
 # https://reproducible-builds.org/specs/source-date-epoch/ on 2017.03.16.
 
+# COMPILED_BY is a similar environment variable whose value is some
+# description of who is doing the build.  If it is not set, we use the
+# value of LOGNAME; if that is not set, we use the value of User; if that
+# is not set, we use the output of program 'whoami'.
+
 SOURCE_DATE_OR_NONE=${SOURCE_DATE_EPOCH:-NONE}
 
-BUILD_DATETIME=$(date +%s)
+NOW_FROM_DATE_PGM=$(date +%s)
+if [ "$NOW_FROM_DATE_PGM" = "%s" ]; then
+    # This system's 'date' doesn't know %s.  (Solaris 10 for example).
+    # Try Perl
+    BUILD_DATETIME=$(perl -e 'print time()')
+else
+    BUILD_DATETIME=$NOW_FROM_DATE_PGM
+fi
 
 LOGNAME_OR_UNKNOWN=${LOGNAME:-UNKNOWN}
-USER=${USER:-$LOGNAME_OR_UNKNOWN}
-if [ "$USER" = "UNKNOWN" ]; then
-    USER=$(whoami)
+USER_OR_UNKNOWN=${USER:-$LOGNAME_OR_UNKNOWN}
+COMPILED_BY_OR_UNKNOWN=${COMPILED_BY:-$USER_OR_UNKNOWN}
+if [ "$COMPILED_BY_OR_UNKNOWN" = "UNKNOWN" ]; then
+    COMPILED_BY=$(whoami)
+else
+    COMPILED_BY=$COMPILED_BY_OR_UNKNOWN
 fi
 
 echo "/* This file tells some facts about the building of the package */"
@@ -29,4 +44,4 @@ if [ "$SOURCE_DATE_OR_NONE" != "NONE" ]; then
   echo "#define SOURCE_DATETIME $SOURCE_DATE_OR_NONE"
 fi
 echo "#define BUILD_DATETIME $BUILD_DATETIME"
-echo "#define COMPILED_BY \"$USER\""
+echo "#define COMPILED_BY \"$COMPILED_BY\""
diff --git a/buildtools/typegen.c b/buildtools/typegen.c
index 5b32af28..6ca86072 100644
--- a/buildtools/typegen.c
+++ b/buildtools/typegen.c
@@ -13,8 +13,8 @@
   the same compile environment as what will actually get used to build
   Netpbm, and thus the one where our inttypes.h will be used.
 
-  Right now, it simply generates either 
-  
+  Right now, it simply generates either
+
     typedef int int32_t;
 
   or
@@ -111,3 +111,6 @@ main(int argc, char **argv) {
 
     return 0;
 }
+
+
+
diff --git a/common.mk b/common.mk
index 749488c2..c86ef910 100644
--- a/common.mk
+++ b/common.mk
@@ -144,13 +144,13 @@ IMPORTINC_ROOT_HEADERS := pm_config.h inttypes_netpbm.h version.h
 
 IMPORTINC_LIB_HEADERS := \
   pm.h pbm.h pgm.h ppm.h pnm.h pam.h pbmfont.h ppmcmap.h \
-  pammap.h colorname.h ppmfloyd.h ppmdraw.h pm_system.h ppmdfont.h \
+  pammap.h colorname.h ppmdraw.h pm_system.h ppmdfont.h \
   pm_gamma.h lum.h dithers.h pamdraw.h
 
 IMPORTINC_LIB_UTIL_HEADERS := \
   bitarith.h bitio.h bitreverse.h filename.h intcode.h floatcode.h io.h \
   matrix.h mallocvar.h \
-  nsleep.h nstring.h pm_c_util.h runlength.h shhopt.h token.h
+  nsleep.h nstring.h pm_c_util.h rand.h runlength.h shhopt.h token.h
 
 IMPORTINC_HEADERS := \
   $(IMPORTINC_ROOT_HEADERS) \
@@ -470,7 +470,7 @@ empty.c:
 # 2000.06.15
 
 # DJGPP can do SYMKINKs for programs but not for ordinary files, so
-# it define SYMLINKEXE, other system don't need it
+# it defines SYMLINKEXE, other system don't need it
 ifeq ($(SYMLINKEXE)x,x)
   SYMLINKEXE := $(SYMLINK)
 endif
diff --git a/converter/other/Makefile b/converter/other/Makefile
index 5dfc27ec..3b3b6aa0 100644
--- a/converter/other/Makefile
+++ b/converter/other/Makefile
@@ -134,14 +134,15 @@ PORTBINARIES =  avstopam bmptopnm fitstopnm \
 		gemtopnm giftopnm hdifftopam infotopam \
 		pamtoavs pamtodjvurle pamtofits pamtogif \
 		pamtohdiff pamtohtmltbl pamtompfont pamtooctaveimg \
-		pamtopam pamtopdbimg pamtopfm pamtopnm pamtosrf pamtouil \
+		pamtopam pamtopdbimg pamtopfm pamtopnm \
+                pamtoqoi pamtosrf pamtouil \
 		pamtowinicon pamtoxvmini \
 		pbmtopgm pdbimgtopam pfmtopam \
 	        pgmtopbm pgmtoppm ppmtopgm pnmtoddif \
 		pnmtopclxl pnmtorast \
-		pnmtosgi pnmtosir pamtotga pnmtoxwd \
+		pnmtosgi pnmtosir pamtotga pnmtoxwd qoitopam \
 		rasttopnm rlatopam sgitopnm sirtopnm srftopam sunicontopnm \
-		winicontopam xwdtopnm yuy2topam zeisstopnm
+		winicontopam xwdtopnm yuy2topam zeisstopnm \
 
 ifneq ($(DONT_HAVE_PROCESS_MGMT),Y)
   PORTBINARIES += pstopnm pnmtops
diff --git a/converter/other/avstopam.c b/converter/other/avstopam.c
index 322f387d..5b2be683 100644
--- a/converter/other/avstopam.c
+++ b/converter/other/avstopam.c
@@ -101,3 +101,6 @@ main(int argc, const char *argv[]) {
 
     return 0;
 }
+
+
+
diff --git a/converter/other/bmptopnm.c b/converter/other/bmptopnm.c
index 3f66634b..091d948a 100644
--- a/converter/other/bmptopnm.c
+++ b/converter/other/bmptopnm.c
@@ -140,9 +140,7 @@ parseCommandLine(int argc, const char ** argv,
    Note that the file spec array we return is stored in the storage that
    was passed to us as the argv array.
 -----------------------------------------------------------------------------*/
-    optEntry * option_def;
-        /* Instructions to OptParseOptions2 on how to parse our options.
-         */
+    optEntry * option_def;   /* Used by OPTENT3 */
     optStruct3 opt;
 
     unsigned int option_def_index;
@@ -156,7 +154,7 @@ parseCommandLine(int argc, const char ** argv,
     opt.short_allowed = FALSE;  /* We have no short (old-fashioned) options */
     opt.allowNegNum = FALSE;  /* We have no parms that are negative numbers */
 
-    pm_optParseOptions3(&argc, (char **)argv, opt, sizeof(opt), 0);
+    pm_optParseOptions4(&argc, argv, opt, sizeof(opt), 0);
         /* Uses and sets argc, argv, and some of *cmdlineP and others. */
 
     if (argc-1 == 0)
@@ -196,6 +194,8 @@ GetShort(FILE * const fp) {
     return v;
 }
 
+
+
 static short
 GetBigShort(FILE * const fp) {
 
@@ -938,6 +938,7 @@ convertRow32(unsigned char      const bmprow[],
 }
 
 
+
 static void
 validateIndex(unsigned int const index,
               unsigned int const cmapSize ) {
@@ -1718,3 +1719,4 @@ main(int argc, const char ** argv) {
 }
 
 
+
diff --git a/converter/other/cameratopam/camera.c b/converter/other/cameratopam/camera.c
index 4610462c..62b58ad5 100644
--- a/converter/other/cameratopam/camera.c
+++ b/converter/other/cameratopam/camera.c
@@ -56,7 +56,6 @@ merror (const void *ptr, const char *where)
 
 
 
-
 static void
 adobeCopyPixel(Image             const image,
                unsigned int      const row,
@@ -87,6 +86,8 @@ adobeCopyPixel(Image             const image,
         --(*rp);
 }
 
+
+
 void
 adobe_dng_load_raw_lj(Image const image) {
 
@@ -187,6 +188,8 @@ nikon_compressed_load_raw(Image const image) {
     free (curve);
 }
 
+
+
 void
 nikon_load_raw(Image const image) {
 
@@ -213,6 +216,8 @@ nikon_load_raw(Image const image) {
   }
 }
 
+
+
 /*
    Figure out if a NEF file is compressed.  These fancy heuristics
    are only needed for the D100, thanks to a bug in some cameras
@@ -235,6 +240,8 @@ nikon_is_compressed()
   return 0;
 }
 
+
+
 /*
    Returns 1 for a Coolpix 990, 0 for a Coolpix 995.
  */
@@ -254,6 +261,8 @@ nikon_e990()
   return 0;
 }
 
+
+
 /*
    Returns 1 for a Coolpix 2100, 0 for anything else.
  */
@@ -273,6 +282,8 @@ nikon_e2100()
   return 1;
 }
 
+
+
 /*
    Separates a Pentax Optio 33WR from a Nikon E3700.
  */
@@ -289,6 +300,8 @@ pentax_optio33()
   return sum[0] < sum[1]*4;
 }
 
+
+
 /*
    Separates a Minolta DiMAGE Z2 from a Nikon E4300.
  */
@@ -305,6 +318,8 @@ minolta_z2()
   return 0;
 }
 
+
+
 void
 nikon_e2100_load_raw(Image const image) {
 
@@ -333,6 +348,8 @@ nikon_e2100_load_raw(Image const image) {
   }
 }
 
+
+
 void
 nikon_e950_load_raw(Image const image) {
 
@@ -349,6 +366,8 @@ nikon_e950_load_raw(Image const image) {
   maximum = 0x3dd;
 }
 
+
+
 /*
    The Fuji Super CCD is just a Bayer grid rotated 45 degrees.
  */
@@ -368,6 +387,8 @@ fuji_s2_load_raw(Image const image) {
   }
 }
 
+
+
 void
 fuji_s3_load_raw(Image const image) {
   unsigned short pixel[4352];
@@ -384,6 +405,8 @@ fuji_s3_load_raw(Image const image) {
   }
 }
 
+
+
 static void
 fuji_common_load_raw(Image        const image,
                      unsigned int const ncol,
@@ -444,6 +467,8 @@ fuji_f700_load_raw(Image const image) {
   }
 }
 
+
+
 void
 rollei_load_raw(Image const image) {
   unsigned char pixel[10];
@@ -470,6 +495,8 @@ rollei_load_raw(Image const image) {
   maximum = 0x3ff;
 }
 
+
+
 void
 phase_one_load_raw(Image const image) {
   int row, col, a, b;
@@ -496,6 +523,8 @@ phase_one_load_raw(Image const image) {
   free (pixel);
 }
 
+
+
 void
 ixpress_load_raw(Image const image) {
   unsigned short pixel[4090];
@@ -510,6 +539,8 @@ ixpress_load_raw(Image const image) {
   }
 }
 
+
+
 void
 leaf_load_raw(Image const image) {
   unsigned short *pixel;
@@ -526,6 +557,8 @@ leaf_load_raw(Image const image) {
   free (pixel);
 }
 
+
+
 /*
    For this function only, raw_width is in bytes, not pixels!
  */
@@ -542,6 +575,8 @@ packed_12_load_raw(Image const image) {
   }
 }
 
+
+
 void
 unpacked_load_raw(Image const image) {
   unsigned short *pixel;
@@ -557,6 +592,8 @@ unpacked_load_raw(Image const image) {
   free (pixel);
 }
 
+
+
 void
 olympus_e300_load_raw(Image const image) {
   unsigned char  *data,  *dp;
@@ -580,6 +617,8 @@ olympus_e300_load_raw(Image const image) {
   free (data);
 }
 
+
+
 void
 olympus_cseries_load_raw(Image const image) {
   int irow, row, col;
@@ -595,6 +634,8 @@ olympus_cseries_load_raw(Image const image) {
   }
 }
 
+
+
 void
 eight_bit_load_raw(Image const image) {
   unsigned char *pixel;
@@ -611,6 +652,8 @@ eight_bit_load_raw(Image const image) {
   maximum = 0xff;
 }
 
+
+
 void
 casio_qv5700_load_raw(Image const image) {
   unsigned char  data[3232],  *dp;
@@ -631,6 +674,8 @@ casio_qv5700_load_raw(Image const image) {
   maximum = 0x3fc;
 }
 
+
+
 void
 nucore_load_raw(Image const image) {
   unsigned short *pixel;
@@ -647,6 +692,8 @@ nucore_load_raw(Image const image) {
   free (pixel);
 }
 
+
+
 static int  radc_token (int tree)
 {
   int t;
@@ -688,6 +735,8 @@ static int  radc_token (int tree)
   return dindex->leaf;
 }
 
+
+
 #define FORYX for (y=1; y < 3; y++) for (x=col+1; x >= col; x--)
 
 #define PREDICTOR (c ? (buf[c][y-1][x] + buf[c][y][x+1]) / 2 \
@@ -770,6 +819,8 @@ kodak_radc_load_raw(Image const image) {
     maximum = 0x1fff;     /* wild guess */
 }
 
+
+
 #undef FORYX
 #undef PREDICTOR
 
@@ -791,6 +842,8 @@ fill_input_buffer (j_decompress_ptr cinfo)
   return TRUE;
 }
 
+
+
 void
 kodak_jpeg_load_raw(Image const image)
 {
@@ -830,6 +883,8 @@ kodak_jpeg_load_raw(Image const image)
   maximum = 0xff << 1;
 }
 
+
+
 #endif
 
 void
@@ -849,6 +904,8 @@ kodak_dc120_load_raw(Image const image)
   maximum = 0xff;
 }
 
+
+
 void
 kodak_dc20_coeff (float const juice)
 {
@@ -868,6 +925,8 @@ kodak_dc20_coeff (float const juice)
   use_coeff = 1;
 }
 
+
+
 void
 kodak_easy_load_raw(Image const image)
 {
@@ -896,6 +955,8 @@ kodak_easy_load_raw(Image const image)
   maximum = curve[0xff];
 }
 
+
+
 void
 kodak_compressed_load_raw(Image const image)
 {
@@ -960,6 +1021,8 @@ kodak_compressed_load_raw(Image const image)
     }
 }
 
+
+
 void
 kodak_yuv_load_raw(Image const image)
 {
@@ -1019,6 +1082,8 @@ kodak_yuv_load_raw(Image const image)
   maximum = 0xe74;
 }
 
+
+
 static void  sony_decrypt (unsigned *data, int len, int start, int key)
 {
   static uint32_t pad[128];
@@ -1053,6 +1118,8 @@ static void  sony_decrypt (unsigned *data, int len, int start, int key)
   }
 }
 
+
+
 void
 sony_load_raw(Image const image)
 {
@@ -1091,6 +1158,8 @@ sony_load_raw(Image const image)
   maximum = 0x3ff0;
 }
 
+
+
 void
 parse_minolta(FILE * const ifp)
 {
@@ -1124,6 +1193,8 @@ parse_minolta(FILE * const ifp)
   data_offset = offset;
 }
 
+
+
 /*
    CIFF block 0x1030 contains an 8x8 white sample.
    Load this into white[][] for use in scale_colors().
@@ -1151,6 +1222,8 @@ static void  ciff_block_1030()
     }
 }
 
+
+
 /*
    Parse a CIFF file, better known as Canon CRW format.
  */
@@ -1266,6 +1339,8 @@ common:
     camera_red = -1;            /* Use my auto WB for this photo */
 }
 
+
+
 void
 parse_rollei(FILE * const ifp)
 {
@@ -1333,6 +1408,8 @@ parse_mos(FILE * const ifp,
     }
 }
 
+
+
 void
 nikon_e950_coeff()
 {
@@ -1504,6 +1581,8 @@ get_timestamp(FILE * const ifp)
     timestamp = ts;
 }
 
+
+
 static void
 parse_exif(FILE * const ifp, int base)
 {
@@ -1529,6 +1608,8 @@ parse_exif(FILE * const ifp, int base)
   }
 }
 
+
+
 static int
 parse_tiff_ifd(FILE * const ifp, int base, int level)
 {
@@ -1725,6 +1806,8 @@ guess_cfa_pc:
   return done;
 }
 
+
+
 void
 parse_tiff(FILE * const ifp, int base)
 {
@@ -1797,3 +1880,5 @@ parse_external_jpeg(const char * const ifname)
     free (jname);
 }
 
+
+
diff --git a/converter/other/cameratopam/camera.h b/converter/other/cameratopam/camera.h
index 02c3f2af..172bc46e 100644
--- a/converter/other/cameratopam/camera.h
+++ b/converter/other/cameratopam/camera.h
@@ -5,7 +5,7 @@
 
 #include "cameratopam.h"
 
-void 
+void
 parse_ciff(FILE * const ifp,
            int    const offset,
            int    const length);
diff --git a/converter/other/cameratopam/cameratopam.c b/converter/other/cameratopam/cameratopam.c
index 78eb6854..693d280c 100644
--- a/converter/other/cameratopam/cameratopam.c
+++ b/converter/other/cameratopam/cameratopam.c
@@ -88,6 +88,8 @@ static void CLASS merror (const void *ptr, const char *where)
         pm_error ("Out of memory in %s", where);
 }
 
+
+
 struct CmdlineInfo {
     /* All the information the user supplied in the command line,
        in a form easy for the program to use.
@@ -136,37 +138,37 @@ parseCommandLine(int argc, char ** argv,
     opt.allowNegNum = FALSE;
 
     option_def_index = 0;   /* incremented by OPTENT3 */
-    OPTENT3(0, "bright", 
+    OPTENT3(0, "bright",
             OPT_FLOAT,   &cmdlineP->bright,     &brightSpec, 0);
-    OPTENT3(0, "red_scale", 
+    OPTENT3(0, "red_scale",
             OPT_FLOAT,   &cmdlineP->red_scale,  &red_scaleSpec, 0);
-    OPTENT3(0, "blue_scale", 
+    OPTENT3(0, "blue_scale",
             OPT_FLOAT,   &cmdlineP->blue_scale, &blue_scaleSpec, 0);
-    OPTENT3(0, "profile", 
+    OPTENT3(0, "profile",
             OPT_STRING,  &cmdlineP->profile,    &profileSpec, 0);
-    OPTENT3(0,   "identify_only",   
+    OPTENT3(0,   "identify_only",
             OPT_FLAG,    NULL, &cmdlineP->identify_only, 0);
-    OPTENT3(0,   "verbose",   
+    OPTENT3(0,   "verbose",
             OPT_FLAG,    NULL, &cmdlineP->verbose, 0);
-    OPTENT3(0,   "half_size",   
+    OPTENT3(0,   "half_size",
             OPT_FLAG,    NULL, &cmdlineP->half_size, 0);
-    OPTENT3(0,   "four_color_rgb",   
+    OPTENT3(0,   "four_color_rgb",
             OPT_FLAG,    NULL, &cmdlineP->four_color_rgb, 0);
-    OPTENT3(0,   "document_mode",   
+    OPTENT3(0,   "document_mode",
             OPT_FLAG,    NULL, &cmdlineP->document_mode, 0);
-    OPTENT3(0,   "quick_interpolate",   
+    OPTENT3(0,   "quick_interpolate",
             OPT_FLAG,    NULL, &cmdlineP->quick_interpolate, 0);
-    OPTENT3(0,   "balance_auto",   
+    OPTENT3(0,   "balance_auto",
             OPT_FLAG,    NULL, &cmdlineP->use_auto_wb, 0);
-    OPTENT3(0,   "balance_camera",   
+    OPTENT3(0,   "balance_camera",
             OPT_FLAG,    NULL, &cmdlineP->use_camera_wb, 0);
-    OPTENT3(0,   "use_secondary",   
+    OPTENT3(0,   "use_secondary",
             OPT_FLAG,    NULL, &cmdlineP->use_secondary, 0);
-    OPTENT3(0,   "no_clip_color",   
+    OPTENT3(0,   "no_clip_color",
             OPT_FLAG,    NULL, &cmdlineP->no_clip_color, 0);
-    OPTENT3(0,   "rgb",   
+    OPTENT3(0,   "rgb",
             OPT_FLAG,    NULL, &cmdlineP->use_camera_rgb, 0);
-    OPTENT3(0,   "linear",   
+    OPTENT3(0,   "linear",
             OPT_FLAG,    NULL, &cmdlineP->linear, 0);
 
     pm_optParseOptions3(&argc, argv, opt, sizeof(opt), 0);
@@ -185,12 +187,12 @@ parseCommandLine(int argc, char ** argv,
         cmdlineP->inputFileName = strdup("-");  /* he wants stdin */
     else if (argc - 1 == 1)
         cmdlineP->inputFileName = strdup(argv[1]);
-    else 
+    else
         pm_error("Too many arguments.  The only argument accepted "
                  "is the input file name");
 }
 
-  
+
 
 static void CLASS
 fixBadPixels(Image const image) {
@@ -658,9 +660,9 @@ fujiRotate(Image * const imageP) {
                     newImage[row*wide+col][i] =
                         (pix[    0][i]*(1-fc) + pix[      1][i]*fc) * (1-fr) +
                         (pix[width][i]*(1-fc) + pix[width+1][i]*fc) * fr;
-                } 
+                }
             }
-        }        
+        }
         free(*imageP);
         width  = wide;
         height = high;
@@ -920,7 +922,7 @@ convertIt(FILE *       const ifP,
     if (flip) {
         if (cmdline.verbose)
             pm_message ("Flipping image %c:%c:%c...",
-                        flip & 1 ? 'H':'0', flip & 2 ? 'V':'0', 
+                        flip & 1 ? 'H':'0', flip & 2 ? 'V':'0',
                         flip & 4 ? 'T':'0');
         flipImage(image);
     }
@@ -931,7 +933,7 @@ convertIt(FILE *       const ifP,
 
 
 
-int 
+int
 main (int argc, char **argv) {
 
     FILE * const ofP = stdout;
diff --git a/converter/other/cameratopam/canon.c b/converter/other/cameratopam/canon.c
index cbf5ece0..f86f43d8 100644
--- a/converter/other/cameratopam/canon.c
+++ b/converter/other/cameratopam/canon.c
@@ -170,3 +170,6 @@ canon_compressed_load_raw(Image const image) {
     if (raw_width > width)
         black /= (raw_width - width) * height;
 }
+
+
+
diff --git a/converter/other/cameratopam/decode.c b/converter/other/cameratopam/decode.c
index e3a62fab..d42f8619 100644
--- a/converter/other/cameratopam/decode.c
+++ b/converter/other/cameratopam/decode.c
@@ -44,15 +44,15 @@ void init_decoder() {
  */
 
 
-unsigned char * 
-make_decoder(const unsigned char * const source, 
+unsigned char *
+make_decoder(const unsigned char * const source,
              int                   const level) {
 
     struct decode *cur;
     static int leaf;
     int i, next;
 
-    if (level==0) 
+    if (level==0)
         leaf=0;
     cur = free_decode++;
     if (free_decode > first_decode+2048) {
@@ -74,7 +74,7 @@ make_decoder(const unsigned char * const source,
 
 
 
-const int * 
+const int *
 make_decoder_int(const int * const source,
                  int         const level) {
 
@@ -98,7 +98,7 @@ make_decoder_int(const int * const source,
 
 
 
-void 
+void
 crw_init_tables(unsigned int const table) {
 
   unsigned int const clippedTableNum = MIN(2, table);
@@ -170,3 +170,5 @@ crw_init_tables(unsigned int const table) {
   make_decoder (second_tree[clippedTableNum], 0);
 }
 
+
+
diff --git a/converter/other/cameratopam/decode.h b/converter/other/cameratopam/decode.h
index b0addc82..e79a6989 100644
--- a/converter/other/cameratopam/decode.h
+++ b/converter/other/cameratopam/decode.h
@@ -1,22 +1,22 @@
 struct decode {
   struct decode *branch[2];
   int leaf;
-}; 
+};
 
 extern struct decode * free_decode;
 extern struct decode first_decode[2048];
 extern struct decode * second_decode;
 
-void 
+void
 init_decoder(void);
 
-void 
+void
 crw_init_tables(unsigned int const table);
 
-const int * 
-make_decoder_int (const int * const source, 
+const int *
+make_decoder_int (const int * const source,
                   int         const level);
 
-unsigned char * 
-make_decoder(const unsigned char * const source, 
+unsigned char *
+make_decoder(const unsigned char * const source,
              int                   const level);
diff --git a/converter/other/cameratopam/dng.c b/converter/other/cameratopam/dng.c
index bddfd9f4..fbd2028f 100644
--- a/converter/other/cameratopam/dng.c
+++ b/converter/other/cameratopam/dng.c
@@ -3,7 +3,7 @@
 
 #include "dng.h"
 
-void 
+void
 dng_coeff (double cc[4][4],
            double cm[4][3],
            double xyz[3]) {
diff --git a/converter/other/cameratopam/dng.h b/converter/other/cameratopam/dng.h
index 56293563..2b7c96df 100644
--- a/converter/other/cameratopam/dng.h
+++ b/converter/other/cameratopam/dng.h
@@ -1,4 +1,4 @@
-void 
+void
 dng_coeff(double cc[4][4],
           double cm[4][3],
           double xyz[3]);
diff --git a/converter/other/cameratopam/foveon.c b/converter/other/cameratopam/foveon.c
index 5a26777b..23cffe67 100644
--- a/converter/other/cameratopam/foveon.c
+++ b/converter/other/cameratopam/foveon.c
@@ -339,6 +339,8 @@ foveon_fixed (void *       const ptr,
     return 1;
 }
 
+
+
 static float  foveon_avg (unsigned short *pix, int range[2], float cfilt)
 {
     int i;
@@ -353,6 +355,8 @@ static float  foveon_avg (unsigned short *pix, int range[2], float cfilt)
     return (sum - min - max) / (range[1] - range[0] - 1);
 }
 
+
+
 static short *foveon_make_curve (double max, double mul, double filt)
 {
     short *curve;
@@ -373,6 +377,8 @@ static short *foveon_make_curve (double max, double mul, double filt)
     return curve;
 }
 
+
+
 static void foveon_make_curves
 (short **curvep, float dq[3], float div[3], float filt)
 {
@@ -384,12 +390,16 @@ static void foveon_make_curves
     FORC3 curvep[c] = foveon_make_curve (max, mul[c], filt);
 }
 
+
+
 static int  foveon_apply_curve (short *curve, int i)
 {
     if (abs(i) >= (unsigned short)curve[0]) return 0;
     return i < 0 ? -(unsigned short)curve[1-i] : (unsigned short)curve[1+i];
 }
 
+
+
 void
 foveon_interpolate(Image const image,
                    float coeff[3][4]) {
@@ -797,3 +807,6 @@ foveon_interpolate(Image const image,
     width = i;
     height = row;
 }
+
+
+
diff --git a/converter/other/cameratopam/foveon.h b/converter/other/cameratopam/foveon.h
index c9bf48a8..584a38f6 100644
--- a/converter/other/cameratopam/foveon.h
+++ b/converter/other/cameratopam/foveon.h
@@ -3,15 +3,15 @@
 #include "cameratopam.h"
 #include "camera.h"
 
-void 
+void
 parse_foveon(FILE * const ifp);
 
-void  
+void
 foveon_interpolate(Image const image,
                    float coeff[3][4]);
 
 LoadRawFn foveon_load_raw;
 
-void  
+void
 foveon_coeff(int * const useCoeffP,
              float       coeff[3][4]);
diff --git a/converter/other/cameratopam/identify.c b/converter/other/cameratopam/identify.c
index e5df6b22..c1eb8a25 100644
--- a/converter/other/cameratopam/identify.c
+++ b/converter/other/cameratopam/identify.c
@@ -263,7 +263,6 @@ adobeCoeff(const char * const make,
 
 
 
-
 int
 identify(FILE *       const ifp,
          bool         const use_secondary,
@@ -1206,3 +1205,6 @@ dng_skip:
 
     return 0;
 }
+
+
+
diff --git a/converter/other/cameratopam/ljpeg.c b/converter/other/cameratopam/ljpeg.c
index 35f50f4b..d1ede87c 100644
--- a/converter/other/cameratopam/ljpeg.c
+++ b/converter/other/cameratopam/ljpeg.c
@@ -161,3 +161,6 @@ lossless_jpeg_load_raw(Image  const image) {
     if (!strcasecmp(make,"KODAK"))
         black = min;
 }
+
+
+
diff --git a/converter/other/cameratopam/ljpeg.h b/converter/other/cameratopam/ljpeg.h
index 9d9d8ee9..7b1cf364 100644
--- a/converter/other/cameratopam/ljpeg.h
+++ b/converter/other/cameratopam/ljpeg.h
@@ -8,11 +8,11 @@ struct jhead {
 
 LoadRawFn lossless_jpeg_load_raw;
 
-int  
+int
 ljpeg_start (FILE *         const ifP,
              struct jhead * const jhP);
 
-int 
+int
 ljpeg_diff (FILE *          const ifP,
             struct decode * const dindexP);
 
diff --git a/converter/other/cameratopam/util.c b/converter/other/cameratopam/util.c
index ede5ef69..d489b23e 100644
--- a/converter/other/cameratopam/util.c
+++ b/converter/other/cameratopam/util.c
@@ -28,6 +28,8 @@ get2(FILE * const ifp)
         return a << 8 | b;
 }
 
+
+
 /*
    Same for a 4-byte integer.
  */
@@ -45,6 +47,8 @@ get4(FILE * const ifp)
         return a << 24 | b << 16 | c << 8 | d;
 }
 
+
+
 /*
    Faster than calling get2() multiple times.
  */
@@ -68,11 +72,13 @@ read_shorts (FILE * const ifp, unsigned short *pixel, int count)
     }
 }
 
+
+
 /*
    getbits(-1) initializes the buffer
    getbits(n) where 0 <= n <= 25 returns an n-bit integer
  */
-unsigned 
+unsigned
 getbits (FILE * const ifp, int nbits)
 {
     static unsigned long bitbuf=0;
@@ -95,3 +101,6 @@ getbits (FILE * const ifp, int nbits)
     }
     return ret;
 }
+
+
+
diff --git a/converter/other/exif.c b/converter/other/exif.c
index 1bfe4b2b..b2a7bd5d 100644
--- a/converter/other/exif.c
+++ b/converter/other/exif.c
@@ -8,19 +8,41 @@
   added more of Wandel's code, from Jhead 1.9 dated December 2002 in
   January 2003.
 
-  An EXIF header is a JFIF APP1 marker.  It is generated by some
-  digital cameras and contains information about the circumstances of
-  the creation of the image (camera settings, etc.).
+  Bryan fundamentally rewrote it in March 2023 because it wasn't properly
+  dealing with the main image vs thumbnail IFDs.
+--------------------------------------------------------------------------*/
+
+/*
+  N.B. "EXIF" refers to a whole image file format; some people think it is
+  just the format of the camera model, orientation, etc. data within the
+  image file.  EXIF is a subset of JFIF; an EXIF file is JFIF file
+  containing an EXIF header in the form of a JFIF APP1 marker.
 
-  The EXIF header uses the TIFF format, only it contains only tag
-  values and no actual image.
+  An EXIF header is generated by some digital cameras and contains information
+  about the circumstances of the creation of the image (camera settings,
+  etc.).
 
-  Note that the image format called EXIF is simply JFIF with an EXIF
-  header, i.e. a subformat of JFIF.
+  The EXIF header uses the TIFF format, only it contains only tag values and
+  no actual image.
+
+  Note that the image format called EXIF is simply JFIF with an EXIF header,
+  i.e. a subformat of JFIF.
 
   See the EXIF specs at http://exif.org (2001.09.01).
 
---------------------------------------------------------------------------*/
+  The basic format of the EXIF header is a sequence of IFDs (directories).  I
+  believe the first IFD is always for the main image and the 2nd IFD is for a
+  thumbnail image and is not present if there is no thumbnail image in the
+  file.
+
+  A directory is a sequence of tag/value pairs.
+
+  Each IFD can contain SubIFD, as the value of an EXIF Offset or Interop
+  Offset tag.
+
+*/
+
+
 #include "pm_config.h"
 #include <stdio.h>
 #include <stdlib.h>
@@ -30,6 +52,7 @@
 #include <errno.h>
 #include <limits.h>
 #include <ctype.h>
+#include <assert.h>
 
 #if MSVCRT
     #include <sys/utime.h>
@@ -42,20 +65,28 @@
 
 #include "pm_c_util.h"
 #include "pm.h"
+#include "mallocvar.h"
 #include "nstring.h"
 
 #include "exif.h"
 
-static const unsigned char * DirWithThumbnailPtrs;
-static double FocalplaneXRes;
-bool HaveXRes;
-static double FocalplaneUnits;
-static int ExifImageWidth;
+
+
+enum Orientation {
+    ORIENT_NORMAL,
+    ORIENT_FLIP_HORIZ,   /* left right reversed mirror */
+    ORIENT_ROTATE_180,   /* upside down */
+    ORIENT_FLIP_VERT,    /* upside down mirror */
+    ORIENT_TRANSPOSE,    /* Flipped about top-left <--> bottom-right axis*/
+    ORIENT_ROTATE_90,    /* rotate 90 cw to right it */
+    ORIENT_TRANSVERSE,   /* flipped about top-right <--> bottom-left axis */
+    ORIENT_ROTATE_270    /* rotate 270 to right it */
+};
 
 typedef struct {
-    unsigned short Tag;
-    const char * Desc;
-} TagTable;
+    unsigned short tag;
+    const char * desc;
+} TagTableEntry;
 
 
 
@@ -63,7 +94,7 @@ typedef struct {
 static int const bytesPerFormat[] = {0,1,1,2,4,8,1,1,2,4,8,4,8};
 #define NUM_FORMATS 12
 
-#define FMT_BYTE       1 
+#define FMT_BYTE       1
 #define FMT_STRING     2
 #define FMT_USHORT     3
 #define FMT_ULONG      4
@@ -119,7 +150,7 @@ static int const bytesPerFormat[] = {0,1,1,2,4,8,1,1,2,4,8,4,8};
 #define TAG_THUMBNAIL_OFFSET  0x0201
 #define TAG_THUMBNAIL_LENGTH  0x0202
 
-static TagTable const tagTable[] = {
+static TagTableEntry const tagTable[] = {
   {   0x100,   "ImageWidth"},
   {   0x101,   "ImageLength"},
   {   0x102,   "BitsPerSample"},
@@ -207,7 +238,7 @@ static TagTable const tagTable[] = {
 
 
 
-typedef enum { NORMAL, MOTOROLA } ByteOrder;
+typedef enum { ORDER_NORMAL, ORDER_MOTOROLA } ByteOrder;
 
 
 
@@ -217,11 +248,11 @@ get16u(const void * const data,
 /*--------------------------------------------------------------------------
    Convert a 16 bit unsigned value from file's native byte order
 --------------------------------------------------------------------------*/
-    if (byteOrder == MOTOROLA){
-        return (((const unsigned char *)data)[0] << 8) | 
+    if (byteOrder == ORDER_MOTOROLA) {
+        return (((const unsigned char *)data)[0] << 8) |
             ((const unsigned char *)data)[1];
-    }else{
-        return (((const unsigned char *)data)[1] << 8) | 
+    } else {
+        return (((const unsigned char *)data)[1] << 8) |
             ((const unsigned char *)data)[0];
     }
 }
@@ -234,17 +265,17 @@ get32s(const void * const data,
 /*--------------------------------------------------------------------------
    Convert a 32 bit signed value from file's native byte order
 --------------------------------------------------------------------------*/
-    if (byteOrder == MOTOROLA){
-        return  
+    if (byteOrder == ORDER_MOTOROLA) {
+        return
             (((const char *)data)[0] << 24) |
             (((const unsigned char *)data)[1] << 16) |
-            (((const unsigned char *)data)[2] << 8 ) | 
+            (((const unsigned char *)data)[2] << 8 ) |
             (((const unsigned char *)data)[3] << 0 );
     } else {
-        return  
+        return
             (((const char *)data)[3] << 24) |
             (((const unsigned char *)data)[2] << 16) |
-            (((const unsigned char *)data)[1] << 8 ) | 
+            (((const unsigned char *)data)[1] << 8 ) |
             (((const unsigned char *)data)[0] << 0 );
     }
 }
@@ -262,100 +293,150 @@ get32u(const void * const data,
 
 
 
-static void
-printFormatNumber(FILE *       const fileP, 
-                  const void * const ValuePtr, 
-                  int          const Format,
-                  int          const ByteCount,
-                  ByteOrder    const byteOrder) {
+static const char *
+numberTraceValue(const void * const valueP,
+                 int          const format,
+                 unsigned int const byteCt,
+                 ByteOrder    const byteOrder) {
 /*--------------------------------------------------------------------------
-   Display a number as one of its many formats
+   Format for display a number represented in any of the numeric formats
 --------------------------------------------------------------------------*/
-    switch(Format){
+    const char * retval;
+
+    switch(format) {
     case FMT_SBYTE:
     case FMT_BYTE:
-        fprintf(fileP, "%02x\n", *(unsigned char *)ValuePtr);
+        pm_asprintf(&retval, "%02x", *(unsigned char *)valueP);
         break;
     case FMT_USHORT:
-        fprintf(fileP, "%d\n",get16u(ValuePtr, byteOrder));
+        pm_asprintf(&retval, "%d",get16u(valueP, byteOrder));
         break;
-    case FMT_ULONG:     
+    case FMT_ULONG:
     case FMT_SLONG:
-        fprintf(fileP, "%d\n",get32s(ValuePtr, byteOrder));
+        pm_asprintf(&retval, "%d",get32s(valueP, byteOrder));
         break;
-    case FMT_SSHORT:    
-        fprintf(fileP, "%hd\n",(signed short)get16u(ValuePtr, byteOrder));
+    case FMT_SSHORT:
+        pm_asprintf(&retval, "%hd",(signed short)get16u(valueP, byteOrder));
         break;
     case FMT_URATIONAL:
-    case FMT_SRATIONAL: 
-        fprintf(fileP, "%d/%d\n",get32s(ValuePtr, byteOrder),
-                get32s(4+(char *)ValuePtr, byteOrder));
+    case FMT_SRATIONAL:
+        pm_asprintf(&retval, "%d/%d",
+                    get32s(valueP, byteOrder),
+                    get32s(4+(char *)valueP,
+                           byteOrder));
         break;
-    case FMT_SINGLE:    
-        fprintf(fileP, "%f\n",(double)*(float *)ValuePtr);
+    case FMT_SINGLE:
+        pm_asprintf(&retval, "%f",(double)*(float *)valueP);
         break;
     case FMT_DOUBLE:
-        fprintf(fileP, "%f\n",*(double *)ValuePtr);
+        pm_asprintf(&retval, "%f",*(double *)valueP);
         break;
-    default: 
-        fprintf(fileP, "Unknown format %d:", Format);
-        {
-            unsigned int a;
-            for (a = 0; a < ByteCount && a < 16; ++a)
-                printf("%02x", ((unsigned char *)ValuePtr)[a]);
+    default: {
+        char * hex;
+
+        MALLOCARRAY(hex, byteCt*2 + 1);
+        if (!hex)
+            retval = pm_strsol;
+        else {
+            unsigned int i;
+            for (i = 0; i < byteCt && i < 16; ++i) {
+                sprintf(&hex[i*2], "%02x",
+                        ((const unsigned char *)valueP)[i]);
+            }
+            pm_asprintf(&retval, "Unknown format %d: %s", format, hex);
         }
-        fprintf(fileP, "\n");
     }
+    }
+    return retval;
 }
 
 
 
 static double
-convertAnyFormat(const void * const ValuePtr,
-                 int          const Format,
-                 ByteOrder    const byteOrder) {
+numericValue(const void * const valuePtr,
+             int          const format,
+             ByteOrder    const byteOrder) {
 /*--------------------------------------------------------------------------
    Evaluate number, be it int, rational, or float from directory.
 --------------------------------------------------------------------------*/
-    double Value;
-    Value = 0;
+    double value;
 
-    switch(Format){
+    switch(format) {
     case FMT_SBYTE:
-        Value = *(signed char *)ValuePtr;
+        value = *(signed char *)valuePtr;
         break;
     case FMT_BYTE:
-        Value = *(unsigned char *)ValuePtr;
+        value = *(unsigned char *)valuePtr;
         break;
     case FMT_USHORT:
-        Value = get16u(ValuePtr, byteOrder);
+        value = get16u(valuePtr, byteOrder);
         break;
     case FMT_ULONG:
-        Value = get32u(ValuePtr, byteOrder);
+        value = get32u(valuePtr, byteOrder);
         break;
     case FMT_URATIONAL:
     case FMT_SRATIONAL: {
         int num, den;
-        num = get32s(ValuePtr, byteOrder);
-        den = get32s(4+(char *)ValuePtr, byteOrder);
-        Value = den == 0 ? 0 : (double)(num/den);
+        num = get32s(valuePtr, byteOrder);
+        den = get32s(4+(char *)valuePtr, byteOrder);
+        value = den == 0 ? 0 : (double)(num/den);
     } break;
     case FMT_SSHORT:
-        Value = (signed short)get16u(ValuePtr, byteOrder);
+        value = (signed short)get16u(valuePtr, byteOrder);
         break;
     case FMT_SLONG:
-        Value = get32s(ValuePtr, byteOrder);
+        value = get32s(valuePtr, byteOrder);
         break;
 
     /* Not sure if this is correct (never seen float used in Exif format) */
     case FMT_SINGLE:
-        Value = (double)*(float *)ValuePtr;
+        value = (double)*(float *)valuePtr;
         break;
     case FMT_DOUBLE:
-        Value = *(double *)ValuePtr;
+        value = *(double *)valuePtr;
         break;
     }
-    return Value;
+    return value;
+}
+
+
+
+static const char *
+stringTraceValue(const unsigned char * const value,
+                 unsigned int          const valueSz) {
+
+    const char * retval;
+    char * buffer;
+
+    MALLOCARRAY(buffer, valueSz + 1);
+    if (!buffer)
+        retval = pm_strsol;
+    else {
+        unsigned int i;
+        bool noPrint;
+            /* We're in a sequence of unprintable characters.  We put one
+               '?' in the value for the whole sequence.
+            */
+        unsigned int outCursor;
+
+        outCursor = 0;  /* initial value */
+
+        for (i = 0, noPrint = false; i < valueSz; ++i) {
+            if (ISPRINT(value[i])) {
+                buffer[outCursor++] = value[i];
+                noPrint = false;
+            } else {
+                if (!noPrint) {
+                    buffer[outCursor++] = '?';
+                    noPrint = true;
+                }
+            }
+        }
+        buffer[outCursor++] = '\0';
+
+        retval = buffer;
+    }
+    return retval;
 }
 
 
@@ -363,72 +444,187 @@ convertAnyFormat(const void * const ValuePtr,
 static void
 traceTag(int                   const tag,
          int                   const format,
-         const unsigned char * const valuePtr,
-         unsigned int          const byteCount,
+         const unsigned char * const value,
+         unsigned int          const valueSz,
          ByteOrder             const byteOrder) {
-             
-    /* Show tag name */
-    unsigned int a;
-    bool found;
-    for (a = 0, found = false; !found; ++a){
-        if (tagTable[a].Tag == 0){
-            fprintf(stderr, "  Unknown Tag %04x Value = ", tag);
-            found = true;
-        }
-        if (tagTable[a].Tag == tag){
-            fprintf(stderr, "    %s = ",tagTable[a].Desc);
-            found = true;
-        }
+
+    const char * tagNm;
+    const char * tagValue;
+    unsigned int i;
+
+    for (i = 0, tagNm = NULL; tagTable[i].tag; ++i) {
+        if (tagTable[i].tag == tag)
+            tagNm = pm_strdup(tagTable[i].desc);
     }
 
+    if (!tagNm)
+        pm_asprintf(&tagNm, "Unknown Tag %04x", tag);
+
     /* Show tag value. */
-    switch(format){
+    switch (format) {
 
     case FMT_UNDEFINED:
         /* Undefined is typically an ascii string. */
-
     case FMT_STRING: {
-        /* String arrays printed without function call
-           (different from int arrays)
-        */
-        bool noPrint;
-        printf("\"");
-        for (a = 0, noPrint = false; a < byteCount; ++a){
-            if (ISPRINT((valuePtr)[a])){
-                fprintf(stderr, "%c", valuePtr[a]);
-                noPrint = false;
-            } else {
-                /* Avoiding indicating too many unprintable characters of
-                   proprietary bits of binary information this program may not
-                   know how to parse.
-                */
-                if (!noPrint){
-                    fprintf(stderr, "?");
-                    noPrint = true;
-                }
-            }
-        }
-        fprintf(stderr, "\"\n");
+        tagValue = stringTraceValue(value, valueSz);
     } break;
 
     default:
         /* Handle arrays of numbers later (will there ever be?)*/
-        printFormatNumber(stderr, valuePtr, format, byteCount, byteOrder);
+        tagValue = numberTraceValue(value, format, valueSz, byteOrder);
     }
+    pm_message("%s = \"%s\"", tagNm, tagValue);
+
+    pm_strfree(tagValue);
+    pm_strfree(tagNm);
+}
+
+
+
+static void
+initializeIfd(exif_ifd * const ifdP) {
+
+    ifdP->cameraMake        = NULL;
+    ifdP->cameraModel       = NULL;
+    ifdP->dateTime          = NULL;
+    ifdP->xResolutionP      = NULL;
+    ifdP->yResolutionP      = NULL;
+    ifdP->orientationP      = NULL;
+    ifdP->isColorP          = NULL;
+    ifdP->flashP            = NULL;
+    ifdP->focalLengthP      = NULL;
+    ifdP->exposureTimeP     = NULL;
+    ifdP->shutterSpeedP     = NULL;
+    ifdP->apertureFNumberP  = NULL;
+    ifdP->distanceP         = NULL;
+    ifdP->exposureBiasP     = NULL;
+    ifdP->whiteBalanceP     = NULL;
+    ifdP->meteringModeP     = NULL;
+    ifdP->exposureProgramP  = NULL;
+    ifdP->isoEquivalentP    = NULL;
+    ifdP->compressionLevelP = NULL;
+    ifdP->comments          = NULL;
+    ifdP->thumbnailOffsetP  = NULL;
+    ifdP->thumbnailLengthP  = NULL;
+    ifdP->exifImageLengthP  = NULL;
+    ifdP->exifImageWidthP   = NULL;
+    ifdP->focalPlaneXResP   = NULL;
+    ifdP->focalPlaneUnitsP  = NULL;
+    ifdP->thumbnail         = NULL;
+}
+
+
+
+static void
+freeIfPresent(const void * const arg) {
+
+    if (arg)
+        free((void *)arg);
+}
+
+
+
+static void
+strfreeIfPresent(const char * const arg) {
+
+    if (arg)
+        pm_strfree(arg);
+}
+
+
+
+static void
+terminateIfd(exif_ifd * const ifdP) {
+
+    strfreeIfPresent(ifdP->cameraMake  );
+    strfreeIfPresent(ifdP->cameraModel );
+    strfreeIfPresent(ifdP->dateTime    );
+    strfreeIfPresent(ifdP->comments    );
+    freeIfPresent(ifdP->xResolutionP      );
+    freeIfPresent(ifdP->yResolutionP      );
+    freeIfPresent(ifdP->orientationP      );
+    freeIfPresent(ifdP->isColorP          );
+    freeIfPresent(ifdP->flashP            );
+    freeIfPresent(ifdP->focalLengthP      );
+    freeIfPresent(ifdP->exposureTimeP     );
+    freeIfPresent(ifdP->shutterSpeedP     );
+    freeIfPresent(ifdP->apertureFNumberP  );
+    freeIfPresent(ifdP->distanceP         );
+    freeIfPresent(ifdP->exposureBiasP     );
+    freeIfPresent(ifdP->whiteBalanceP     );
+    freeIfPresent(ifdP->meteringModeP     );
+    freeIfPresent(ifdP->exposureProgramP  );
+    freeIfPresent(ifdP->isoEquivalentP    );
+    freeIfPresent(ifdP->compressionLevelP );
+    freeIfPresent(ifdP->thumbnailOffsetP  );
+    freeIfPresent(ifdP->thumbnailLengthP  );
+    freeIfPresent(ifdP->exifImageLengthP  );
+    freeIfPresent(ifdP->exifImageWidthP   );
+    freeIfPresent(ifdP->focalPlaneXResP   );
+    freeIfPresent(ifdP->focalPlaneUnitsP  );
+}
+
+
+
+static const char *
+commentValue(const unsigned char * const valuePtr,
+             unsigned int          const valueSz) {
+
+    /* Olympus has this padded with trailing spaces.  We stop the copy
+       where those start.
+    */
+    const char * const value = (const char *)valuePtr;
+
+    const char * retval;
+    char * buffer;  /* malloc'ed */
+    unsigned int cursor;
+    unsigned int end;
+
+    for (end = valueSz; end > 0 && value[end] == ' '; --end);
+
+    /* Skip "ASCII" if it is there */
+    if (end >= 5 && memeq(value, "ASCII", 5))
+        cursor = 5;
+    else
+        cursor = 0;
+
+    /* Skip consecutive blanks and NULs */
+
+    for (;
+         cursor < valueSz &&
+             (value[cursor] == '\0' || value[cursor] == ' ');
+         ++cursor);
+
+    /* Copy the rest as the comment */
+
+    MALLOCARRAY(buffer, end - cursor + 1);
+    if (!buffer)
+        retval = pm_strsol;
+    else {
+        unsigned int outCursor;
+        for (outCursor = 0; cursor < end; ++cursor)
+            buffer[outCursor++] = value[cursor];
+
+        buffer[outCursor++] = '\0';
+
+        retval = buffer;
+    }
+    return retval;
 }
 
 
 
 /* Forward declaration for recursion */
 
-static void 
-processExifDir(const unsigned char *  const ExifData, 
-               unsigned int           const ExifLength,
-               unsigned int           const DirOffset,
-               exif_ImageInfo *       const imageInfoP, 
-               ByteOrder              const byteOrder,
-               bool                   const wantTagTrace,
-               const unsigned char ** const LastExifRefdP);
+static void
+processIfd(const unsigned char *  const exifData,
+           unsigned int           const exifLength,
+           const unsigned char *  const ifdData,
+           ByteOrder              const byteOrder,
+           bool                   const wantTagTrace,
+           exif_ifd *             const ifdP,
+           const unsigned char ** const nextIfdPP,
+           const char **          const errorP);
 
 
 static void
@@ -437,11 +633,8 @@ processDirEntry(const unsigned char *  const dirEntry,
                 unsigned int           const exifLength,
                 ByteOrder              const byteOrder,
                 bool                   const wantTagTrace,
-                exif_ImageInfo *       const imageInfoP, 
-                unsigned int *         const thumbnailOffsetP,
-                unsigned int *         const thumbnailSizeP,
-                bool *                 const haveThumbnailP,
-                const unsigned char ** const lastExifRefdP) {
+                exif_ifd *             const ifdP,
+                const char **          const errorP) {
 
     int const tag        = get16u(&dirEntry[0], byteOrder);
     int const format     = get16u(&dirEntry[2], byteOrder);
@@ -452,27 +645,29 @@ processDirEntry(const unsigned char *  const dirEntry,
            other types when used.  But we use it as a byte-by-byte cursor, so
            we declare it as a pointer to a generic byte here.
         */
-    unsigned int byteCount;
+    unsigned int valueSz;
+
+    *errorP = NULL;  /* initial assumption */
 
     if ((format-1) >= NUM_FORMATS) {
         /* (-1) catches illegal zero case as unsigned underflows
-           to positive large.  
+           to positive large.
         */
         pm_message("Illegal number format %d for tag %04x", format, tag);
         return;
     }
-        
-    byteCount = components * bytesPerFormat[format];
 
-    if (byteCount > 4){
+    valueSz = components * bytesPerFormat[format];
+
+    if (valueSz > 4) {
         unsigned const offsetVal = get32u(&dirEntry[8], byteOrder);
         /* If its bigger than 4 bytes, the dir entry contains an offset.*/
-        if (offsetVal + byteCount > exifLength){
+        if (offsetVal + valueSz > exifLength) {
             /* Bogus pointer offset and / or bytecount value */
             pm_message("Illegal pointer offset value in EXIF "
                        "for tag %04x.  "
                        "Offset %d bytes %d ExifLen %d\n",
-                       tag, offsetVal, byteCount, exifLength);
+                       tag, offsetVal, valueSz, exifLength);
             return;
         }
         valuePtr = &exifData[offsetVal];
@@ -481,366 +676,361 @@ processDirEntry(const unsigned char *  const dirEntry,
         valuePtr = &dirEntry[8];
     }
 
-    if (*lastExifRefdP < valuePtr + byteCount){
-        /* Keep track of last byte in the exif header that was actually
-           referenced.  That way, we know where the discardable thumbnail data
-           begins.
-        */
-        *lastExifRefdP = valuePtr + byteCount;
-    }
-
     if (wantTagTrace)
-        traceTag(tag, format, valuePtr, byteCount, byteOrder);
-
-    *haveThumbnailP = (tag == TAG_THUMBNAIL_OFFSET);
-
+        traceTag(tag, format, valuePtr, valueSz, byteOrder);
+    /* TODO: Need to deal with nonterminated strings in tag value */
+    /* TODO: Deal with repeated tag */
     /* Extract useful components of tag */
-    switch (tag){
-
+    switch (tag) {
     case TAG_MAKE:
-        STRSCPY(imageInfoP->CameraMake, (const char*)valuePtr);
+        ifdP->cameraMake = pm_strdup((const char*)valuePtr);
         break;
 
     case TAG_MODEL:
-        STRSCPY(imageInfoP->CameraModel, (const char*)valuePtr);
+        ifdP->cameraModel = pm_strdup((const char*)valuePtr);
         break;
 
     case TAG_XRESOLUTION:
-        imageInfoP->XResolution = 
-            convertAnyFormat(valuePtr, format, byteOrder);
+        MALLOCVAR_NOFAIL(ifdP->xResolutionP);
+        *ifdP->xResolutionP = numericValue(valuePtr, format, byteOrder);
         break;
 
     case TAG_YRESOLUTION:
-        imageInfoP->YResolution = 
-            convertAnyFormat(valuePtr, format, byteOrder);
+        MALLOCVAR_NOFAIL(ifdP->yResolutionP);
+        *ifdP->yResolutionP = numericValue(valuePtr, format, byteOrder);
         break;
 
     case TAG_DATETIME_ORIGINAL:
-        STRSCPY(imageInfoP->DateTime, (const char*)valuePtr);
-        imageInfoP->DatePointer = (const char*)valuePtr;
+        ifdP->dateTime = pm_strdup((const char*)valuePtr);
         break;
 
-    case TAG_USERCOMMENT: {
-        /* Olympus has this padded with trailing spaces.  We stop the copy
-           where those start.
-        */
-        const char * const value = (const char *)valuePtr;
-
-        unsigned int cursor;
-        unsigned int outCursor;
-        unsigned int end;
-
-        for (end = byteCount; end > 0 && value[end] == ' '; --end);
-
-        /* Skip "ASCII" if it is there */
-        if (end >= 5 && MEMEQ(value, "ASCII", 5))
-            cursor = 5;
-        else
-            cursor = 0;
-
-        /* Skip consecutive blanks and NULs */
-
-        for (;
-             cursor < byteCount && 
-                 (value[cursor] == '\0' || value[cursor] == ' ');
-             ++cursor);
-
-        /* Copy the rest as the comment */
-
-        for (outCursor = 0;
-             cursor < end && outCursor < MAX_COMMENT-1;
-             ++cursor)
-            imageInfoP->Comments[outCursor++] = value[cursor];
-
-        imageInfoP->Comments[outCursor++] = '\0';
-    } break;
+    case TAG_USERCOMMENT:
+        ifdP->comments = commentValue(valuePtr, valueSz);
+        break;
 
     case TAG_FNUMBER:
         /* Simplest way of expressing aperture, so I trust it the most.
-           (overwrite previously computd value if there is one)
+           (replace any existing value, as it will be based on a less useful
+           tag that came earlier in the IFD).
         */
-        imageInfoP->ApertureFNumber = 
-            (float)convertAnyFormat(valuePtr, format, byteOrder);
+        if (ifdP->apertureFNumberP)
+            free(ifdP->apertureFNumberP);
+
+        MALLOCVAR_NOFAIL(ifdP->apertureFNumberP);
+        *ifdP->apertureFNumberP =
+            (float)numericValue(valuePtr, format, byteOrder);
         break;
 
     case TAG_APERTURE:
     case TAG_MAXAPERTURE:
-        /* More relevant info always comes earlier, so only use this field if
-           we don't have appropriate aperture information yet.
+        /* If we already have aperture information, it probably came from an
+           FNUMBER tag and is superior, so we leave it alone
         */
-        if (imageInfoP->ApertureFNumber == 0){
-            imageInfoP->ApertureFNumber = (float)
-                exp(convertAnyFormat(valuePtr, format, byteOrder)
+        if (!ifdP->apertureFNumberP) {
+            MALLOCVAR_NOFAIL(ifdP->apertureFNumberP);
+            *ifdP->apertureFNumberP = (float)
+                exp(numericValue(valuePtr, format, byteOrder)
                     * log(2) * 0.5);
         }
         break;
 
     case TAG_FOCALLENGTH:
         /* Nice digital cameras actually save the focal length
-           as a function of how farthey are zoomed in. 
+           as a function of how farthey are zoomed in.
         */
 
-        imageInfoP->FocalLength = 
-            (float)convertAnyFormat(valuePtr, format, byteOrder);
+        MALLOCVAR_NOFAIL(ifdP->focalLengthP);
+        *ifdP->focalLengthP =
+            (float)numericValue(valuePtr, format, byteOrder);
         break;
 
     case TAG_SUBJECT_DISTANCE:
         /* Inidcates the distacne the autofocus camera is focused to.
            Tends to be less accurate as distance increases.
         */
-        imageInfoP->Distance = 
-            (float)convertAnyFormat(valuePtr, format, byteOrder);
+        MALLOCVAR_NOFAIL(ifdP->distanceP);
+        *ifdP->distanceP =
+            (float)numericValue(valuePtr, format, byteOrder);
         break;
 
     case TAG_EXPOSURETIME:
-        /* Simplest way of expressing exposure time, so I
-           trust it most.  (overwrite previously computd value
-           if there is one) 
-        */
-        imageInfoP->ExposureTime = 
-            (float)convertAnyFormat(valuePtr, format, byteOrder);
+        MALLOCVAR_NOFAIL(ifdP->exposureTimeP);
+        *ifdP->exposureTimeP =
+            (float)numericValue(valuePtr, format, byteOrder);
         break;
 
     case TAG_SHUTTERSPEED:
-        /* More complicated way of expressing exposure time,
-           so only use this value if we don't already have it
-           from somewhere else.  
-        */
-        if (imageInfoP->ExposureTime == 0){
-            imageInfoP->ExposureTime = (float)
-                (1/exp(convertAnyFormat(valuePtr, format, byteOrder)
-                       * log(2)));
-        }
+        MALLOCVAR_NOFAIL(ifdP->shutterSpeedP);
+        *ifdP->shutterSpeedP =
+            1 << (unsigned int)numericValue(valuePtr, format, byteOrder);
         break;
 
-    case TAG_FLASH:
-        if ((int)convertAnyFormat(valuePtr, format, byteOrder) & 0x7){
-            imageInfoP->FlashUsed = TRUE;
-        }else{
-            imageInfoP->FlashUsed = FALSE;
-        }
-        break;
+    case TAG_FLASH: {
+        unsigned int const tagValue =
+            (unsigned int)numericValue(valuePtr, format, byteOrder);
+
+        MALLOCVAR_NOFAIL(ifdP->flashP);
+
+        *ifdP->flashP = ((tagValue & 0x7) != 0);
+
+    } break;
 
-    case TAG_ORIENTATION:
-        imageInfoP->Orientation = 
-            (int)convertAnyFormat(valuePtr, format, byteOrder);
-        if (imageInfoP->Orientation < 1 || 
-            imageInfoP->Orientation > 8){
-            pm_message("Undefined rotation value %d",
-                       imageInfoP->Orientation);
-            imageInfoP->Orientation = 0;
+    case TAG_ORIENTATION: {
+        unsigned int const tagValue =
+            (unsigned int)numericValue(valuePtr, format, byteOrder);
+
+        if (tagValue < 1 || tagValue > 8)
+            pm_asprintf(errorP, "Unrecognized orientation value %d",
+                        tagValue);
+        else {
+            MALLOCVAR_NOFAIL(ifdP->orientationP);
+
+            switch (tagValue) {
+            case 1: *ifdP->orientationP = ORIENT_NORMAL;     break;
+            case 2: *ifdP->orientationP = ORIENT_FLIP_HORIZ; break;
+            case 3: *ifdP->orientationP = ORIENT_ROTATE_180; break;
+            case 4: *ifdP->orientationP = ORIENT_FLIP_VERT;  break;
+            case 5: *ifdP->orientationP = ORIENT_TRANSPOSE;  break;
+            case 6: *ifdP->orientationP = ORIENT_ROTATE_90;  break;
+            case 7: *ifdP->orientationP = ORIENT_TRANSVERSE; break;
+            case 8: *ifdP->orientationP = ORIENT_ROTATE_270; break;
+            default:
+                assert(false);
+            }
         }
-        break;
+        } break;
 
     case TAG_EXIF_IMAGELENGTH:
+        MALLOCVAR_NOFAIL(ifdP->exifImageLengthP);
+        *ifdP->exifImageLengthP =
+            (unsigned int)numericValue(valuePtr, format, byteOrder);
+        break;
+
     case TAG_EXIF_IMAGEWIDTH:
-        /* Use largest of height and width to deal with images
-           that have been rotated to portrait format.  
-        */
-        ExifImageWidth =
-            MIN(ExifImageWidth,
-                (int)convertAnyFormat(valuePtr, format, byteOrder));
+        MALLOCVAR_NOFAIL(ifdP->exifImageWidthP);
+        *ifdP->exifImageWidthP =
+            (unsigned int)numericValue(valuePtr, format, byteOrder);
         break;
 
     case TAG_FOCALPLANEXRES:
-        HaveXRes = TRUE;
-        FocalplaneXRes = convertAnyFormat(valuePtr, format, byteOrder);
+        MALLOCVAR_NOFAIL(ifdP->focalPlaneXResP);
+        *ifdP->focalPlaneXResP = numericValue(valuePtr, format, byteOrder);
         break;
 
-    case TAG_FOCALPLANEUNITS:
-        switch((int)convertAnyFormat(valuePtr, format, byteOrder)){
-        case 1: FocalplaneUnits = 25.4; break; /* 1 inch */
-        case 2: 
-            /* According to the information I was using, 2
-               means meters.  But looking at the Cannon
-               powershot's files, inches is the only
-               sensible value.  
-            */
-            FocalplaneUnits = 25.4;
-            break;
+    case TAG_FOCALPLANEUNITS: {
+        int const tagValue = (int)numericValue(valuePtr, format, byteOrder);
 
-        case 3: FocalplaneUnits = 10;   break;  /* 1 centimeter*/
-        case 4: FocalplaneUnits = 1;    break;  /* 1 millimeter*/
-        case 5: FocalplaneUnits = .001; break;  /* 1 micrometer*/
+        if (tagValue < 1 || tagValue > 5) {
+            pm_asprintf(errorP, "Unrecognized FOCALPLANEUNITS value %d.  "
+                        "We know only 1, 2, 3, 4, and 5",
+                        tagValue);
+        } else {
+            MALLOCVAR_NOFAIL(ifdP->focalPlaneUnitsP);
+
+            switch (tagValue) {
+            case 1: *ifdP->focalPlaneUnitsP = 25.4;  break; /* 1 inch */
+            case 2: *ifdP->focalPlaneUnitsP = 100.0; break; /* 1 meter */
+            case 3: *ifdP->focalPlaneUnitsP = 10.0;  break;  /* 1 centimeter*/
+            case 4: *ifdP->focalPlaneUnitsP = 1.0;   break;  /* 1 millimeter*/
+            case 5: *ifdP->focalPlaneUnitsP = .001;  break;  /* 1 micrometer*/
+            }
+            /* According to the information I was using, 2 means meters.  But
+               looking at the Cannon powershot's files, inches is the only
+               sensible value.
+            */
         }
-        break;
+    } break;
 
         /* Remaining cases contributed by: Volker C. Schoech
            (schoech@gmx.de)
         */
 
     case TAG_EXPOSURE_BIAS:
-        imageInfoP->ExposureBias = 
-            (float) convertAnyFormat(valuePtr, format, byteOrder);
+        MALLOCVAR_NOFAIL(ifdP->exposureBiasP);
+        *ifdP->exposureBiasP =
+            (float) numericValue(valuePtr, format, byteOrder);
         break;
 
     case TAG_WHITEBALANCE:
-        imageInfoP->Whitebalance = 
-            (int)convertAnyFormat(valuePtr, format, byteOrder);
+        MALLOCVAR_NOFAIL(ifdP->whiteBalanceP);
+        *ifdP->whiteBalanceP = (int)numericValue(valuePtr, format, byteOrder);
         break;
 
     case TAG_METERING_MODE:
-        imageInfoP->MeteringMode = 
-            (int)convertAnyFormat(valuePtr, format, byteOrder);
+        MALLOCVAR_NOFAIL(ifdP->meteringModeP);
+        *ifdP->meteringModeP = (int)numericValue(valuePtr, format, byteOrder);
         break;
 
     case TAG_EXPOSURE_PROGRAM:
-        imageInfoP->ExposureProgram = 
-            (int)convertAnyFormat(valuePtr, format, byteOrder);
+        MALLOCVAR_NOFAIL(ifdP->exposureProgramP);
+        *ifdP->exposureProgramP =
+            (int)numericValue(valuePtr, format, byteOrder);
         break;
 
-    case TAG_ISO_EQUIVALENT:
-        imageInfoP->ISOequivalent = 
-            (int)convertAnyFormat(valuePtr, format, byteOrder);
-        if ( imageInfoP->ISOequivalent < 50 ) 
-            imageInfoP->ISOequivalent *= 200;
-        break;
+    case TAG_ISO_EQUIVALENT: {
+        int const tagValue = (int)numericValue(valuePtr, format, byteOrder);
+
+        MALLOCVAR_NOFAIL(ifdP->isoEquivalentP);
+        if (tagValue < 50)
+            *ifdP->isoEquivalentP = tagValue * 200;
+        else
+            *ifdP->isoEquivalentP = tagValue;
+    } break;
 
     case TAG_COMPRESSION_LEVEL:
-        imageInfoP->CompressionLevel = 
-            (int)convertAnyFormat(valuePtr, format, byteOrder);
+        MALLOCVAR_NOFAIL(ifdP->compressionLevelP);
+        *ifdP->compressionLevelP =
+            (int)numericValue(valuePtr, format, byteOrder);
         break;
 
     case TAG_THUMBNAIL_OFFSET:
-        *thumbnailOffsetP = (unsigned int)
-            convertAnyFormat(valuePtr, format, byteOrder);
+        MALLOCVAR_NOFAIL(ifdP->thumbnailOffsetP);
+        *ifdP->thumbnailOffsetP = (unsigned int)
+            numericValue(valuePtr, format, byteOrder);
         break;
 
     case TAG_THUMBNAIL_LENGTH:
-        *thumbnailSizeP = (unsigned int)
-            convertAnyFormat(valuePtr, format, byteOrder);
+        MALLOCVAR_NOFAIL(ifdP->thumbnailLengthP);
+        *ifdP->thumbnailLengthP = (unsigned int)
+            numericValue(valuePtr, format, byteOrder);
         break;
 
     case TAG_EXIF_OFFSET:
     case TAG_INTEROP_OFFSET: {
-        unsigned int const subdirOffset = get32u(valuePtr, byteOrder);
-        if (subdirOffset >= exifLength)
-            pm_message("Illegal exif or interop offset "
+        unsigned int const subIfdOffset = get32u(valuePtr, byteOrder);
+        if (subIfdOffset + 4 > exifLength)
+            pm_message("Invalid exif or interop offset "
                        "directory link.  Offset is %u, "
                        "but Exif data is only %u bytes.",
-                       subdirOffset, exifLength);
-        else
-            processExifDir(exifData, exifLength, subdirOffset, 
-                           imageInfoP, byteOrder, wantTagTrace,
-                           lastExifRefdP);
+                       subIfdOffset, exifLength);
+        else {
+            /* Process the chain of IFDs starting at 'subIfdOffset'.
+               Merge whatever tags are in them into *ifdP
+            */
+            const unsigned char * nextIfdP;
+
+            for (nextIfdP = exifData + subIfdOffset; nextIfdP;) {
+                const char * error;
+
+                if (wantTagTrace)
+                    pm_message("Processing subIFD");
+
+                processIfd(exifData, exifLength, exifData + subIfdOffset,
+                           byteOrder, wantTagTrace,
+                           ifdP, &nextIfdP, &error);
+
+                if (error) {
+                    pm_asprintf(errorP, "Failed to process "
+                                "ExifOffset/InteropOffset tag.  %s", error);
+                    pm_strfree(error);
+                }
+            }
+        }
     } break;
     }
 }
 
 
 
-static void 
-processExifDir(const unsigned char *  const exifData, 
-               unsigned int           const exifLength,
-               unsigned int           const dirOffset,
-               exif_ImageInfo *       const imageInfoP, 
-               ByteOrder              const byteOrder,
-               bool                   const wantTagTrace,
-               const unsigned char ** const lastExifRefdP) {
+static void
+locateNextIfd(const unsigned char *  const exifData,
+              unsigned int           const exifLength,
+              ByteOrder              const byteOrder,
+              const unsigned char *  const nextIfdLinkPtr,
+              const unsigned char ** const nextIfdPP,
+              const char **          const errorP) {
+
+    if (nextIfdLinkPtr + 4 > exifData + exifLength)
+        pm_asprintf(errorP, "EXIF header ends before next-IFD link");
+    else {
+        if (nextIfdLinkPtr + 4 <= exifData + exifLength) {
+            unsigned int const nextIfdLink =
+                get32u(nextIfdLinkPtr, byteOrder);
+                /* Offset in EXIF header of next IFD, or zero if none */
+
+            if (nextIfdLink) {
+                if (nextIfdLink + 4 >= exifLength) {
+                    pm_asprintf(errorP, "Next IFD link is %u, "
+                                "but EXIF header is only %u bytes long",
+                                nextIfdLink, exifLength);
+                } else
+                    *nextIfdPP = exifData + nextIfdLink;
+            } else
+                *nextIfdPP = NULL;
+        }
+    }
+}
+
+
+
+static void
+processIfd(const unsigned char *  const exifData,
+           unsigned int           const exifLength,
+           const unsigned char *  const ifdData,
+           ByteOrder              const byteOrder,
+           bool                   const wantTagTrace,
+           exif_ifd *             const ifdP,
+           const unsigned char ** const nextIfdPP,
+           const char **          const errorP) {
 /*--------------------------------------------------------------------------
-   Process one of the nested EXIF directories.
+   Process one EXIF IFD (Image File Directory).
+
+   The text of the IFD is at 'ifdData'.
+
+   The text of the EXIF header of which the IFD is part is the 'exifLength'
+   bytes at 'exifData'.
+
+   Return the contents of the directory (tags) as *ifdP.
+
+   Return as *nextIfdPP a pointer into the EXIF header at 'exifData'
+   to the next IFD in the chain, or NULL if this is the last IFD.
 --------------------------------------------------------------------------*/
-    const unsigned char * const dirStart = exifData + dirOffset;
-    unsigned int const numDirEntries = get16u(&dirStart[0], byteOrder);
+    unsigned int const numDirEntries = get16u(&ifdData[0], byteOrder);
+
     unsigned int de;
-    bool haveThumbnail;
-    unsigned int thumbnailOffset;
-    unsigned int thumbnailSize;
-
-    #define DIR_ENTRY_ADDR(Start, Entry) (Start+2+12*(Entry))
-
-    {
-        const unsigned char * const dirEnd =
-            DIR_ENTRY_ADDR(dirStart, numDirEntries);
-        if (dirEnd + 4 > (exifData + exifLength)){
-            if (dirEnd + 2 == exifData + exifLength || 
-                dirEnd == exifData + exifLength){
-                /* Version 1.3 of jhead would truncate a bit too much.
-                   This also caught later on as well.
-                */
-            }else{
-                /* Note: Files that had thumbnails trimmed with jhead
-                   1.3 or earlier might trigger this.
-                */
-                pm_message("Illegal directory entry size");
-                return;
-            }
-        }
-        *lastExifRefdP = MAX(*lastExifRefdP, dirEnd);
-    }
+
+    *errorP = NULL;  /* initial value */
+
+    #define DIR_ENTRY_ADDR(Start, Entry) (Start + 2 + 12*(Entry))
 
     if (wantTagTrace)
-        pm_message("Directory with %d entries", numDirEntries);
-
-    haveThumbnail   = false;  /* initial value */
-    thumbnailOffset = 0;      /* initial value */
-    thumbnailSize   = 0;      /* initial value */
-
-    for (de = 0; de < numDirEntries; ++de)
-        processDirEntry(DIR_ENTRY_ADDR(dirStart, de), exifData, exifLength,
-                        byteOrder, wantTagTrace, imageInfoP,
-                        &thumbnailOffset, &thumbnailSize, &haveThumbnail,
-                        lastExifRefdP);
-
-    if (haveThumbnail)
-        DirWithThumbnailPtrs = dirStart;
-
-    {
-        /* In addition to linking to subdirectories via exif tags,
-           there's also a potential link to another directory at the end
-           of each directory.  This has got to be the result of a
-           committee!  
-        */
-        if (DIR_ENTRY_ADDR(dirStart, numDirEntries) + 4 <= 
-            exifData + exifLength){
-            unsigned int const subdirOffset =
-                get32u(dirStart + 2 + 12*numDirEntries, byteOrder);
-            if (subdirOffset){
-                const unsigned char * const subdirStart =
-                    exifData + subdirOffset;
-                if (subdirStart > exifData + exifLength){
-                    if (subdirStart < exifData + exifLength + 20){
-                        /* Jhead 1.3 or earlier would crop the whole directory!
-                           As Jhead produces this form of format incorrectness,
-                           I'll just let it pass silently.
-                        */
-                        if (wantTagTrace) 
-                            printf("Thumbnail removed with "
-                                   "Jhead 1.3 or earlier\n");
-                    }else{
-                        pm_message("Illegal subdirectory link");
-                    }
-                }else{
-                    if (subdirOffset <= exifLength)
-                        processExifDir(exifData, exifLength, subdirOffset,
-                                       imageInfoP, byteOrder, wantTagTrace,
-                                       lastExifRefdP);
-                }
-            }
-        }else{
-            /* The exif header ends before the last next directory pointer. */
+        pm_message("Processing IFD at %p with %u entries",
+                   ifdData, numDirEntries);
+
+    for (de = 0; de < numDirEntries && !*errorP; ++de) {
+        const char * error;
+        processDirEntry(DIR_ENTRY_ADDR(ifdData, de), exifData, exifLength,
+                        byteOrder, wantTagTrace, ifdP,
+                        &error);
+
+        if (error) {
+            pm_asprintf(errorP, "Failed to process tag %u.  %s",
+                        de, error);
+            pm_strfree(error);
         }
     }
 
-    if (thumbnailSize && thumbnailOffset){
-        if (thumbnailSize + thumbnailOffset <= exifLength){
-            /* The thumbnail pointer appears to be valid.  Store it. */
-            imageInfoP->ThumbnailPointer = exifData + thumbnailOffset;
-            imageInfoP->ThumbnailSize = thumbnailSize;
+    locateNextIfd(exifData, exifLength, byteOrder,
+                  DIR_ENTRY_ADDR(ifdData, numDirEntries),
+                  nextIfdPP, errorP);
 
-            if (wantTagTrace){
-                fprintf(stderr, "Thumbnail size: %u bytes\n", thumbnailSize);
-            }
+    if (ifdP->thumbnailOffsetP && ifdP->thumbnailLengthP) {
+        if (*ifdP->thumbnailOffsetP + *ifdP->thumbnailLengthP <= exifLength) {
+            /* The thumbnail pointer appears to be valid.  Store it. */
+            ifdP->thumbnail     = exifData + *ifdP->thumbnailOffsetP;
+            ifdP->thumbnailSize = *ifdP->thumbnailLengthP;
         }
     }
+    if (wantTagTrace)
+        pm_message("Done processing IFD at %p", ifdData);
 }
 
 
 
-void 
+void
 exif_parse(const unsigned char * const exifData,
            unsigned int          const length,
-           exif_ImageInfo *      const imageInfoP, 
+           exif_ImageInfo *      const imageInfoP,
            bool                  const wantTagTrace,
            const char **         const errorP) {
 /*--------------------------------------------------------------------------
@@ -852,34 +1042,33 @@ exif_parse(const unsigned char * const exifData,
   'length' is the length of the Exif section.
 --------------------------------------------------------------------------*/
     ByteOrder byteOrder;
-    int FirstOffset;
-    const unsigned char * lastExifRefd;
+    unsigned int firstOffset;
 
     *errorP = NULL;  /* initial assumption */
 
     if (wantTagTrace)
-        fprintf(stderr, "Exif header %d bytes long\n",length);
+        pm_message("Exif header %u bytes long", length);
 
-    if (MEMEQ(exifData + 0, "II" , 2)) {
-        if (wantTagTrace) 
-            fprintf(stderr, "Exif header in Intel order\n");
-        byteOrder = NORMAL;
+    if (memeq(exifData + 0, "II" , 2)) {
+        if (wantTagTrace)
+            pm_message("Exif header in Intel order");
+        byteOrder = ORDER_NORMAL;
     } else {
-        if (MEMEQ(exifData + 0, "MM", 2)) {
-            if (wantTagTrace) 
-                fprintf(stderr, "Exif header in Motorola order\n");
-            byteOrder = MOTOROLA;
+        if (memeq(exifData + 0, "MM", 2)) {
+            if (wantTagTrace)
+                pm_message("Exif header in Motorola order");
+            byteOrder = ORDER_MOTOROLA;
         } else {
             pm_asprintf(errorP, "Invalid alignment marker in Exif "
                         "data.  First two bytes are '%c%c' (0x%02x%02x) "
-                        "instead of 'II' or 'MM'.", 
+                        "instead of 'II' or 'MM'.",
                         exifData[0], exifData[1], exifData[0], exifData[1]);
         }
     }
     if (!*errorP) {
         unsigned short const start = get16u(exifData + 2, byteOrder);
         /* Check the next value for correctness. */
-        if (start != 0x002a){
+        if (start != 0x002a) {
             pm_asprintf(errorP, "Invalid Exif header start.  "
                         "two bytes after the alignment marker "
                         "should be 0x002a, but is 0x%04x",
@@ -887,237 +1076,288 @@ exif_parse(const unsigned char * const exifData,
         }
     }
     if (!*errorP) {
-        FirstOffset = get32u(exifData + 4, byteOrder);
-        if (FirstOffset < 8 || FirstOffset > 16){
+        const char * error;
+        const unsigned char * nextIfdP;
+
+        firstOffset = get32u(exifData + 4, byteOrder);
+        if (firstOffset < 8 || firstOffset > 16) {
             /* I used to ensure this was set to 8 (website I used
-               indicated its 8) but PENTAX Optio 230 has it set
+               indicated it's 8) but PENTAX Optio 230 has it set
                differently, and uses it as offset. (Sept 11 2002)
-                */
+            */
             pm_message("Suspicious offset of first IFD value in Exif header");
         }
-        
-        imageInfoP->Comments[0] = '\0';  /* Initial value - null string */
-        
-        HaveXRes = FALSE;  /* Initial assumption */
-        FocalplaneUnits = 0;
-        ExifImageWidth = 0;
-        
-        lastExifRefd = exifData;
-        DirWithThumbnailPtrs = NULL;
-        
-        processExifDir(exifData, length, FirstOffset, 
-                       imageInfoP, byteOrder, wantTagTrace, &lastExifRefd);
-        
-        /* Compute the CCD width, in millimeters. */
-        if (HaveXRes){
-            imageInfoP->HaveCCDWidth = 1;
-            imageInfoP->CCDWidth = 
-                    (float)(ExifImageWidth * FocalplaneUnits / FocalplaneXRes);
-        } else
-            imageInfoP->HaveCCDWidth = 0;
-            
-        if (wantTagTrace){
-            fprintf(stderr, 
-                    "Non-settings part of Exif header: %lu bytes\n",
-                    (unsigned long)(exifData + length - lastExifRefd));
+
+        initializeIfd(&imageInfoP->mainImage);
+        initializeIfd(&imageInfoP->thumbnailImage);
+
+        if (wantTagTrace)
+            pm_message("Processing main image IFD (IFD0)");
+
+        processIfd(exifData, length, exifData + firstOffset, byteOrder,
+                   wantTagTrace,
+                   &imageInfoP->mainImage, &nextIfdP, &error);
+
+        if (error) {
+            pm_asprintf(errorP, "Failed to process main image IFD.  %s",
+                        error);
+            pm_strfree(error);
+        }
+
+        if (nextIfdP) {
+            const char * error;
+
+            if (wantTagTrace)
+                pm_message("Processing thumbnail IFD (IFD1)");
+
+            processIfd(exifData, length, nextIfdP, byteOrder,
+                       wantTagTrace,
+                       &imageInfoP->thumbnailImage, &nextIfdP, &error);
+
+            if (error) {
+                pm_asprintf(errorP,
+                            "Failed to process thumbnail image IFD.  %s",
+                            error);
+                pm_strfree(error);
+            } else {
+                if (nextIfdP) {
+                    pm_message("Ignoring third IFD in EXIF header because "
+                               "We understand only two -- one for the main "
+                               "image and one for the thumbnail");
+                }
+            }
+        }
+        if (!*errorP) {
+            /* Compute the CCD width, in millimeters. */
+            if (imageInfoP->mainImage.focalPlaneXResP &&
+                imageInfoP->mainImage.focalPlaneUnitsP &&
+                imageInfoP->mainImage.exifImageWidthP &&
+                imageInfoP->mainImage.exifImageLengthP) {
+
+                unsigned int const maxDim =
+                    MAX(*imageInfoP->mainImage.exifImageWidthP,
+                        *imageInfoP->mainImage.exifImageLengthP);
+
+                MALLOCVAR_NOFAIL(imageInfoP->ccdWidthP);
+                *imageInfoP->ccdWidthP =
+                    (float)(maxDim *
+                            *imageInfoP->mainImage.focalPlaneUnitsP /
+                            *imageInfoP->mainImage.focalPlaneXResP);
+            } else
+                imageInfoP->ccdWidthP = NULL;
         }
     }
 }
 
 
 
-void 
-exif_showImageInfo(const exif_ImageInfo * const imageInfoP,
-                   FILE *                 const fileP) {
-/*--------------------------------------------------------------------------
-   Show the collected image info, displaying camera F-stop and shutter
-   speed in a consistent and legible fashion.
---------------------------------------------------------------------------*/
-    if (imageInfoP->CameraMake[0]) {
-        fprintf(fileP, "Camera make  : %s\n", imageInfoP->CameraMake);
-        fprintf(fileP, "Camera model : %s\n", imageInfoP->CameraModel);
-    }
-    if (imageInfoP->DateTime[0])
-        fprintf(fileP, "Date/Time    : %s\n", imageInfoP->DateTime);
-
-    fprintf(fileP, "Resolution   : %f x %f\n",
-            imageInfoP->XResolution, imageInfoP->YResolution);
-
-    if (imageInfoP->Orientation > 1) {
-
-        /* Only print orientation if one was supplied, and if its not
-           1 (normal orientation)
-
-           1 - The 0th row is at the visual top of the image
-               and the 0th column is the visual left-hand side.
-           2 - The 0th row is at the visual top of the image
-               and the 0th column is the visual right-hand side.
-           3 - The 0th row is at the visual bottom of the image
-               and the 0th column is the visual right-hand side.
-           4 - The 0th row is at the visual bottom of the image
-               and the 0th column is the visual left-hand side.
-           5 - The 0th row is the visual left-hand side of of the image
-               and the 0th column is the visual top.
-           6 - The 0th row is the visual right-hand side of of the image
-               and the 0th column is the visual top.
-           7 - The 0th row is the visual right-hand side of of the image
-               and the 0th column is the visual bottom.
-           8 - The 0th row is the visual left-hand side of of the image
-               and the 0th column is the visual bottom.
-
-           Note: The descriptions here are the same as the name of the
-           command line option to pass to jpegtran to right the image
-        */
-        static const char * OrientTab[9] = {
-            "Undefined",
-            "Normal",           /* 1 */
-            "flip horizontal",  /* left right reversed mirror */
-            "rotate 180",       /* 3 */
-            "flip vertical",    /* upside down mirror */
-            "transpose",    /* Flipped about top-left <--> bottom-right axis.*/
-            "rotate 90",        /* rotate 90 cw to right it. */
-            "transverse",   /* flipped about top-right <--> bottom-left axis */
-            "rotate 270",       /* rotate 270 to right it. */
-        };
-
-        fprintf(fileP, "Orientation  : %s\n", 
-                OrientTab[imageInfoP->Orientation]);
-    }
+static void
+showIfd(const exif_ifd * const ifdP) {
 
-    if (imageInfoP->IsColor == 0)
-        fprintf(fileP, "Color/bw     : Black and white\n");
+    if (ifdP->cameraMake)
+        pm_message("Camera make  : %s", ifdP->cameraMake);
 
-    if (imageInfoP->FlashUsed >= 0)
-        fprintf(fileP, "Flash used   : %s\n",
-                imageInfoP->FlashUsed ? "Yes" :"No");
+    if (ifdP->cameraModel)
+        pm_message("Camera model : %s", ifdP->cameraModel);
 
-    if (imageInfoP->FocalLength) {
-        fprintf(fileP, "Focal length : %4.1fmm",
-                (double)imageInfoP->FocalLength);
-        if (imageInfoP->HaveCCDWidth){
-            fprintf(fileP, "  (35mm equivalent: %dmm)",
-                    (int)
-                    (imageInfoP->FocalLength/imageInfoP->CCDWidth*36 + 0.5));
-        }
-        fprintf(fileP, "\n");
-    }
+    if (ifdP->dateTime)
+        pm_message("Date/Time    : %s", ifdP->dateTime);
 
-    if (imageInfoP->HaveCCDWidth)
-        fprintf(fileP, "CCD width    : %2.4fmm\n",
-                (double)imageInfoP->CCDWidth);
-
-    if (imageInfoP->ExposureTime) {
-        if (imageInfoP->ExposureTime < 0.010){
-            fprintf(fileP, 
-                    "Exposure time: %6.4f s ",
-                    (double)imageInfoP->ExposureTime);
-        }else{
-            fprintf(fileP, 
-                    "Exposure time: %5.3f s ",
-                    (double)imageInfoP->ExposureTime);
-        }
-        if (imageInfoP->ExposureTime <= 0.5){
-            fprintf(fileP, " (1/%d)",(int)(0.5 + 1/imageInfoP->ExposureTime));
+    if (ifdP->xResolutionP && ifdP->yResolutionP)
+        pm_message("Resolution   : %f x %f",
+                   *ifdP->xResolutionP, *ifdP->yResolutionP);
+
+    if (ifdP->orientationP) {
+        /* Note that orientation is usually understood to be the orientation
+           of the camera, not of the image.  The top, bottom, left, and right
+           sides of an image are defined in the JFIF format.
+
+           But values such as "flip horizontal" make no sense for that.
+        */
+
+        const char * orientDisp;
+
+        switch (*ifdP->orientationP) {
+        case ORIENT_NORMAL:     orientDisp = "Normal";          break;
+        case ORIENT_FLIP_HORIZ: orientDisp = "Flip horizontal"; break;
+        case ORIENT_ROTATE_180: orientDisp = "Rotate 180";      break;
+        case ORIENT_FLIP_VERT:  orientDisp = "Flip vertical";   break;
+        case ORIENT_TRANSPOSE:  orientDisp = "Transpose";       break;
+        case ORIENT_ROTATE_90:  orientDisp = "Rotate 90";       break;
+        case ORIENT_TRANSVERSE: orientDisp = "Transverse";      break;
+        case ORIENT_ROTATE_270: orientDisp = "Rotate 270";      break;
         }
-        fprintf(fileP, "\n");
-    }
-    if (imageInfoP->ApertureFNumber){
-        fprintf(fileP, "Aperture     : f/%3.1f\n",
-                (double)imageInfoP->ApertureFNumber);
+
+        pm_message("Orientation  : %s", orientDisp);
     }
-    if (imageInfoP->Distance){
-        if (imageInfoP->Distance < 0){
-            fprintf(fileP, "Focus dist.  : Infinite\n");
-        }else{
-            fprintf(fileP, "Focus dist.  :%5.2fm\n",
-                    (double)imageInfoP->Distance);
+
+    if (ifdP->isColorP)
+        pm_message("Color/bw     : %s",
+                   *ifdP->isColorP ? "Color" : "Black and white");
+
+    if (ifdP->flashP)
+        pm_message("Flash used   : %s",
+                   *ifdP->flashP ? "Yes" :"No");
+
+    if (ifdP->exposureTimeP) {
+        const char * timeDisp;
+        const char * recipDisp;
+
+        if (*ifdP->exposureTimeP < 0.010) {
+            pm_asprintf(&timeDisp, "%6.4f s", *ifdP->exposureTimeP);
+        } else {
+            pm_asprintf(&timeDisp, "%5.3f s", *ifdP->exposureTimeP);
         }
+        /* We've seen the EXPOSURETIME tag be present but contain zero.
+           I don't know why.
+        */
+        if (*ifdP->exposureTimeP <= 0.5 && *ifdP->exposureTimeP > 0) {
+            pm_asprintf(&recipDisp, " (1/%d)",
+                        (int)(0.5 + 1 / *ifdP->exposureTimeP));
+        } else
+            recipDisp = pm_strdup("");
+
+        pm_message("Exposure time: %s %s", timeDisp, recipDisp);
+
+        pm_strfree(recipDisp);
+        pm_strfree(timeDisp);
     }
+    if (ifdP->shutterSpeedP)
+        pm_message("Shutter speed: 1/%u", *ifdP->shutterSpeedP);
 
-    if (imageInfoP->ISOequivalent){ /* 05-jan-2001 vcs */
-        fprintf(fileP, "ISO equiv.   : %2d\n",(int)imageInfoP->ISOequivalent);
+    if (ifdP->apertureFNumberP) {
+        pm_message("Aperture     : f/%3.1f", *ifdP->apertureFNumberP);
     }
-    if (imageInfoP->ExposureBias){ /* 05-jan-2001 vcs */
-        fprintf(fileP, "Exposure bias:%4.2f\n",
-                (double)imageInfoP->ExposureBias);
+    if (ifdP->distanceP) {
+        if (*ifdP->distanceP < 0)
+            pm_message("Focus dist.  : Infinite");
+        else
+            pm_message("Focus dist.  :%5.2fm", *ifdP->distanceP);
     }
-        
-    if (imageInfoP->Whitebalance){ /* 05-jan-2001 vcs */
-        switch(imageInfoP->Whitebalance) {
-        case 1:
-            fprintf(fileP, "Whitebalance : sunny\n");
-            break;
-        case 2:
-            fprintf(fileP, "Whitebalance : fluorescent\n");
-            break;
-        case 3:
-            fprintf(fileP, "Whitebalance : incandescent\n");
-            break;
-        default:
-            fprintf(fileP, "Whitebalance : cloudy\n");
+
+    if (ifdP->isoEquivalentP)
+        pm_message("ISO equiv.   : %2d", *ifdP->isoEquivalentP);
+
+    if (ifdP->exposureBiasP)
+        pm_message("Exposure bias: %4.2f", *ifdP->exposureBiasP);
+
+    if (ifdP->whiteBalanceP) {
+        const char * whiteBalanceDisp;
+
+        switch(*ifdP->whiteBalanceP) {
+        case 1:  whiteBalanceDisp = "sunny";         break;
+        case 2:  whiteBalanceDisp = "fluorescent";   break;
+        case 3:  whiteBalanceDisp = "incandescent";  break;
+        default: whiteBalanceDisp = "cloudy";        break;
         }
+        pm_message("Whitebalance : %s", whiteBalanceDisp);
     }
-    if (imageInfoP->MeteringMode){ /* 05-jan-2001 vcs */
-        switch(imageInfoP->MeteringMode) {
-        case 2:
-            fprintf(fileP, "Metering Mode: center weight\n");
-            break;
-        case 3:
-            fprintf(fileP, "Metering Mode: spot\n");
-            break;
-        case 5:
-            fprintf(fileP, "Metering Mode: matrix\n");
-            break;
+    if (ifdP->meteringModeP) {
+        const char * meteringModeDisp;
+
+        switch(*ifdP->meteringModeP) {
+        case 2:  meteringModeDisp = "center weight";  break;
+        case 3:  meteringModeDisp = "spot";           break;
+        case 5:  meteringModeDisp = "matrix";         break;
+        default: meteringModeDisp = "?";              break;
         }
+        pm_message("Metering Mode: %s", meteringModeDisp);
     }
-    if (imageInfoP->ExposureProgram){ /* 05-jan-2001 vcs */
-        switch(imageInfoP->ExposureProgram) {
-        case 2:
-            fprintf(fileP, "Exposure     : program (auto)\n");
-            break;
-        case 3:
-            fprintf(fileP, "Exposure     : aperture priority (semi-auto)\n");
-            break;
-        case 4:
-            fprintf(fileP, "Exposure     : shutter priority (semi-auto)\n");
-            break;
+    if (ifdP->exposureProgramP) {
+        const char * exposureDisp;
+
+        switch(*ifdP->exposureProgramP) {
+        case 2:  exposureDisp = "program (auto)";                break;
+        case 3:  exposureDisp = "aperture priority (semi-auto)"; break;
+        case 4:  exposureDisp = "shutter priority (semi-auto)";  break;
+        default: exposureDisp = "?";                              break;
         }
+        pm_message("Exposure     : %s", exposureDisp);
     }
-    if (imageInfoP->CompressionLevel){ /* 05-jan-2001 vcs */
-        switch(imageInfoP->CompressionLevel) {
-        case 1:
-            fprintf(fileP, "Jpeg Quality  : basic\n");
-            break;
-        case 2:
-            fprintf(fileP, "Jpeg Quality  : normal\n");
-            break;
-        case 4:
-            fprintf(fileP, "Jpeg Quality  : fine\n");
-            break;
+    if (ifdP->compressionLevelP) {
+        const char * jpegQualityDisp;
+
+        switch(*ifdP->compressionLevelP) {
+        case 1:  jpegQualityDisp = "basic";  break;
+        case 2:  jpegQualityDisp = "normal"; break;
+        case 4:  jpegQualityDisp = "fine";   break;
+        default: jpegQualityDisp = "?";      break;
        }
+        pm_message("Jpeg Quality  : %s", jpegQualityDisp);
     }
 
-    /* Print the comment. Print 'Comment:' for each new line of comment. */
-    if (imageInfoP->Comments[0]) {
-        unsigned int a;
+    if (ifdP->comments) {
+        char * buffer;
 
-        fprintf(fileP, "Comment      : ");
+        MALLOCARRAY(buffer, strlen(ifdP->comments) + 1);
 
-        for (a = 0; a < MAX_COMMENT && imageInfoP->Comments[a]; ++a) {
-            char const c = imageInfoP->Comments[a];
-            if (c == '\n'){
-                /* Do not start a new line if the string ends with a cr */
-                if (imageInfoP->Comments[a+1] != '\0')
-                    fprintf(fileP, "\nComment      : ");
-                else
-                    fprintf(fileP, "\n");
-            } else
-                putc(c, fileP);
+        if (!buffer)
+            pm_message("Out of memory allocating a buffer for %u "
+                       "characters of comments",
+                       (unsigned)strlen(ifdP->comments));
+        else {
+            unsigned int i;
+            unsigned int outCursor;
+
+            strcpy(buffer, "Comment:  ");  /* Permanently in buffer */
+
+            outCursor = 10;  /* initial value */
+
+            for (i = 0; ifdP->comments[i]; ++i) {
+                char const c = ifdP->comments[i];
+                if (c == '\n') {
+                    buffer[outCursor++] = '\0';
+                    pm_message("%s", buffer);
+                    outCursor = 10;
+                } else
+                    buffer[outCursor++] = c;
+            }
+            if (outCursor > 10)
+                pm_message("%s", buffer);
+
+            free(buffer);
         }
-        fprintf(fileP, "\n");
     }
+}
 
-    fprintf(fileP, "\n");
+
+
+void
+exif_showImageInfo(const exif_ImageInfo * const imageInfoP) {
+/*--------------------------------------------------------------------------
+   Show the collected image info, displaying camera F-stop and shutter
+   speed in a consistent and legible fashion.
+--------------------------------------------------------------------------*/
+    showIfd(&imageInfoP->mainImage);
+
+    if (imageInfoP->mainImage.focalLengthP) {
+        const char * mm35equiv;
+
+        if (imageInfoP->ccdWidthP) {
+            pm_asprintf(&mm35equiv, "  (35mm equivalent: %dmm)",
+                        (int) (*imageInfoP->mainImage.focalLengthP /
+                               *imageInfoP->ccdWidthP * 36 + 0.5));
+        } else
+            mm35equiv = pm_strdup("");
+
+        pm_message("Focal length : %4.1fmm %s",
+                   *imageInfoP->mainImage.focalLengthP, mm35equiv);
+
+        pm_strfree(mm35equiv);
+    }
+
+    if (imageInfoP->ccdWidthP)
+        pm_message("CCD width    : %2.4fmm", *imageInfoP->ccdWidthP);
 }
 
 
+
+void
+exif_terminateImageInfo(exif_ImageInfo * const imageInfoP) {
+
+    terminateIfd(&imageInfoP->mainImage);
+    terminateIfd(&imageInfoP->thumbnailImage);
+}
+
+
+
diff --git a/converter/other/exif.h b/converter/other/exif.h
index 57eb745b..37dcf240 100644
--- a/converter/other/exif.h
+++ b/converter/other/exif.h
@@ -10,52 +10,77 @@
     #define PATH_MAX _MAX_PATH
 #endif
 
+typedef struct {
 /*--------------------------------------------------------------------------
-  This structure stores Exif header image elements in a simple manner
-  Used to store camera data as extracted from the various ways that it can be
-  stored in an exif header
+  A structure of this type contains the information from an EXIF header
+  Image File Directory (IFD).
+
+  It appears that some of these members are possible only for certain kinds of
+  IFD (e.g. ThumbnailSize does not appear in a legal IFD for a main image),
+  but we recognize all tags in all IFDs all the same.
 --------------------------------------------------------------------------*/
+    /* In all of the following members, a null pointer means "not present,"
+       which normally means the tag from which the information comes was
+       not present in the IFD.
+
+       The EXIF format might require certain tags to be present, but we
+       don't.
+    */
+    const char *   cameraMake;
+    const char *   cameraModel;
+    const char *   dateTime;
+    float *        xResolutionP;
+    float *        yResolutionP;
+    int *          orientationP;
+    int *          isColorP;
+    int *          flashP;
+    float *        focalLengthP;
+    float *        exposureTimeP;
+    unsigned int * shutterSpeedP;  /* e.g. 128 for 1/128 second */
+    float *        apertureFNumberP;
+    float *        distanceP;
+    float *        exposureBiasP;
+    int *          whiteBalanceP;
+    int *          meteringModeP;
+    int *          exposureProgramP;
+    int *          isoEquivalentP;
+    int *          compressionLevelP;
+    const char *   comments;
+    unsigned int * thumbnailOffsetP;
+    unsigned int * thumbnailLengthP;
+    unsigned int * exifImageLengthP;
+    unsigned int * exifImageWidthP;
+    double *       focalPlaneXResP;
+    double *       focalPlaneUnitsP;
+
+    const unsigned char * thumbnail;  /* Pointer at the thumbnail */
+    unsigned thumbnailSize;     /* Size of thumbnail. */
+} exif_ifd;
+
+
 typedef struct {
-    char  CameraMake   [32];
-    char  CameraModel  [40];
-    char  DateTime     [20];
-    float XResolution;
-    float YResolution;
-    int   Orientation;
-    int   IsColor;
-    int   FlashUsed;
-    float FocalLength;
-    float ExposureTime;
-    float ApertureFNumber;
-    float Distance;
-    int   HaveCCDWidth;  /* boolean */
-    float CCDWidth;
-    float ExposureBias;
-    int   Whitebalance;
-    int   MeteringMode;
-    int   ExposureProgram;
-    int   ISOequivalent;
-    int   CompressionLevel;
-    char  Comments[MAX_COMMENT];
-
-    const unsigned char * ThumbnailPointer;  /* Pointer at the thumbnail */
-    unsigned ThumbnailSize;     /* Size of thumbnail. */
-
-    const char * DatePointer;
+/*--------------------------------------------------------------------------
+  A structure of this type contains the information from an EXIF header.
+--------------------------------------------------------------------------*/
+    exif_ifd mainImage;       /* aka IFD0 */
+    exif_ifd thumbnailImage;  /* aka IFD1 */
+    float *  ccdWidthP;  /* NULL means none */
 } exif_ImageInfo;
 
 
 /* Prototypes for exif.c functions. */
 
-void 
-exif_parse(const unsigned char * const exifSection, 
+void
+exif_parse(const unsigned char * const exifSection,
            unsigned int          const length,
-           exif_ImageInfo *      const imageInfoP, 
+           exif_ImageInfo *      const imageInfoP,
            bool                  const wantTagTrace,
            const char **         const errorP);
 
-void 
-exif_showImageInfo(const exif_ImageInfo * const imageInfoP,
-                   FILE *                 const fileP);
+void
+exif_showImageInfo(const exif_ImageInfo * const imageInfoP);
+
+void
+exif_terminateImageInfo(exif_ImageInfo * const imageInfoP);
 
 #endif
diff --git a/converter/other/fiasco/Makefile b/converter/other/fiasco/Makefile
index 392e843c..5ce529fd 100644
--- a/converter/other/fiasco/Makefile
+++ b/converter/other/fiasco/Makefile
@@ -25,7 +25,7 @@ FIASCOLIBS = codec/libfiasco_codec.a \
 	     output/libfiasco_output.a \
 	     lib/libfiasco_lib.a 
 
-ADDL_OBJECTS = binerror.o getopt.o getopt1.o params.o
+ADDL_OBJECTS = getopt.o getopt1.o params.o
 
 OBJECTS = $(BINARIES:%=%.o) $(ADDL_OBJECTS)
 
diff --git a/converter/other/fiasco/binerror.c b/converter/other/fiasco/binerror.c
deleted file mode 100644
index 9820d853..00000000
--- a/converter/other/fiasco/binerror.c
+++ /dev/null
@@ -1,136 +0,0 @@
-/*
- *  error.c:		Error handling
- *
- *  Written by:		Stefan Frank
- *			Ullrich Hafner
- *  
- *  Credits:	Modelled after variable argument routines from Jef
- *		Poskanzer's pbmplus package. 
- *
- *  This file is part of FIASCO (Fractal Image And Sequence COdec)
- *  Copyright (C) 1994-2000 Ullrich Hafner
- */
-
-/*
- *  $Date: 2000/03/20 21:29:59 $
- *  $Author: hafner $
- *  $Revision: 4.3 $
- *  $State: Exp $
- */
-
-#define _DEFAULT_SOURCE 1 /* New name for SVID & BSD source defines */
-#define _BSD_SOURCE 1   /* Make sure strdup() is in string.h */
-#define _XOPEN_SOURCE 500  /* Make sure strdup() is in string.h */
-#define _ERROR_C
-
-#include "config.h"
-
-#include <stdlib.h>
-#include <stdio.h>
-
-#if STDC_HEADERS
-#	include <stdarg.h>
-#	define VA_START(args, lastarg) va_start(args, lastarg)
-#else  /* not STDC_HEADERS */
-#	include <varargs.h>
-#	define VA_START(args, lastarg) va_start(args)
-#endif /* not STDC_HEADERS */
-#include <string.h>
-
-#if HAVE_SETJMP_H
-#	include <setjmp.h>
-#endif /* HAVE_SETJMP_H */
-
-#include "fiasco.h"
-#include "binerror.h"
-
-/*****************************************************************************
-
-			     global variables
-  
-*****************************************************************************/
-
-int   error_line = 0;
-const char *error_file = NULL;
-
-/*****************************************************************************
-
-			     local variables
-  
-*****************************************************************************/
-
-static const char *executable = "(name not initialized)";
-
-/*****************************************************************************
-
-			       public code
-  
-*****************************************************************************/
-
-void
-init_error_handling (const char *name)
-/*
- *  Initialize filename of executable.
- *
- *  No return value.
- */
-{
-   if (name)
-      executable = strdup (name);
-}
-
-void
-_error (const char *format, ...)
-/*
- *  Print error message and exit.
- *
- *  No return value.
- */
-{
-   va_list	args;
-
-   VA_START (args, format);
-
-   fprintf (stderr, "%s: %s: line %d:\nError: ",
-	    executable, error_file, error_line);
-   vfprintf (stderr, format, args);
-   fputc ('\n', stderr);
-   va_end(args);
-
-   exit (1);
-}
-
-void
-_file_error (const char *filename)
-/*
- *  Print file error message and exit.
- *
- *  No return value.
- */
-{
-   fprintf (stderr, "%s: %s: line %d:\nError: ",
-	    executable, error_file, error_line);
-   perror (filename);
-
-   exit (2);
-}
-
-void 
-_warning (const char *format, ...)
-/*
- *  Issue a warning and continue execution.
- *
- *  No return value.
- */
-{
-   va_list args;
-
-   VA_START (args, format);
-
-   fprintf (stderr, "%s: %s: line %d:\nWarning: ",
-	    executable, error_file, error_line);
-   vfprintf (stderr, format, args);
-   fputc ('\n', stderr);
-
-   va_end (args);
-}
diff --git a/converter/other/fiasco/binerror.h b/converter/other/fiasco/binerror.h
deleted file mode 100644
index 4f313aca..00000000
--- a/converter/other/fiasco/binerror.h
+++ /dev/null
@@ -1,50 +0,0 @@
-/*
- *  error.h
- *  
- *  Written by:		Stefan Frank
- *			Ullrich Hafner
- *
- *  This file is part of FIASCO (Fractal Image And Sequence COdec)
- *  Copyright (C) 1994-2000 Ullrich Hafner
- */
-
-/*
- *  $Date: 2000/03/20 21:29:59 $
- *  $Author: hafner $
- *  $Revision: 4.3 $
- *  $State: Exp $
- */
-
-#ifndef _ERROR_H
-#define _ERROR_H
-
-#define error          error_line=__LINE__,error_file=__FILE__,_error
-#define warning        error_line=__LINE__,error_file=__FILE__,_warning
-#define file_error(fn) error_line=__LINE__,error_file=__FILE__,_file_error(fn)
-
-#ifdef _ERROR_C
-#define _EXTERN_TYPE
-#else
-#define _EXTERN_TYPE	extern
-#endif
-
-_EXTERN_TYPE int   error_line;
-_EXTERN_TYPE const char *error_file;
-
-void
-init_error_handling (const char *name);
-void
-_error (const char *format, ...);
-void
-_warning (const char *format, ...);
-void
-_file_error (const char *filename);
-
-#if HAVE_ASSERT_H
-#	include <assert.h>
-#else /* not HAVE_ASSERT_H */
-#	define assert(exp)	{if (!(exp)) error ("Assertion `" #exp " != NULL' failed.");}
-#endif /* not HAVE_ASSERT_H */
-
-#endif /* not _ERROR_H */
-
diff --git a/converter/other/fiasco/buttons.c b/converter/other/fiasco/buttons.c
deleted file mode 100644
index fc54d84a..00000000
--- a/converter/other/fiasco/buttons.c
+++ /dev/null
@@ -1,510 +0,0 @@
-/*
- *  buttons.c:		Draw MWFA player buttons in X11 window	
- *
- *  Written by:		Ullrich Hafner
- *		
- *  This file is part of FIASCO (Fractal Image And Sequence COdec)
- *  Copyright (C) 1994-2000 Ullrich Hafner
- */
-
-/*
- *  $Date: 2000/06/15 17:23:11 $
- *  $Author: hafner $
- *  $Revision: 5.2 $
- *  $State: Exp $
- */
-
-#include "config.h"
-
-#ifndef X_DISPLAY_MISSING
-
-#include <X11/Xlib.h>
-#include <X11/Intrinsic.h>
-#include <X11/StringDefs.h>
-
-#if STDC_HEADERS
-#	include <stdlib.h>
-#endif /* not STDC_HEADERS */
-
-#include "types.h"
-#include "macros.h"
-
-#include "display.h"
-#include "binerror.h"
-#include "buttons.h"
-
-/*****************************************************************************
-
-			     local variables
-  
-*****************************************************************************/
-
-static const int EVENT_MASK = (KeyPressMask | ButtonPressMask |
-			       ButtonReleaseMask | ExposureMask);
-
-/*****************************************************************************
-
-				prototypes
-  
-*****************************************************************************/
-
-static void
-draw_progress_bar (x11_info_t *xinfo, binfo_t *binfo, unsigned n,
-		   unsigned n_frames);
-static void
-draw_button (x11_info_t *xinfo, binfo_t *binfo,
-	     buttons_t button, bool_t pressed);
-static void
-draw_control_panel (x11_info_t *xinfo, binfo_t *binfo,
-		    unsigned n, unsigned n_frames);
-
-/*****************************************************************************
-
-				public code
-  
-*****************************************************************************/
-
-binfo_t * 
-init_buttons (x11_info_t *xinfo, unsigned n, unsigned n_frames,
-	      unsigned buttons_height, unsigned progbar_height)
-/*
- *  Initialize a toolbar with the typical collection of video player
- *  buttons (pause, play, record, next, etc.) in the window given by 'xinfo'.
- *  'n' gives the current frame, 'whereas' n_frames is the total number of
- *  frames of the video stream.
- *  The size of the button toolbar is given by 'buttons_height',
- *  the size of the progressbar is given by 'progbar_height'.
- *
- *  Return value:
- *	struct managing the toolbar and progressbar information
- */
-{
-   XGCValues  values;
-   XEvent     event;
-   Colormap   cmap;
-   XColor     gray, dgray, lgray, red;
-   XColor     graye, dgraye, lgraye, rede;
-   buttons_t  button;			/* counter */
-   binfo_t   *binfo = calloc (1, sizeof (binfo_t));
-
-   if (!binfo)
-      error ("Out of memory.");
-   
-   binfo->width            = xinfo->ximage->width;
-   binfo->height           = buttons_height;
-   binfo->progbar_height   = progbar_height;
-   binfo->record_is_rewind = NO;
-
-   /*
-    *  Generate sub-window for control panel
-    */
-   binfo->window = XCreateSimpleWindow (xinfo->display, xinfo->window,
-					0, xinfo->ximage->height,
-					binfo->width, binfo->height, 0,
-					BlackPixel (xinfo->display,
-						    xinfo->screen),
-					WhitePixel (xinfo->display,
-						    xinfo->screen));
-   XSelectInput(xinfo->display, binfo->window, StructureNotifyMask);
-   XMapWindow (xinfo->display, binfo->window);
-   do
-   {
-      XNextEvent (xinfo->display, &event);
-   }
-   while (event.type != MapNotify || event.xmap.event != binfo->window);
-   XSelectInput (xinfo->display, binfo->window, EVENT_MASK);
-
-   /*
-    *  Generate graphic contexts for different colors.
-    */
-   cmap = DefaultColormap (xinfo->display, xinfo->screen);
-   XAllocNamedColor (xinfo->display, cmap, "#404040", &dgray, &dgraye);
-   XAllocNamedColor (xinfo->display, cmap, "white", &lgray, &lgraye);
-   XAllocNamedColor (xinfo->display, cmap, "#a8a8a8", &gray, &graye);
-   XAllocNamedColor (xinfo->display, cmap, "red", &red, &rede);
-   
-   values.foreground = BlackPixel (xinfo->display, xinfo->screen);
-   values.background = WhitePixel (xinfo->display, xinfo->screen);
-   binfo->gc [BLACK] = XCreateGC (xinfo->display,
-				  RootWindow (xinfo->display, xinfo->screen),
-				  (GCForeground | GCBackground), &values);
-   values.foreground = BlackPixel (xinfo->display, xinfo->screen);
-   values.background = WhitePixel (xinfo->display, xinfo->screen);
-   values.line_width = 3;
-   values.join_style = JoinRound;
-   binfo->gc [THICKBLACK] = XCreateGC (xinfo->display,
-				       RootWindow (xinfo->display,
-						   xinfo->screen),
-				       (GCForeground | GCBackground
-					| GCLineWidth | GCJoinStyle), &values);
-   values.foreground = gray.pixel;
-   values.background = WhitePixel (xinfo->display, xinfo->screen);
-   binfo->gc [NGRAY] = XCreateGC (xinfo->display,
-				  RootWindow (xinfo->display, xinfo->screen),
-				  (GCForeground | GCBackground), &values);
-   values.foreground = lgray.pixel;
-   values.background = WhitePixel (xinfo->display, xinfo->screen);
-   binfo->gc [LGRAY] = XCreateGC (xinfo->display,
-				  RootWindow (xinfo->display, xinfo->screen),
-				  (GCForeground | GCBackground), &values);
-   values.foreground = dgray.pixel;
-   values.background = WhitePixel (xinfo->display, xinfo->screen);
-   binfo->gc [DGRAY] = XCreateGC (xinfo->display,
-				  RootWindow (xinfo->display, xinfo->screen),
-				  (GCForeground | GCBackground), &values);
-   values.foreground = red.pixel;
-   values.background = WhitePixel (xinfo->display, xinfo->screen);
-   binfo->gc [RED]   = XCreateGC (xinfo->display,
-				  RootWindow (xinfo->display, xinfo->screen),
-				  (GCForeground | GCBackground), &values);
-
-   for (button = 0; button < NO_BUTTON; button++)
-      binfo->pressed [button] = NO;
-
-   draw_control_panel (xinfo, binfo, n, n_frames); 
-   
-   return binfo;
-}
-
-void
-wait_for_input (x11_info_t *xinfo)
-/*
- *  Wait for key press or mouse click in window 'xinfo'.
- *  Redraw 'image' if event other then ButtonPress or KeyPress occurs.
- *  Enlarge or reduce size of image by factor 2^'enlarge_factor'.
- *
- *  No return value.
- *
- *  Side effect:
- *	program is terminated after key press or mouse click.
- */
-{
-   bool_t leave_loop = NO;
-   
-   XSelectInput (xinfo->display, xinfo->window, EVENT_MASK);
-
-   while (!leave_loop)
-   {
-      XEvent event;
-
-      XMaskEvent (xinfo->display, EVENT_MASK, &event);
-      switch (event.type)
-      {
-	 case ButtonPress:
-	 case KeyPress:
-	    leave_loop = YES;
-	    break;
-	 default:
-	    display_image (0, 0, xinfo);
-	    break;
-      }
-   }
-}
-
-void
-check_events (x11_info_t *xinfo, binfo_t *binfo, unsigned n, unsigned n_frames)
-/*
- *  Check the X11 event loop. If the PAUSE buttonin the of panel 'binfo'
- *  is activated wait until next event occurs.
- *  Redraw 'image' if event other then ButtonPress or ButtonRelease occurs.
- *  Enlarge or reduce size of image by factor 2^'enlarge_factor'.
- *  'n' gives the current frame, 'whereas' n_frames is the total number of
- *  frames of the video stream.
- *
- *  No return values.
- *
- *  Side effects:
- *	status of buttons (binfo->pressed [button]) is changed accordingly.
- */
-{
-   bool_t leave_eventloop;
-
-   leave_eventloop = (!binfo->pressed [PAUSE_BUTTON]
-		      && binfo->pressed [PLAY_BUTTON])
-		     || (!binfo->pressed [PAUSE_BUTTON]
-			 && binfo->record_is_rewind
-			 && binfo->pressed [RECORD_BUTTON])
-		     || binfo->pressed [RECORD_BUTTON];
-   draw_progress_bar (xinfo, binfo, n, n_frames);
-
-   if (binfo->pressed [PAUSE_BUTTON] && binfo->pressed [PLAY_BUTTON])
-   {
-      XFlush (xinfo->display);
-      draw_button (xinfo, binfo, PLAY_BUTTON, NO); /* clear PLAY mode */
-      XFlush (xinfo->display);
-   }
-   if (binfo->pressed [PAUSE_BUTTON]
-       && binfo->record_is_rewind && binfo->pressed [RECORD_BUTTON])
-   {
-      XFlush (xinfo->display);
-      draw_button (xinfo, binfo, RECORD_BUTTON, NO); /* clear PLAY mode */
-      XFlush (xinfo->display);
-   }
-
-   if (binfo->pressed [STOP_BUTTON])
-   {
-      XFlush (xinfo->display);
-      draw_button (xinfo, binfo, STOP_BUTTON, NO); /* clear STOP button */
-      XFlush (xinfo->display);
-   }
-
-   do
-   {
-      XEvent event;
-      int    button;
-      bool_t wait_release = NO;
-	 
-      
-      if (XCheckMaskEvent (xinfo->display, EVENT_MASK, &event))
-      {
-	 switch (event.type)
-	 {
-	    case ButtonPress:
-	       wait_release = NO;
-	       if (!(binfo->pressed [RECORD_BUTTON] &&
-		     !binfo->record_is_rewind))
-		  for (button = 0; button < NO_BUTTON; button++)
-		  {
-		     int x0, y0, x1, y1; /* button coordinates */
-		  
-		     x0 = button * (binfo->width / NO_BUTTON);
-		     y0 = binfo->progbar_height;
-		     x1 = x0 + binfo->width / NO_BUTTON;
-		     y1 = y0 + binfo->height - binfo->progbar_height - 1;
-		     if (event.xbutton.x > x0 && event.xbutton.x < x1
-			 && event.xbutton.y > y0 && event.xbutton.y < y1) 
-		     {
-			draw_button (xinfo, binfo, button,
-				     !binfo->pressed [button]);
-			wait_release = YES;
-			break;
-		     }
-		  }
-	       break;
-	    case ButtonRelease:
-	       wait_release = NO;
-	       break;
-	    default:
-	       wait_release = NO;
-	       draw_control_panel (xinfo, binfo, n, n_frames);
-	       display_image (0, 0, xinfo);
-	       break;
-	 }
-	 leave_eventloop = !wait_release
-			   && (binfo->pressed [PLAY_BUTTON]
-			       || binfo->pressed [STOP_BUTTON]
-			       || binfo->pressed [RECORD_BUTTON]
-			       || binfo->pressed [QUIT_BUTTON]);
-      }
-   } while (!leave_eventloop);
-
-   if ((binfo->pressed [RECORD_BUTTON] && !binfo->record_is_rewind)
-       && n == n_frames - 1)
-   {
-      binfo->record_is_rewind = YES;
-      draw_button (xinfo, binfo, RECORD_BUTTON, NO);
-   }
-}
-
-/*****************************************************************************
-
-				private code
-  
-*****************************************************************************/
-
-static void
-draw_control_panel (x11_info_t *xinfo, binfo_t *binfo,
-		    unsigned n, unsigned n_frames)
-/*
- *  Draw control panel 'binfo' with all buttons and progressbar in
- *  the given 'window'.
- *  'n' gives the current frame, 'whereas' n_frames is the total number of
- *  frames of the video stream.
- *
- *  No return value.
- */
-{
-   buttons_t button;
-   
-   XFillRectangle (xinfo->display, binfo->window, binfo->gc [NGRAY],
-		   0, 0, binfo->width, binfo->height);
-   draw_progress_bar (xinfo, binfo, n, n_frames);
-   for (button = 0; button < NO_BUTTON; button++)
-      draw_button (xinfo, binfo, button, binfo->pressed [button]);
-}
-
-static void
-draw_progress_bar (x11_info_t *xinfo, binfo_t *binfo, unsigned n,
-		   unsigned n_frames)
-/*
- *  Draw progressbar of control panel 'binfo' in the given 'window'.
- *  'n' gives the current frame, whereas 'n_frames' is the total number of
- *  frames of the video stream.
- *
- *  No return value.
- */
-{
-   unsigned x, y, width, height;
-
-   x 	  = 2;
-   y 	  = 1;
-   width  = binfo->width - 5;
-   height = binfo->progbar_height - 3;
-   
-   XDrawLine (xinfo->display, binfo->window, binfo->gc [DGRAY],
-	      x, y, x + width, y);
-   XDrawLine (xinfo->display, binfo->window, binfo->gc [DGRAY],
-	      x, y, x, y + height - 1);
-   XDrawLine (xinfo->display, binfo->window, binfo->gc [LGRAY],
-	      x + width, y + 1, x + width, y + height);
-   XDrawLine (xinfo->display, binfo->window, binfo->gc [LGRAY],
-	      x, y + height, x + width, y + height);
-
-   x++; y++; width  -= 2; height -= 2;
-   XFillRectangle (xinfo->display, binfo->window, binfo->gc [NGRAY],
-		   x, y, width, height);
-
-   XFillRectangle (xinfo->display, binfo->window, binfo->gc [BLACK],
-		   x + n * max (1, width / n_frames), y,
-		   max (1, width / n_frames), height);
-}
-
-static void
-draw_button (x11_info_t *xinfo, binfo_t *binfo,
-	     buttons_t button, bool_t pressed)
-/*
- *  Draw 'button' of control panel 'binfo' in the given 'window'.
- *  'pressed' indicates whether the button is pressed or not.
- *
- *  No return value.
- */
-{
-   grayscale_t top, bottom;		/* index of GC */
-   unsigned    x, y, width, height;	/* coordinates of button */
-   
-   x 	  = button * (binfo->width / NO_BUTTON);
-   y 	  = binfo->progbar_height;
-   width  = binfo->width / NO_BUTTON;
-   height = binfo->height - binfo->progbar_height - 1;
-   
-   if (width < 4 || height < 4)
-      return;
-   
-   if (pressed)
-   {
-      top    = DGRAY;
-      bottom = LGRAY;
-   }
-   else
-   {
-      top    = LGRAY;
-      bottom = DGRAY;
-   }
-
-   x 	 += 2;
-   width -= 4;
-   
-   XDrawLine (xinfo->display, binfo->window, binfo->gc [top],
-	      x, y, x + width, y);
-   XDrawLine (xinfo->display, binfo->window, binfo->gc [top],
-	      x, y, x, y + height - 1);
-   XDrawLine (xinfo->display, binfo->window, binfo->gc [bottom],
-	      x + width, y + 1, x + width, y + height);
-   XDrawLine (xinfo->display, binfo->window, binfo->gc [bottom],
-	      x, y + height, x + width, y + height);
-
-   x++; y++; width  -= 2; height -= 2;
-   XFillRectangle (xinfo->display, binfo->window, binfo->gc [NGRAY],
-		   x, y, width, height);
-
-   switch (button)
-   {
-      case STOP_BUTTON:
-	 XFillRectangle (xinfo->display, binfo->window, binfo->gc [BLACK],
-			 x + width / 2 - 6, y + height / 2 - 4, 11, 11);
-	 if (pressed && !binfo->pressed [STOP_BUTTON])
-	 {
-	    draw_button (xinfo, binfo, PLAY_BUTTON, NO);
-	    draw_button (xinfo, binfo, PAUSE_BUTTON, NO); 
-	    draw_button (xinfo, binfo, RECORD_BUTTON, NO); 
-	 }
-	 break;
-      case PAUSE_BUTTON:
-	 XFillRectangle (xinfo->display, binfo->window, binfo->gc [BLACK],
-			 x + width / 2 - 6, y + height / 2 - 4, 5, 11);
-	 XFillRectangle (xinfo->display, binfo->window, binfo->gc [BLACK],
-			 x + width / 2 + 1, y + height / 2 - 4, 5, 11);
-	 break;
-      case PLAY_BUTTON:
-	 {
-	    XPoint triangle [3];
-
-	    triangle [0].x = x + width / 2 - 5;
-	    triangle [0].y = y + height / 2 - 5;
-	    triangle [1].x = 10;
-	    triangle [1].y = 6;
-	    triangle [2].x = -10;
-	    triangle [2].y = 6;
-
-	    XFillPolygon (xinfo->display, binfo->window, binfo->gc [BLACK],
-			  triangle, 3, Convex, CoordModePrevious);
-	    if (pressed && !binfo->pressed [PLAY_BUTTON]
-		&& binfo->pressed [RECORD_BUTTON])
-	       draw_button (xinfo, binfo, RECORD_BUTTON, NO);
-	 }
-	 break;
-      case RECORD_BUTTON:
-	 if (!binfo->record_is_rewind)
-	 {
-	    XFillArc (xinfo->display, binfo->window, binfo->gc [RED],
-		      x + width / 2 - 5, y + height / 2 - 5, 11, 11, 0,
-		      360 * 64);
-	    if (pressed && !binfo->pressed [RECORD_BUTTON])
-	    {
-	       draw_button (xinfo, binfo, STOP_BUTTON, YES);
-	       draw_button (xinfo, binfo, PLAY_BUTTON, NO);
-	       draw_button (xinfo, binfo, PAUSE_BUTTON, NO); 
-	    }
-	 }
-	 else
-	 {
-	    XPoint triangle [3];
-
-	    triangle [0].x = x + width / 2 + 5;
-	    triangle [0].y = y + height / 2 - 5;
-	    triangle [1].x = -10;
-	    triangle [1].y = 6;
-	    triangle [2].x = 10;
-	    triangle [2].y = 6;
-
-	    XFillPolygon (xinfo->display, binfo->window, binfo->gc [BLACK],
-			  triangle, 3, Convex, CoordModePrevious);
-	    if (pressed && !binfo->pressed [RECORD_BUTTON]
-		&& binfo->pressed [PLAY_BUTTON])
-	       draw_button (xinfo, binfo, PLAY_BUTTON, NO);
-	 }
-	 break;
-      case QUIT_BUTTON:
-	 {
-	    XPoint triangle [3];
-
-	    triangle [0].x = x + width / 2 - 6;
-	    triangle [0].y = y + height / 2 + 2;
-	    triangle [1].x = 6;
-	    triangle [1].y = -7;
-	    triangle [2].x = 6;
-	    triangle [2].y = 7;
-
-	    XFillPolygon (xinfo->display, binfo->window, binfo->gc [BLACK],
-			  triangle, 3, Convex, CoordModePrevious);
-	    XFillRectangle (xinfo->display, binfo->window, binfo->gc [BLACK],
-			    x + width / 2 - 5, y + height / 2 + 4, 11, 3);
-	 }
-	 break;
-      default:
-	 break;
-   }
-   binfo->pressed [button] = pressed;
-}
-
-#endif /* not X_DISPLAY_MISSING */
diff --git a/converter/other/fiasco/buttons.h b/converter/other/fiasco/buttons.h
deleted file mode 100644
index 079715f5..00000000
--- a/converter/other/fiasco/buttons.h
+++ /dev/null
@@ -1,50 +0,0 @@
-/*
- *  buttons.h
- *
- *  Written by:		Ullrich Hafner
- *		
- *  This file is part of FIASCO (Fractal Image And Sequence COdec)
- *  Copyright (C) 1994-2000 Ullrich Hafner
- */
-
-/*
- *  $Date: 2000/06/14 20:51:17 $
- *  $Author: hafner $
- *  $Revision: 5.1 $
- *  $State: Exp $
- */
-
-#ifndef _BUTTONS_H
-#define _BUTTONS_H
-
-#ifndef X_DISPLAY_MISSING
-
-typedef enum grayscale_e {BLACK, NGRAY, LGRAY, DGRAY, RED,
-			  THICKBLACK, NO_GC} grayscale_t;
-typedef enum buttons_e {STOP_BUTTON, PLAY_BUTTON, PAUSE_BUTTON, RECORD_BUTTON,
-			QUIT_BUTTON, NO_BUTTON} buttons_t;
-
-typedef struct buttoninfo
-{
-   Window   window;
-   bool_t   pressed [NO_BUTTON];
-   GC	    gc [NO_GC];
-   unsigned width;
-   unsigned height;
-   unsigned progbar_height;
-   bool_t   record_is_rewind;
-} binfo_t;
-
-void
-check_events (x11_info_t *xinfo, binfo_t *binfo, unsigned n,
-	      unsigned n_frames);
-void
-wait_for_input (x11_info_t *xinfo);
-binfo_t * 
-init_buttons (x11_info_t *xinfo, unsigned n, unsigned n_frames,
-	      unsigned buttons_height, unsigned progbar_height);
-
-#endif /* not X_DISPLAY_MISSING */
-
-#endif /* not _BUTTONS_H */
-
diff --git a/converter/other/fiasco/codec/approx.c b/converter/other/fiasco/codec/approx.c
index d8fefcaa..a3f6523d 100644
--- a/converter/other/fiasco/codec/approx.c
+++ b/converter/other/fiasco/codec/approx.c
@@ -2,7 +2,7 @@
  *  approx.c:       Approximation of range images with matching pursuit
  *
  *  Written by:     Ullrich Hafner
- *      
+ *
  *  This file is part of FIASCO (Fractal Image And Sequence COdec)
  *  Copyright (C) 1994-2000 Ullrich Hafner
  */
@@ -35,7 +35,7 @@
 /*****************************************************************************
 
                  local variables
-  
+
 *****************************************************************************/
 
 typedef struct mp
@@ -53,13 +53,13 @@ typedef struct mp
 /*****************************************************************************
 
                  prototypes
-  
+
 *****************************************************************************/
 
 static void
 orthogonalize (unsigned index, unsigned n, unsigned level, real_t min_norm,
            const word_t *domain_blocks, const coding_t *c);
-static void 
+static void
 matching_pursuit (mp_t *mp, bool_t full_search, real_t price,
           unsigned max_edges, int y_state, const range_t *range,
           const domain_pool_t *domain_pool, const coeff_t *coeff,
@@ -68,14 +68,14 @@ matching_pursuit (mp_t *mp, bool_t full_search, real_t price,
 /*****************************************************************************
 
                 public code
-  
+
 *****************************************************************************/
 
-real_t 
+real_t
 approximate_range (real_t max_costs, real_t price, int max_edges,
                    int y_state, range_t *range, domain_pool_t *domain_pool,
                    coeff_t *coeff, const wfa_t *wfa, const coding_t *c) {
-/*---------------------------------------------------------------------------- 
+/*----------------------------------------------------------------------------
   Approximate image block 'range' by matching pursuit. This functions
   calls the matching pursuit algorithm several times (with different
   parameters) in order to find the best approximation. Refer to function
@@ -99,15 +99,15 @@ approximate_range (real_t max_costs, real_t price, int max_edges,
      */
     if (c->options.second_domain_block) {
         mp_t tmp_mp;
-      
+
         tmp_mp = mp;  /* initial value */
 
         tmp_mp.exclude[0] = tmp_mp.indices [0];
         tmp_mp.exclude[1] = NO_EDGE;
-        
+
         matching_pursuit(&tmp_mp, c->options.full_search, price, max_edges,
                          y_state, range, domain_pool, coeff, wfa, c);
-        if (tmp_mp.costs < mp.costs)  /* success */ 
+        if (tmp_mp.costs < mp.costs)  /* success */
             mp = tmp_mp;
     }
 
@@ -123,23 +123,23 @@ approximate_range (real_t max_costs, real_t price, int max_edges,
 
         tmp_mp = mp;  /* initial value */
         iteration = -1;  /* initial value */
-      
+
         do {
             int i;
-            
+
             ++iteration;
             tmp_mp.exclude[iteration] = NO_EDGE;
-     
+
             for (i = 0; isdomain(tmp_mp.indices[i]); ++i) {
                 if (tmp_mp.weight [i] == 0) {
                     tmp_mp.exclude[iteration] = tmp_mp.indices [i];
                     break;
                 }
-            }      
+            }
             if (isdomain (tmp_mp.exclude [iteration])) {
                 /* try again */
                 tmp_mp.exclude [iteration + 1] = NO_EDGE;
-        
+
                 matching_pursuit(&tmp_mp, c->options.full_search, price,
                                  max_edges, y_state, range, domain_pool,
                                  coeff, wfa, c);
@@ -165,25 +165,25 @@ approximate_range (real_t max_costs, real_t price, int max_edges,
 
         do {
             int i;
- 
+
             ++iteration;
             tmp_mp.exclude[iteration] = NO_EDGE;
-     
+
             for (i = 0; isdomain (tmp_mp.indices [i]); ++i) {
                 rpf_t * const rpf =
                     tmp_mp.indices [i] ? coeff->rpf : coeff->dc_rpf;
-        
+
                 if (tmp_mp.weight [i] == btor (rtob (200, rpf), rpf)
                     || tmp_mp.weight [i] == btor (rtob (-200, rpf), rpf)) {
                     tmp_mp.exclude [iteration] = tmp_mp.indices [i];
                     break;
                 }
             }
-      
+
             if (isdomain(tmp_mp.exclude[iteration])) {
                 /* try again */
                 tmp_mp.exclude[iteration + 1] = NO_EDGE;
-        
+
                 matching_pursuit(&tmp_mp, c->options.full_search, price,
                                  max_edges, y_state, range, domain_pool,
                                  coeff, wfa, c);
@@ -226,10 +226,10 @@ approximate_range (real_t max_costs, real_t price, int max_edges,
                                 range->level, y_state, wfa,
                                 domain_pool->model);
             coeff->update (mp.weight, mp.into, range->level, coeff);
-     
+
             Free(domain_blocks);
         }
-      
+
         for (edge = 0; isedge (mp.indices [edge]); ++edge) {
             range->into   [edge] = mp.into   [edge];
             range->weight [edge] = mp.weight [edge];
@@ -242,7 +242,7 @@ approximate_range (real_t max_costs, real_t price, int max_edges,
         range->into [0] = NO_EDGE;
         mp.costs        = MAXCOSTS;
     }
-   
+
     return mp.costs;
 }
 
@@ -251,25 +251,25 @@ approximate_range (real_t max_costs, real_t price, int max_edges,
 /*****************************************************************************
 
                  local variables
-  
+
 *****************************************************************************/
 
-static real_t norm_ortho_vector [MAXSTATES];     
+static real_t norm_ortho_vector [MAXSTATES];
 /*
  *  Square-norm of the i-th vector of the orthogonal basis (OB)
  *  ||o_i||^2; i = 0, ... ,n
  */
 static real_t ip_image_ortho_vector [MAXEDGES];
-/* 
- *  Inner product between the i-th vector of the OB and the given range: 
- *  <b, o_i>; i = 0, ... ,n 
+/*
+ *  Inner product between the i-th vector of the OB and the given range:
+ *  <b, o_i>; i = 0, ... ,n
  */
 static real_t ip_domain_ortho_vector [MAXSTATES][MAXEDGES];
-/* 
- *  Inner product between the i-th vector of the OB and the image of domain j: 
- *  <s_j, o_i>; j = 0, ... , wfa->states; i = 0, ... ,n, 
+/*
+ *  Inner product between the i-th vector of the OB and the image of domain j:
+ *  <s_j, o_i>; j = 0, ... , wfa->states; i = 0, ... ,n,
  */
-static real_t rem_denominator [MAXSTATES];     
+static real_t rem_denominator [MAXSTATES];
 static real_t rem_numerator [MAXSTATES];
 /*
  *  At step n of the orthogonalization the comparative value
@@ -280,7 +280,7 @@ static real_t rem_numerator [MAXSTATES];
  *  the constant (remaining) parts of every domain are
  *  stored in 'rem_numerator' and 'rem_denominator' separately
  */
-static bool_t used [MAXSTATES];    
+static bool_t used [MAXSTATES];
 /*
  *  Shows whether a domain image was already used in a
  *  linear combination (YES) or not (NO)
@@ -289,10 +289,10 @@ static bool_t used [MAXSTATES];
 /*****************************************************************************
 
                 private code
-  
+
 *****************************************************************************/
 
-static void 
+static void
 matching_pursuit (mp_t *mp, bool_t full_search, real_t price,
                   unsigned max_edges, int y_state, const range_t *range,
                   const domain_pool_t *domain_pool, const coeff_t *coeff,
@@ -313,7 +313,7 @@ matching_pursuit (mp_t *mp, bool_t full_search, real_t price,
  *  elements in the linear combination is limited by 'max_edges'. In
  *  'mp', vectors may be specified which should be excluded during the
  *  approximation.
- *  
+ *
  *  No return value.
  *
  *  Side effects:
@@ -329,7 +329,7 @@ matching_pursuit (mp_t *mp, bool_t full_search, real_t price,
     const real_t  min_norm = 2e-3;   /* lower bound of norm */
     unsigned      best_n   = 0;
     unsigned  size     = size_of_level (range->level);
- 
+
     /*
      *  Initialize domain pool and inner product arrays
      */
@@ -378,7 +378,7 @@ matching_pursuit (mp_t *mp, bool_t full_search, real_t price,
                         + additional_bits) * price + mp->err;
 
     n = 0;
-    do 
+    do
     {
         /*
          *  Current approximation is: b = d_0 o_0 + ... + d_(n-1) o_(n-1)
@@ -390,15 +390,15 @@ matching_pursuit (mp_t *mp, bool_t full_search, real_t price,
          *  which has minimal costs: s_index.
          *  (No progress is indicated by index == -1)
          */
-      
+
         real_t min_matrix_bits  = 0;
         real_t min_weights_bits = 0;
         real_t min_error        = 0;
         real_t min_weight [MAXEDGES];
         real_t min_costs = full_search ? MAXCOSTS : mp->costs;
-      
-        for (index = -1, domain = 0; domain_blocks [domain] >= 0; domain++) 
-            if (!used [domain]) 
+
+        for (index = -1, domain = 0; domain_blocks [domain] >= 0; domain++)
+            if (!used [domain])
             {
                 real_t    matrix_bits, weights_bits;
                 /*
@@ -413,7 +413,7 @@ matching_pursuit (mp_t *mp, bool_t full_search, real_t price,
                     word_t   states [MAXEDGES + 1];
                     real_t   weights [MAXEDGES + 1];
                     unsigned i, k;
-          
+
                     for (i = 0, k = 0; k < n; k++)
                         if (mp->weight [k] != 0)
                         {
@@ -477,7 +477,7 @@ matching_pursuit (mp_t *mp, bool_t full_search, real_t price,
                         f[k] = ip_image_ortho_vector[k] / norm_ortho_vector[k];
                         v [k] = mp->indices [k];
                     }
-        
+
                     for (l = n; l >= 0; --l) {
                         rpf_t * const rpf = domain_blocks[v[l]]
                             ? coeff->rpf : coeff->dc_rpf;
@@ -488,13 +488,13 @@ matching_pursuit (mp_t *mp, bool_t full_search, real_t price,
 
                         {
                             real_t const fl = f[l];
-             
+
                             for (k = 0; k < l; ++k) {
                                 f[k] -= fl * ip_domain_ortho_vector[v[l]][k]
                                     / norm_ortho_vector[k];
                             }
                         }
-                    } 
+                    }
 
                     /*
                      *  Compute the number of output bits of the linear
@@ -507,7 +507,7 @@ matching_pursuit (mp_t *mp, bool_t full_search, real_t price,
                         word_t states [MAXEDGES + 1];
                         real_t weights [MAXEDGES + 1];
                         int    i;
-          
+
                         for (i = 0, k = 0; k <= n; k++)
                             if (f [k] != 0)
                             {
@@ -525,10 +525,10 @@ matching_pursuit (mp_t *mp, bool_t full_search, real_t price,
                                                     range->level, y_state,
                                                     wfa, domain_pool->model);
                     }
-           
+
                     /*
                      *  To compute the approximation error, the corresponding
-                     *  linear factors of the linear combination 
+                     *  linear factors of the linear combination
                      *  b = r_0 o_0 + ... + r_(n-1) o_(n-1) + r_n o_'domain'
                      *  with orthogonal vectors must be computed with following
                      *  formula:
@@ -546,7 +546,7 @@ matching_pursuit (mp_t *mp, bool_t full_search, real_t price,
                         a = get_ip_state_state (domain_blocks [v [l]],
                                                 domain_blocks [domain],
                                                 range->level, c);
-                        for (k = 0; k < n; k++) 
+                        for (k = 0; k < n; k++)
                             a -= ip_domain_ortho_vector [v [l]][k]
                                 / norm_ortho_vector [k]
                                 * ip_domain_ortho_vector [domain][k];
@@ -554,7 +554,7 @@ matching_pursuit (mp_t *mp, bool_t full_search, real_t price,
                     }
                     norm_ortho_vector [n]     = rem_denominator [domain];
                     ip_image_ortho_vector [n] = rem_numerator [domain];
-        
+
                     for (k = 0; k <= n; k++)
                         for (l = k + 1; (unsigned) l <= n; l++)
                             r [k] += ip_domain_ortho_vector [v [l]][k] * r [l]
@@ -586,40 +586,40 @@ matching_pursuit (mp_t *mp, bool_t full_search, real_t price,
                     }
                 }
             }
-      
+
         if (index >= 0)           /* found a better approximation */
         {
             if (min_costs < mp->costs)
             {
                 unsigned k;
-        
+
                 mp->costs        = min_costs;
                 mp->err          = min_error;
                 mp->matrix_bits  = min_matrix_bits;
                 mp->weights_bits = min_weights_bits;
-        
+
                 for (k = 0; k <= n; k++)
                     mp->weight [k] = min_weight [k];
 
                 best_n = n + 1;
             }
-     
+
             mp->indices [n] = index;
             mp->into [n]    = domain_blocks [index];
 
             used [index] = YES;
 
-            /* 
-             *  Gram-Schmidt orthogonalization step n 
+            /*
+             *  Gram-Schmidt orthogonalization step n
              */
             orthogonalize (index, n, range->level, min_norm, domain_blocks, c);
             n++;
-        } 
-    } 
+        }
+    }
     while (n < max_edges && index >= 0);
 
     mp->indices [best_n] = NO_EDGE;
-   
+
     mp->costs = (mp->matrix_bits + mp->weights_bits + additional_bits) * price
         + mp->err;
 
@@ -641,31 +641,31 @@ orthogonalize (unsigned index, unsigned n, unsigned level, real_t min_norm,
  *
  *  Side effects:
  *  The remainder values (numerator and denominator) of
- *  all 'domain_blocks' are updated. 
+ *  all 'domain_blocks' are updated.
  */
 {
    unsigned domain;
-   
+
    ip_image_ortho_vector [n] = rem_numerator [index];
    norm_ortho_vector [n]     = rem_denominator [index];
 
    /*
-    *  Compute inner products between all domain images and 
+    *  Compute inner products between all domain images and
     *  vector n of the orthogonal basis:
-    *  for (i = 0, ... , wfa->states)  
+    *  for (i = 0, ... , wfa->states)
     *  <s_i, o_n> := <s_i, v_n> -
     *      \sum (k = 0, ... , n - 1){ <v_n, o_k> <s_i, o_k> / ||o_k||^2}
     *  Moreover the denominator and numerator parts of the comparative
     *  value are updated.
     */
-   for (domain = 0; domain_blocks [domain] >= 0; domain++) 
-      if (!used [domain]) 
+   for (domain = 0; domain_blocks [domain] >= 0; domain++)
+      if (!used [domain])
       {
      unsigned k;
      real_t   tmp = get_ip_state_state (domain_blocks [index],
                         domain_blocks [domain], level, c);
-     
-     for (k = 0; k < n; k++) 
+
+     for (k = 0; k < n; k++)
         tmp -= ip_domain_ortho_vector [domain][k] / norm_ortho_vector [k]
            * ip_domain_ortho_vector [index][k];
      ip_domain_ortho_vector [domain][n] = tmp;
@@ -677,8 +677,8 @@ orthogonalize (unsigned index, unsigned n, unsigned level, real_t min_norm,
      /*
       *  Exclude vectors with small denominator
       */
-     if (!used [domain]) 
-        if (rem_denominator [domain] / size_of_level (level) < min_norm) 
+     if (!used [domain])
+        if (rem_denominator [domain] / size_of_level (level) < min_norm)
            used [domain] = YES;
       }
 }
diff --git a/converter/other/fiasco/codec/approx.h b/converter/other/fiasco/codec/approx.h
index 42f1458a..cce27eb6 100644
--- a/converter/other/fiasco/codec/approx.h
+++ b/converter/other/fiasco/codec/approx.h
@@ -1,8 +1,8 @@
 /*
  *  approx.h
  *
- *  Written by:		Ullrich Hafner
- *		
+ *  Written by:         Ullrich Hafner
+ *
  *  This file is part of FIASCO (Fractal Image And Sequence COdec)
  *  Copyright (C) 1994-2000 Ullrich Hafner
  */
@@ -21,10 +21,10 @@
 #include "cwfa.h"
 #include "domain-pool.h"
 
-real_t 
+real_t
 approximate_range (real_t max_costs, real_t price, int max_edges,
-		   int y_state, range_t *range, domain_pool_t *domain_pool,
-		   coeff_t *coeff, const wfa_t *wfa, const coding_t *c);
+                   int y_state, range_t *range, domain_pool_t *domain_pool,
+                   coeff_t *coeff, const wfa_t *wfa, const coding_t *c);
 
 #endif /* not _APPROX_H */
 
diff --git a/converter/other/fiasco/codec/bintree.c b/converter/other/fiasco/codec/bintree.c
index b050ab63..ca828fb2 100644
--- a/converter/other/fiasco/codec/bintree.c
+++ b/converter/other/fiasco/codec/bintree.c
@@ -1,8 +1,8 @@
 /*
- *  bintree.c:		Bintree model of WFA tree	
+ *  bintree.c:          Bintree model of WFA tree
+ *
+ *  Written by:         Ullrich Hafner
  *
- *  Written by:		Ullrich Hafner
- *		
  *  This file is part of FIASCO (Fractal Image And Sequence COdec)
  *  Copyright (C) 1994-2000 Ullrich Hafner
  */
@@ -28,8 +28,8 @@
 
 /*****************************************************************************
 
-				public code
-  
+                                public code
+
 *****************************************************************************/
 
 void
@@ -40,7 +40,7 @@ tree_update (bool_t child, unsigned level, tree_t *model)
  *  No return value.
  *
  *  Side effects:
- *	tree model is changed.
+ *      tree model is changed.
  */
 {
    if (!child)
@@ -59,7 +59,7 @@ tree_bits (bool_t child, unsigned level, const tree_t *model)
  *  For each 'level' a different context is used.
  *
  *  Return value:
- *	# bits
+ *      # bits
  */
 {
    real_t prob = model->counts [level] / (real_t) model->total [level];
@@ -80,13 +80,13 @@ init_tree_model (tree_t *tree_model)
 {
    unsigned level;
    unsigned counts_0 [MAXLEVEL] = {20, 17, 15, 10, 5,  4,  3,
-				   2,  1,  1,  1,  1,  1,  1,  1,
-				   1,  1,  1,  1 , 1,  1,  1};
+                                   2,  1,  1,  1,  1,  1,  1,  1,
+                                   1,  1,  1,  1 , 1,  1,  1};
    unsigned counts_1 [MAXLEVEL] = {1 , 1,  1,  1,  1,  1,  1,
-				   1,  1,  2,  3,  5,  10, 15, 20,
-				   25, 30, 35, 60, 60, 60, 60};
-   
-   for (level = 0; level < MAXLEVEL ; level++) 
+                                   1,  1,  2,  3,  5,  10, 15, 20,
+                                   25, 30, 35, 60, 60, 60, 60};
+
+   for (level = 0; level < MAXLEVEL ; level++)
    {
       tree_model->counts [level] = counts_1 [level];
       tree_model->total [level]  = counts_0 [level] + counts_1 [level];
diff --git a/converter/other/fiasco/codec/bintree.h b/converter/other/fiasco/codec/bintree.h
index 3dc88ac1..c68b2e7b 100644
--- a/converter/other/fiasco/codec/bintree.h
+++ b/converter/other/fiasco/codec/bintree.h
@@ -1,8 +1,8 @@
 /*
  *  bintree.h
  *
- *  Written by:		Ullrich Hafner
- *		
+ *  Written by:         Ullrich Hafner
+ *              
  *  This file is part of FIASCO (Fractal Image And Sequence COdec)
  *  Copyright (C) 1994-2000 Ullrich Hafner
  */
@@ -28,8 +28,8 @@ typedef struct tree
  *  which indicate whether there exists a tree edge or not.
  */
 {
-   unsigned counts [MAXLEVEL];		/* # NO_RANGE symbols at given level */
-   unsigned total [MAXLEVEL];		/* total number of symbols at  ''   */
+   unsigned counts [MAXLEVEL];          /* # NO_RANGE symbols at given level */
+   unsigned total [MAXLEVEL];           /* total number of symbols at  ''   */
 } tree_t;
 
 real_t
diff --git a/converter/other/fiasco/codec/coder.h b/converter/other/fiasco/codec/coder.h
index 2fe81d81..4e8e400d 100644
--- a/converter/other/fiasco/codec/coder.h
+++ b/converter/other/fiasco/codec/coder.h
@@ -1,8 +1,8 @@
 /*
  *  coder.h
  *
- *  Written by:		Ullrich Hafner
- *		
+ *  Written by:         Ullrich Hafner
+ *              
  *  This file is part of FIASCO (Fractal Image And Sequence COdec)
  *  Copyright (C) 1994-2000 Ullrich Hafner
  */
diff --git a/converter/other/fiasco/codec/coeff.c b/converter/other/fiasco/codec/coeff.c
index 6d33bad5..3a5a6a0a 100644
--- a/converter/other/fiasco/codec/coeff.c
+++ b/converter/other/fiasco/codec/coeff.c
@@ -1,8 +1,8 @@
 /*
- *  coeff.c:		Matching pursuit coefficients probability model
+ *  coeff.c:            Matching pursuit coefficients probability model
+ *
+ *  Written by:         Ullrich Hafner
  *
- *  Written by:		Ullrich Hafner
- *		
  *  This file is part of FIASCO (Fractal Image And Sequence COdec)
  *  Copyright (C) 1994-2000 Ullrich Hafner
  */
@@ -28,9 +28,9 @@
 /*
  *  Coefficient model interface:
  *  Implementing the coefficients model interface requires the
- *  following steps: 
+ *  following steps:
  *  - Add a constructor that initializes the coeff_t structure
- *  - Allocate new model with default_alloc() 
+ *  - Allocate new model with default_alloc()
  *  - Fill the c_array_t coeff_models[] array with constructor and name
  *  - Write code for methods bits() and update()
  *  - Either use default functions for remaining methods or override them
@@ -38,21 +38,21 @@
  */
 
 /*****************************************************************************
-		  uniform distribution coefficients model
+                  uniform distribution coefficients model
 *****************************************************************************/
 
 static coeff_t *
 alloc_uniform_coeff_model (rpf_t *rpf, rpf_t *dc_rpf,
-			   unsigned min_level, unsigned max_level);
+                           unsigned min_level, unsigned max_level);
 static void
 uniform_update (const real_t *used_coeff, const word_t *used_states,
-		unsigned level, coeff_t *coeff);
+                unsigned level, coeff_t *coeff);
 static real_t
 uniform_bits (const real_t *used_coeff, const word_t *used_states,
-	      unsigned level, const coeff_t *coeff);
+              unsigned level, const coeff_t *coeff);
 
 /*****************************************************************************
-			  default functions
+                          default functions
 *****************************************************************************/
 
 static void
@@ -63,15 +63,15 @@ static void
 default_free (coeff_t *coeff);
 static coeff_t *
 default_alloc (rpf_t *rpf, rpf_t *dc_rpf,
-	       unsigned min_level, unsigned max_level);
+               unsigned min_level, unsigned max_level);
 
 /*****************************************************************************
-		adaptive arithmetic coding model
+                adaptive arithmetic coding model
 *****************************************************************************/
 
 static coeff_t *
 alloc_aac_coeff_model (rpf_t *rpf, rpf_t *dc_rpf,
-		       unsigned min_level, unsigned max_level);
+                       unsigned min_level, unsigned max_level);
 static void
 aac_model_free (void *model);
 static void *
@@ -80,70 +80,70 @@ static void *
 aac_model_duplicate (const coeff_t *coeff, const void *model);
 static void
 aac_update (const real_t *used_coeff, const word_t *used_states,
-	    unsigned level, coeff_t *coeff);
+            unsigned level, coeff_t *coeff);
 static real_t
 aac_bits (const real_t *used_coeff, const word_t *used_states,
-	  unsigned level, const coeff_t *coeff);
+          unsigned level, const coeff_t *coeff);
 
 /*****************************************************************************
 
-				public code
-  
+                                public code
+
 *****************************************************************************/
 
 typedef struct c_array
 {
    const char *identifier;
    coeff_t    *(*function) (rpf_t *rpf, rpf_t *dc_rpf,
-			    unsigned min_level, unsigned max_level);
+                            unsigned min_level, unsigned max_level);
 } c_array_t;
 
 c_array_t coeff_models[] = {{"adaptive", alloc_aac_coeff_model},
-			    {"uniform",	 alloc_uniform_coeff_model},
-			    {NULL,	 NULL}};
+                            {"uniform",  alloc_uniform_coeff_model},
+                            {NULL,       NULL}};
 
 coeff_t *
 alloc_coeff_model (const char *coeff_model_name, rpf_t *rpf, rpf_t *dc_rpf,
-		   unsigned min_level, unsigned max_level)
+                   unsigned min_level, unsigned max_level)
 /*
  *  Allocate a new coefficients model which is identified by the string
  *  'coeff_model_name'.  'rpf' and 'dc_rpf' define the reduced
  *  precision formats the should be used to quantize normal and DC
  *  components, respectively. 'min_level' and 'max_level' define the
  *  range of range approximations.
- * 
+ *
  *  Return value:
- *	pointer to the allocated coefficients model
+ *      pointer to the allocated coefficients model
  *
  *  Note:
  *      Refer to 'coeff.h' for a short description of the member functions.  */
 {
    unsigned n;
-   
+
    for (n = 0; coeff_models [n].identifier; n++) /* step through all id's */
-      if (strcaseeq (coeff_models [n].identifier, coeff_model_name)) 
-	 return coeff_models [n].function (rpf, dc_rpf, min_level, max_level);
+      if (strcaseeq (coeff_models [n].identifier, coeff_model_name))
+         return coeff_models [n].function (rpf, dc_rpf, min_level, max_level);
 
    warning ("Can't initialize coefficients model '%s'. "
-	    "Using default value '%s'.",
-	    coeff_model_name, coeff_models [0].identifier);
+            "Using default value '%s'.",
+            coeff_model_name, coeff_models [0].identifier);
 
    return coeff_models [0].function (rpf, dc_rpf, min_level, max_level);
 }
 
 /*****************************************************************************
 
-				private code
-  
+                                private code
+
 *****************************************************************************/
 
 /*****************************************************************************
-		  uniform distribution coefficients model
+                  uniform distribution coefficients model
 *****************************************************************************/
 
 static coeff_t *
 alloc_uniform_coeff_model (rpf_t *rpf, rpf_t *dc_rpf,
-			   unsigned min_level, unsigned max_level)
+                           unsigned min_level, unsigned max_level)
 /*
  *  Underlying probability model: uniform distribution.
  *  I.e. each coefficient is written as such with
@@ -154,21 +154,21 @@ alloc_uniform_coeff_model (rpf_t *rpf, rpf_t *dc_rpf,
 
    coeff->bits   = uniform_bits;
    coeff->update = uniform_update;
-   
+
    return coeff;
 }
 
 static real_t
 uniform_bits (const real_t *used_coeff, const word_t *used_states,
-	      unsigned level, const coeff_t *coeff)
+              unsigned level, const coeff_t *coeff)
 {
    unsigned edge;
-   real_t   bits = 0;			/* #bits to store coefficients */
-   
+   real_t   bits = 0;                   /* #bits to store coefficients */
+
    for (edge = 0; isedge (used_states [edge]); edge++)
    {
       rpf_t *rpf = used_states [edge] ? coeff->rpf : coeff->dc_rpf;
-      
+
       bits += rpf->mantissa_bits + 1;
    }
 
@@ -177,13 +177,13 @@ uniform_bits (const real_t *used_coeff, const word_t *used_states,
 
 static void
 uniform_update (const real_t *used_coeff, const word_t *used_states,
-		unsigned level, coeff_t *coeff)
+                unsigned level, coeff_t *coeff)
 {
-   return;				/* nothing to do */
+   return;                              /* nothing to do */
 }
 
 /*****************************************************************************
-		adaptive arithmetic coding  model
+                adaptive arithmetic coding  model
 *****************************************************************************/
 
 typedef struct aac_model
@@ -194,74 +194,74 @@ typedef struct aac_model
 
 static coeff_t *
 alloc_aac_coeff_model (rpf_t *rpf, rpf_t *dc_rpf,
-		       unsigned min_level, unsigned max_level)
+                       unsigned min_level, unsigned max_level)
 /*
  *  Underlying probability model: adaptive arithmetic coding using
  *  the level of a range as context.
  */
 {
    coeff_t *coeff = default_alloc (rpf, dc_rpf, min_level, max_level);
-   
+
    coeff->bits            = aac_bits;
    coeff->update          = aac_update;
    coeff->model_free      = aac_model_free;
    coeff->model_duplicate = aac_model_duplicate;
-   coeff->model		  = aac_model_alloc (coeff);
-   
+   coeff->model           = aac_model_alloc (coeff);
+
    return coeff;
 }
 
 static real_t
 aac_bits (const real_t *used_coeff, const word_t *used_states,
-	  unsigned level, const coeff_t *coeff)
+          unsigned level, const coeff_t *coeff)
 {
-   real_t	bits  = 0;		/* # bits to store coefficients */
-   unsigned	edge;
-   int		state;
+   real_t       bits  = 0;              /* # bits to store coefficients */
+   unsigned     edge;
+   int          state;
    word_t      *counts;
    aac_model_t *model = (aac_model_t *) coeff->model;
 
    counts = model->counts
-	    + (1 << (1 + coeff->dc_rpf->mantissa_bits))
-	    + ((level - coeff->min_level)
-	       * (1 << (1 + coeff->rpf->mantissa_bits)));
-   
+            + (1 << (1 + coeff->dc_rpf->mantissa_bits))
+            + ((level - coeff->min_level)
+               * (1 << (1 + coeff->rpf->mantissa_bits)));
+
    for (edge = 0; isedge (state = used_states [edge]); edge++)
       if (state)
-	 bits -= log2 (counts [rtob (used_coeff [edge], coeff->rpf)]
-		       / (real_t) model->totals [level
-						- coeff->min_level + 1]);
+         bits -= log2 (counts [rtob (used_coeff [edge], coeff->rpf)]
+                       / (real_t) model->totals [level
+                                                - coeff->min_level + 1]);
       else
-	 bits -= log2 (model->counts [rtob (used_coeff [edge], coeff->dc_rpf)]
-		       / (real_t) model->totals [0]);
-   
+         bits -= log2 (model->counts [rtob (used_coeff [edge], coeff->dc_rpf)]
+                       / (real_t) model->totals [0]);
+
    return bits;
 }
 
 static void
 aac_update (const real_t *used_coeff, const word_t *used_states,
-	    unsigned level, coeff_t *coeff)
+            unsigned level, coeff_t *coeff)
 {
-   unsigned	edge;
-   int		state;
+   unsigned     edge;
+   int          state;
    word_t      *counts;
    aac_model_t *model = (aac_model_t *) coeff->model;
 
    counts = model->counts
-	    + (1 << (1 + coeff->dc_rpf->mantissa_bits))
-	    + ((level - coeff->min_level)
-	       * (1 << (1 + coeff->rpf->mantissa_bits)));
+            + (1 << (1 + coeff->dc_rpf->mantissa_bits))
+            + ((level - coeff->min_level)
+               * (1 << (1 + coeff->rpf->mantissa_bits)));
 
    for (edge = 0; isedge (state = used_states [edge]); edge++)
       if (state)
       {
-	 counts [rtob (used_coeff [edge], coeff->rpf)]++;
-	 model->totals [level - coeff->min_level + 1]++;
+         counts [rtob (used_coeff [edge], coeff->rpf)]++;
+         model->totals [level - coeff->min_level + 1]++;
       }
       else
       {
-	 model->counts [rtob (used_coeff [edge], coeff->dc_rpf)]++;
-	 model->totals [0]++;
+         model->counts [rtob (used_coeff [edge], coeff->dc_rpf)]++;
+         model->totals [0]++;
       }
 }
 
@@ -272,12 +272,12 @@ aac_model_duplicate (const coeff_t *coeff, const void *model)
    aac_model_t *dst = aac_model_alloc (coeff);
 
    memcpy (dst->counts, src->counts,
-	   sizeof (word_t) * ((coeff->max_level - coeff->min_level + 1)
-			      * (1 << (1 + coeff->rpf->mantissa_bits))
-			      + (1 << (1 + coeff->dc_rpf->mantissa_bits))));
+           sizeof (word_t) * ((coeff->max_level - coeff->min_level + 1)
+                              * (1 << (1 + coeff->rpf->mantissa_bits))
+                              + (1 << (1 + coeff->dc_rpf->mantissa_bits))));
    memcpy (dst->totals, src->totals,
-	   sizeof (word_t) * (coeff->max_level - coeff->min_level + 1 + 1));
-   
+           sizeof (word_t) * (coeff->max_level - coeff->min_level + 1 + 1));
+
    return dst;
 }
 
@@ -285,36 +285,36 @@ static void *
 aac_model_alloc (const coeff_t *coeff)
 {
    aac_model_t *model;
-   unsigned	size = (coeff->max_level - coeff->min_level + 1)
-		       * (1 << (1 + coeff->rpf->mantissa_bits))
-		       + (1 << (1 + coeff->dc_rpf->mantissa_bits));
-   
-   model 	 = Calloc (1, sizeof (aac_model_t));
+   unsigned     size = (coeff->max_level - coeff->min_level + 1)
+                       * (1 << (1 + coeff->rpf->mantissa_bits))
+                       + (1 << (1 + coeff->dc_rpf->mantissa_bits));
+
+   model         = Calloc (1, sizeof (aac_model_t));
    model->counts = Calloc (size, sizeof (word_t));
    model->totals = Calloc (coeff->max_level - coeff->min_level + 1 + 1,
-			   sizeof (word_t));
+                           sizeof (word_t));
    /*
     *  Initialize model
     */
    {
       unsigned  n;
       word_t   *ptr = model->counts;
-      
+
       for (n = size; n; n--)
-	 *ptr++ = 1;
+         *ptr++ = 1;
       model->totals [0] = 1 << (1 + coeff->dc_rpf->mantissa_bits);
       for (n = coeff->min_level; n <= coeff->max_level; n++)
-	 model->totals [n - coeff->min_level + 1]
-	    = 1 << (1 + coeff->rpf->mantissa_bits);
+         model->totals [n - coeff->min_level + 1]
+            = 1 << (1 + coeff->rpf->mantissa_bits);
    }
-   
+
    return (void *) model;
 }
 
 static void
 aac_model_free (void *model)
 {
-   aac_model_t	*aac_model = (aac_model_t *) model;
+   aac_model_t  *aac_model = (aac_model_t *) model;
 
    if (aac_model)
    {
@@ -325,26 +325,26 @@ aac_model_free (void *model)
 }
 
 /*****************************************************************************
-				default functions
+                                default functions
 *****************************************************************************/
 
 static coeff_t *
 default_alloc (rpf_t *rpf, rpf_t *dc_rpf,
-	       unsigned min_level, unsigned max_level)
+               unsigned min_level, unsigned max_level)
 {
    coeff_t *coeff = Calloc (1, sizeof (coeff_t));
 
-   coeff->rpf 	      	  = rpf;
-   coeff->dc_rpf       	  = dc_rpf;
-   coeff->min_level	  = min_level;
-   coeff->max_level	  = max_level;
-   coeff->model	      	  = NULL;
-   coeff->bits	      	  = NULL;
-   coeff->update      	  = NULL;
-   coeff->free	      	  = default_free;
-   coeff->model_free  	  = default_model_free;
+   coeff->rpf             = rpf;
+   coeff->dc_rpf          = dc_rpf;
+   coeff->min_level       = min_level;
+   coeff->max_level       = max_level;
+   coeff->model           = NULL;
+   coeff->bits            = NULL;
+   coeff->update          = NULL;
+   coeff->free            = default_free;
+   coeff->model_free      = default_model_free;
    coeff->model_duplicate = default_model_duplicate;
-   
+
    return coeff;
 }
 
diff --git a/converter/other/fiasco/codec/coeff.h b/converter/other/fiasco/codec/coeff.h
index 6193e2ee..f22de2d7 100644
--- a/converter/other/fiasco/codec/coeff.h
+++ b/converter/other/fiasco/codec/coeff.h
@@ -1,8 +1,8 @@
 /*
  *  coeff.h
  *
- *  Written by:		Ullrich Hafner
- *		
+ *  Written by:         Ullrich Hafner
+ *              
  *  This file is part of FIASCO (Fractal Image And Sequence COdec)
  *  Copyright (C) 1994-2000 Ullrich Hafner
  */
@@ -23,23 +23,23 @@
 
 typedef struct coeff
 {
-   rpf_t    *rpf;			/* reduced precision format */
-   rpf_t    *dc_rpf;			/* RPF of DC (state 0) component */
-   unsigned min_level, max_level;	/* allocate memory for [min,..,max] */
-   void	    *model;			/* generic pointer to prob. model */
+   rpf_t    *rpf;                       /* reduced precision format */
+   rpf_t    *dc_rpf;                    /* RPF of DC (state 0) component */
+   unsigned min_level, max_level;       /* allocate memory for [min,..,max] */
+   void     *model;                     /* generic pointer to prob. model */
    real_t (*bits) (const real_t *used_coeff, const word_t *used_domains,
-		   unsigned level, const struct coeff *coeff);
+                   unsigned level, const struct coeff *coeff);
    /*
     *  Compute bit-rate of a range approximation with coefficients given by
     *  -1 terminated list 'used_domains'.
     */
    void   (*update) (const real_t *used_coeff, const word_t *used_domains,
-		       unsigned level, struct coeff *coeff);
+                       unsigned level, struct coeff *coeff);
    /*
     *  Update the probability model according to the chosen approximation.
     *  (given by the -1 terminated list 'used_domains').
     */
-   void	  (*free) (struct coeff *coeff);
+   void   (*free) (struct coeff *coeff);
    /*
     *  Discard the given coefficients struct.
     */
@@ -55,7 +55,7 @@ typedef struct coeff
 
 coeff_t *
 alloc_coeff_model (const char *coeff_model_name, rpf_t *rpf, rpf_t *dc_rpf,
-		   unsigned min_level, unsigned max_level);
+                   unsigned min_level, unsigned max_level);
 
 #endif /* not _COEFF_H */
 
diff --git a/converter/other/fiasco/codec/control.c b/converter/other/fiasco/codec/control.c
index 2ea06052..0588623f 100644
--- a/converter/other/fiasco/codec/control.c
+++ b/converter/other/fiasco/codec/control.c
@@ -1,8 +1,8 @@
 /*
- *  control.c:		Control unit of WFA structure
+ *  control.c:          Control unit of WFA structure
+ *
+ *  Written by:         Ullrich Hafner
  *
- *  Written by:		Ullrich Hafner
- *		
  *  This file is part of FIASCO (Fractal Image And Sequence COdec)
  *  Copyright (C) 1994-2000 Ullrich Hafner
  */
@@ -17,7 +17,7 @@
 #include "config.h"
 
 #include <string.h>
- 
+
 #include "types.h"
 #include "macros.h"
 #include "error.h"
@@ -30,24 +30,24 @@
 
 /*****************************************************************************
 
-				prototypes
-  
+                                prototypes
+
 *****************************************************************************/
 
-static void 
+static void
 clear_or_alloc (real_t **ptr, size_t size);
-static void 
+static void
 compute_images (unsigned from, unsigned to, const wfa_t *wfa, coding_t *c);
 
 /*****************************************************************************
 
-				public code
-  
+                                public code
+
 *****************************************************************************/
 
-void    
+void
 append_state (bool_t auxiliary_state, real_t final, unsigned level_of_state,
-	      wfa_t *wfa, coding_t *c)
+              wfa_t *wfa, coding_t *c)
 /*
  *  Append a 'wfa' state. If 'auxiliary_state' == YES then
  *  allocate memory for inner products and state images.  'final' is
@@ -57,13 +57,13 @@ append_state (bool_t auxiliary_state, real_t final, unsigned level_of_state,
  *  No return value.
  *
  *  Side effects:
- *	The WFA information are updated in structure 'wfa'
- *	State images are computed and inner products are cleared (in 'c')
+ *      The WFA information are updated in structure 'wfa'
+ *      State images are computed and inner products are cleared (in 'c')
  */
 {
    wfa->final_distribution [wfa->states] = final;
    wfa->level_of_state [wfa->states]     = level_of_state;
-   
+
    if (!auxiliary_state)
    {
       unsigned level;
@@ -74,63 +74,63 @@ append_state (bool_t auxiliary_state, real_t final, unsigned level_of_state,
        *  Allocate memory for inner products and for state images
        */
       clear_or_alloc (&c->images_of_state [wfa->states],
-		      size_of_tree (c->options.images_level));
-	 
+                      size_of_tree (c->options.images_level));
+
       for (level = c->options.images_level + 1;
-	   level <= c->options.lc_max_level; level++)
-	 clear_or_alloc (&c->ip_states_state [wfa->states][level],
-			 wfa->states + 1);
+           level <= c->options.lc_max_level; level++)
+         clear_or_alloc (&c->ip_states_state [wfa->states][level],
+                         wfa->states + 1);
 
       clear_or_alloc (&c->ip_images_state [wfa->states],
-		      size_of_tree (c->products_level));
+                      size_of_tree (c->products_level));
 
       /*
        *  Compute the images of the current state at level 0,..,'imageslevel'
        */
-      
+
       c->images_of_state [wfa->states][0] = final;
-      compute_images (wfa->states, wfa->states, wfa, c);  
+      compute_images (wfa->states, wfa->states, wfa, c);
 
       /*
        *  Compute the inner products between the current state and the
        *  old states 0,...,'states'-1
-       */ 
-      
+       */
+
       compute_ip_states_state (wfa->states, wfa->states, wfa, c);
    }
    else
    {
       unsigned level;
-      
+
       wfa->domain_type [wfa->states] = 0;
-	    
+
       /*
        *  Free the allocated memory
        */
       if (c->images_of_state [wfa->states] != NULL)
       {
-	 Free (c->images_of_state [wfa->states]);
-	 c->images_of_state [wfa->states] = NULL;
+         Free (c->images_of_state [wfa->states]);
+         c->images_of_state [wfa->states] = NULL;
       }
       for (level = 0; level <= c->options.lc_max_level; level++)
-	 if (c->ip_states_state [wfa->states][level])
-	 {
-	    Free (c->ip_states_state [wfa->states][level]);
-	    c->ip_states_state [wfa->states][level] = NULL;
-	 }
+         if (c->ip_states_state [wfa->states][level])
+         {
+            Free (c->ip_states_state [wfa->states][level]);
+            c->ip_states_state [wfa->states][level] = NULL;
+         }
       if (c->ip_images_state [wfa->states])
       {
-	 Free (c->ip_images_state [wfa->states]);
-	 c->ip_images_state [wfa->states] = NULL;
+         Free (c->ip_images_state [wfa->states]);
+         c->ip_images_state [wfa->states] = NULL;
       }
    }
-   
+
    wfa->states++;
-   if (wfa->states >= MAXSTATES) 
+   if (wfa->states >= MAXSTATES)
       error ("Maximum number of states reached!");
-}	
- 
-void 
+}
+
+void
 append_basis_states (unsigned basis_states, wfa_t *wfa, coding_t *c)
 /*
  *  Append the WFA basis states 0, ... , ('basis_states' - 1).
@@ -138,8 +138,8 @@ append_basis_states (unsigned basis_states, wfa_t *wfa, coding_t *c)
  *  No return value.
  *
  *  Side effects:
- *	The WFA information are updated in structure 'wfa'
- *	State images and inner products are computed (in 'c')
+ *      The WFA information are updated in structure 'wfa'
+ *      State images and inner products are computed (in 'c')
  */
 {
    unsigned level, state;
@@ -151,30 +151,30 @@ append_basis_states (unsigned basis_states, wfa_t *wfa, coding_t *c)
    for (state = 0; state < basis_states; state++)
    {
       clear_or_alloc (&c->images_of_state [state],
-		      size_of_tree (c->options.images_level));
+                      size_of_tree (c->options.images_level));
 
       for (level = c->options.images_level + 1;
-	   level <= c->options.lc_max_level; level++)
-	 clear_or_alloc (&c->ip_states_state [state][level], state + 1);
+           level <= c->options.lc_max_level; level++)
+         clear_or_alloc (&c->ip_states_state [state][level], state + 1);
 
       clear_or_alloc (&c->ip_images_state [state],
-		      size_of_tree (c->products_level));
+                      size_of_tree (c->products_level));
 
       c->images_of_state [state][0] = wfa->final_distribution [state];
       wfa->level_of_state [state]   = -1;
    }
-   
-   compute_images (0, basis_states - 1, wfa, c);  
+
+   compute_images (0, basis_states - 1, wfa, c);
    compute_ip_states_state (0, basis_states - 1, wfa, c);
    wfa->states = basis_states;
-   
-   if (wfa->states >= MAXSTATES) 
+
+   if (wfa->states >= MAXSTATES)
       error ("Maximum number of states reached!");
-}	
- 
-void 
+}
+
+void
 append_transitions (unsigned state, unsigned label, const real_t *weight,
-		    const word_t *into, wfa_t *wfa)
+                    const word_t *into, wfa_t *wfa)
 /*
  *  Append the 'wfa' transitions (given by the arrays 'weight' and 'into')
  *  of the range ('state','label').
@@ -182,7 +182,7 @@ append_transitions (unsigned state, unsigned label, const real_t *weight,
  *  No return value.
  *
  *  Side effects:
- *	new 'wfa' edges are appended
+ *      new 'wfa' edges are appended
  */
 {
    unsigned edge;
@@ -192,81 +192,81 @@ append_transitions (unsigned state, unsigned label, const real_t *weight,
    {
       append_edge (state, into [edge], weight [edge], label, wfa);
       if (into [edge] == wfa->y_state [state][label])
-	 wfa->y_column [state][label] = 1;
+         wfa->y_column [state][label] = 1;
    }
 }
 
 /*****************************************************************************
 
-				private code
-  
+                                private code
+
 *****************************************************************************/
 
-static void 
+static void
 compute_images (unsigned from, unsigned to, const wfa_t *wfa, coding_t *c)
 /*
- *  Computes the images of the given states 'from', ... , 'to' 
+ *  Computes the images of the given states 'from', ... , 'to'
  *  at level 0,...,'c->imagelevel'.
  *  Uses the fact that each state image is a linear combination of state
  *  images, i.e. s_i := c_0 s_0 + ... + c_i s_i.
  */
 {
    unsigned label, level, state;
-   
+
    /*
     *  Compute the images Phi(state)
-    *  #		level = 0
-    *  ##		level = 1
-    *  ####		level = 2
-    *  ########    	level = 3
+    *  #                level = 0
+    *  ##               level = 1
+    *  ####             level = 2
+    *  ########         level = 3
     *  ...
     *  ########...##    level = imageslevel
     */
-   
+
    for (level = 1; level <= c->options.images_level; level++)
       for (state = from; state <= to; state++)
-	 for (label = 0; label < MAXLABELS; label++)
-	 {
-	    real_t   *dst, *src;
-	    unsigned  edge;
-	    int	      domain;		/* current domain */
-	    
-	    if (ischild (domain = wfa->tree[state][label]))
-	    {
-	       dst = c->images_of_state [state] + address_of_level (level) +
-		     label * size_of_level (level - 1);
-	       src = c->images_of_state [domain]
-		     + address_of_level (level - 1);
-	       memcpy (dst, src, size_of_level (level - 1) * sizeof (real_t));
-	    }
-	    for (edge = 0; isedge (domain = wfa->into[state][label][edge]);
-		 edge++)
-	    {
-	       unsigned n;
-	       real_t 	weight = wfa->weight [state][label][edge];
-	       
-	       dst = c->images_of_state [state] + address_of_level (level) +
-		     label * size_of_level (level - 1);
-	       src = c->images_of_state [domain]
-		     + address_of_level (level - 1);
-		  
-	       for (n = size_of_level (level - 1); n; n--)
-		  *dst++ += *src++ * weight;
-	    }
-	 }
+         for (label = 0; label < MAXLABELS; label++)
+         {
+            real_t   *dst, *src;
+            unsigned  edge;
+            int       domain;           /* current domain */
+
+            if (ischild (domain = wfa->tree[state][label]))
+            {
+               dst = c->images_of_state [state] + address_of_level (level) +
+                     label * size_of_level (level - 1);
+               src = c->images_of_state [domain]
+                     + address_of_level (level - 1);
+               memcpy (dst, src, size_of_level (level - 1) * sizeof (real_t));
+            }
+            for (edge = 0; isedge (domain = wfa->into[state][label][edge]);
+                 edge++)
+            {
+               unsigned n;
+               real_t   weight = wfa->weight [state][label][edge];
+
+               dst = c->images_of_state [state] + address_of_level (level) +
+                     label * size_of_level (level - 1);
+               src = c->images_of_state [domain]
+                     + address_of_level (level - 1);
+
+               for (n = size_of_level (level - 1); n; n--)
+                  *dst++ += *src++ * weight;
+            }
+         }
 
 }
 
-static void 
+static void
 clear_or_alloc (real_t **ptr, size_t size)
 /*
- *  if *ptr == NULL 	allocate memory with Calloc 
- *  otherwise 		fill the real_t-array ptr[] with 0
+ *  if *ptr == NULL     allocate memory with Calloc
+ *  otherwise           fill the real_t-array ptr[] with 0
  */
 {
-   if (*ptr == NULL) 
+   if (*ptr == NULL)
       *ptr = Calloc (size, sizeof (real_t));
-   else 
+   else
       memset (*ptr, 0, size * sizeof (real_t));
-    
+
 }
diff --git a/converter/other/fiasco/codec/control.h b/converter/other/fiasco/codec/control.h
index 6c0834a1..9bfc9b50 100644
--- a/converter/other/fiasco/codec/control.h
+++ b/converter/other/fiasco/codec/control.h
@@ -1,8 +1,8 @@
 /*
  *  control.h
  *
- *  Written by:		Ullrich Hafner
- *		
+ *  Written by:         Ullrich Hafner
+ *
  *  This file is part of FIASCO (Fractal Image And Sequence COdec)
  *  Copyright (C) 1994-2000 Ullrich Hafner
  */
@@ -20,14 +20,14 @@
 #include "cwfa.h"
 #include "types.h"
 
-void 
+void
 append_transitions (unsigned state, unsigned label, const real_t *weight,
-		    const word_t *into, wfa_t *wfa);
-void 
+                    const word_t *into, wfa_t *wfa);
+void
 append_basis_states (unsigned basis_states, wfa_t *wfa, coding_t *c);
-void    
+void
 append_state (bool_t auxiliary_state, real_t final, unsigned level_of_state,
-	      wfa_t *wfa, coding_t *c);
+              wfa_t *wfa, coding_t *c);
 
 #endif /* not _CONTROL_H */
 
diff --git a/converter/other/fiasco/codec/cwfa.h b/converter/other/fiasco/codec/cwfa.h
index e8e2d474..4fed343c 100644
--- a/converter/other/fiasco/codec/cwfa.h
+++ b/converter/other/fiasco/codec/cwfa.h
@@ -1,8 +1,8 @@
 /*
  *  cwfa.h
  *
- *  Written by:		Ullrich Hafner
- *		
+ *  Written by:         Ullrich Hafner
+ *
  *  This file is part of FIASCO (Fractal Image And Sequence COdec)
  *  Copyright (C) 1994-2000 Ullrich Hafner
  */
@@ -32,15 +32,15 @@ extern const real_t MAXCOSTS;
 
 typedef struct motion
 {
-   image_t	 *original;		/* Current image */
-   image_t	 *past;			/* Preceding image */
-   image_t	 *future;		/* Succeeding image */
-   frame_type_e	  frame_type;		/* frame type: B_, P_ I_FRAME */
-   unsigned	  number;		/* display number of frame */
-   real_t        *xbits;		/* # bits for mv x-component */
-   real_t        *ybits;		/* # bits for mv y-component */
-   real_t       **mc_forward_norms; 	/* norms of mcpe */
-   real_t       **mc_backward_norms; 	/* norms of mcpe */
+   image_t       *original;             /* Current image */
+   image_t       *past;                 /* Preceding image */
+   image_t       *future;               /* Succeeding image */
+   frame_type_e   frame_type;           /* frame type: B_, P_ I_FRAME */
+   unsigned       number;               /* display number of frame */
+   real_t        *xbits;                /* # bits for mv x-component */
+   real_t        *ybits;                /* # bits for mv y-component */
+   real_t       **mc_forward_norms;     /* norms of mcpe */
+   real_t       **mc_backward_norms;    /* norms of mcpe */
 } motion_t;
 
 typedef struct range
@@ -48,30 +48,30 @@ typedef struct range
  *  Information about current range in the original image.
  *  Approximation data (error, encoding bits, approximation type and factors
  *  of the linear combination) are also saved.
- */ 
+ */
 {
    unsigned global_address;             /* We need absolute image addresses
-				           for distance calculations. */
-   unsigned x, y;			/* Coordinates of upper left corner */
-   unsigned image;			/* Position in the tree */
-   unsigned address;			/* Address of the pixel data */
-   unsigned level;			/* Level of the range */
-   real_t   weight [MAXEDGES + 1];	/* coeff. of the approximation */
-   word_t   into [MAXEDGES + 1];	/* used domains of the approximation */
-   int	    tree;			/* == domain : range is approximated
-					   with new state 'domain'
-					   == RANGE  :
-					   with a linear comb. */
-   real_t   err;			/* approximation error */
-   real_t   tree_bits;			/* # bits to encode tree */
-   real_t   matrix_bits;		/* # bits to encode matrices */
-   real_t   weights_bits;		/* # bits to encode weights */
-   mv_t	    mv;				/* motion vector */
-   real_t   mv_tree_bits;		/* # bits to encode mv tree */
-   real_t   mv_coord_bits;		/* # bits to encode mv coordinates */
-   real_t   nd_tree_bits;		/* # bits to encode nd tree */
-   real_t   nd_weights_bits;		/* # bits to encode nd factors */
-   bool_t   prediction;			/* range is predicted? */
+                                           for distance calculations. */
+   unsigned x, y;                       /* Coordinates of upper left corner */
+   unsigned image;                      /* Position in the tree */
+   unsigned address;                    /* Address of the pixel data */
+   unsigned level;                      /* Level of the range */
+   real_t   weight [MAXEDGES + 1];      /* coeff. of the approximation */
+   word_t   into [MAXEDGES + 1];        /* used domains of the approximation */
+   int      tree;                       /* == domain : range is approximated
+                                           with new state 'domain'
+                                           == RANGE  :
+                                           with a linear comb. */
+   real_t   err;                        /* approximation error */
+   real_t   tree_bits;                  /* # bits to encode tree */
+   real_t   matrix_bits;                /* # bits to encode matrices */
+   real_t   weights_bits;               /* # bits to encode weights */
+   mv_t     mv;                         /* motion vector */
+   real_t   mv_tree_bits;               /* # bits to encode mv tree */
+   real_t   mv_coord_bits;              /* # bits to encode mv coordinates */
+   real_t   nd_tree_bits;               /* # bits to encode nd tree */
+   real_t   nd_weights_bits;            /* # bits to encode nd factors */
+   bool_t   prediction;                 /* range is predicted? */
 } range_t;
 
 typedef struct coding
@@ -80,27 +80,27 @@ typedef struct coding
  *  process.
  */
 {
-   real_t     	   price;		/* determines quality of approx. */
-   real_t   	 **images_of_state;	/* image of state i at level
-					   0, ... , imageslevel */
+   real_t          price;               /* determines quality of approx. */
+   real_t        **images_of_state;     /* image of state i at level
+                                           0, ... , imageslevel */
    real_t   *(*ip_states_state)[MAXLEVEL]; /* inner products between state i
-					      and states 0, ... , i
-					      at all image levels */
-   real_t   	 **ip_images_state;	/* inner products between all
-					   ranges and state i */
-   real_t    	  *pixels;		/* current image pixels stored in tree
-					   order (only leaves are stored) */
-   unsigned   	   products_level;	/* inner products are stored up to
-					   this level */
-   tiling_t   	  *tiling;		/* tiling of the entire image */
-   tree_t     	   tree;		/* probability model */
-   tree_t     	   p_tree;		/* prediction probability model */
-   motion_t   	  *mt;			/* motion compensation information */
-   coeff_t   	  *coeff;
-   coeff_t   	  *d_coeff;
+                                              and states 0, ... , i
+                                              at all image levels */
+   real_t        **ip_images_state;     /* inner products between all
+                                           ranges and state i */
+   real_t         *pixels;              /* current image pixels stored in tree
+                                           order (only leaves are stored) */
+   unsigned        products_level;      /* inner products are stored up to
+                                           this level */
+   tiling_t       *tiling;              /* tiling of the entire image */
+   tree_t          tree;                /* probability model */
+   tree_t          p_tree;              /* prediction probability model */
+   motion_t       *mt;                  /* motion compensation information */
+   coeff_t        *coeff;
+   coeff_t        *d_coeff;
    domain_pool_t  *domain_pool;
    domain_pool_t  *d_domain_pool;
-   c_options_t     options;		/* global options */
+   c_options_t     options;             /* global options */
 } coding_t;
 
 #endif /* not _CWFA_H */
diff --git a/converter/other/fiasco/codec/decoder.h b/converter/other/fiasco/codec/decoder.h
index 7823ab91..d11ccefd 100644
--- a/converter/other/fiasco/codec/decoder.h
+++ b/converter/other/fiasco/codec/decoder.h
@@ -1,8 +1,8 @@
 /*
  *  decode.h
- *		
- *  Written by:		Ullrich Hafner
- *		
+ *              
+ *  Written by:         Ullrich Hafner
+ *              
  *  This file is part of FIASCO (Fractal Image And Sequence COdec)
  *  Copyright (C) 1994-2000 Ullrich Hafner
  */
@@ -23,41 +23,41 @@
 
 typedef struct video
 {
-   unsigned  future_display;		/* number of a future frame */
-   unsigned  display;			/* current display number */
-   image_t  *frame;			/* current frame */
-   image_t  *sframe;			/* current smoothed frame */
-   image_t  *future;			/* future reference */
-   image_t  *sfuture;			/* future (smmothed) reference */
-   image_t  *past ;			/* past reference */
-   wfa_t    *wfa;			/* current wfa */
-   wfa_t    *wfa_future;		/* future wfa */
-   wfa_t    *wfa_past;			/* past wfa */
+   unsigned  future_display;            /* number of a future frame */
+   unsigned  display;                   /* current display number */
+   image_t  *frame;                     /* current frame */
+   image_t  *sframe;                    /* current smoothed frame */
+   image_t  *future;                    /* future reference */
+   image_t  *sfuture;                   /* future (smmothed) reference */
+   image_t  *past ;                     /* past reference */
+   wfa_t    *wfa;                       /* current wfa */
+   wfa_t    *wfa_future;                /* future wfa */
+   wfa_t    *wfa_past;                  /* past wfa */
 } video_t;
 
 typedef struct dectimer
 {
-   unsigned int	input [3];
-   unsigned int	preprocessing [3];
-   unsigned int	decoder [3];
-   unsigned int	cleanup [3];
-   unsigned int	motion [3];
-   unsigned int	smooth [3];
-   unsigned int	display [3];
-   unsigned int	frames [3];
+   unsigned int input [3];
+   unsigned int preprocessing [3];
+   unsigned int decoder [3];
+   unsigned int cleanup [3];
+   unsigned int motion [3];
+   unsigned int smooth [3];
+   unsigned int display [3];
+   unsigned int frames [3];
 } dectimer_t;
 
 image_t *
 get_next_frame (bool_t store_wfa, int enlarge_factor,
-		int smoothing, const char *reference_frame,
-		format_e format, video_t *video, dectimer_t *timer,
-		wfa_t *orig_wfa, bitfile_t *input);
+                int smoothing, const char *reference_frame,
+                format_e format, video_t *video, dectimer_t *timer,
+                wfa_t *orig_wfa, bitfile_t *input);
 image_t *
 decode_image (unsigned orig_width, unsigned orig_height, format_e format,
-	      unsigned *dec_timer, const wfa_t *wfa);
+              unsigned *dec_timer, const wfa_t *wfa);
 word_t *
 decode_range (unsigned range_state, unsigned range_label, unsigned range_level,
-	      word_t **domain, wfa_t *wfa);
+              word_t **domain, wfa_t *wfa);
 image_t *
 decode_state (unsigned state, unsigned level, wfa_t *wfa);
 void
diff --git a/converter/other/fiasco/codec/dfiasco.c b/converter/other/fiasco/codec/dfiasco.c
index ce25654a..3f5d3fcc 100644
--- a/converter/other/fiasco/codec/dfiasco.c
+++ b/converter/other/fiasco/codec/dfiasco.c
@@ -1,7 +1,7 @@
 /*
- *  dfiasco.c:		Decoder public interface
+ *  dfiasco.c:          Decoder public interface
  *
- *  Written by:		Ullrich Hafner
+ *  Written by:         Ullrich Hafner
  *
  *  This file is part of FIASCO (Fractal Image And Sequence COdec)
  *  Copyright (C) 1994-2000 Ullrich Hafner
@@ -37,7 +37,7 @@
 
 /*****************************************************************************
 
-				prototypes
+                                prototypes
 
 *****************************************************************************/
 
@@ -47,11 +47,11 @@ static void
 free_dfiasco (dfiasco_t *dfiasco);
 static dfiasco_t *
 alloc_dfiasco (wfa_t *wfa, video_t *video, bitfile_t *input,
-	       int enlarge_factor, int smoothing, format_e image_format);
+               int enlarge_factor, int smoothing, format_e image_format);
 
 /*****************************************************************************
 
-				public code
+                                public code
 
 *****************************************************************************/
 
@@ -60,24 +60,24 @@ fiasco_decoder_new (const char *filename, const fiasco_d_options_t *options)
 {
    try
    {
-      bitfile_t        	 *input;	/* pointer to WFA FIASCO stream */
-      wfa_t            	 *wfa;		/* wfa structure */
-      video_t          	 *video;	/* information about decoder state */
-      const d_options_t  *dop;		/* decoder additional options */
-      dfiasco_t	       	 *dfiasco;	/* decoder internal state */
-      fiasco_decoder_t 	 *decoder;	/* public interface to decoder */
+      bitfile_t          *input;        /* pointer to WFA FIASCO stream */
+      wfa_t              *wfa;          /* wfa structure */
+      video_t            *video;        /* information about decoder state */
+      const d_options_t  *dop;          /* decoder additional options */
+      dfiasco_t          *dfiasco;      /* decoder internal state */
+      fiasco_decoder_t   *decoder;      /* public interface to decoder */
       fiasco_d_options_t *default_options = NULL;
 
       if (options)
       {
-	 dop = cast_d_options ((fiasco_d_options_t *) options);
-	 if (!dop)
-	    return NULL;
+         dop = cast_d_options ((fiasco_d_options_t *) options);
+         if (!dop)
+            return NULL;
       }
       else
       {
-	 default_options = fiasco_d_options_new ();
-	 dop 		 = cast_d_options (default_options);
+         default_options = fiasco_d_options_new ();
+         dop             = cast_d_options (default_options);
       }
 
       wfa   = alloc_wfa (NO);
@@ -85,8 +85,8 @@ fiasco_decoder_new (const char *filename, const fiasco_d_options_t *options)
       input = open_wfa (filename, wfa->wfainfo);
       read_basis (wfa->wfainfo->basis_name, wfa);
 
-      decoder 	       	   = Calloc (1, sizeof (fiasco_decoder_t));
-      decoder->delete  	   = fiasco_decoder_delete;
+      decoder              = Calloc (1, sizeof (fiasco_decoder_t));
+      decoder->delete      = fiasco_decoder_delete;
       decoder->write_frame = fiasco_decoder_write_frame;
       decoder->get_frame   = fiasco_decoder_get_frame;
       decoder->get_length  = fiasco_decoder_get_length;
@@ -98,46 +98,46 @@ fiasco_decoder_new (const char *filename, const fiasco_d_options_t *options)
       decoder->is_color    = fiasco_decoder_is_color;
 
       decoder->private = dfiasco
-		       = alloc_dfiasco (wfa, video, input,
-					dop->magnification,
-					dop->smoothing,
-					dop->image_format);
+                       = alloc_dfiasco (wfa, video, input,
+                                        dop->magnification,
+                                        dop->smoothing,
+                                        dop->image_format);
 
       if (default_options)
-	 fiasco_d_options_delete (default_options);
+         fiasco_d_options_delete (default_options);
       if (dfiasco->enlarge_factor >= 0)
       {
-	 int 	       n;
-	 unsigned long pixels = wfa->wfainfo->width * wfa->wfainfo->height;
-
-	 for (n = 1; n <= (int) dfiasco->enlarge_factor; n++)
-	 {
-	    if (pixels << (n << 1) > 2048 * 2048)
-	    {
-	       set_error (_("Magnifaction factor `%d' is too large. "
-			    "Maximum value is %d."),
-			  dfiasco->enlarge_factor, MAX(0, n - 1));
-	       fiasco_decoder_delete (decoder);
-	       return NULL;
-	    }
-	 }
+         int           n;
+         unsigned long pixels = wfa->wfainfo->width * wfa->wfainfo->height;
+
+         for (n = 1; n <= (int) dfiasco->enlarge_factor; n++)
+         {
+            if (pixels << (n << 1) > 2048 * 2048)
+            {
+               set_error (_("Magnifaction factor `%d' is too large. "
+                            "Maximum value is %d."),
+                          dfiasco->enlarge_factor, MAX(0, n - 1));
+               fiasco_decoder_delete (decoder);
+               return NULL;
+            }
+         }
       }
       else
       {
-	 int n;
-
-	 for (n = 0; n <= (int) - dfiasco->enlarge_factor; n++)
-	 {
-	    if (wfa->wfainfo->width >> n < 32
-		|| wfa->wfainfo->height >> n < 32)
-	    {
-	       set_error (_("Magnifaction factor `%d' is too small. "
-			    "Minimum value is %d."),
-			  dfiasco->enlarge_factor, - MAX(0, n - 1));
-	       fiasco_decoder_delete (decoder);
-	       return NULL;
-	    }
-	 }
+         int n;
+
+         for (n = 0; n <= (int) - dfiasco->enlarge_factor; n++)
+         {
+            if (wfa->wfainfo->width >> n < 32
+                || wfa->wfainfo->height >> n < 32)
+            {
+               set_error (_("Magnifaction factor `%d' is too small. "
+                            "Minimum value is %d."),
+                          dfiasco->enlarge_factor, - MAX(0, n - 1));
+               fiasco_decoder_delete (decoder);
+               return NULL;
+            }
+         }
       }
       return (fiasco_decoder_t *) decoder;
    }
@@ -149,7 +149,7 @@ fiasco_decoder_new (const char *filename, const fiasco_d_options_t *options)
 
 int
 fiasco_decoder_write_frame (fiasco_decoder_t *decoder,
-			    const char *filename)
+                            const char *filename)
 {
    dfiasco_t *dfiasco = cast_dfiasco (decoder);
 
@@ -159,15 +159,15 @@ fiasco_decoder_write_frame (fiasco_decoder_t *decoder,
    {
       try
       {
-	 image_t *frame = get_next_frame (NO, dfiasco->enlarge_factor,
-					  dfiasco->smoothing, NULL,
-					  FORMAT_4_4_4, dfiasco->video, NULL,
-					  dfiasco->wfa, dfiasco->input);
-	 write_image (filename, frame);
+         image_t *frame = get_next_frame (NO, dfiasco->enlarge_factor,
+                                          dfiasco->smoothing, NULL,
+                                          FORMAT_4_4_4, dfiasco->video, NULL,
+                                          dfiasco->wfa, dfiasco->input);
+         write_image (filename, frame);
       }
       catch
       {
-	 return 0;
+         return 0;
       }
       return 1;
    }
@@ -184,25 +184,25 @@ fiasco_decoder_get_frame (fiasco_decoder_t *decoder)
    {
       try
       {
-	 fiasco_image_t *image = Calloc (1, sizeof (fiasco_image_t));
-	 image_t 	*frame = get_next_frame (NO, dfiasco->enlarge_factor,
-						 dfiasco->smoothing, NULL,
-						 dfiasco->image_format,
-						 dfiasco->video, NULL,
-						 dfiasco->wfa, dfiasco->input);
-
-	 frame->reference_count++;	/* for motion compensation */
-	 image->private    = frame;
-	 image->delete     = fiasco_image_delete;
-	 image->get_width  = fiasco_image_get_width;
-	 image->get_height = fiasco_image_get_height;
-	 image->is_color   = fiasco_image_is_color;
-
-	 return image;
+         fiasco_image_t *image = Calloc (1, sizeof (fiasco_image_t));
+         image_t        *frame = get_next_frame (NO, dfiasco->enlarge_factor,
+                                                 dfiasco->smoothing, NULL,
+                                                 dfiasco->image_format,
+                                                 dfiasco->video, NULL,
+                                                 dfiasco->wfa, dfiasco->input);
+
+         frame->reference_count++;      /* for motion compensation */
+         image->private    = frame;
+         image->delete     = fiasco_image_delete;
+         image->get_width  = fiasco_image_get_width;
+         image->get_height = fiasco_image_get_height;
+         image->is_color   = fiasco_image_is_color;
+
+         return image;
       }
       catch
       {
-	 return NULL;
+         return NULL;
       }
    }
 }
@@ -241,9 +241,9 @@ fiasco_decoder_get_width (fiasco_decoder_t *decoder)
       unsigned width;
 
       if (dfiasco->enlarge_factor >= 0)
-	 width = dfiasco->wfa->wfainfo->width << dfiasco->enlarge_factor;
+         width = dfiasco->wfa->wfainfo->width << dfiasco->enlarge_factor;
       else
-	 width = dfiasco->wfa->wfainfo->width >> - dfiasco->enlarge_factor;
+         width = dfiasco->wfa->wfainfo->width >> - dfiasco->enlarge_factor;
 
       return width & 1 ? width + 1 : width;
    }
@@ -261,9 +261,9 @@ fiasco_decoder_get_height (fiasco_decoder_t *decoder)
       unsigned height;
 
       if (dfiasco->enlarge_factor >= 0)
-	 height = dfiasco->wfa->wfainfo->height << dfiasco->enlarge_factor;
+         height = dfiasco->wfa->wfainfo->height << dfiasco->enlarge_factor;
       else
-	 height = dfiasco->wfa->wfainfo->height >> - dfiasco->enlarge_factor;
+         height = dfiasco->wfa->wfainfo->height >> - dfiasco->enlarge_factor;
 
       return height & 1 ? height + 1 : height;
    }
@@ -329,30 +329,30 @@ fiasco_decoder_delete (fiasco_decoder_t *decoder)
 
 /*****************************************************************************
 
-				private code
+                                private code
 
 *****************************************************************************/
 
 static dfiasco_t *
 alloc_dfiasco (wfa_t *wfa, video_t *video, bitfile_t *input,
-	       int enlarge_factor, int smoothing, format_e image_format)
+               int enlarge_factor, int smoothing, format_e image_format)
 /*
  *  FIASCO decoder constructor:
  *  Initialize decoder structure.
  *
  *  Return value:
- *	pointer to the new decoder structure
+ *      pointer to the new decoder structure
  */
 {
    dfiasco_t *dfiasco = Calloc (1, sizeof (dfiasco_t));
 
    strcpy (dfiasco->id, "DFIASCO");
 
-   dfiasco->wfa 	   = wfa;
-   dfiasco->video 	   = video;
-   dfiasco->input 	   = input;
+   dfiasco->wfa            = wfa;
+   dfiasco->video          = video;
+   dfiasco->input          = input;
    dfiasco->enlarge_factor = enlarge_factor;
-   dfiasco->smoothing  	   = smoothing;
+   dfiasco->smoothing      = smoothing;
    dfiasco->image_format   = image_format;
 
    return dfiasco;
@@ -367,7 +367,7 @@ free_dfiasco (dfiasco_t *dfiasco)
  *  No return value.
  *
  *  Side effects:
- *	'video' struct is discarded.
+ *      'video' struct is discarded.
  */
 {
    Free (dfiasco);
@@ -380,7 +380,7 @@ cast_dfiasco (fiasco_decoder_t *dfiasco)
  *  Check whether `dfiasco' is a valid object of type dfiasco_t.
  *
  *  Return value:
- *	pointer to dfiasco_t struct on success
+ *      pointer to dfiasco_t struct on success
  *      NULL otherwise
  */
 {
@@ -389,8 +389,8 @@ cast_dfiasco (fiasco_decoder_t *dfiasco)
    {
       if (!streq (this->id, "DFIASCO"))
       {
-	 set_error (_("Parameter `dfiasco' doesn't match required type."));
-	 return NULL;
+         set_error (_("Parameter `dfiasco' doesn't match required type."));
+         return NULL;
       }
    }
    else
diff --git a/converter/other/fiasco/codec/dfiasco.h b/converter/other/fiasco/codec/dfiasco.h
index eed12b6b..765a09d4 100644
--- a/converter/other/fiasco/codec/dfiasco.h
+++ b/converter/other/fiasco/codec/dfiasco.h
@@ -1,8 +1,8 @@
 /*
  *  dfiasco.h
- *		
- *  Written by:		Ullrich Hafner
- *		
+ *              
+ *  Written by:         Ullrich Hafner
+ *              
  *  This file is part of FIASCO (Fractal Image And Sequence COdec)
  *  Copyright (C) 1994-2000 Ullrich Hafner
  */
@@ -29,7 +29,7 @@ typedef struct dfiasco
    wfa_t     *wfa;
    video_t   *video;
    bitfile_t *input;
-   int	      enlarge_factor;
+   int        enlarge_factor;
    int        smoothing;
    format_e   image_format;
 } dfiasco_t;
diff --git a/converter/other/fiasco/codec/domain-pool.c b/converter/other/fiasco/codec/domain-pool.c
index 1c14a30c..e9986269 100644
--- a/converter/other/fiasco/codec/domain-pool.c
+++ b/converter/other/fiasco/codec/domain-pool.c
@@ -2,7 +2,7 @@
  *  domain-pool.c:  Domain pool management (probability model)
  *
  *  Written by:     Ullrich Hafner
- *      
+ *
  *  This file is part of FIASCO (Fractal Image And Sequence COdec)
  *  Copyright (C) 1994-2000 Ullrich Hafner
  */
@@ -34,9 +34,9 @@
 /*
  *  Domain pool model interface:
  *  Implementing the domain pool model interface requires the
- *  following steps: 
+ *  following steps:
  *  - Add a constructor that initializes the domain_pool_t structure
- *  - Allocate new model with default_alloc() 
+ *  - Allocate new model with default_alloc()
  *  - Fill the dp_array_t domain_pools array with constructor and name
  *  - Write code for methods bits() and generate()
  *  - Either use default functions for remaining methods or override them
@@ -44,9 +44,9 @@
  */
 
 /*****************************************************************************
-                                          
+
                   local variables
-                  
+
 *****************************************************************************/
 
 static real_t *matrix_0 = NULL;
@@ -174,7 +174,7 @@ default_alloc (void);
 /*****************************************************************************
 
                 public code
-  
+
 *****************************************************************************/
 
 typedef struct dp_array
@@ -185,7 +185,7 @@ typedef struct dp_array
 } dp_array_t;
 
 dp_array_t const domain_pools[] = {{"adaptive", alloc_qac_domain_pool},
-                                   {"constant",   alloc_const_domain_pool}, 
+                                   {"constant",   alloc_const_domain_pool},
                                    {"basis",      alloc_basis_domain_pool},
                                    {"uniform",    alloc_uniform_domain_pool},
                                    {"rle",        alloc_rle_domain_pool},
@@ -199,8 +199,8 @@ alloc_domain_pool (const char *domain_pool_name, unsigned max_domains,
  *  Allocate a new domain pool identified by the string
  *  'domain_pool_name'.  Maximum number of domain images (each one
  *  represented by one state of the given 'wfa') is specified by
- *  'max_domains'. 
- * 
+ *  'max_domains'.
+ *
  *  Return value:
  *  pointer to the allocated domain pool
  *
@@ -209,16 +209,16 @@ alloc_domain_pool (const char *domain_pool_name, unsigned max_domains,
  */
 {
     unsigned n;
-   
+
     if (!max_domains)
     {
         warning ("Can't generate empty domain pool. "
                  "Using at least DC component.");
         max_domains = 1;
     }
-   
+
     for (n = 0; domain_pools [n].identifier; n++) /* step through all id's */
-        if (strcaseeq (domain_pools [n].identifier, domain_pool_name)) 
+        if (strcaseeq (domain_pools [n].identifier, domain_pool_name))
             return domain_pools [n].function (max_domains, max_edges, wfa);
 
     warning ("Can't initialize domain pool '%s'. Using default value '%s'.",
@@ -230,7 +230,7 @@ alloc_domain_pool (const char *domain_pool_name, unsigned max_domains,
 /*****************************************************************************
 
                 private code
-  
+
 *****************************************************************************/
 
 /*****************************************************************************
@@ -256,7 +256,7 @@ alloc_qac_domain_pool (unsigned max_domains, unsigned max_edges,
 {
     domain_pool_t *pool;
     unsigned   state;
-   
+
     pool                  = default_alloc ();
     pool->model           = qac_model_alloc (max_domains);
     pool->generate        = qac_generate;
@@ -266,7 +266,7 @@ alloc_qac_domain_pool (unsigned max_domains, unsigned max_edges,
     pool->chroma      = qac_chroma;
     pool->model_free      = qac_model_free;
     pool->model_duplicate = qac_model_duplicate;
-   
+
     for (state = 0; state < wfa->basis_states; state++)
         if (usedomain (state, wfa))
             qac_append (state, -1, wfa, pool->model);
@@ -308,7 +308,7 @@ qac_model_duplicate (const void *src)
     qdst      = qac_model_alloc (qsrc->max_domains);
     qdst->y_index = qsrc->y_index;
     qdst->n       = qsrc->n;
-   
+
     memcpy (qdst->index, qsrc->index, qsrc->n * sizeof (word_t));
     memcpy (qdst->states, qsrc->states, qsrc->n * sizeof (word_t));
 
@@ -325,14 +325,14 @@ qac_generate (unsigned level, int y_state, const wfa_t *wfa, const void *model)
 
     if (y_state >= 0 && !usedomain (y_state, wfa)) /* don't use y-state */
         y_state = -1;
-   
+
     domains = Calloc (qac_model->n + 2, sizeof (word_t));
 
     memcpy (domains, qac_model->states, qac_model->n * sizeof (word_t));
 
     for (n = 0; n < qac_model->n; n++)
         if (domains [n] == y_state)   /* match */
-            y_state_is_domain = YES;       
+            y_state_is_domain = YES;
 
     if (y_state_is_domain)
         domains [qac_model->n] = -1;  /* end marker */
@@ -361,11 +361,11 @@ qac_bits (const word_t *domains, const word_t *used_domains,
             bits += matrix_0 [qac_model->index [domain]];
     if (y_state >= 0)
         bits += matrix_0 [qac_model->y_index];
-   
+
     if (used_domains != NULL)
     {
         unsigned edge;
-      
+
         for (edge = 0; isedge (domain = used_domains [edge]); edge++)
             if (domains [domain] == y_state)
             {
@@ -377,8 +377,8 @@ qac_bits (const word_t *domains, const word_t *used_domains,
                 bits -= matrix_0 [qac_model->index [domain]];
                 bits += matrix_1 [qac_model->index [domain]];
             }
-    } 
-   
+    }
+
     return bits;
 }
 
@@ -391,7 +391,7 @@ qac_update (const word_t *domains, const word_t *used_domains,
     bool_t   used_y_state      = NO;
     qac_model_t *qac_model     = (qac_model_t *) model;
     bool_t   y_state_is_domain = NO;
-   
+
     if (y_state >= 0 && !usedomain (y_state, wfa)) /* don't use y-state */
         y_state = -1;
 
@@ -399,9 +399,9 @@ qac_update (const word_t *domains, const word_t *used_domains,
     {
         qac_model->index [domain]++;  /* mark domains unused. */
         if (qac_model->states [domain] == y_state) /* match */
-            y_state_is_domain = YES;       
+            y_state_is_domain = YES;
     }
-   
+
     for (edge = 0; isedge (domain = used_domains [edge]); edge++)
         if (domains [domain] == y_state) /* chroma coding */
         {
@@ -413,24 +413,24 @@ qac_update (const word_t *domains, const word_t *used_domains,
         else              /* luminance coding */
         {
             qac_model->index [used_domains [edge]]--; /* undo */
-            qac_model->index [used_domains [edge]] >>= 1;      
+            qac_model->index [used_domains [edge]] >>= 1;
         }
 
     if (y_state >= 0 && !used_y_state)
         qac_model->y_index++;     /* update y-state model */
-   
+
     for (domain = 0; domain < qac_model->n; domain++)
         if (qac_model->index [domain] > 1020) /* check for overflow */
-            qac_model->index [domain] = 1020; 
+            qac_model->index [domain] = 1020;
     if (qac_model->y_index > 1020)   /* check for overflow */
-        qac_model->y_index = 1020; 
+        qac_model->y_index = 1020;
 }
 
 static bool_t
 qac_append (unsigned new_state, unsigned level, const wfa_t *wfa, void *model)
 {
     qac_model_t  *qac_model = (qac_model_t *) model; /* probability model */
-   
+
     if (qac_model->n >= qac_model->max_domains)
         return NO;            /* don't use state in domain pool */
     else
@@ -448,14 +448,14 @@ static void
 qac_chroma (unsigned max_domains, const wfa_t *wfa, void *model)
 {
     qac_model_t *qac_model = (qac_model_t *) model; /* probability model */
-   
+
     if (max_domains < qac_model->n)  /* choose most probable domains */
     {
         word_t   *domains;
         unsigned  n, new, old;
         word_t   *states = Calloc (max_domains, sizeof (word_t));
         word_t   *index  = Calloc (max_domains, sizeof (word_t));
-   
+
         domains = compute_hits (wfa->basis_states, wfa->states - 1,
                                 max_domains, wfa);
         for (n = 0; n < max_domains && domains [n] >= 0; n++)
@@ -491,11 +491,11 @@ alloc_const_domain_pool (unsigned max_domains, unsigned max_edges,
  */
 {
     domain_pool_t *pool;
-   
-    pool           = default_alloc ();   
+
+    pool           = default_alloc ();
     pool->generate = const_generate;
     pool->bits     = const_bits;
-   
+
     return pool;
 }
 
@@ -504,10 +504,10 @@ const_generate (unsigned level, int y_state, const wfa_t *wfa,
                 const void *model)
 {
     word_t *domains = Calloc (2, sizeof (word_t));
-   
+
     domains [0] = 0;
     domains [1] = -1;
-   
+
     return domains;
 }
 
@@ -548,11 +548,11 @@ alloc_uniform_domain_pool (unsigned max_domains, unsigned max_edges,
  */
 {
     domain_pool_t *pool;
-   
-    pool           = default_alloc ();   
+
+    pool           = default_alloc ();
     pool->generate = uniform_generate;
     pool->bits     = uniform_bits;
-   
+
     return pool;
 }
 
@@ -567,17 +567,17 @@ uniform_generate (unsigned level, int y_state, const wfa_t *wfa,
         if (usedomain (state, wfa))
             domains [n++] = state;
     domains [n] = -1;
-   
+
     return domains;
 }
- 
+
 static real_t
 uniform_bits (const word_t *domains, const word_t *used_domains,
               unsigned level, int y_state, const wfa_t *wfa, const void *model)
 {
     unsigned state, n;
     real_t   bits = 0;
-   
+
     for (state = 0, n = 0; state < wfa->states; state++)
         if (usedomain (state, wfa))
             n++;
@@ -587,7 +587,7 @@ uniform_bits (const word_t *domains, const word_t *used_domains,
     if (used_domains != NULL)
     {
         int edge;
-      
+
         for (edge = 0; isedge (used_domains [edge]); edge++)
             bits -= log2 (1.0 / n);
     }
@@ -615,13 +615,13 @@ alloc_rle_domain_pool (unsigned max_domains, unsigned max_edges,
                        const wfa_t *wfa)
 /*
  *  Domain pool with state images {0, ..., 'max_domains').
- *  Underlying probability model: rle 
+ *  Underlying probability model: rle
  */
 {
     domain_pool_t *pool;
     unsigned   state;
-   
-    pool                  = default_alloc ();    
+
+    pool                  = default_alloc ();
     pool->model           = rle_model_alloc (max_domains);
     pool->model_free      = rle_model_free;
     pool->model_duplicate = rle_model_duplicate;
@@ -643,7 +643,7 @@ rle_model_alloc (unsigned max_domains)
 {
     unsigned m;
     rle_model_t *model = Calloc (1, sizeof (rle_model_t));
-   
+
     for (m = model->total = 0; m < MAXEDGES + 1; m++, model->total++)
         model->count [m] = 1;
 
@@ -652,7 +652,7 @@ rle_model_alloc (unsigned max_domains)
     model->n       = 0;
     model->y_index     = 0;
     model->max_domains = max_domains;
-   
+
     return model;
 }
 
@@ -676,12 +676,12 @@ rle_model_duplicate (const void *src)
     model->states      = Calloc (model->max_domains, sizeof (word_t));
     model->total       = rle_src->total;
     model->y_index     = rle_src->y_index;
-   
+
     memcpy (model->states, rle_src->states,
             model->max_domains * sizeof (word_t));
     memcpy (model->count, rle_src->count,
             (MAXEDGES + 1) * sizeof (word_t));
-   
+
     return model;
 }
 
@@ -692,17 +692,17 @@ rle_generate (unsigned level, int y_state, const wfa_t *wfa, const void *model)
     unsigned n;
     rle_model_t *rle_model     = (rle_model_t *) model;
     bool_t   y_state_is_domain = NO;
-   
+
     if (y_state >= 0 && !usedomain (y_state, wfa)) /* don't use y-state */
         y_state = -1;
-   
+
     domains = Calloc (rle_model->n + 2, sizeof (word_t));
 
     memcpy (domains, rle_model->states, rle_model->n * sizeof (word_t));
 
     for (n = 0; n < rle_model->n; n++)
         if (domains [n] == y_state)   /* match */
-            y_state_is_domain = YES;       
+            y_state_is_domain = YES;
 
     if (y_state_is_domain)
         domains [rle_model->n] = -1;  /* end marker */
@@ -726,17 +726,17 @@ rle_bits (const word_t *domains, const word_t *used_domains,
     rle_model_t *rle_model = (rle_model_t *) model;
     unsigned last;
     int      into;
-   
+
     if (y_state >= 0 && !usedomain (y_state, wfa)) /* don't use y-state */
         y_state = -1;
 
     if (used_domains)
     {
         word_t domain;
-      
+
         if (y_state >= 0)
             bits += matrix_0 [rle_model->y_index];
-      
+
         for (edge = n = 0; isedge (domain = used_domains [edge]); edge++)
             if (domains [domain] != y_state)
                 sorted [n++] = used_domains [edge];
@@ -745,7 +745,7 @@ rle_bits (const word_t *domains, const word_t *used_domains,
                 bits -= matrix_0 [rle_model->y_index];
                 bits += matrix_1 [rle_model->y_index];
             }
-      
+
         if (n > 1)
             qsort (sorted, n, sizeof (word_t), sort_asc_word);
     }
@@ -761,7 +761,7 @@ rle_bits (const word_t *domains, const word_t *used_domains,
         word_t array0 [2] = {NO_EDGE};
         bits += qac_bits (array0, array0, level, y_state, wfa, rle_model->domain_0);
     }
-   
+
     last = 1;
     for (edge = 0; edge < n; edge++)
         if ((into = sorted [edge]) && rle_model->n - 1 - last)
@@ -769,7 +769,7 @@ rle_bits (const word_t *domains, const word_t *used_domains,
             bits += bits_bin_code (into - last, rle_model->n - 1 - last);
             last  = into + 1;
         }
-   
+
     return bits;
 }
 
@@ -781,21 +781,21 @@ rle_update (const word_t *domains, const word_t *used_domains,
     bool_t   state_0    = NO, state_y = NO;
     word_t   array0 [2] = {0, NO_EDGE};
     unsigned     edge = 0;
-   
+
     if (y_state >= 0 && !usedomain (y_state, wfa)) /* don't use y-state */
         y_state = -1;
 
     if (used_domains)
     {
         word_t   domain;
-      
+
         for (edge = 0; isedge (domain = used_domains [edge]); edge++)
             if (domains [domain] == 0)
                 state_0 = YES;
             else if (domains [domain] == y_state)
                 state_y = YES;
     }
-   
+
     rle_model->count [edge]++;
     rle_model->total++;
 
@@ -807,14 +807,14 @@ rle_update (const word_t *domains, const word_t *used_domains,
     else
         rle_model->y_index++;
     if (rle_model->y_index > 1020)   /* check for overflow */
-        rle_model->y_index = 1020; 
+        rle_model->y_index = 1020;
 }
 
 static bool_t
 rle_append (unsigned new_state, unsigned level, const wfa_t *wfa, void *model)
 {
     rle_model_t *rle_model = (rle_model_t *) model; /* probability model */
-   
+
     if (rle_model->n >= rle_model->max_domains)
         return NO;            /* don't use state in domain pool */
     else
@@ -827,7 +827,7 @@ rle_append (unsigned new_state, unsigned level, const wfa_t *wfa, void *model)
             assert (rle_model->n == 1);
             qac_append (0, -1, wfa, rle_model->domain_0);
         }
-      
+
         return YES;           /* state will be used in domain pool */
     }
 }
@@ -836,14 +836,14 @@ static void
 rle_chroma (unsigned max_domains, const wfa_t *wfa, void *model)
 {
     rle_model_t *rle_model = (rle_model_t *) model; /* probability model */
-   
+
     if (max_domains < rle_model->n)  /* choose most probable domains */
     {
         unsigned  n;
         word_t   *states  = Calloc (max_domains, sizeof (word_t));
         word_t   *domains = compute_hits (wfa->basis_states, wfa->states - 1,
                                           max_domains, wfa);
-      
+
         for (n = 0; n < max_domains && domains [n] >= 0; n++)
             states [n] = domains [n];
 
@@ -868,12 +868,12 @@ alloc_rle_no_chroma_domain_pool (unsigned max_domains, unsigned max_edges,
                                  const wfa_t *wfa)
 /*
  *  Domain pool with state images {0, ..., 'max_domains').
- *  Underlying probability model: rle 
+ *  Underlying probability model: rle
  *  Domain pool is not changed for chroma bands
  */
 {
     domain_pool_t *pool = alloc_rle_domain_pool (max_domains, max_edges, wfa);
-   
+
     pool->chroma = default_chroma;
 
     return pool;
@@ -898,7 +898,7 @@ default_alloc (void)
     pool->free            = default_free;
     pool->model_free      = default_model_free;
     pool->model_duplicate = default_model_duplicate;
-   
+
     return pool;
 }
 
@@ -964,12 +964,12 @@ init_matrix_probabilities (void)
 {
     if (matrix_0 == NULL || matrix_1 == NULL)
     {
-        unsigned index;           
+        unsigned index;
         unsigned n, exp;
-      
+
         matrix_0 = Calloc (1 << (MAX_PROB + 1), sizeof (real_t));
         matrix_1 = Calloc (1 << (MAX_PROB + 1), sizeof (real_t));
-   
+
         for (index = 0, n = MIN_PROB; n <= MAX_PROB; n++)
             for (exp = 0; exp < (unsigned) 1 << n; exp++, index++)
             {
diff --git a/converter/other/fiasco/codec/domain-pool.h b/converter/other/fiasco/codec/domain-pool.h
index a2c46141..b3258b67 100644
--- a/converter/other/fiasco/codec/domain-pool.h
+++ b/converter/other/fiasco/codec/domain-pool.h
@@ -1,8 +1,8 @@
 /*
  *  domain-pool.h
  *
- *  Written by:		Ullrich Hafner
- *		
+ *  Written by:         Ullrich Hafner
+ *
  *  This file is part of FIASCO (Fractal Image And Sequence COdec)
  *  Copyright (C) 1994-2000 Ullrich Hafner
  */
@@ -22,42 +22,42 @@
 
 typedef struct domain_pool
 {
-   void	  *model;			/* probability model */
+   void   *model;                       /* probability model */
    word_t *(*generate) (unsigned level, int y_state, const wfa_t *wfa,
-			const void  *model);
+                        const void  *model);
    /*
     *  Generate set of domain images which may be used for an approximation.
     *  Use parameters 'level', 'y_state' and 'wfa' to make the decision.
     */
    real_t (*bits) (const word_t *domains, const word_t *used_domains,
-		   unsigned level, int y_state, const wfa_t *wfa,
-		   const void *model);
+                   unsigned level, int y_state, const wfa_t *wfa,
+                   const void *model);
    /*
     *  Compute bit-rate of a range approximation with domains given by
     *  the -1 terminated list 'used_domains'.
     */
-   void	  (*update) (const word_t *domains, const word_t *used_domains,
-		     unsigned level, int y_state, const wfa_t *wfa,
-		     void *model);
+   void   (*update) (const word_t *domains, const word_t *used_domains,
+                     unsigned level, int y_state, const wfa_t *wfa,
+                     void *model);
    /*
     *  Update the probability model according to the chosen approximation.
     *  (given by the -1 terminated list 'used_domains').
     */
    bool_t (*append) (unsigned state, unsigned level, const wfa_t *wfa,
-		     void *model);
+                     void *model);
    /*
     *  Try to append a new state to the domain pool.
     */
-   void	  (*chroma) (unsigned max_domains, const wfa_t *wfa, void *model);
+   void   (*chroma) (unsigned max_domains, const wfa_t *wfa, void *model);
    /*
     *  Derive a new domain pool that will be used for chroma channel
-    *  coding 
+    *  coding
     */
    void   (*free) (struct domain_pool *pool);
    /*
     *  Discard the given domain pool struct.
     */
-   void   (*model_free)	(void *model);
+   void   (*model_free) (void *model);
    /*
     *  Free given probability model.
     */
@@ -69,7 +69,7 @@ typedef struct domain_pool
 
 domain_pool_t *
 alloc_domain_pool (const char *domain_pool_name, unsigned max_domains,
-		   unsigned max_edges, const wfa_t *wfa);
+                   unsigned max_edges, const wfa_t *wfa);
 
 #endif /* not _DOMAIN_POOL_H */
 
diff --git a/converter/other/fiasco/codec/ip.c b/converter/other/fiasco/codec/ip.c
index 18257a06..4209ab21 100644
--- a/converter/other/fiasco/codec/ip.c
+++ b/converter/other/fiasco/codec/ip.c
@@ -1,7 +1,7 @@
 /*
- *  ip.c:		Computation of inner products
+ *  ip.c:               Computation of inner products
  *
- *  Written by:		Ullrich Hafner
+ *  Written by:         Ullrich Hafner
  *
  *  This file is part of FIASCO (Fractal Image And Sequence COdec)
  *  Copyright (C) 1994-2000 Ullrich Hafner
@@ -26,29 +26,29 @@
 
 /*****************************************************************************
 
-				prototypes
+                                prototypes
 
 *****************************************************************************/
 
 static real_t
 standard_ip_image_state (unsigned address, unsigned level, unsigned domain,
-			 const coding_t *c);
+                         const coding_t *c);
 static real_t
 standard_ip_state_state (unsigned domain1, unsigned domain2, unsigned level,
-			 const coding_t *c);
+                         const coding_t *c);
 
 /*****************************************************************************
 
-				public code
+                                public code
 
 *****************************************************************************/
 
 real_t
 get_ip_image_state (unsigned image, unsigned address, unsigned level,
-		    unsigned domain, const coding_t *c)
+                    unsigned domain, const coding_t *c)
 /*
  *  Return value:
- *	Inner product between 'image' ('address') and
+ *      Inner product between 'image' ('address') and
  *      'domain' at given 'level'
  */
 {
@@ -71,8 +71,8 @@ get_ip_image_state (unsigned image, unsigned address, unsigned level,
 
 void
 compute_ip_images_state (unsigned image, unsigned address, unsigned level,
-			 unsigned n, unsigned from,
-			 const wfa_t *wfa, coding_t *c)
+                         unsigned n, unsigned from,
+                         const wfa_t *wfa, coding_t *c)
 /*
  *  Compute the inner products between all states
  *  'from', ... , 'wfa->max_states' and the range images 'image'
@@ -81,84 +81,84 @@ compute_ip_images_state (unsigned image, unsigned address, unsigned level,
  *  No return value.
  *
  *  Side effects:
- *	inner product tables 'c->ip_images_states' are updated
+ *      inner product tables 'c->ip_images_states' are updated
  */
 {
    if (level > c->options.images_level)
    {
       unsigned state, label;
 
-      if (level > c->options.images_level + 1)	/* recursive computation */
-	 compute_ip_images_state (MAXLABELS * image + 1, address * MAXLABELS,
-				  level - 1, MAXLABELS * n, from, wfa, c);
+      if (level > c->options.images_level + 1)  /* recursive computation */
+         compute_ip_images_state (MAXLABELS * image + 1, address * MAXLABELS,
+                                  level - 1, MAXLABELS * n, from, wfa, c);
 
       /*
        *  Compute inner product <f, Phi_i>
        */
       for (label = 0; label < MAXLABELS; label++)
-	 for (state = from; state < wfa->states; state++)
-	    if (need_image (state, wfa))
-	    {
-	       unsigned  edge, count;
-	       int     	 domain;
-	       real_t 	*dst, *src;
-
-	       if (ischild (domain = wfa->tree [state][label]))
-	       {
-		  if (level > c->options.images_level + 1)
-		  {
-		     dst = c->ip_images_state [state] + image;
-		     src = c->ip_images_state [domain]
-			   + image * MAXLABELS + label + 1;
-		     for (count = n; count; count--, src += MAXLABELS)
-			*dst++ += *src;
-		  }
-		  else
-		  {
-		     unsigned newadr = address * MAXLABELS + label;
-
-		     dst = c->ip_images_state [state] + image;
-
-		     for (count = n; count; count--, newadr += MAXLABELS)
-			*dst++ += standard_ip_image_state (newadr, level - 1,
-							   domain, c);
-		  }
-	       }
-	       for (edge = 0; isedge (domain = wfa->into [state][label][edge]);
-		    edge++)
-	       {
-		  real_t weight = wfa->weight [state][label][edge];
-
-		  if (level > c->options.images_level + 1)
-		  {
-		     dst = c->ip_images_state [state] + image;
-		     src = c->ip_images_state [domain]
-			   + image * MAXLABELS + label + 1;
-		     for (count = n; count; count--, src += MAXLABELS)
-			*dst++ += *src * weight;
-		  }
-		  else
-		  {
-		     unsigned newadr = address * MAXLABELS + label;
-
-		     dst = c->ip_images_state [state] + image;
-
-		     for (count = n; count; count--, newadr += MAXLABELS)
-			*dst++ += weight *
-				  standard_ip_image_state (newadr, level - 1,
-							   domain, c);
-		  }
-	       }
-	    }
+         for (state = from; state < wfa->states; state++)
+            if (need_image (state, wfa))
+            {
+               unsigned  edge, count;
+               int       domain;
+               real_t   *dst, *src;
+
+               if (ischild (domain = wfa->tree [state][label]))
+               {
+                  if (level > c->options.images_level + 1)
+                  {
+                     dst = c->ip_images_state [state] + image;
+                     src = c->ip_images_state [domain]
+                           + image * MAXLABELS + label + 1;
+                     for (count = n; count; count--, src += MAXLABELS)
+                        *dst++ += *src;
+                  }
+                  else
+                  {
+                     unsigned newadr = address * MAXLABELS + label;
+
+                     dst = c->ip_images_state [state] + image;
+
+                     for (count = n; count; count--, newadr += MAXLABELS)
+                        *dst++ += standard_ip_image_state (newadr, level - 1,
+                                                           domain, c);
+                  }
+               }
+               for (edge = 0; isedge (domain = wfa->into [state][label][edge]);
+                    edge++)
+               {
+                  real_t weight = wfa->weight [state][label][edge];
+
+                  if (level > c->options.images_level + 1)
+                  {
+                     dst = c->ip_images_state [state] + image;
+                     src = c->ip_images_state [domain]
+                           + image * MAXLABELS + label + 1;
+                     for (count = n; count; count--, src += MAXLABELS)
+                        *dst++ += *src * weight;
+                  }
+                  else
+                  {
+                     unsigned newadr = address * MAXLABELS + label;
+
+                     dst = c->ip_images_state [state] + image;
+
+                     for (count = n; count; count--, newadr += MAXLABELS)
+                        *dst++ += weight *
+                                  standard_ip_image_state (newadr, level - 1,
+                                                           domain, c);
+                  }
+               }
+            }
    }
 }
 
 real_t
 get_ip_state_state (unsigned domain1, unsigned domain2, unsigned level,
-		    const coding_t *c)
+                    const coding_t *c)
 /*
  *  Return value:
- *	Inner product between 'domain1' and 'domain2' at given 'level'.
+ *      Inner product between 'domain1' and 'domain2' at given 'level'.
  */
 {
    if (level <= c->options.images_level)
@@ -175,15 +175,15 @@ get_ip_state_state (unsigned domain1, unsigned domain2, unsigned level,
        *  Use already computed inner products stored in 'ip_images_states'
        */
       if (domain2 < domain1)
-	 return c->ip_states_state [domain1][level][domain2];
+         return c->ip_states_state [domain1][level][domain2];
       else
-	 return c->ip_states_state [domain2][level][domain1];
+         return c->ip_states_state [domain2][level][domain1];
    }
 }
 
 void
 compute_ip_states_state (unsigned from, unsigned to,
-			 const wfa_t *wfa, coding_t *c)
+                         const wfa_t *wfa, coding_t *c)
 /*
  *  Computes the inner products between the current state 'state1' and the
  *  old states 0,...,'state1'-1
@@ -191,7 +191,7 @@ compute_ip_states_state (unsigned from, unsigned to,
  *  No return value.
  *
  *  Side effects:
- *	inner product tables 'c->ip_states_state' are computed.
+ *      inner product tables 'c->ip_states_state' are computed.
  */
 {
    unsigned level;
@@ -202,72 +202,72 @@ compute_ip_states_state (unsigned from, unsigned to,
     */
 
    for (level = c->options.images_level + 1;
-	level <= c->options.lc_max_level; level++)
+        level <= c->options.lc_max_level; level++)
       for (state1 = from; state1 <= to; state1++)
-	 for (state2 = 0; state2 <= state1; state2++)
-	    if (need_image (state2, wfa))
-	    {
-	       unsigned	label;
-	       real_t	ip = 0;
-
-	       for (label = 0; label < MAXLABELS; label++)
-	       {
-		  int	   domain1, domain2;
-		  unsigned edge1, edge2;
-		  real_t   sum, weight2;
-
-		  if (ischild (domain1 = wfa->tree [state1][label]))
-		  {
-		     sum = 0;
-		     if (ischild (domain2 = wfa->tree [state2][label]))
-			sum = get_ip_state_state (domain1, domain2,
-						  level - 1, c);
-
-		     for (edge2 = 0;
-			  isedge (domain2 = wfa->into [state2][label][edge2]);
-			  edge2++)
-		     {
-			weight2 = wfa->weight [state2][label][edge2];
-			sum += weight2 * get_ip_state_state (domain1, domain2,
-							     level - 1, c);
-		     }
-		     ip += sum;
-		  }
-		  for (edge1 = 0;
-		       isedge (domain1 = wfa->into [state1][label][edge1]);
-		       edge1++)
-		  {
-		     real_t weight1 = wfa->weight [state1][label][edge1];
-
-		     sum = 0;
-		     if (ischild (domain2 = wfa->tree [state2][label]))
-			sum = get_ip_state_state (domain1, domain2,
-						  level - 1, c);
-
-		     for (edge2 = 0;
-			  isedge (domain2 = wfa->into [state2][label][edge2]);
-			  edge2++)
-		     {
-			weight2 = wfa->weight [state2][label][edge2];
-			sum += weight2 * get_ip_state_state (domain1, domain2,
-							     level - 1, c);
-		     }
-		     ip += weight1 * sum;
-		  }
-	       }
-	       c->ip_states_state [state1][level][state2] = ip;
-	    }
+         for (state2 = 0; state2 <= state1; state2++)
+            if (need_image (state2, wfa))
+            {
+               unsigned label;
+               real_t   ip = 0;
+
+               for (label = 0; label < MAXLABELS; label++)
+               {
+                  int      domain1, domain2;
+                  unsigned edge1, edge2;
+                  real_t   sum, weight2;
+
+                  if (ischild (domain1 = wfa->tree [state1][label]))
+                  {
+                     sum = 0;
+                     if (ischild (domain2 = wfa->tree [state2][label]))
+                        sum = get_ip_state_state (domain1, domain2,
+                                                  level - 1, c);
+
+                     for (edge2 = 0;
+                          isedge (domain2 = wfa->into [state2][label][edge2]);
+                          edge2++)
+                     {
+                        weight2 = wfa->weight [state2][label][edge2];
+                        sum += weight2 * get_ip_state_state (domain1, domain2,
+                                                             level - 1, c);
+                     }
+                     ip += sum;
+                  }
+                  for (edge1 = 0;
+                       isedge (domain1 = wfa->into [state1][label][edge1]);
+                       edge1++)
+                  {
+                     real_t weight1 = wfa->weight [state1][label][edge1];
+
+                     sum = 0;
+                     if (ischild (domain2 = wfa->tree [state2][label]))
+                        sum = get_ip_state_state (domain1, domain2,
+                                                  level - 1, c);
+
+                     for (edge2 = 0;
+                          isedge (domain2 = wfa->into [state2][label][edge2]);
+                          edge2++)
+                     {
+                        weight2 = wfa->weight [state2][label][edge2];
+                        sum += weight2 * get_ip_state_state (domain1, domain2,
+                                                             level - 1, c);
+                     }
+                     ip += weight1 * sum;
+                  }
+               }
+               c->ip_states_state [state1][level][state2] = ip;
+            }
 }
 
 /*****************************************************************************
 
-				private code
+                                private code
 
 *****************************************************************************/
 
 static real_t
 standard_ip_image_state (unsigned address, unsigned level, unsigned domain,
-			 const coding_t *c)
+                         const coding_t *c)
 /*
  *  Returns the inner product between the subimage 'address' and the
  *  state image 'domain' at given 'level'.  The stored state images
@@ -275,7 +275,7 @@ standard_ip_image_state (unsigned address, unsigned level, unsigned domain,
  *  standard way by multiplying the corresponding pixel values.
  *
  *  Return value:
- *	computed inner product
+ *      computed inner product
  */
 {
    unsigned i;
@@ -296,7 +296,7 @@ standard_ip_image_state (unsigned address, unsigned level, unsigned domain,
 
 static real_t
 standard_ip_state_state (unsigned domain1, unsigned domain2, unsigned level,
-			 const coding_t *c)
+                         const coding_t *c)
 /*
  *  Returns the inner product between the subimage 'address' and the
  *  state image 'state' at given 'level'.  The stored state images are
@@ -304,7 +304,7 @@ standard_ip_state_state (unsigned domain1, unsigned domain2, unsigned level,
  *  multiplying the corresponding pixel values.
  *
  *  Return value:
- *	computed inner product
+ *      computed inner product
  */
 {
    unsigned i;
diff --git a/converter/other/fiasco/codec/ip.h b/converter/other/fiasco/codec/ip.h
index 0c693826..f7d7efac 100644
--- a/converter/other/fiasco/codec/ip.h
+++ b/converter/other/fiasco/codec/ip.h
@@ -1,8 +1,8 @@
 /*
  *  ip.h
  *
- *  Written by:		Ullrich Hafner
- *		
+ *  Written by:         Ullrich Hafner
+ *
  *  This file is part of FIASCO (Fractal Image And Sequence COdec)
  *  Copyright (C) 1994-2000 Ullrich Hafner
  */
@@ -19,19 +19,19 @@
 
 #include "cwfa.h"
 
-void 
+void
 compute_ip_states_state (unsigned from, unsigned to,
-			 const wfa_t *wfa, coding_t *c);
-real_t 
+                         const wfa_t *wfa, coding_t *c);
+real_t
 get_ip_state_state (unsigned domain1, unsigned domain2, unsigned level,
-		    const coding_t *c);
-void 
+                    const coding_t *c);
+void
 compute_ip_images_state (unsigned image, unsigned address, unsigned level,
-			 unsigned n, unsigned from,
-			 const wfa_t *wfa, coding_t *c);
-real_t 
+                         unsigned n, unsigned from,
+                         const wfa_t *wfa, coding_t *c);
+real_t
 get_ip_image_state (unsigned image, unsigned address, unsigned level,
-		    unsigned domain, const coding_t *c);
+                    unsigned domain, const coding_t *c);
 
 #endif /* not _IP_H */
 
diff --git a/converter/other/fiasco/codec/motion.c b/converter/other/fiasco/codec/motion.c
index 0d1fa099..18d3bdd3 100644
--- a/converter/other/fiasco/codec/motion.c
+++ b/converter/other/fiasco/codec/motion.c
@@ -1,9 +1,9 @@
 /*
- *  motion.c:		Motion compensation code	
+ *  motion.c:           Motion compensation code
+ *
+ *  Written by:         Ullrich Hafner
+ *                      Michael Unger
  *
- *  Written by:		Ullrich Hafner
- *			Michael Unger
- *		
  *  This file is part of FIASCO (Fractal Image And Sequence COdec)
  *  Copyright (C) 1994-2000 Ullrich Hafner
  */
@@ -31,13 +31,13 @@
 
 /*****************************************************************************
 
-				public code
-  
+                                public code
+
 *****************************************************************************/
 
 void
 restore_mc (int enlarge_factor, image_t *image, const image_t *past,
-	    const image_t *future, const wfa_t *wfa)
+            const image_t *future, const wfa_t *wfa)
 /*
  *  Restore motion compensated prediction of 'image' represented by 'wfa'.
  *  If 'enlarge_factor' != 0 then enlarge image by given amount.
@@ -48,193 +48,193 @@ restore_mc (int enlarge_factor, image_t *image, const image_t *past,
 {
    unsigned  state, label;
    unsigned  root_state;
-   word_t   *mcblock1, *mcblock2;	/* MC blocks */
+   word_t   *mcblock1, *mcblock2;       /* MC blocks */
 
 #define FX(v) ((image->format == FORMAT_4_2_0) && band != Y ? ((v) / 2) : v)
-   
+
    mcblock1 = Calloc (size_of_level (MAX((int) wfa->wfainfo->p_max_level
-					  + 2 * enlarge_factor, 0)),
-		      sizeof (word_t));
+                                          + 2 * enlarge_factor, 0)),
+                      sizeof (word_t));
    mcblock2 = Calloc (size_of_level (MAX((int) wfa->wfainfo->p_max_level
-					  + 2 * enlarge_factor, 0)),
-		      sizeof (word_t));
+                                          + 2 * enlarge_factor, 0)),
+                      sizeof (word_t));
 
    if (!image->color)
       root_state = wfa->root_state;
    else
       root_state  = wfa->tree [wfa->tree [wfa->root_state][0]][0];
-   
+
    for (state = wfa->basis_states; state <= root_state; state++)
       for (label = 0; label < MAXLABELS; label++)
-	 if (wfa->mv_tree[state][label].type != NONE)
-	 {
-	    color_e band;
-	    unsigned level  = wfa->level_of_state [state] - 1;
-	    unsigned width  = width_of_level (level);
-	    unsigned height = height_of_level (level);
-	    unsigned offset = image->width - width;
-	    
-	    switch (wfa->mv_tree [state][label].type)
-	    {
-	       case FORWARD:
-		  for (band  = first_band (image->color);
-		       band <= last_band (image->color); band++)
-		  {
-		     extract_mc_block (mcblock1, FX (width), FX (height),
-				       past->pixels [band], FX (past->width),
-				       wfa->wfainfo->half_pixel,
-				       FX (wfa->x [state][label]),
-				       FX (wfa->y [state][label]),
-				       FX (wfa->mv_tree [state][label].fx),
-				       FX (wfa->mv_tree [state][label].fy));
-		     {
-			word_t   *mc1;	/* current pixel in MC block */
-			word_t 	 *orig;	/* current pixel in original image */
-			unsigned  x, y;	/* pixel coordinates */
-			
-			mc1  = mcblock1;
-			orig = (word_t *) image->pixels [band]
-			       + FX (wfa->x[state][label])
-			       + FX (wfa->y[state][label]) * FX (image->width);
-		     
-			for (y = FX (height); y; y--)
-			{
-			   for (x = FX (width); x; x--)
-			      *orig++ += *mc1++;
-
-			   orig += FX (offset);
-			}
-		     }
-		  }
-		  break;
-	       case BACKWARD:
-		  for (band  = first_band (image->color);
-		       band <= last_band (image->color); band++)
-		  {
-		     extract_mc_block (mcblock1, FX (width), FX (height),
-				       future->pixels [band],
-				       FX (future->width),
-				       wfa->wfainfo->half_pixel,
-				       FX (wfa->x [state][label]),
-				       FX (wfa->y [state][label]),
-				       FX (wfa->mv_tree [state][label].bx),
-				       FX (wfa->mv_tree [state][label].by));
-		     {
-			word_t   *mc1;	/* current pixel in MC block 1 */
-			word_t   *orig;	/* current pixel in original image */
-			unsigned  x, y;	/* pixel coordinates */
-			
-			mc1  = mcblock1;
-			orig = (word_t *) image->pixels [band]
-			       + FX (wfa->x[state][label])
-			       + FX (wfa->y[state][label]) * FX (image->width);
-		     
-			for (y = FX (height); y; y--)
-			{
-			   for (x = FX (width); x; x--)
-			      *orig++ += *mc1++;
-
-			   orig += FX (offset);
-			}
-		     }
-		  }
-		  break;
-	       case INTERPOLATED:
-		  for (band  = first_band (image->color);
-		       band <= last_band (image->color); band++)
-		  {
-		     extract_mc_block (mcblock1, FX (width), FX (height),
-				       past->pixels [band], FX (past->width),
-				       wfa->wfainfo->half_pixel,
-				       FX (wfa->x[state][label]),
-				       FX (wfa->y[state][label]),
-				       FX (wfa->mv_tree[state][label].fx),
-				       FX (wfa->mv_tree[state][label].fy));
-		     extract_mc_block (mcblock2, FX (width), FX (height),
-				       future->pixels [band],
-				       FX (future->width),
-				       wfa->wfainfo->half_pixel,
-				       FX (wfa->x[state][label]),
-				       FX (wfa->y[state][label]),
-				       FX (wfa->mv_tree[state][label].bx),
-				       FX (wfa->mv_tree[state][label].by));
-		     {
-			word_t   *mc1;	/* current pixel in MC block 1 */
-			word_t   *mc2;	/* current pixel in MC block 1 */
-			word_t   *orig;	/* current pixel in original image */
-			unsigned  x, y;	/* pixel coordinates */
-			
-			mc1  = mcblock1;
-			mc2  = mcblock2;
-			orig = (word_t *) image->pixels [band]
-			       + FX (wfa->x[state][label])
-			       + FX (wfa->y[state][label]) * FX (image->width);
-			
-			for (y = FX (height); y; y--)
-			{
-			   for (x = FX (width); x; x--)
+         if (wfa->mv_tree[state][label].type != NONE)
+         {
+            color_e band;
+            unsigned level  = wfa->level_of_state [state] - 1;
+            unsigned width  = width_of_level (level);
+            unsigned height = height_of_level (level);
+            unsigned offset = image->width - width;
+
+            switch (wfa->mv_tree [state][label].type)
+            {
+               case FORWARD:
+                  for (band  = first_band (image->color);
+                       band <= last_band (image->color); band++)
+                  {
+                     extract_mc_block (mcblock1, FX (width), FX (height),
+                                       past->pixels [band], FX (past->width),
+                                       wfa->wfainfo->half_pixel,
+                                       FX (wfa->x [state][label]),
+                                       FX (wfa->y [state][label]),
+                                       FX (wfa->mv_tree [state][label].fx),
+                                       FX (wfa->mv_tree [state][label].fy));
+                     {
+                        word_t   *mc1;  /* current pixel in MC block */
+                        word_t   *orig; /* current pixel in original image */
+                        unsigned  x, y; /* pixel coordinates */
+
+                        mc1  = mcblock1;
+                        orig = (word_t *) image->pixels [band]
+                               + FX (wfa->x[state][label])
+                               + FX (wfa->y[state][label]) * FX (image->width);
+
+                        for (y = FX (height); y; y--)
+                        {
+                           for (x = FX (width); x; x--)
+                              *orig++ += *mc1++;
+
+                           orig += FX (offset);
+                        }
+                     }
+                  }
+                  break;
+               case BACKWARD:
+                  for (band  = first_band (image->color);
+                       band <= last_band (image->color); band++)
+                  {
+                     extract_mc_block (mcblock1, FX (width), FX (height),
+                                       future->pixels [band],
+                                       FX (future->width),
+                                       wfa->wfainfo->half_pixel,
+                                       FX (wfa->x [state][label]),
+                                       FX (wfa->y [state][label]),
+                                       FX (wfa->mv_tree [state][label].bx),
+                                       FX (wfa->mv_tree [state][label].by));
+                     {
+                        word_t   *mc1;  /* current pixel in MC block 1 */
+                        word_t   *orig; /* current pixel in original image */
+                        unsigned  x, y; /* pixel coordinates */
+
+                        mc1  = mcblock1;
+                        orig = (word_t *) image->pixels [band]
+                               + FX (wfa->x[state][label])
+                               + FX (wfa->y[state][label]) * FX (image->width);
+
+                        for (y = FX (height); y; y--)
+                        {
+                           for (x = FX (width); x; x--)
+                              *orig++ += *mc1++;
+
+                           orig += FX (offset);
+                        }
+                     }
+                  }
+                  break;
+               case INTERPOLATED:
+                  for (band  = first_band (image->color);
+                       band <= last_band (image->color); band++)
+                  {
+                     extract_mc_block (mcblock1, FX (width), FX (height),
+                                       past->pixels [band], FX (past->width),
+                                       wfa->wfainfo->half_pixel,
+                                       FX (wfa->x[state][label]),
+                                       FX (wfa->y[state][label]),
+                                       FX (wfa->mv_tree[state][label].fx),
+                                       FX (wfa->mv_tree[state][label].fy));
+                     extract_mc_block (mcblock2, FX (width), FX (height),
+                                       future->pixels [band],
+                                       FX (future->width),
+                                       wfa->wfainfo->half_pixel,
+                                       FX (wfa->x[state][label]),
+                                       FX (wfa->y[state][label]),
+                                       FX (wfa->mv_tree[state][label].bx),
+                                       FX (wfa->mv_tree[state][label].by));
+                     {
+                        word_t   *mc1;  /* current pixel in MC block 1 */
+                        word_t   *mc2;  /* current pixel in MC block 1 */
+                        word_t   *orig; /* current pixel in original image */
+                        unsigned  x, y; /* pixel coordinates */
+
+                        mc1  = mcblock1;
+                        mc2  = mcblock2;
+                        orig = (word_t *) image->pixels [band]
+                               + FX (wfa->x[state][label])
+                               + FX (wfa->y[state][label]) * FX (image->width);
+
+                        for (y = FX (height); y; y--)
+                        {
+                           for (x = FX (width); x; x--)
 #ifdef HAVE_SIGNED_SHIFT
-			      *orig++ += (*mc1++ + *mc2++) >> 1;
+                              *orig++ += (*mc1++ + *mc2++) >> 1;
 #else /* not HAVE_SIGNED_SHIFT */
-			   *orig++ += (*mc1++ + *mc2++) / 2;
+                           *orig++ += (*mc1++ + *mc2++) / 2;
 #endif /* not HAVE_SIGNED_SHIFT */
 
-			   orig += FX (offset);
-			}
-		     }
-		  }
-		  break;
-	       default:
-		  break;
-	    }
-	 }
+                           orig += FX (offset);
+                        }
+                     }
+                  }
+                  break;
+               default:
+                  break;
+            }
+         }
 
    if (image->color)
    {
-      unsigned	  n;
-      word_t	 *ptr;
+      unsigned    n;
+      word_t     *ptr;
       static int *clipping = NULL;
-      unsigned	  shift    = image->format == FORMAT_4_2_0 ? 2 : 0;
+      unsigned    shift    = image->format == FORMAT_4_2_0 ? 2 : 0;
 
-      if (!clipping)			/* initialize clipping table */
+      if (!clipping)                    /* initialize clipping table */
       {
-	 int i;
-	    
-	 clipping = Calloc (256 * 3, sizeof (int));
-	 for (i = -128; i < 128; i++)
-	    clipping [256 + i + 128] = i;
-	 for (i = 0; i < 256; i++)
-	    clipping [i] = clipping [256];
-	 for (i = 512; i < 512 + 256; i++)
-	    clipping [i] = clipping [511];
-	 clipping += 256 + 128;
+         int i;
+
+         clipping = Calloc (256 * 3, sizeof (int));
+         for (i = -128; i < 128; i++)
+            clipping [256 + i + 128] = i;
+         for (i = 0; i < 256; i++)
+            clipping [i] = clipping [256];
+         for (i = 512; i < 512 + 256; i++)
+            clipping [i] = clipping [511];
+         clipping += 256 + 128;
       }
-	 
+
       ptr = image->pixels [Cb];
       for (n = (image->width * image->height) >> shift; n; n--, ptr++)
 #ifdef HAVE_SIGNED_SHIFT
-	 *ptr = clipping [*ptr >> 4] << 4;
+         *ptr = clipping [*ptr >> 4] << 4;
 #else /* not HAVE_SIGNED_SHIFT */
-	 *ptr = clipping [*ptr / 16] * 16;
+         *ptr = clipping [*ptr / 16] * 16;
 #endif /* not HAVE_SIGNED_SHIFT */
       ptr = image->pixels [Cr];
       for (n = (image->width * image->height) >> shift; n; n--, ptr++)
 #ifdef HAVE_SIGNED_SHIFT
-	*ptr = clipping [*ptr >> 4] << 4;
+        *ptr = clipping [*ptr >> 4] << 4;
 #else /* not HAVE_SIGNED_SHIFT */
         *ptr = clipping [*ptr / 16] * 16;
 #endif /* not HAVE_SIGNED_SHIFT */
    }
-   
+
    Free (mcblock1);
    Free (mcblock2);
 }
 
 void
 extract_mc_block (word_t *mcblock, unsigned width, unsigned height,
-		  const word_t *reference, unsigned ref_width,
-		  bool_t half_pixel, unsigned xo, unsigned yo,
-		  unsigned mx, unsigned my)
+                  const word_t *reference, unsigned ref_width,
+                  bool_t half_pixel, unsigned xo, unsigned yo,
+                  unsigned mx, unsigned my)
 /*
  *  Extract motion compensation image 'mcblock' of size 'width'x'height'
  *  from 'reference' image (width is given by 'ref_width').
@@ -244,93 +244,93 @@ extract_mc_block (word_t *mcblock, unsigned width, unsigned height,
  *  No return value.
  *
  *  Side effects:
- *	'mcblock[]'	MCPE block is filled with reference pixels 
+ *      'mcblock[]'     MCPE block is filled with reference pixels
  */
 {
-   if (!half_pixel)			/* Fullpixel precision */
+   if (!half_pixel)                     /* Fullpixel precision */
    {
-      const word_t *rblock;		/* pointer to reference image */
-      unsigned	    y;			/* current row */
-      
+      const word_t *rblock;             /* pointer to reference image */
+      unsigned      y;                  /* current row */
+
       rblock  = reference + (yo + my) * ref_width + (xo + mx);
-      for (y = height; y; y--) 
+      for (y = height; y; y--)
       {
-	 memcpy (mcblock, rblock, width * sizeof (word_t));
+         memcpy (mcblock, rblock, width * sizeof (word_t));
 
-	 mcblock += width;
-	 rblock  += ref_width;
+         mcblock += width;
+         rblock  += ref_width;
       }
    }
-   else					/* Halfpixel precision */
+   else                                 /* Halfpixel precision */
    {
-      unsigned	    x, y;		/* current coordinates */
-      unsigned	    offset;		/* remaining pixels in row */
-      const word_t *rblock;		/* pointer to reference image */
-      const word_t *ryblock;		/* pointer to next line */
-      const word_t *rxblock;		/* pointer to next column */
-      const word_t *rxyblock;		/* pointer to next column & row */
-   
+      unsigned      x, y;               /* current coordinates */
+      unsigned      offset;             /* remaining pixels in row */
+      const word_t *rblock;             /* pointer to reference image */
+      const word_t *ryblock;            /* pointer to next line */
+      const word_t *rxblock;            /* pointer to next column */
+      const word_t *rxyblock;           /* pointer to next column & row */
+
       rblock   = reference + (yo + my / 2) * ref_width + (xo + mx / 2);
-      ryblock  = rblock + ref_width;	/* pixel in next row */
-      rxblock  = rblock + 1;		/* pixel in next column */
-      rxyblock = ryblock + 1;		/* pixel in next row & column */
+      ryblock  = rblock + ref_width;    /* pixel in next row */
+      rxblock  = rblock + 1;            /* pixel in next column */
+      rxyblock = ryblock + 1;           /* pixel in next row & column */
       offset   = ref_width - width;
-      
+
       if ((mx & 1) == 0)
       {
-	 if ((my & 1) == 0)		/* Don't use halfpixel refinement */
-	    for (y = height; y; y--) 
-	    {
-	       memcpy (mcblock, rblock, width * sizeof (word_t));
-	       
-	       mcblock += width;
-	       rblock  += ref_width;
-	    }
-	 else				/* Halfpixel in y direction */
-	    for (y = height; y; y--) 
-	    {
-	       for (x = width; x; x--)
+         if ((my & 1) == 0)             /* Don't use halfpixel refinement */
+            for (y = height; y; y--)
+            {
+               memcpy (mcblock, rblock, width * sizeof (word_t));
+
+               mcblock += width;
+               rblock  += ref_width;
+            }
+         else                           /* Halfpixel in y direction */
+            for (y = height; y; y--)
+            {
+               for (x = width; x; x--)
 #ifdef HAVE_SIGNED_SHIFT
-		  *mcblock++ = (*rblock++ + *ryblock++) >> 1;
+                  *mcblock++ = (*rblock++ + *ryblock++) >> 1;
 #else /* not HAVE_SIGNED_SHIFT */
-		  *mcblock++ = (*rblock++ + *ryblock++) / 2;
+                  *mcblock++ = (*rblock++ + *ryblock++) / 2;
 #endif /* not HAVE_SIGNED_SHIFT */
 
-	       rblock  += offset;
-	       ryblock += offset;
-	    }
+               rblock  += offset;
+               ryblock += offset;
+            }
       }
       else
       {
-	 if ((my & 1) == 0)		/* Halfpixel in x direction */
-	    for (y = height; y; y--) 
-	    {
-	       for (x = width; x; x--)
+         if ((my & 1) == 0)             /* Halfpixel in x direction */
+            for (y = height; y; y--)
+            {
+               for (x = width; x; x--)
 #ifdef HAVE_SIGNED_SHIFT
-		  *mcblock++ = (*rblock++ + *rxblock++) >> 1;
+                  *mcblock++ = (*rblock++ + *rxblock++) >> 1;
 #else /* not HAVE_SIGNED_SHIFT */
-		  *mcblock++ = (*rblock++ + *rxblock++) / 2;
+                  *mcblock++ = (*rblock++ + *rxblock++) / 2;
 #endif /* not HAVE_SIGNED_SHIFT */
 
-	       rblock  += offset;
-	       rxblock += offset;
-	    }
-	 else				/* Halfpixel in xy direction */
-	    for (y = height; y; y--) 
-	    {
-	       for (x = width; x; x--)
+               rblock  += offset;
+               rxblock += offset;
+            }
+         else                           /* Halfpixel in xy direction */
+            for (y = height; y; y--)
+            {
+               for (x = width; x; x--)
 #ifdef HAVE_SIGNED_SHIFT
-		  *mcblock++ = (*rblock++ + *rxblock++
-				+ *ryblock++ + *rxyblock++) >> 2;
+                  *mcblock++ = (*rblock++ + *rxblock++
+                                + *ryblock++ + *rxyblock++) >> 2;
 #else /* not HAVE_SIGNED_SHIFT */
-		  *mcblock++ = (*rblock++ + *rxblock++
-				+ *ryblock++ + *rxyblock++) / 4;
+                  *mcblock++ = (*rblock++ + *rxblock++
+                                + *ryblock++ + *rxyblock++) / 4;
 #endif /* not HAVE_SIGNED_SHIFT */
-	       rblock   += offset;
-	       ryblock  += offset;
-	       rxblock  += offset;
-	       rxyblock += offset;
-	    }
+               rblock   += offset;
+               ryblock  += offset;
+               rxblock  += offset;
+               rxyblock += offset;
+            }
       }
    }
 }
diff --git a/converter/other/fiasco/codec/motion.h b/converter/other/fiasco/codec/motion.h
index 82d1f1ec..f913c65d 100644
--- a/converter/other/fiasco/codec/motion.h
+++ b/converter/other/fiasco/codec/motion.h
@@ -1,9 +1,9 @@
 /*
  *  motion.h
  *
- *  Written by:		Ullrich Hafner
- *			Michael Unger
- *		
+ *  Written by:         Ullrich Hafner
+ *                      Michael Unger
+ *              
  *  This file is part of FIASCO (Fractal Image And Sequence COdec)
  *  Copyright (C) 1994-2000 Ullrich Hafner
  */
@@ -24,12 +24,12 @@
 
 void
 restore_mc (int enlarge_factor, image_t *image, const image_t *past,
-	    const image_t *future, const wfa_t *wfa);
+            const image_t *future, const wfa_t *wfa);
 void
 extract_mc_block (word_t *mcblock, unsigned width, unsigned height,
-		  const word_t *reference, unsigned ref_width,
-		  bool_t half_pixel, unsigned xo, unsigned yo,
-		  unsigned mx, unsigned my);
+                  const word_t *reference, unsigned ref_width,
+                  bool_t half_pixel, unsigned xo, unsigned yo,
+                  unsigned mx, unsigned my);
 
 #endif /* not _MOTION_H */
 
diff --git a/converter/other/fiasco/codec/mwfa.c b/converter/other/fiasco/codec/mwfa.c
index 0be08a4f..f83f2d00 100644
--- a/converter/other/fiasco/codec/mwfa.c
+++ b/converter/other/fiasco/codec/mwfa.c
@@ -1,9 +1,9 @@
 /*
- *  mwfa.c:		Initialization of MWFA coder
+ *  mwfa.c:             Initialization of MWFA coder
+ *
+ *  Written by:         Michael Unger
+ *                      Ullrich Hafner
  *
- *  Written by:		Michael Unger
- *			Ullrich Hafner
- *		
  *  This file is part of FIASCO (Fractal Image And Sequence COdec)
  *  Copyright (C) 1994-2000 Ullrich Hafner
  */
@@ -38,33 +38,33 @@ static const unsigned local_range = 6;
 
 /*****************************************************************************
 
-				prototypes
-  
+                                prototypes
+
 *****************************************************************************/
 
 static void
 get_mcpe (word_t *mcpe, const image_t *original,
-	  unsigned x0, unsigned y0, unsigned width, unsigned height,
-	  const word_t *mcblock1, const word_t *mcblock2);
+          unsigned x0, unsigned y0, unsigned width, unsigned height,
+          const word_t *mcblock1, const word_t *mcblock2);
 static real_t
 mcpe_norm (const image_t *original, unsigned x0, unsigned y0, unsigned width,
-	   unsigned height, const word_t *mcblock1, const word_t *mcblock2);
-static real_t 
+           unsigned height, const word_t *mcblock1, const word_t *mcblock2);
+static real_t
 find_best_mv (real_t price, const image_t *original, const image_t *reference,
-	      unsigned x0, unsigned y0, unsigned width, unsigned height,
-	      real_t *bits, int *mx, int *my, const real_t *mc_norms,
-	      const wfa_info_t *wi, const motion_t *mt);
+              unsigned x0, unsigned y0, unsigned width, unsigned height,
+              real_t *bits, int *mx, int *my, const real_t *mc_norms,
+              const wfa_info_t *wi, const motion_t *mt);
 static real_t
 find_second_mv (real_t price, const image_t *original,
-		const image_t *reference, const word_t *mcblock1,
-		unsigned xr, unsigned yr, unsigned width, unsigned height,
-		real_t *bits, int *mx, int *my, const wfa_info_t *wi,
-		const motion_t *mt);
+                const image_t *reference, const word_t *mcblock1,
+                unsigned xr, unsigned yr, unsigned width, unsigned height,
+                real_t *bits, int *mx, int *my, const wfa_info_t *wi,
+                const motion_t *mt);
 
 /*****************************************************************************
 
-				public code
-  
+                                public code
+
 *****************************************************************************/
 
 motion_t *
@@ -75,32 +75,32 @@ alloc_motion (const wfa_info_t *wi)
  *  fill in default values specified by 'wi'.
  *
  *  Return value:
- *	pointer to the new option structure or NULL on error
+ *      pointer to the new option structure or NULL on error
  */
 {
-   int	     dx;			/* motion vector coordinate */
+   int       dx;                        /* motion vector coordinate */
    unsigned  level;
    unsigned range_size = wi->half_pixel
-			 ? square (wi->search_range)
-			 : square (2 * wi->search_range);
+                         ? square (wi->search_range)
+                         : square (2 * wi->search_range);
    motion_t *mt        = Calloc (1, sizeof (motion_t));
-   
+
    mt->original = NULL;
    mt->past     = NULL;
    mt->future   = NULL;
-   mt->xbits 	= Calloc (2 * wi->search_range, sizeof (real_t));
-   mt->ybits 	= Calloc (2 * wi->search_range, sizeof (real_t));
+   mt->xbits    = Calloc (2 * wi->search_range, sizeof (real_t));
+   mt->ybits    = Calloc (2 * wi->search_range, sizeof (real_t));
 
    for (dx = -wi->search_range; dx < (int) wi->search_range; dx++)
    {
       mt->xbits [dx + wi->search_range]
-	 = mt->ybits [dx + wi->search_range]
-	 = mv_code_table [dx + wi->search_range][1];
+         = mt->ybits [dx + wi->search_range]
+         = mv_code_table [dx + wi->search_range][1];
    }
-   
+
    mt->mc_forward_norms = Calloc (MAXLEVEL, sizeof (real_t *));
    mt->mc_backward_norms = Calloc (MAXLEVEL, sizeof (real_t *));
-   
+
    for (level = wi->p_min_level; level <= wi->p_max_level; level++)
    {
       mt->mc_forward_norms  [level] = Calloc (range_size, sizeof (real_t));
@@ -119,7 +119,7 @@ free_motion (motion_t *mt)
  *  No return value.
  *
  *  Side effects:
- *	structure 'motion' is discarded.
+ *      structure 'motion' is discarded.
  */
 {
    unsigned level;
@@ -129,9 +129,9 @@ free_motion (motion_t *mt)
    for (level = 0; level < MAXLEVEL; level++)
    {
       if (mt->mc_forward_norms [level])
-	 Free (mt->mc_forward_norms [level]);
+         Free (mt->mc_forward_norms [level]);
       if (mt->mc_backward_norms [level])
-	 Free (mt->mc_backward_norms [level]);
+         Free (mt->mc_backward_norms [level]);
    }
    Free (mt->mc_forward_norms);
    Free (mt->mc_backward_norms);
@@ -140,7 +140,7 @@ free_motion (motion_t *mt)
 
 void
 subtract_mc (image_t *image, const image_t *past, const image_t *future,
-	     const wfa_t *wfa)
+             const wfa_t *wfa)
 /*
  *  Subtract motion compensation from chrom channels of 'image'.
  *  Reference frames are given by 'past' and 'future'.
@@ -150,135 +150,135 @@ subtract_mc (image_t *image, const image_t *past, const image_t *future,
 {
    unsigned  state, label;
    word_t   *mcblock1 = Calloc (size_of_level (wfa->wfainfo->p_max_level),
-				sizeof (word_t));
+                                sizeof (word_t));
    word_t   *mcblock2 = Calloc (size_of_level (wfa->wfainfo->p_max_level),
-				sizeof (word_t));
+                                sizeof (word_t));
 
    for (state = wfa->basis_states; state < wfa->states; state++)
       for (label = 0; label < MAXLABELS; label++)
-	 if (wfa->mv_tree [state][label].type != NONE)
-	 {
-	    color_e  band;		/* current color band */
-	    unsigned width, height;	/* size of mcblock */
-	    unsigned offset;		/* remaining pixels in original */
-	    
-	    width  = width_of_level (wfa->level_of_state [state] - 1);
-	    height = height_of_level (wfa->level_of_state [state] - 1);
-	    offset = image->width - width;
-	    
-	    switch (wfa->mv_tree [state][label].type)
-	    {
-	       case FORWARD:
-		  for (band  = first_band (image->color) + 1;
-		       band <= last_band (image->color); band++)
-		  {
-		     unsigned  y;	/* row of block */
-		     word_t   *mc1;	/* pixel in MC block 1 */
-		     word_t   *orig;	/* pixel in original image */
-		     
-		     extract_mc_block (mcblock1, width, height,
-				       past->pixels [band], past->width,
-				       wfa->wfainfo->half_pixel,
-				       wfa->x [state][label],
-				       wfa->y [state][label],
-				       (wfa->mv_tree [state][label].fx / 2)
-				       * 2,
-				       (wfa->mv_tree [state][label].fy / 2)
-				       * 2);
-		     mc1  = mcblock1;
-		     orig = image->pixels [band] + wfa->x [state][label]
-			    + wfa->y [state][label] * image->width;
-		     
- 		     for (y = height; y; y--)
-		     {
-			unsigned x;	/* column of block */
-			
-			for (x = width; x; x--)
-			   *orig++ -= *mc1++;
-
-			orig += offset;
-		     }
-		  }
-		  break;
-	       case BACKWARD:
-		  for (band  = first_band (image->color) + 1;
-		       band <= last_band (image->color); band++)
-		  {
-		     unsigned  y;	/* row of block */
-		     word_t   *mc1;	/* pixel in MC block 1 */
-		     word_t   *orig;	/* pixel in original image */
-		     
-		     extract_mc_block (mcblock1, width, height,
-				       future->pixels [band], future->width,
-				       wfa->wfainfo->half_pixel,
-				       wfa->x [state][label],
-				       wfa->y [state][label],
-				       (wfa->mv_tree [state][label].bx / 2)
-				       * 2,
-				       (wfa->mv_tree [state][label].by / 2)
-				       * 2);
-		     mc1  = mcblock1;
-		     orig = image->pixels [band] + wfa->x [state][label]
-			    + wfa->y [state][label] * image->width;
-		     
-		     for (y = height; y; y--)
-		     {
-			unsigned x;	/* column of block */
-			
-			for (x = width; x; x--)
-			   *orig++ -= *mc1++;
-
-			orig += offset;
-		     }
-		  }
-		  break;
-	       case INTERPOLATED:
-		  for (band  = first_band (image->color) + 1;
-		       band <= last_band (image->color); band++)
-		  {
-		     unsigned  y;	/* row of block */
-		     word_t   *mc1;	/* pixel in MC block 1 */
-		     word_t   *mc2;	/* pixel in MC block 2 */
-		     word_t   *orig;	/* pixel in original image */
-		     
-		     extract_mc_block (mcblock1, width, height,
-				       past->pixels [band], past->width,
-				       wfa->wfainfo->half_pixel,
-				       wfa->x [state][label],
-				       wfa->y [state][label],
-				       (wfa->mv_tree[state][label].fx / 2)
-				       * 2,
-				       (wfa->mv_tree[state][label].fy / 2)
-				       * 2);
-		     extract_mc_block (mcblock2, width, height,
-				       future->pixels [band], future->width,
-				       wfa->wfainfo->half_pixel,
-				       wfa->x [state][label],
-				       wfa->y [state][label],
-				       (wfa->mv_tree[state][label].bx / 2)
-				       * 2,
-				       (wfa->mv_tree[state][label].by / 2)
-				       * 2);
-		     mc1  = mcblock1;
-		     mc2  = mcblock2;
-		     orig = image->pixels [band] + wfa->x [state][label]
-			    + wfa->y [state][label] * image->width;
-		     
-		     for (y = height; y; y--)
-		     {
-			unsigned x;	/* column of block */
-			
-			for (x = width; x; x--)
-			   *orig++ -= (*mc1++ + *mc2++) / 2;
-
-			orig += offset;
-		     }
-		  }
-		  break;
-	       default:
-		  break;
-	    }
-	 }
+         if (wfa->mv_tree [state][label].type != NONE)
+         {
+            color_e  band;              /* current color band */
+            unsigned width, height;     /* size of mcblock */
+            unsigned offset;            /* remaining pixels in original */
+
+            width  = width_of_level (wfa->level_of_state [state] - 1);
+            height = height_of_level (wfa->level_of_state [state] - 1);
+            offset = image->width - width;
+
+            switch (wfa->mv_tree [state][label].type)
+            {
+               case FORWARD:
+                  for (band  = first_band (image->color) + 1;
+                       band <= last_band (image->color); band++)
+                  {
+                     unsigned  y;       /* row of block */
+                     word_t   *mc1;     /* pixel in MC block 1 */
+                     word_t   *orig;    /* pixel in original image */
+
+                     extract_mc_block (mcblock1, width, height,
+                                       past->pixels [band], past->width,
+                                       wfa->wfainfo->half_pixel,
+                                       wfa->x [state][label],
+                                       wfa->y [state][label],
+                                       (wfa->mv_tree [state][label].fx / 2)
+                                       * 2,
+                                       (wfa->mv_tree [state][label].fy / 2)
+                                       * 2);
+                     mc1  = mcblock1;
+                     orig = image->pixels [band] + wfa->x [state][label]
+                            + wfa->y [state][label] * image->width;
+
+                     for (y = height; y; y--)
+                     {
+                        unsigned x;     /* column of block */
+
+                        for (x = width; x; x--)
+                           *orig++ -= *mc1++;
+
+                        orig += offset;
+                     }
+                  }
+                  break;
+               case BACKWARD:
+                  for (band  = first_band (image->color) + 1;
+                       band <= last_band (image->color); band++)
+                  {
+                     unsigned  y;       /* row of block */
+                     word_t   *mc1;     /* pixel in MC block 1 */
+                     word_t   *orig;    /* pixel in original image */
+
+                     extract_mc_block (mcblock1, width, height,
+                                       future->pixels [band], future->width,
+                                       wfa->wfainfo->half_pixel,
+                                       wfa->x [state][label],
+                                       wfa->y [state][label],
+                                       (wfa->mv_tree [state][label].bx / 2)
+                                       * 2,
+                                       (wfa->mv_tree [state][label].by / 2)
+                                       * 2);
+                     mc1  = mcblock1;
+                     orig = image->pixels [band] + wfa->x [state][label]
+                            + wfa->y [state][label] * image->width;
+
+                     for (y = height; y; y--)
+                     {
+                        unsigned x;     /* column of block */
+
+                        for (x = width; x; x--)
+                           *orig++ -= *mc1++;
+
+                        orig += offset;
+                     }
+                  }
+                  break;
+               case INTERPOLATED:
+                  for (band  = first_band (image->color) + 1;
+                       band <= last_band (image->color); band++)
+                  {
+                     unsigned  y;       /* row of block */
+                     word_t   *mc1;     /* pixel in MC block 1 */
+                     word_t   *mc2;     /* pixel in MC block 2 */
+                     word_t   *orig;    /* pixel in original image */
+
+                     extract_mc_block (mcblock1, width, height,
+                                       past->pixels [band], past->width,
+                                       wfa->wfainfo->half_pixel,
+                                       wfa->x [state][label],
+                                       wfa->y [state][label],
+                                       (wfa->mv_tree[state][label].fx / 2)
+                                       * 2,
+                                       (wfa->mv_tree[state][label].fy / 2)
+                                       * 2);
+                     extract_mc_block (mcblock2, width, height,
+                                       future->pixels [band], future->width,
+                                       wfa->wfainfo->half_pixel,
+                                       wfa->x [state][label],
+                                       wfa->y [state][label],
+                                       (wfa->mv_tree[state][label].bx / 2)
+                                       * 2,
+                                       (wfa->mv_tree[state][label].by / 2)
+                                       * 2);
+                     mc1  = mcblock1;
+                     mc2  = mcblock2;
+                     orig = image->pixels [band] + wfa->x [state][label]
+                            + wfa->y [state][label] * image->width;
+
+                     for (y = height; y; y--)
+                     {
+                        unsigned x;     /* column of block */
+
+                        for (x = width; x; x--)
+                           *orig++ -= (*mc1++ + *mc2++) / 2;
+
+                        orig += offset;
+                     }
+                  }
+                  break;
+               default:
+                  break;
+            }
+         }
 
    Free (mcblock1);
    Free (mcblock2);
@@ -286,7 +286,7 @@ subtract_mc (image_t *image, const image_t *past, const image_t *future,
 
 void
 find_P_frame_mc (word_t *mcpe, real_t price, range_t *range,
-		 const wfa_info_t *wi, const motion_t *mt)
+                 const wfa_info_t *wi, const motion_t *mt)
 /*
  *  Determine best motion vector for P-frame.
  *
@@ -301,7 +301,7 @@ find_P_frame_mc (word_t *mcpe, real_t price, range_t *range,
    unsigned  width   = width_of_level (range->level);
    unsigned  height  = height_of_level (range->level);
    word_t   *mcblock = Calloc (width * height, sizeof (word_t));
-   
+
    range->mv_tree_bits = 1;
    range->mv.type      = FORWARD;
 
@@ -309,24 +309,24 @@ find_P_frame_mc (word_t *mcpe, real_t price, range_t *range,
     *  Find best matching forward prediction
     */
    find_best_mv (price, mt->original, mt->past, range->x, range->y,
-		 width, height, &range->mv_coord_bits, &range->mv.fx,
-		 &range->mv.fy, mt->mc_forward_norms [range->level], wi, mt);
+                 width, height, &range->mv_coord_bits, &range->mv.fx,
+                 &range->mv.fy, mt->mc_forward_norms [range->level], wi, mt);
 
    /*
     *  Compute MCPE
     */
    extract_mc_block (mcblock, width, height, mt->past->pixels [GRAY],
-		     mt->past->width, wi->half_pixel, range->x, range->y,
-		     range->mv.fx, range->mv.fy);
+                     mt->past->width, wi->half_pixel, range->x, range->y,
+                     range->mv.fx, range->mv.fy);
    get_mcpe (mcpe, mt->original, range->x, range->y, width, height,
-	     mcblock, NULL);
+             mcblock, NULL);
 
    Free (mcblock);
 }
 
 void
 find_B_frame_mc (word_t *mcpe, real_t price, range_t *range,
-		 const wfa_info_t *wi, const motion_t *mt)
+                 const wfa_info_t *wi, const motion_t *mt)
 /*
  *  Determines best motion compensation for B-frame.
  *  Steps:
@@ -338,104 +338,104 @@ find_B_frame_mc (word_t *mcpe, real_t price, range_t *range,
  *    FORWARD      000
  *    BACKWARD     001
  *    INTERPOLATED  01
- *  
+ *
  *  Return values:
  *            range->mvt_bits  (# of mv-tree bits)
  *            range->mvxybits  (# of bits for vector components)
  *            mt->mcpe         (MCPE in scan-order)
  */
 {
-   mc_type_e  mctype;			/* type of motion compensation */
-   real_t     forward_costs;		/* costs of FORWARD mc */
-   real_t     backward_costs;		/* costs of BACKWARD mc */
-   real_t     interp_costs;		/* costs of INTERPOLATED mc */
-   real_t     forward_bits;		/* bits for FORWARD mc */
-   real_t     backward_bits;		/* bits for BACKWARD mc */
-   real_t     interp_bits;		/* bits for INTERPOLATED mc */
-   int	      fx,  fy;			/* coordinates FORWARD mc */
-   int	      bx,  by;			/* coordinates BACKWARD mc */
-   int	      ifx, ify;			/* coordinates forw. INTERPOLATED mc */
-   int	      ibx, iby;			/* coordinates back. INTERPOLATED mc */
+   mc_type_e  mctype;                   /* type of motion compensation */
+   real_t     forward_costs;            /* costs of FORWARD mc */
+   real_t     backward_costs;           /* costs of BACKWARD mc */
+   real_t     interp_costs;             /* costs of INTERPOLATED mc */
+   real_t     forward_bits;             /* bits for FORWARD mc */
+   real_t     backward_bits;            /* bits for BACKWARD mc */
+   real_t     interp_bits;              /* bits for INTERPOLATED mc */
+   int        fx,  fy;                  /* coordinates FORWARD mc */
+   int        bx,  by;                  /* coordinates BACKWARD mc */
+   int        ifx, ify;                 /* coordinates forw. INTERPOLATED mc */
+   int        ibx, iby;                 /* coordinates back. INTERPOLATED mc */
    unsigned   width    = width_of_level (range->level);
    unsigned   height   = height_of_level (range->level);
    word_t    *mcblock1 = Calloc (width * height, sizeof (word_t));
    word_t    *mcblock2 = Calloc (width * height, sizeof (word_t));
-   
+
    /*
     *  Forward interpolation: use past frame as reference
     */
    forward_costs = find_best_mv (price, mt->original, mt->past,
-				 range->x, range->y, width, height,
-				 &forward_bits, &fx, &fy,
-				 mt->mc_forward_norms [range->level], wi, mt)
-		   + 3 * price; /* code 000 */
+                                 range->x, range->y, width, height,
+                                 &forward_bits, &fx, &fy,
+                                 mt->mc_forward_norms [range->level], wi, mt)
+                   + 3 * price; /* code 000 */
 
    /*
     *  Backward interpolation: use future frame as reference
     */
    backward_costs = find_best_mv (price, mt->original, mt->future,
-				  range->x, range->y, width, height,
-				  &backward_bits, &bx, &by,
-				  mt->mc_backward_norms [range->level], wi, mt)
-		    + 3 * price; /* code 001 */
+                                  range->x, range->y, width, height,
+                                  &backward_bits, &bx, &by,
+                                  mt->mc_backward_norms [range->level], wi, mt)
+                    + 3 * price; /* code 001 */
 
    /*
     *  Bidirectional interpolation: use both past and future frame as reference
     */
-   if (wi->cross_B_search) 
+   if (wi->cross_B_search)
    {
-      real_t icosts1;			/* costs interpolation alternative 1 */
-      real_t icosts2;			/* costs interpolation alternative 2 */
-      real_t ibackward_bits;		/* additional bits alternative 1 */
-      real_t iforward_bits;		/* additional bits alternative 1 */
-      
+      real_t icosts1;                   /* costs interpolation alternative 1 */
+      real_t icosts2;                   /* costs interpolation alternative 2 */
+      real_t ibackward_bits;            /* additional bits alternative 1 */
+      real_t iforward_bits;             /* additional bits alternative 1 */
+
       /*
        *  Alternative 1: keep forward mv and vary backward mv locally
        */
       extract_mc_block (mcblock1, width, height, mt->past->pixels [GRAY],
-			mt->past->width, wi->half_pixel,
-			range->x, range->y, fx, fy);
+                        mt->past->width, wi->half_pixel,
+                        range->x, range->y, fx, fy);
 
-      ibx = bx;				/* start with backward coordinates */
+      ibx = bx;                         /* start with backward coordinates */
       iby = by;
       icosts1 = find_second_mv (price, mt->original, mt->future,
-				mcblock1, range->x, range->y, width, height,
-				&ibackward_bits, &ibx, &iby, wi, mt)
-		+ (forward_bits + 2) * price; /* code 01 */
+                                mcblock1, range->x, range->y, width, height,
+                                &ibackward_bits, &ibx, &iby, wi, mt)
+                + (forward_bits + 2) * price; /* code 01 */
 
       /*
        *  Alternative 2: Keep backward mv and vary forward mv locally
        */
       extract_mc_block (mcblock1, width, height, mt->future->pixels [GRAY],
-			mt->future->width, wi->half_pixel,
-			range->x, range->y, bx, by);
+                        mt->future->width, wi->half_pixel,
+                        range->x, range->y, bx, by);
 
       ifx = fx;
       ify = fy;
       icosts2 = find_second_mv (price, mt->original, mt->past,
-				mcblock1, range->x, range->y, width, height,
-				&iforward_bits, &ifx, &ify, wi, mt)
-		+ (backward_bits + 2) * price; /* code 01 */
-      
+                                mcblock1, range->x, range->y, width, height,
+                                &iforward_bits, &ifx, &ify, wi, mt)
+                + (backward_bits + 2) * price; /* code 01 */
+
       /*
        *  Choose best alternative
        */
       if (icosts1 < icosts2)
       {
-	 ifx 	      = fx;
-	 ify 	      = fy;
-	 interp_bits  = forward_bits + ibackward_bits;
-	 interp_costs = icosts1;
+         ifx          = fx;
+         ify          = fy;
+         interp_bits  = forward_bits + ibackward_bits;
+         interp_costs = icosts1;
       }
       else
       {
-	 ibx 	      = bx;
-	 iby 	      = by;
-	 interp_bits  = iforward_bits + backward_bits;
-	 interp_costs = icosts2;
+         ibx          = bx;
+         iby          = by;
+         interp_bits  = iforward_bits + backward_bits;
+         interp_costs = icosts2;
       }
    }
-   else					/* local exhaustive search */
+   else                                 /* local exhaustive search */
    {
       /*
        *  Keep forward and backward mv because of time constraints
@@ -448,14 +448,14 @@ find_B_frame_mc (word_t *mcpe, real_t price, range_t *range,
       interp_bits = forward_bits + backward_bits;
 
       extract_mc_block (mcblock1, width, height, mt->past->pixels [GRAY],
-			mt->past->width, wi->half_pixel,
-			range->x, range->y, fx, fy);
+                        mt->past->width, wi->half_pixel,
+                        range->x, range->y, fx, fy);
       extract_mc_block (mcblock2, width, height, mt->future->pixels [GRAY],
-			mt->future->width, wi->half_pixel,
-			range->x, range->y, bx, by);
+                        mt->future->width, wi->half_pixel,
+                        range->x, range->y, bx, by);
       interp_costs = mcpe_norm (mt->original, range->x, range->y,
-				width, height, mcblock1, mcblock2)
-		     + (interp_bits + 2) * price; /* code 01 */
+                                width, height, mcblock1, mcblock2)
+                     + (interp_bits + 2) * price; /* code 01 */
    }
 
    /*
@@ -464,63 +464,63 @@ find_B_frame_mc (word_t *mcpe, real_t price, range_t *range,
    if (forward_costs <= interp_costs)
    {
       if (forward_costs <= backward_costs)
-	 mctype = FORWARD;
+         mctype = FORWARD;
       else
-	 mctype = BACKWARD;
+         mctype = BACKWARD;
    }
    else
    {
       if (backward_costs <= interp_costs)
-	 mctype = BACKWARD;
+         mctype = BACKWARD;
       else
-	 mctype = INTERPOLATED;
+         mctype = INTERPOLATED;
    }
 
    switch (mctype)
    {
       case FORWARD:
-	 range->mv_tree_bits  = 3;
-	 range->mv_coord_bits = forward_bits;
-	 range->mv.type       = FORWARD;
-	 range->mv.fx         = fx;
-	 range->mv.fy         = fy;
-	 extract_mc_block (mcblock1, width, height, mt->past->pixels [GRAY],
-			   mt->past->width, wi->half_pixel,
-			   range->x, range->y, range->mv.fx, range->mv.fy);
-	 get_mcpe (mcpe, mt->original, range->x, range->y, width, height,
-		   mcblock1, NULL);
-	 break;
+         range->mv_tree_bits  = 3;
+         range->mv_coord_bits = forward_bits;
+         range->mv.type       = FORWARD;
+         range->mv.fx         = fx;
+         range->mv.fy         = fy;
+         extract_mc_block (mcblock1, width, height, mt->past->pixels [GRAY],
+                           mt->past->width, wi->half_pixel,
+                           range->x, range->y, range->mv.fx, range->mv.fy);
+         get_mcpe (mcpe, mt->original, range->x, range->y, width, height,
+                   mcblock1, NULL);
+         break;
       case BACKWARD:
-	 range->mv_tree_bits  = 3;
-	 range->mv_coord_bits = backward_bits;
-	 range->mv.type       = BACKWARD;
-	 range->mv.bx         = bx;
-	 range->mv.by         = by;
-	 extract_mc_block (mcblock1, width, height, mt->future->pixels [GRAY],
-			   mt->future->width, wi->half_pixel,
-			   range->x, range->y, range->mv.bx, range->mv.by);
-	 get_mcpe (mcpe, mt->original, range->x, range->y, width, height,
-		   mcblock1, NULL);
-	 break;
+         range->mv_tree_bits  = 3;
+         range->mv_coord_bits = backward_bits;
+         range->mv.type       = BACKWARD;
+         range->mv.bx         = bx;
+         range->mv.by         = by;
+         extract_mc_block (mcblock1, width, height, mt->future->pixels [GRAY],
+                           mt->future->width, wi->half_pixel,
+                           range->x, range->y, range->mv.bx, range->mv.by);
+         get_mcpe (mcpe, mt->original, range->x, range->y, width, height,
+                   mcblock1, NULL);
+         break;
       case INTERPOLATED:
-	 range->mv_tree_bits  = 2;
-	 range->mv_coord_bits = interp_bits;
-	 range->mv.type       = INTERPOLATED;
-	 range->mv.fx         = ifx;
-	 range->mv.fy         = ify;
-	 range->mv.bx         = ibx;
-	 range->mv.by         = iby;
-	 extract_mc_block (mcblock1, width, height, mt->past->pixels [GRAY],
-			   mt->past->width, wi->half_pixel,
-			   range->x, range->y, range->mv.fx, range->mv.fy);
-	 extract_mc_block (mcblock2, width, height, mt->future->pixels [GRAY],
-			   mt->future->width, wi->half_pixel,
-			   range->x, range->y, range->mv.bx, range->mv.by);
-	 get_mcpe (mcpe, mt->original, range->x, range->y, width, height,
-		   mcblock1, mcblock2);
-	 break;
+         range->mv_tree_bits  = 2;
+         range->mv_coord_bits = interp_bits;
+         range->mv.type       = INTERPOLATED;
+         range->mv.fx         = ifx;
+         range->mv.fy         = ify;
+         range->mv.bx         = ibx;
+         range->mv.by         = iby;
+         extract_mc_block (mcblock1, width, height, mt->past->pixels [GRAY],
+                           mt->past->width, wi->half_pixel,
+                           range->x, range->y, range->mv.fx, range->mv.fy);
+         extract_mc_block (mcblock2, width, height, mt->future->pixels [GRAY],
+                           mt->future->width, wi->half_pixel,
+                           range->x, range->y, range->mv.bx, range->mv.by);
+         get_mcpe (mcpe, mt->original, range->x, range->y, width, height,
+                   mcblock1, mcblock2);
+         break;
       default:
-	 break;
+         break;
    }
 
    Free (mcblock1);
@@ -529,7 +529,7 @@ find_B_frame_mc (word_t *mcpe, real_t price, range_t *range,
 
 void
 fill_norms_table (unsigned x0, unsigned y0, unsigned level,
-		  const wfa_info_t *wi, motion_t *mt)
+                  const wfa_info_t *wi, motion_t *mt)
 /*
  *  Compute norms of difference images for all possible displacements
  *  in 'mc_forward_norm' and 'mc_backward_norm'.
@@ -537,50 +537,50 @@ fill_norms_table (unsigned x0, unsigned y0, unsigned level,
  *  No return value.
  *
  *  Side effects:
- *	'mt->mc_backward_norms' are computed
- *	'mt->mc_forward_norms' are computed 
+ *      'mt->mc_backward_norms' are computed
+ *      'mt->mc_forward_norms' are computed
  */
 {
-   int	     mx, my;			/* coordinates of motion vector */
-   unsigned  sr;			/* mv search range +-'sr' pixels */
-   unsigned  index   = 0;		/* index of motion vector */
+   int       mx, my;                    /* coordinates of motion vector */
+   unsigned  sr;                        /* mv search range +-'sr' pixels */
+   unsigned  index   = 0;               /* index of motion vector */
    unsigned  width   = width_of_level (level);
    unsigned  height  = height_of_level (level);
    word_t   *mcblock = Calloc (width * height, sizeof (word_t));
 
    sr = wi->half_pixel ? wi->search_range / 2 :  wi->search_range;
-   
+
    for (my = -sr; my < (int) sr; my++)
       for (mx = -sr; mx < (int) sr; mx++, index++)
       {
-	  if ((int) x0 + mx < 0 ||	/* block outside visible area */
-	      x0 + mx + width > mt->original->width || 
-	      (int) y0 + my < 0 ||
-	      y0 + my + height > mt->original->height)
-	  {
-	     mt->mc_forward_norms [level][index]  = 0.0;
-	     mt->mc_backward_norms [level][index] = 0.0;
-	  }
-	  else
-	  {
-	     extract_mc_block (mcblock, width, height, mt->past->pixels [GRAY],
-			       mt->past->width, wi->half_pixel,
-			       x0, y0, mx, my);
-	     mt->mc_forward_norms [level][index]
-		= mcpe_norm (mt->original, x0, y0, width, height,
-			     mcblock, NULL);
-
-	     if (mt->frame_type == B_FRAME)
-	     {
-		extract_mc_block (mcblock, width, height,
-				  mt->future->pixels [GRAY],
-				  mt->future->width, wi->half_pixel,
-				  x0, y0, mx, my);
-		mt->mc_backward_norms[level][index]
-		   = mcpe_norm (mt->original, x0, y0, width, height,
-				mcblock, NULL); 
-	     }
-	  }
+          if ((int) x0 + mx < 0 ||      /* block outside visible area */
+              x0 + mx + width > mt->original->width ||
+              (int) y0 + my < 0 ||
+              y0 + my + height > mt->original->height)
+          {
+             mt->mc_forward_norms [level][index]  = 0.0;
+             mt->mc_backward_norms [level][index] = 0.0;
+          }
+          else
+          {
+             extract_mc_block (mcblock, width, height, mt->past->pixels [GRAY],
+                               mt->past->width, wi->half_pixel,
+                               x0, y0, mx, my);
+             mt->mc_forward_norms [level][index]
+                = mcpe_norm (mt->original, x0, y0, width, height,
+                             mcblock, NULL);
+
+             if (mt->frame_type == B_FRAME)
+             {
+                extract_mc_block (mcblock, width, height,
+                                  mt->future->pixels [GRAY],
+                                  mt->future->width, wi->half_pixel,
+                                  x0, y0, mx, my);
+                mt->mc_backward_norms[level][index]
+                   = mcpe_norm (mt->original, x0, y0, width, height,
+                                mcblock, NULL);
+             }
+          }
        }
 
    Free (mcblock);
@@ -588,14 +588,14 @@ fill_norms_table (unsigned x0, unsigned y0, unsigned level,
 
 /*****************************************************************************
 
-				private code
-  
+                                private code
+
 *****************************************************************************/
 
 static void
 get_mcpe (word_t *mcpe, const image_t *original, unsigned x0, unsigned y0,
-	  unsigned width, unsigned height, const word_t *mcblock1,
-	  const word_t *mcblock2)
+          unsigned width, unsigned height, const word_t *mcblock1,
+          const word_t *mcblock2)
 /*
  *  Compute MCPE image 'original' - reference. The reference is either
  *  composed of 'mcblock1' or of ('mcblock1' + 'mcblock2') / 2 (if
@@ -605,44 +605,44 @@ get_mcpe (word_t *mcpe, const image_t *original, unsigned x0, unsigned y0,
  *  No return value.
  *
  *  Side effects:
- *	'mcpe []' is filled with the delta image
+ *      'mcpe []' is filled with the delta image
  */
 {
-   const word_t	*oblock;		/* pointer to original image */
+   const word_t *oblock;                /* pointer to original image */
 
    assert (mcpe);
-   
+
    oblock = original->pixels [GRAY] + y0 * original->width + x0;
 
-   if (mcblock2 != NULL)		/* interpolated prediction */
+   if (mcblock2 != NULL)                /* interpolated prediction */
    {
-      unsigned x, y;			/* current coordinates */
-      
-      for (y = height; y; y--) 
+      unsigned x, y;                    /* current coordinates */
+
+      for (y = height; y; y--)
       {
-	 for (x = width; x; x--)
-	    *mcpe++ = *oblock++ - (*mcblock1++ + *mcblock2++) / 2;
+         for (x = width; x; x--)
+            *mcpe++ = *oblock++ - (*mcblock1++ + *mcblock2++) / 2;
 
-	 oblock += original->width - width;
+         oblock += original->width - width;
       }
    }
-   else					/* forward or backward prediction */
+   else                                 /* forward or backward prediction */
    {
-      unsigned x, y;			/* current coordinates */
-      
-      for (y = height; y; y--) 
+      unsigned x, y;                    /* current coordinates */
+
+      for (y = height; y; y--)
       {
-	 for (x = width; x; x--)
-	    *mcpe++ = *oblock++ - *mcblock1++;
-      
-	 oblock += original->width - width;
+         for (x = width; x; x--)
+            *mcpe++ = *oblock++ - *mcblock1++;
+
+         oblock += original->width - width;
       }
    }
 }
 
 static real_t
 mcpe_norm (const image_t *original, unsigned x0, unsigned y0, unsigned width,
-	   unsigned height, const word_t *mcblock1, const word_t *mcblock2)
+           unsigned height, const word_t *mcblock1, const word_t *mcblock2)
 /*
  *  Compute norm of motion compensation prediction error.
  *  Coordinates of 'original' block are given by ('x0', 'y0')
@@ -650,79 +650,79 @@ mcpe_norm (const image_t *original, unsigned x0, unsigned y0, unsigned width,
  *  Reference blocks are stored in 'mcimage1' and 'mcimage2'.
  *
  *  Return value:
- *	square of norm of difference image
+ *      square of norm of difference image
  */
 {
    unsigned  n;
    real_t    norm = 0;
    word_t   *mcpe = Calloc (width * height, sizeof (word_t));
    word_t   *ptr  = mcpe;
-   
+
    get_mcpe (mcpe, original, x0, y0, width, height, mcblock1, mcblock2);
 
-   for (n = height * width; n; n--, ptr++) 
+   for (n = height * width; n; n--, ptr++)
       norm += square (*ptr / 16);
-   
+
    Free (mcpe);
-   
+
    return norm;
 }
 
-static real_t 
+static real_t
 find_best_mv (real_t price, const image_t *original, const image_t *reference,
-	      unsigned x0, unsigned y0, unsigned width, unsigned height,
-	      real_t *bits, int *mx, int *my, const real_t *mc_norms,
-	      const wfa_info_t *wi, const motion_t *mt)
+              unsigned x0, unsigned y0, unsigned width, unsigned height,
+              real_t *bits, int *mx, int *my, const real_t *mc_norms,
+              const wfa_info_t *wi, const motion_t *mt)
 /*
  *  Find best matching motion vector in image 'reference' to predict
  *  the block ('x0', 'y0') of size 'width'x'height in image 'original'.
  *
  *  Return values:
- *	prediction costs
+ *      prediction costs
  *
  *  Side effects:
- *	'mx', 'my'		coordinates of motion vector
- *	'bits'			number of bits to encode mv
+ *      'mx', 'my'              coordinates of motion vector
+ *      'bits'                  number of bits to encode mv
  */
 {
-   unsigned sr;				/* mv search range +/- 'sr' pixels */
-   unsigned index;			/* index of motion vector */
-   int 	    x, y;			/* coordinates of motion vector */
-   real_t   costs;			/* costs arising if mv is chosen */
-   real_t   mincosts = MAXCOSTS;	/* best costs so far  */
-   unsigned bitshift;			/* half_pixel coordinates multiplier */
-   
+   unsigned sr;                         /* mv search range +/- 'sr' pixels */
+   unsigned index;                      /* index of motion vector */
+   int      x, y;                       /* coordinates of motion vector */
+   real_t   costs;                      /* costs arising if mv is chosen */
+   real_t   mincosts = MAXCOSTS;        /* best costs so far  */
+   unsigned bitshift;                   /* half_pixel coordinates multiplier */
+
    *mx = *my = 0;
 
    /*
     *  Find best fitting motion vector:
     *  Use exhaustive search in the interval x,y +- sr (no halfpixel accuracy)
-    *					  or x,y +- sr/2  (halfpixel accuracy)
+    *                                     or x,y +- sr/2  (halfpixel accuracy)
     */
-   sr 	    = wi->half_pixel ? wi->search_range / 2 :  wi->search_range;
-   bitshift = (wi->half_pixel ? 2 : 1);	/* bit0 reserved for halfpixel pred. */
-   
+   sr       = wi->half_pixel ? wi->search_range / 2 :  wi->search_range;
+   bitshift = (wi->half_pixel ? 2 : 1); /* bit0 reserved for halfpixel pred. */
+
    for (index = 0, y = -sr; y < (int) sr; y++)
       for (x = -sr; x < (int) sr; x++, index++)
-	 if ((int) x0 + x >= 0 && (int) y0 + y >= 0 &&	
-	     x0 + x + width  <= original->width && 
-	     y0 + y + height <= original->height)
-	 {
-	    /*
-	     *  Block is inside visible area.
-	     *  Compare current costs with 'mincosts'
-	     */
-	    costs = mc_norms [index]
-		    + (mt->xbits [(x + sr) * bitshift]
-		       + mt->ybits [(y + sr) * bitshift]) * price;
-
-	     if (costs < mincosts)
-	     {
-		mincosts = costs;
-		*mx      = x * bitshift;
-		*my      = y * bitshift;
-	     }
-	 }
+         if ((int) x0 + x >= 0 && (int) y0 + y >= 0 &&
+             x0 + x + width  <= original->width &&
+             y0 + y + height <= original->height)
+         {
+            /*
+             *  Block is inside visible area.
+             *  Compare current costs with 'mincosts'
+             */
+            costs = mc_norms [index]
+                    + (mt->xbits [(x + sr) * bitshift]
+                       + mt->ybits [(y + sr) * bitshift]) * price;
+
+             if (costs < mincosts)
+             {
+                mincosts = costs;
+                *mx      = x * bitshift;
+                *my      = y * bitshift;
+             }
+         }
 
    /*
     *  Halfpixel prediction:
@@ -730,53 +730,53 @@ find_best_mv (real_t price, const image_t *original, const image_t *reference,
     */
    if (wi->half_pixel)
    {
-      int	rx, ry;			/* halfpixel refinement */
-      unsigned	bestrx, bestry;		/* coordinates of best mv */
+      int       rx, ry;                 /* halfpixel refinement */
+      unsigned  bestrx, bestry;         /* coordinates of best mv */
       word_t   *mcblock = Calloc (width * height, sizeof (word_t));
-      
+
       bestrx = bestry = 0;
       for (rx = -1; rx <= 1; rx++)
-	 for (ry = -1; ry <= 1; ry++)
-	 {
-	    /*
-	     *  Check if the new motion vector is in allowed area
-	     */
-	    if (rx == 0 && ry == 0)	/* already tested */
-	       continue;
-	    if ((int) x0 + (*mx / 2) + rx < 0 || /* outside visible area */
-		x0 + (*mx / 2) + rx + width > original->width ||
-		(int) y0 + (*my / 2) + ry < 0 || 
-		y0 + (*my / 2) + ry + height > original->height)
-	       continue;
-	    if (*mx + rx < (int) -sr || *mx + rx >= (int) sr ||
-		*my + ry < (int) -sr || *my + ry >= (int) sr) 
-	       continue;		/* out of bounds */
-
-	    /*
-	     *  Compute costs of new motion compensation
-	     */
-	    extract_mc_block (mcblock, width, height,
-			      reference->pixels [GRAY],
-			      reference->width, wi->half_pixel,
-			      x0, y0, *mx + rx, *my + ry);
-	    costs = mcpe_norm (mt->original, x0, y0, width, height, mcblock,
-			       NULL)
-		    + (mt->xbits [*mx + rx + sr * bitshift]
-		       + mt->ybits [*my + ry + sr * bitshift]) * price;
-	    if (costs < mincosts)
-	    {
-	       bestrx   = rx;
-	       bestry   = ry;
-	       mincosts = costs;
-	    }
-	 }
+         for (ry = -1; ry <= 1; ry++)
+         {
+            /*
+             *  Check if the new motion vector is in allowed area
+             */
+            if (rx == 0 && ry == 0)     /* already tested */
+               continue;
+            if ((int) x0 + (*mx / 2) + rx < 0 || /* outside visible area */
+                x0 + (*mx / 2) + rx + width > original->width ||
+                (int) y0 + (*my / 2) + ry < 0 ||
+                y0 + (*my / 2) + ry + height > original->height)
+               continue;
+            if (*mx + rx < (int) -sr || *mx + rx >= (int) sr ||
+                *my + ry < (int) -sr || *my + ry >= (int) sr)
+               continue;                /* out of bounds */
+
+            /*
+             *  Compute costs of new motion compensation
+             */
+            extract_mc_block (mcblock, width, height,
+                              reference->pixels [GRAY],
+                              reference->width, wi->half_pixel,
+                              x0, y0, *mx + rx, *my + ry);
+            costs = mcpe_norm (mt->original, x0, y0, width, height, mcblock,
+                               NULL)
+                    + (mt->xbits [*mx + rx + sr * bitshift]
+                       + mt->ybits [*my + ry + sr * bitshift]) * price;
+            if (costs < mincosts)
+            {
+               bestrx   = rx;
+               bestry   = ry;
+               mincosts = costs;
+            }
+         }
 
       *mx += bestrx;
       *my += bestry;
 
       Free (mcblock);
    } /* halfpixel */
-	     
+
    *bits = mt->xbits [*mx + sr * bitshift] + mt->ybits [*my + sr * bitshift];
 
    return mincosts;
@@ -784,28 +784,28 @@ find_best_mv (real_t price, const image_t *original, const image_t *reference,
 
 static real_t
 find_second_mv (real_t price, const image_t *original,
-		const image_t *reference, const word_t *mcblock1,
-		unsigned xr, unsigned yr, unsigned width, unsigned height,
-		real_t *bits, int *mx, int *my, const wfa_info_t *wi,
-		const motion_t *mt)
+                const image_t *reference, const word_t *mcblock1,
+                unsigned xr, unsigned yr, unsigned width, unsigned height,
+                real_t *bits, int *mx, int *my, const wfa_info_t *wi,
+                const motion_t *mt)
 /*
  *  Search local area (*mx,*my) for best additional mv.
  *  Overwrite mt->tmpblock.
  *  TODO check sr = search_range
  *
  *  Return values:
- *	prediction costs
+ *      prediction costs
  *
  *  Side effects:
- *	'mx','my'	coordinates of mv
- *      'bits'		number of bits to encode mv
+ *      'mx','my'       coordinates of mv
+ *      'bits'          number of bits to encode mv
  */
 {
-   real_t    mincosts = MAXCOSTS;	/* best costs so far  */
-   unsigned  sr;			/* MV search range +/- 'sr' pixels */
-   int       x, y;			/* coordinates of motion vector */
-   int       y0, y1, x0, x1;		/* start/end coord. of search range */
-   unsigned  bitshift;			/* half_pixel coordinates multiplier */
+   real_t    mincosts = MAXCOSTS;       /* best costs so far  */
+   unsigned  sr;                        /* MV search range +/- 'sr' pixels */
+   int       x, y;                      /* coordinates of motion vector */
+   int       y0, y1, x0, x1;            /* start/end coord. of search range */
+   unsigned  bitshift;                  /* half_pixel coordinates multiplier */
    word_t   *mcblock2 = Calloc (width * height, sizeof (word_t));
 
    sr = wi->search_range;
@@ -817,40 +817,40 @@ find_second_mv (real_t price, const image_t *original,
 
    *mx = *my = 0;
 
-   bitshift = (wi->half_pixel ? 2 : 1);	/* bit0 reserved for halfpixel pred. */
+   bitshift = (wi->half_pixel ? 2 : 1); /* bit0 reserved for halfpixel pred. */
+
 
-   
    for (y = y0; y < y1; y++)
       for (x = x0; x < x1; x++)
       {
-	 real_t costs;			/* costs arising if mv is chosen */
-	 
-	 /*
-	  *  Test each mv ('x', 'y') in the given search range:
-	  *  Get the new motion compensation image from 'reference' and compute
-	  *  the norm of the motion compensation prediction error
-	  *  'original' - 0.5 * ('firstmc' + 'reference')
-	  */
-	 if ((int) (xr * bitshift) + x < 0 ||	/* outside visible area */
-	     xr * bitshift + x > (original->width - width) * bitshift ||
-	     (int) (yr * bitshift) + y < 0 ||
-	     yr * bitshift + y > (original->height - height) * bitshift)
-	    continue;
-	 
-	 extract_mc_block (mcblock2, width, height,
-			   reference->pixels [GRAY], reference->width,
-			   wi->half_pixel, x0, y0, x, y);
-
-	 costs  = mcpe_norm (mt->original, x0, y0, width, height,
-			     mcblock1, mcblock2)
-		  + (mt->xbits [x + sr] + mt->ybits [y + sr]) * price;
-	 
-	 if (costs < mincosts)
-	 {
-	    mincosts = costs;
-	    *mx      = x;
-	    *my      = y;
-	 }
+         real_t costs;                  /* costs arising if mv is chosen */
+
+         /*
+          *  Test each mv ('x', 'y') in the given search range:
+          *  Get the new motion compensation image from 'reference' and compute
+          *  the norm of the motion compensation prediction error
+          *  'original' - 0.5 * ('firstmc' + 'reference')
+          */
+         if ((int) (xr * bitshift) + x < 0 ||   /* outside visible area */
+             xr * bitshift + x > (original->width - width) * bitshift ||
+             (int) (yr * bitshift) + y < 0 ||
+             yr * bitshift + y > (original->height - height) * bitshift)
+            continue;
+
+         extract_mc_block (mcblock2, width, height,
+                           reference->pixels [GRAY], reference->width,
+                           wi->half_pixel, x0, y0, x, y);
+
+         costs  = mcpe_norm (mt->original, x0, y0, width, height,
+                             mcblock1, mcblock2)
+                  + (mt->xbits [x + sr] + mt->ybits [y + sr]) * price;
+
+         if (costs < mincosts)
+         {
+            mincosts = costs;
+            *mx      = x;
+            *my      = y;
+         }
       }
 
    *bits = mt->xbits [*mx + sr] + mt->ybits [*my + sr];
diff --git a/converter/other/fiasco/codec/mwfa.h b/converter/other/fiasco/codec/mwfa.h
index 2c1e7c9f..1e35eef2 100644
--- a/converter/other/fiasco/codec/mwfa.h
+++ b/converter/other/fiasco/codec/mwfa.h
@@ -1,9 +1,9 @@
 /*
  *  mwfa.h
  *
- *  Written by:		Michael Unger
- *			Ullrich Hafner
- *		
+ *  Written by:         Michael Unger
+ *                      Ullrich Hafner
+ *              
  *  This file is part of FIASCO (Fractal Image And Sequence COdec)
  *  Copyright (C) 1994-2000 Ullrich Hafner
  */
@@ -25,16 +25,16 @@
 
 void
 fill_norms_table (unsigned x0, unsigned y0, unsigned level,
-		  const wfa_info_t *wi, motion_t *mt);
+                  const wfa_info_t *wi, motion_t *mt);
 void
 find_B_frame_mc (word_t *mcpe, real_t price, range_t *range,
-		 const wfa_info_t *wi, const motion_t *mt);
+                 const wfa_info_t *wi, const motion_t *mt);
 void
 find_P_frame_mc (word_t *mcpe, real_t price, range_t *range,
-		 const wfa_info_t *wi, const motion_t *mt);
+                 const wfa_info_t *wi, const motion_t *mt);
 void
 subtract_mc (image_t *image, const image_t *past, const image_t *future,
-	     const wfa_t *wfa);
+             const wfa_t *wfa);
 void
 free_motion (motion_t *mt);
 motion_t *
diff --git a/converter/other/fiasco/codec/options.c b/converter/other/fiasco/codec/options.c
index b9c64efd..8029a48e 100644
--- a/converter/other/fiasco/codec/options.c
+++ b/converter/other/fiasco/codec/options.c
@@ -1,8 +1,8 @@
 /*
- *  options.c:		FIASCO options handling
+ *  options.c:          FIASCO options handling
+ *
+ *  Written by:         Ullrich Hafner
  *
- *  Written by:		Ullrich Hafner
- *		
  *  This file is part of FIASCO (Fractal Image And Sequence COdec)
  *  Copyright (C) 1994-2000 Ullrich Hafner
  */
@@ -44,10 +44,10 @@ fiasco_c_options_new (void)
  *  fill in default values.
  *
  *  Return value:
- *	pointer to the new option structure
+ *      pointer to the new option structure
  */
 {
-   c_options_t 	      *options = calloc (1, sizeof (c_options_t));
+   c_options_t        *options = calloc (1, sizeof (c_options_t));
    fiasco_c_options_t *public  = calloc (1, sizeof (fiasco_c_options_t));
 
    if (!options || !public)
@@ -55,9 +55,9 @@ fiasco_c_options_new (void)
       set_error (_("Out of memory."));
       return NULL;
    }
-   public->private 	      = options;
-   public->delete 	      = fiasco_c_options_delete;
-   public->set_tiling 	      = fiasco_c_options_set_tiling;
+   public->private            = options;
+   public->delete             = fiasco_c_options_delete;
+   public->set_tiling         = fiasco_c_options_set_tiling;
    public->set_frame_pattern  = fiasco_c_options_set_frame_pattern;
    public->set_basisfile      = fiasco_c_options_set_basisfile;
    public->set_chroma_quality = fiasco_c_options_set_chroma_quality;
@@ -66,57 +66,57 @@ fiasco_c_options_new (void)
    public->set_quantization   = fiasco_c_options_set_quantization;
    public->set_progress_meter = fiasco_c_options_set_progress_meter;
    public->set_smoothing      = fiasco_c_options_set_smoothing;
-   public->set_title   	      = fiasco_c_options_set_title;
+   public->set_title          = fiasco_c_options_set_title;
    public->set_comment        = fiasco_c_options_set_comment;
-   
+
    strcpy (options->id, "COFIASCO");
 
    /*
     *  Set default value of fiasco options
     */
-   options->basis_name 		  = strdup ("small.fco");
-   options->lc_min_level 	  = 4;
-   options->lc_max_level 	  = 12;
-   options->p_min_level 	  = 8;
-   options->p_max_level 	  = 10;
-   options->images_level 	  = 5;
-   options->max_states 		  = MAXSTATES;
-   options->chroma_max_states 	  = 40;
-   options->max_elements 	  = MAXEDGES;
-   options->tiling_exponent 	  = 4;
-   options->tiling_method 	  = FIASCO_TILING_VARIANCE_DSC;
-   options->id_domain_pool 	  = strdup ("rle");
-   options->id_d_domain_pool 	  = strdup ("rle");
-   options->id_rpf_model 	  = strdup ("adaptive");
-   options->id_d_rpf_model 	  = strdup ("adaptive");
-   options->rpf_mantissa 	  = 3;
-   options->rpf_range 		  = FIASCO_RPF_RANGE_1_50;
-   options->dc_rpf_mantissa 	  = 5;
-   options->dc_rpf_range 	  = FIASCO_RPF_RANGE_1_00;
-   options->d_rpf_mantissa 	  = 3;
-   options->d_rpf_range 	  = FIASCO_RPF_RANGE_1_50;
-   options->d_dc_rpf_mantissa 	  = 5;
-   options->d_dc_rpf_range 	  = FIASCO_RPF_RANGE_1_00;
-   options->chroma_decrease 	  = 2.0;
-   options->prediction 		  = NO;
-   options->delta_domains 	  = YES;
-   options->normal_domains 	  = YES;
-   options->search_range 	  = 16;
-   options->fps 		  = 25;
-   options->pattern 		  = strdup ("IPPPPPPPPP");
-   options->reference_filename 	  = NULL;
+   options->basis_name            = strdup ("small.fco");
+   options->lc_min_level          = 4;
+   options->lc_max_level          = 12;
+   options->p_min_level           = 8;
+   options->p_max_level           = 10;
+   options->images_level          = 5;
+   options->max_states            = MAXSTATES;
+   options->chroma_max_states     = 40;
+   options->max_elements          = MAXEDGES;
+   options->tiling_exponent       = 4;
+   options->tiling_method         = FIASCO_TILING_VARIANCE_DSC;
+   options->id_domain_pool        = strdup ("rle");
+   options->id_d_domain_pool      = strdup ("rle");
+   options->id_rpf_model          = strdup ("adaptive");
+   options->id_d_rpf_model        = strdup ("adaptive");
+   options->rpf_mantissa          = 3;
+   options->rpf_range             = FIASCO_RPF_RANGE_1_50;
+   options->dc_rpf_mantissa       = 5;
+   options->dc_rpf_range          = FIASCO_RPF_RANGE_1_00;
+   options->d_rpf_mantissa        = 3;
+   options->d_rpf_range           = FIASCO_RPF_RANGE_1_50;
+   options->d_dc_rpf_mantissa     = 5;
+   options->d_dc_rpf_range        = FIASCO_RPF_RANGE_1_00;
+   options->chroma_decrease       = 2.0;
+   options->prediction            = NO;
+   options->delta_domains         = YES;
+   options->normal_domains        = YES;
+   options->search_range          = 16;
+   options->fps                   = 25;
+   options->pattern               = strdup ("IPPPPPPPPP");
+   options->reference_filename    = NULL;
    options->half_pixel_prediction = NO;
-   options->cross_B_search 	  = YES;
-   options->B_as_past_ref 	  = YES;
+   options->cross_B_search        = YES;
+   options->B_as_past_ref         = YES;
    options->check_for_underflow   = NO;
-   options->check_for_overflow 	  = NO;
+   options->check_for_overflow    = NO;
    options->second_domain_block   = NO;
-   options->full_search 	  = NO;
-   options->progress_meter 	  = FIASCO_PROGRESS_NONE;
-   options->smoothing 	 	  = 70;
-   options->comment 		  = strdup ("");
-   options->title 		  = strdup ("");
-   
+   options->full_search           = NO;
+   options->progress_meter        = FIASCO_PROGRESS_NONE;
+   options->smoothing             = 70;
+   options->comment               = strdup ("");
+   options->title                 = strdup ("");
+
    return public;
 }
 
@@ -129,14 +129,14 @@ fiasco_c_options_delete (fiasco_c_options_t *options)
  *  No return value.
  *
  *  Side effects:
- *	structure 'options' is discarded.
+ *      structure 'options' is discarded.
  */
 {
    c_options_t *this = cast_c_options (options);
 
    if (!this)
       return;
-   
+
    Free (this->id_domain_pool);
    Free (this->id_d_domain_pool);
    Free (this->id_rpf_model);
@@ -144,7 +144,7 @@ fiasco_c_options_delete (fiasco_c_options_t *options)
    Free (this->pattern);
    Free (this->comment);
    Free (this->title);
-   
+
    Free (this);
 
    return;
@@ -152,15 +152,15 @@ fiasco_c_options_delete (fiasco_c_options_t *options)
 
 int
 fiasco_c_options_set_tiling (fiasco_c_options_t *options,
-			     fiasco_tiling_e method, unsigned exponent)
+                             fiasco_tiling_e method, unsigned exponent)
 /*
  *  Set tiling `method' and `exponent'.
  *  See type `fiasco_tiling_e' for a list of valid  tiling `methods'.
  *  The image is subdivied into 2^`exponent' tiles
  *
  *  Return value:
- *	1 on success
- *	0 otherwise
+ *      1 on success
+ *      0 otherwise
  */
 {
    c_options_t *this = (c_options_t *) cast_c_options (options);
@@ -175,21 +175,21 @@ fiasco_c_options_set_tiling (fiasco_c_options_t *options,
       case FIASCO_TILING_SPIRAL_DSC:
       case FIASCO_TILING_VARIANCE_ASC:
       case FIASCO_TILING_VARIANCE_DSC:
-	 this->tiling_method = method;
-	 break;
+         this->tiling_method = method;
+         break;
       default:
-	 set_error (_("Invalid tiling method `%d' specified "
-		      "(valid methods are 0, 1, 2, or 3)."), method);
-	 return 0;
+         set_error (_("Invalid tiling method `%d' specified "
+                      "(valid methods are 0, 1, 2, or 3)."), method);
+         return 0;
    }
    this->tiling_exponent = exponent;
-   
+
    return 1;
 }
 
 int
 fiasco_c_options_set_frame_pattern (fiasco_c_options_t *options,
-				    const char *pattern)
+                                    const char *pattern)
 /*
  *  Set `pattern' of input frames.
  *  `pattern' has to be a sequence of the following
@@ -201,10 +201,10 @@ fiasco_c_options_set_frame_pattern (fiasco_c_options_t *options,
  *
  *  When coding video frames the prediction type of input frame N is determined
  *  by reading `pattern' [N] (`pattern' is periodically extended).
- *  
+ *
  *  Return value:
- *	1 on success
- *	0 otherwise
+ *      1 on success
+ *      0 otherwise
  */
 {
    c_options_t *this = (c_options_t *) cast_c_options (options);
@@ -226,49 +226,49 @@ fiasco_c_options_set_frame_pattern (fiasco_c_options_t *options,
    else
    {
       const char *str;
-      bool_t 	  parse_error = NO;
-      int	  c 	      = 0;
-      
+      bool_t      parse_error = NO;
+      int         c           = 0;
+
       for (str = pattern; *str && !parse_error; str++)
-	 switch (*str)
-	 {
-	    case 'i':
-	    case 'I':
-	    case 'b':
-	    case 'B':
-	    case 'p':
-	    case 'P':
-	       break;
-	    default:
-	       c = *str;
-	       parse_error = YES;
-	 }
+         switch (*str)
+         {
+            case 'i':
+            case 'I':
+            case 'b':
+            case 'B':
+            case 'p':
+            case 'P':
+               break;
+            default:
+               c = *str;
+               parse_error = YES;
+         }
 
       if (parse_error)
       {
-	 set_error (_("Frame type pattern contains invalid character `%c' "
-		      "(choose I, B or P)."), c);
-	 return 0;
+         set_error (_("Frame type pattern contains invalid character `%c' "
+                      "(choose I, B or P)."), c);
+         return 0;
       }
       else
       {
-	 Free (this->pattern);
-	 this->pattern = strdup (pattern);
+         Free (this->pattern);
+         this->pattern = strdup (pattern);
 
-	 return 1;
+         return 1;
       }
    }
 }
 
 int
 fiasco_c_options_set_basisfile (fiasco_c_options_t *options,
-				const char *filename)
+                                const char *filename)
 /*
  *  Set `filename' of FIASCO initial basis.
- *  
+ *
  *  Return value:
- *	1 on success (if the file is readable)
- *	0 otherwise
+ *      1 on success (if the file is readable)
+ *      0 otherwise
  */
 {
    c_options_t *this = (c_options_t *) cast_c_options (options);
@@ -289,14 +289,14 @@ fiasco_c_options_set_basisfile (fiasco_c_options_t *options,
       FILE *file = open_file (filename, "FIASCO_DATA", READ_ACCESS);
       if (file)
       {
-	 fclose (file);
-	 return 1;
+         fclose (file);
+         return 1;
       }
       else
       {
-	 set_error (_("Can't read basis file `%s'.\n%s."), filename,
-		    get_system_error ());
-	 return 0;
+         set_error (_("Can't read basis file `%s'.\n%s."), filename,
+                    get_system_error ());
+         return 0;
       }
       */ return 1;
    }
@@ -304,20 +304,20 @@ fiasco_c_options_set_basisfile (fiasco_c_options_t *options,
 
 int
 fiasco_c_options_set_chroma_quality (fiasco_c_options_t *options,
-				     float quality_factor,
-				     unsigned dictionary_size)
+                                     float quality_factor,
+                                     unsigned dictionary_size)
 /*
  *  Set color compression parameters.
  *  When coding chroma channels (Cb and Cr)
  *  - approximation quality is given by `quality_factor' * `Y quality' and
  *  - `dictionary_size' gives the number of dictionary elements.
- *  
+ *
  *  If 'quality' <= 0 then the luminancy coding quality is also during
  *  chroma channel coding.
- *  
+ *
  *  Return value:
- *	1 on success
- *	0 otherwise
+ *      1 on success
+ *      0 otherwise
  */
 {
    c_options_t *this = (c_options_t *) cast_c_options (options);
@@ -329,13 +329,13 @@ fiasco_c_options_set_chroma_quality (fiasco_c_options_t *options,
    else if (!dictionary_size)
    {
       set_error (_("Size of chroma compression dictionary has to be "
-		   "a positive number."));
+                   "a positive number."));
       return 0;
    }
    else if (quality_factor <= 0)
    {
       set_error (_("Quality of chroma channel compression has to be "
-		   "positive value."));
+                   "positive value."));
       return 0;
    }
    else
@@ -349,32 +349,32 @@ fiasco_c_options_set_chroma_quality (fiasco_c_options_t *options,
 
 int
 fiasco_c_options_set_optimizations (fiasco_c_options_t *options,
-				    unsigned min_block_level,
-				    unsigned max_block_level,
-				    unsigned max_elements,
-				    unsigned dictionary_size,
-				    unsigned optimization_level)
+                                    unsigned min_block_level,
+                                    unsigned max_block_level,
+                                    unsigned max_elements,
+                                    unsigned dictionary_size,
+                                    unsigned optimization_level)
 /*
  *  Set various optimization parameters.
  *  - During compression only image blocks of size
  *    {`min_block_level', ... ,`max_block_level'} are considered.
  *    The smaller this set of blocks is the faster the coder runs
- *    and the worse the image quality will be.  
+ *    and the worse the image quality will be.
  *  - An individual approximation may use at most `max_elements'
  *    elements of the dictionary which itself contains at most
  *    `dictionary_size' elements. The smaller these values are
- *    the faster the coder runs and the worse the image quality will be. 
+ *    the faster the coder runs and the worse the image quality will be.
  *  - `optimization_level' enables some additional low level optimizations.
  *    0: standard approximation method
  *    1: significantly increases the approximation quality,
  *       running time is twice as high as with the standard method
- *    2: hardly increases the approximation quality of method 1, 
+ *    2: hardly increases the approximation quality of method 1,
  *       running time is twice as high as with method 1
  *       (this method just remains for completeness)
  *
  *  Return value:
- *	1 on success
- *	0 otherwise
+ *      1 on success
+ *      0 otherwise
  */
 {
    c_options_t *this = (c_options_t *) cast_c_options (options);
@@ -391,7 +391,7 @@ fiasco_c_options_set_optimizations (fiasco_c_options_t *options,
    else if (!max_elements)
    {
       set_error (_("At least one dictionary element has to be used "
-		   "in an approximation."));
+                   "in an approximation."));
       return 0;
    }
    else if (max_block_level < 4)
@@ -407,19 +407,19 @@ fiasco_c_options_set_optimizations (fiasco_c_options_t *options,
    else if (max_block_level < min_block_level)
    {
       set_error (_("Maximum block size has to be larger or "
-		   "equal minimum block size."));
+                   "equal minimum block size."));
       return 0;
    }
    else
    {
-      this->lc_min_level 	= min_block_level;
-      this->lc_max_level 	= max_block_level;
-      this->max_states 	 	= dictionary_size;
-      this->max_elements 	= max_elements;
+      this->lc_min_level        = min_block_level;
+      this->lc_max_level        = max_block_level;
+      this->max_states          = dictionary_size;
+      this->max_elements        = max_elements;
       this->second_domain_block = optimization_level > 0 ? YES : NO;
       this->check_for_overflow  = optimization_level > 1 ? YES : NO;
       this->check_for_underflow = optimization_level > 1 ? YES : NO;
-      this->full_search 	= optimization_level > 1 ? YES : NO;
+      this->full_search         = optimization_level > 1 ? YES : NO;
 
       return 1;
    }
@@ -427,9 +427,9 @@ fiasco_c_options_set_optimizations (fiasco_c_options_t *options,
 
 int
 fiasco_c_options_set_prediction (fiasco_c_options_t *options,
-				 int intra_prediction,
-				 unsigned min_block_level,
-				 unsigned max_block_level)
+                                 int intra_prediction,
+                                 unsigned min_block_level,
+                                 unsigned max_block_level)
 /*
  *  Set minimum and maximum size of image block prediction to
  *  `min_block_level' and `max_block_level'.
@@ -438,8 +438,8 @@ fiasco_c_options_set_prediction (fiasco_c_options_t *options,
  *  Prediction of intra frames is only used if `intra_prediction' != 0.
  *
  *  Return value:
- *	1 on success
- *	0 otherwise
+ *      1 on success
+ *      0 otherwise
  */
 {
    c_options_t *this = (c_options_t *) cast_c_options (options);
@@ -451,19 +451,19 @@ fiasco_c_options_set_prediction (fiasco_c_options_t *options,
    else if (max_block_level < 6)
    {
       set_error (_("Maximum prediction block size has to be "
-		   "at least level 6"));
+                   "at least level 6"));
       return 0;
    }
    else if (min_block_level < 6)
    {
       set_error (_("Minimum prediction block size has to be "
-		   "at least level 6"));
+                   "at least level 6"));
       return 0;
    }
    else if (max_block_level < min_block_level)
    {
       set_error (_("Maximum prediction block size has to be larger or "
-		   "equal minimum block size."));
+                   "equal minimum block size."));
       return 0;
    }
    else
@@ -471,17 +471,17 @@ fiasco_c_options_set_prediction (fiasco_c_options_t *options,
       this->p_min_level = min_block_level;
       this->p_max_level = max_block_level;
       this->prediction  = intra_prediction;
-      
+
       return 1;
    }
 }
 
 int
 fiasco_c_options_set_video_param (fiasco_c_options_t *options,
-				  unsigned frames_per_second,
-				  int half_pixel_prediction,
-				  int cross_B_search,
-				  int B_as_past_ref)
+                                  unsigned frames_per_second,
+                                  int half_pixel_prediction,
+                                  int cross_B_search,
+                                  int B_as_past_ref)
 /*
  *  Set various parameters used for video compensation.
  *  'frames_per_second' defines the frame rate which should be
@@ -494,10 +494,10 @@ fiasco_c_options_set_video_param (fiasco_c_options_t *options,
  *  exhaustive search (in the given search range) is used.
  *  If 'B_as_past_ref' is not 0 then B frames are allowed to be used
  *  for B frame predicion.
- *  
+ *
  *  Return value:
- *	1 on success
- *	0 otherwise
+ *      1 on success
+ *      0 otherwise
  */
 {
    c_options_t *this = (c_options_t *) cast_c_options (options);
@@ -508,10 +508,10 @@ fiasco_c_options_set_video_param (fiasco_c_options_t *options,
    }
    else
    {
-      this->fps 	  	  = frames_per_second;
+      this->fps                   = frames_per_second;
       this->half_pixel_prediction = half_pixel_prediction;
-      this->cross_B_search 	  = cross_B_search;
-      this->B_as_past_ref 	  = B_as_past_ref;
+      this->cross_B_search        = cross_B_search;
+      this->B_as_past_ref         = B_as_past_ref;
 
       return 1;
    }
@@ -519,20 +519,20 @@ fiasco_c_options_set_video_param (fiasco_c_options_t *options,
 
 int
 fiasco_c_options_set_quantization (fiasco_c_options_t *options,
-				   unsigned mantissa,
-				   fiasco_rpf_range_e range,
-				   unsigned dc_mantissa,
-				   fiasco_rpf_range_e dc_range)
+                                   unsigned mantissa,
+                                   fiasco_rpf_range_e range,
+                                   unsigned dc_mantissa,
+                                   fiasco_rpf_range_e dc_range)
 /*
  *  Set accuracy of coefficients quantization.
  *  DC coefficients (of the constant dictionary vector f(x,y) = 1)
  *  are quantized to values of the interval [-`dc_range', `dc_range'] using
  *  #`dc_mantissa' bits. All other quantized coefficients are quantized in
  *  an analogous way using the parameters `range' and `mantissa'.
- *  
+ *
  *  Return value:
- *	1 on success
- *	0 otherwise
+ *      1 on success
+ *      0 otherwise
  */
 {
    c_options_t *this = (c_options_t *) cast_c_options (options);
@@ -544,46 +544,46 @@ fiasco_c_options_set_quantization (fiasco_c_options_t *options,
    else if (mantissa < 2 || mantissa > 8 || dc_mantissa < 2 || dc_mantissa > 8)
    {
       set_error (_("Number of RPF mantissa bits `%d', `%d' have to be in "
-		   "the interval [2,8]."), mantissa, dc_mantissa);
+                   "the interval [2,8]."), mantissa, dc_mantissa);
       return 0;
    }
    else
    {
       if ((range == FIASCO_RPF_RANGE_0_75
-	  || range == FIASCO_RPF_RANGE_1_00
-	  || range == FIASCO_RPF_RANGE_1_50
-	   || range == FIASCO_RPF_RANGE_2_00)
-	  &&
-	  (dc_range == FIASCO_RPF_RANGE_0_75
-	   || dc_range == FIASCO_RPF_RANGE_1_00
-	   || dc_range == FIASCO_RPF_RANGE_1_50
-	   || dc_range == FIASCO_RPF_RANGE_2_00))
+          || range == FIASCO_RPF_RANGE_1_00
+          || range == FIASCO_RPF_RANGE_1_50
+           || range == FIASCO_RPF_RANGE_2_00)
+          &&
+          (dc_range == FIASCO_RPF_RANGE_0_75
+           || dc_range == FIASCO_RPF_RANGE_1_00
+           || dc_range == FIASCO_RPF_RANGE_1_50
+           || dc_range == FIASCO_RPF_RANGE_2_00))
       {
-	 this->rpf_range       = range;
-	 this->dc_rpf_range    = dc_range;
-	 this->rpf_mantissa    = mantissa;
-	 this->dc_rpf_mantissa = dc_mantissa;
+         this->rpf_range       = range;
+         this->dc_rpf_range    = dc_range;
+         this->rpf_mantissa    = mantissa;
+         this->dc_rpf_mantissa = dc_mantissa;
 
-	 return 1;
+         return 1;
       }
       else
       {
-	 set_error (_("Invalid RPF ranges `%d', `%d' specified."),
-		    range, dc_range);
-	 return 0;
+         set_error (_("Invalid RPF ranges `%d', `%d' specified."),
+                    range, dc_range);
+         return 0;
       }
    }
 }
 
 int
 fiasco_c_options_set_progress_meter (fiasco_c_options_t *options,
-				     fiasco_progress_e type)
+                                     fiasco_progress_e type)
 /*
  *  Set type of progress meter.
  *
  *  Return value:
- *	1 on success
- *	0 otherwise
+ *      1 on success
+ *      0 otherwise
  */
 {
    c_options_t *this = (c_options_t *) cast_c_options (options);
@@ -597,12 +597,12 @@ fiasco_c_options_set_progress_meter (fiasco_c_options_t *options,
       case FIASCO_PROGRESS_BAR:
       case FIASCO_PROGRESS_PERCENT:
       case FIASCO_PROGRESS_NONE:
-	 this->progress_meter = type;
-	 break;
+         this->progress_meter = type;
+         break;
       default:
-	 set_error (_("Invalid progress meter `%d' specified "
-		      "(valid values are 0, 1, or 2)."), type);
-	 return 0;
+         set_error (_("Invalid progress meter `%d' specified "
+                      "(valid values are 0, 1, or 2)."), type);
+         return 0;
    }
    return 1;
 }
@@ -611,10 +611,10 @@ int
 fiasco_c_options_set_smoothing (fiasco_c_options_t *options, int smoothing)
 /*
  *  Define `smoothing'-percentage along partitioning borders.
- *  
+ *
  *  Return value:
- *	1 on success
- *	0 otherwise
+ *      1 on success
+ *      0 otherwise
  */
 {
    c_options_t *this = (c_options_t *) cast_c_options (options);
@@ -639,10 +639,10 @@ int
 fiasco_c_options_set_comment (fiasco_c_options_t *options, const char *comment)
 /*
  *  Define `comment' of FIASCO stream.
- *  
+ *
  *  Return value:
- *	1 on success
- *	0 otherwise
+ *      1 on success
+ *      0 otherwise
  */
 {
    c_options_t *this = (c_options_t *) cast_c_options (options);
@@ -667,10 +667,10 @@ int
 fiasco_c_options_set_title (fiasco_c_options_t *options, const char *title)
 /*
  *  Define `title' of FIASCO stream.
- *  
+ *
  *  Return value:
- *	1 on success
- *	0 otherwise
+ *      1 on success
+ *      0 otherwise
  */
 {
    c_options_t *this = (c_options_t *) cast_c_options (options);
@@ -698,7 +698,7 @@ cast_c_options (fiasco_c_options_t *options)
  *  Check whether `options' is a valid object of type c_options_t.
  *
  *  Return value:
- *	pointer to options struct on success
+ *      pointer to options struct on success
  *      NULL otherwise
  */
 {
@@ -707,8 +707,8 @@ cast_c_options (fiasco_c_options_t *options)
    {
       if (!streq (this->id, "COFIASCO"))
       {
-	 set_error (_("Parameter `options' doesn't match required type."));
-	 return NULL;
+         set_error (_("Parameter `options' doesn't match required type."));
+         return NULL;
       }
    }
    else
@@ -721,7 +721,7 @@ cast_c_options (fiasco_c_options_t *options)
 
 /**************************************************************************
 ***************************************************************************
-			       DECODER
+                               DECODER
 ***************************************************************************
 **************************************************************************/
 
@@ -733,10 +733,10 @@ fiasco_d_options_new (void)
  *  fill in default values.
  *
  *  Return value:
- *	pointer to the new option structure
+ *      pointer to the new option structure
  */
 {
-   d_options_t 	      *options = calloc (1, sizeof (d_options_t));
+   d_options_t        *options = calloc (1, sizeof (d_options_t));
    fiasco_d_options_t *public  = calloc (1, sizeof (fiasco_d_options_t));
 
    if (!options || !public)
@@ -744,21 +744,21 @@ fiasco_d_options_new (void)
       set_error (_("Out of memory."));
       return NULL;
    }
-   public->private 	      = options;
-   public->delete 	      = fiasco_d_options_delete;
+   public->private            = options;
+   public->delete             = fiasco_d_options_delete;
    public->set_smoothing      = fiasco_d_options_set_smoothing;
    public->set_magnification  = fiasco_d_options_set_magnification;
    public->set_4_2_0_format   = fiasco_d_options_set_4_2_0_format;
-   
+
    strcpy (options->id, "DOFIASCO");
 
    /*
     *  Set default value of fiasco decoder options
     */
-   options->smoothing 	  = 70;
+   options->smoothing     = 70;
    options->magnification = 0;
    options->image_format  = FORMAT_4_4_4;
-   
+
    return public;
 }
 
@@ -771,14 +771,14 @@ fiasco_d_options_delete (fiasco_d_options_t *options)
  *  No return value.
  *
  *  Side effects:
- *	structure 'options' is discarded.
+ *      structure 'options' is discarded.
  */
 {
    d_options_t *this = cast_d_options (options);
 
    if (!this)
       return;
-   
+
    Free (this);
 
    return;
@@ -788,10 +788,10 @@ int
 fiasco_d_options_set_smoothing (fiasco_d_options_t *options, int smoothing)
 /*
  *  Define `smoothing'-percentage along partitioning borders.
- *  
+ *
  *  Return value:
- *	1 on success
- *	0 otherwise
+ *      1 on success
+ *      0 otherwise
  */
 {
    d_options_t *this = (d_options_t *) cast_d_options (options);
@@ -822,8 +822,8 @@ fiasco_d_options_set_magnification (fiasco_d_options_t *options, int level)
  *  etc.
  *
  *  Return value:
- *	1 on success
- *	0 otherwise
+ *      1 on success
+ *      0 otherwise
  */
 {
    d_options_t *this = (d_options_t *) cast_d_options (options);
@@ -843,10 +843,10 @@ int
 fiasco_d_options_set_4_2_0_format (fiasco_d_options_t *options, int format)
 /*
  *  Set image format to 4:2:0 or 4:4:4.
- *  
+ *
  *  Return value:
- *	1 on success
- *	0 otherwise
+ *      1 on success
+ *      0 otherwise
  */
 {
    d_options_t *this = (d_options_t *) cast_d_options (options);
@@ -869,18 +869,18 @@ cast_d_options (fiasco_d_options_t *options)
  *  Check whether `options' is a valid object of type d_options_t.
  *
  *  Return value:
- *	pointer to options struct on success
+ *      pointer to options struct on success
  *      NULL otherwise
  */
 {
    d_options_t *this = (d_options_t *) options->private;
-   
+
    if (this)
    {
       if (!streq (this->id, "DOFIASCO"))
       {
-	 set_error (_("Parameter `options' doesn't match required type."));
-	 return NULL;
+         set_error (_("Parameter `options' doesn't match required type."));
+         return NULL;
       }
    }
    else
diff --git a/converter/other/fiasco/codec/options.h b/converter/other/fiasco/codec/options.h
index 783c41ef..e39550f6 100644
--- a/converter/other/fiasco/codec/options.h
+++ b/converter/other/fiasco/codec/options.h
@@ -1,8 +1,8 @@
 /*
  *  options.h
  *
- *  Written by:		Ullrich Hafner
- *		
+ *  Written by:         Ullrich Hafner
+ *              
  *  This file is part of FIASCO (Fractal Image And Sequence COdec)
  *  Copyright (C) 1994-2000 Ullrich Hafner
  */
@@ -19,49 +19,49 @@
 
 typedef struct c_options
 {
-   char      	       id [9];
-   char  	      *basis_name;
-   unsigned  	       lc_min_level;
-   unsigned  	       lc_max_level;
-   unsigned  	       p_min_level;
-   unsigned  	       p_max_level;
-   unsigned  	       images_level;
-   unsigned  	       max_states;
-   unsigned  	       chroma_max_states;
-   unsigned  	       max_elements;
-   unsigned  	       tiling_exponent;
+   char                id [9];
+   char               *basis_name;
+   unsigned            lc_min_level;
+   unsigned            lc_max_level;
+   unsigned            p_min_level;
+   unsigned            p_max_level;
+   unsigned            images_level;
+   unsigned            max_states;
+   unsigned            chroma_max_states;
+   unsigned            max_elements;
+   unsigned            tiling_exponent;
    fiasco_tiling_e     tiling_method;
-   char        	      *id_domain_pool;
-   char        	      *id_d_domain_pool;
-   char        	      *id_rpf_model;
-   char        	      *id_d_rpf_model;
-   unsigned  	       rpf_mantissa;
-   real_t    	       rpf_range;
-   unsigned  	       dc_rpf_mantissa;
+   char               *id_domain_pool;
+   char               *id_d_domain_pool;
+   char               *id_rpf_model;
+   char               *id_d_rpf_model;
+   unsigned            rpf_mantissa;
+   real_t              rpf_range;
+   unsigned            dc_rpf_mantissa;
    fiasco_rpf_range_e  dc_rpf_range;
-   unsigned  	       d_rpf_mantissa;
+   unsigned            d_rpf_mantissa;
    fiasco_rpf_range_e  d_rpf_range;
-   unsigned  	       d_dc_rpf_mantissa;
+   unsigned            d_dc_rpf_mantissa;
    fiasco_rpf_range_e  d_dc_rpf_range;
-   real_t    	       chroma_decrease;
-   bool_t    	       prediction;
-   bool_t    	       delta_domains;
-   bool_t    	       normal_domains;
-   unsigned  	       search_range;
-   unsigned  	       fps;
-   char        	      *pattern;
-   char        	      *reference_filename;
-   bool_t    	       half_pixel_prediction;
-   bool_t    	       cross_B_search;
-   bool_t    	       B_as_past_ref;
-   bool_t    	       check_for_underflow;
-   bool_t    	       check_for_overflow;
-   bool_t    	       second_domain_block;
-   bool_t    	       full_search;
+   real_t              chroma_decrease;
+   bool_t              prediction;
+   bool_t              delta_domains;
+   bool_t              normal_domains;
+   unsigned            search_range;
+   unsigned            fps;
+   char               *pattern;
+   char               *reference_filename;
+   bool_t              half_pixel_prediction;
+   bool_t              cross_B_search;
+   bool_t              B_as_past_ref;
+   bool_t              check_for_underflow;
+   bool_t              check_for_overflow;
+   bool_t              second_domain_block;
+   bool_t              full_search;
    fiasco_progress_e   progress_meter;
-   char 	      *title;
-   char 	      *comment;
-   unsigned    	       smoothing;
+   char               *title;
+   char               *comment;
+   unsigned            smoothing;
 } c_options_t;
 
 typedef struct d_options
diff --git a/converter/other/fiasco/codec/prediction.c b/converter/other/fiasco/codec/prediction.c
index c592baa5..c321391a 100644
--- a/converter/other/fiasco/codec/prediction.c
+++ b/converter/other/fiasco/codec/prediction.c
@@ -1,8 +1,8 @@
 /*
- *  prediction.c:	Range image prediction with MC or ND
+ *  prediction.c:       Range image prediction with MC or ND
  *
- *  Written by:		Ullrich Hafner
- *			Michael Unger
+ *  Written by:         Ullrich Hafner
+ *                      Michael Unger
  *
  *  This file is part of FIASCO (Fractal Image And Sequence COdec)
  *  Copyright (C) 1994-2000 Ullrich Hafner
@@ -40,7 +40,7 @@
 
 /*****************************************************************************
 
-			     local variables
+                             local variables
 
 *****************************************************************************/
 
@@ -55,7 +55,7 @@ typedef struct state_data
    real_t *ip_states_state [MAXLEVEL];
 
    word_t tree [MAXLABELS];
-   mv_t	  mv_tree [MAXLABELS];
+   mv_t   mv_tree [MAXLABELS];
    word_t y_state [MAXLABELS];
    byte_t y_column [MAXLABELS];
    byte_t prediction [MAXLABELS];
@@ -70,49 +70,49 @@ typedef struct state_data
 
 /*****************************************************************************
 
-				prototypes
+                                prototypes
 
 *****************************************************************************/
 
 static real_t
 nd_prediction (real_t max_costs, real_t price, unsigned band, int y_state,
-	       range_t *range, wfa_t *wfa, coding_t *c);
+               range_t *range, wfa_t *wfa, coding_t *c);
 static real_t
 mc_prediction (real_t max_costs, real_t price, unsigned band, int y_state,
-	       range_t *range, wfa_t *wfa, coding_t *c);
+               range_t *range, wfa_t *wfa, coding_t *c);
 static state_data_t *
 store_state_data (unsigned from, unsigned to, unsigned max_level,
-		  wfa_t *wfa, coding_t *c);
+                  wfa_t *wfa, coding_t *c);
 static void
 restore_state_data (unsigned from, unsigned to, unsigned max_level,
-		    state_data_t *data, wfa_t *wfa, coding_t *c);
+                    state_data_t *data, wfa_t *wfa, coding_t *c);
 
 /*****************************************************************************
 
-				public code
+                                public code
 
 *****************************************************************************/
 
 real_t
 predict_range (real_t max_costs, real_t price, range_t *range, wfa_t *wfa,
-	       coding_t *c, unsigned band, int y_state, unsigned states,
-	       const tree_t *tree_model, const tree_t *p_tree_model,
-	       const void *domain_model, const void *d_domain_model,
-	       const void *coeff_model, const void *d_coeff_model)
+               coding_t *c, unsigned band, int y_state, unsigned states,
+               const tree_t *tree_model, const tree_t *p_tree_model,
+               const void *domain_model, const void *d_domain_model,
+               const void *coeff_model, const void *d_coeff_model)
 {
-   unsigned	 state;		     	/* counter */
-   void		*rec_domain_model;   	/* domain model after recursion */
-   void		*rec_d_domain_model; 	/* p domain model after recursion */
-   void		*rec_coeff_model;    	/* coeff model after recursion */
-   void		*rec_d_coeff_model;  	/* d coeff model after recursion */
-   tree_t	 rec_tree_model;	/* tree_model after '' */
-   tree_t	 rec_p_tree_model;    	/* p_tree_model after '' */
-   unsigned	 rec_states;	     	/* wfa->states after '' */
-   real_t	*rec_pixels;	     	/* c->pixels after '' */
-   state_data_t	*rec_state_data;     	/* state_data struct after '' */
-   real_t	 costs;		     	/* current approximation costs */
-   unsigned	 level;		     	/* counter */
-   state_data_t	*sd;		     	/* pointer to state_data field */
+   unsigned      state;                 /* counter */
+   void         *rec_domain_model;      /* domain model after recursion */
+   void         *rec_d_domain_model;    /* p domain model after recursion */
+   void         *rec_coeff_model;       /* coeff model after recursion */
+   void         *rec_d_coeff_model;     /* d coeff model after recursion */
+   tree_t        rec_tree_model;        /* tree_model after '' */
+   tree_t        rec_p_tree_model;      /* p_tree_model after '' */
+   unsigned      rec_states;            /* wfa->states after '' */
+   real_t       *rec_pixels;            /* c->pixels after '' */
+   state_data_t *rec_state_data;        /* state_data struct after '' */
+   real_t        costs;                 /* current approximation costs */
+   unsigned      level;                 /* counter */
+   state_data_t *sd;                    /* pointer to state_data field */
 
    /*
     *  Store WFA data from state 'lc_states' to 'wfa->states' - 1 and
@@ -127,7 +127,7 @@ predict_range (real_t max_costs, real_t price, range_t *range, wfa_t *wfa,
    rec_states         = wfa->states;
    rec_pixels         = c->pixels;
    rec_state_data     = store_state_data (states, rec_states - 1,
-					  c->options.lc_max_level, wfa, c);
+                                          c->options.lc_max_level, wfa, c);
 
    /*
     *  Restore probability models to the state before the recursive subdivision
@@ -138,9 +138,9 @@ predict_range (real_t max_costs, real_t price, range_t *range, wfa_t *wfa,
    c->p_tree               = *p_tree_model;
    c->domain_pool->model   = c->domain_pool->model_duplicate (domain_model);
    c->d_domain_pool->model = c->d_domain_pool->model_duplicate (d_domain_model);
-   c->coeff->model   	   = c->coeff->model_duplicate (c->coeff, coeff_model);
-   c->d_coeff->model   	   = c->d_coeff->model_duplicate (c->d_coeff,
-							  d_coeff_model);
+   c->coeff->model         = c->coeff->model_duplicate (c->coeff, coeff_model);
+   c->d_coeff->model       = c->d_coeff->model_duplicate (c->d_coeff,
+                                                          d_coeff_model);
 
    if (c->mt->frame_type == I_FRAME)
       costs = nd_prediction (max_costs, price, band, y_state, range, wfa, c);
@@ -156,27 +156,27 @@ predict_range (real_t max_costs, real_t price, range_t *range, wfa_t *wfa,
        */
       for (state = states; state < rec_states; state++)
       {
-	 sd = &rec_state_data [state - states];
-	 for (level = c->options.images_level + 1;
-	      level <= c->options.lc_max_level; level++)
-	    if (sd->ip_states_state [level] != NULL)
-	       Free (sd->ip_states_state [level]);
-	 if (sd->images_of_state != NULL)
-	    Free (sd->images_of_state);
-	 if (sd->inner_products != NULL)
-	    Free (sd->inner_products);
+         sd = &rec_state_data [state - states];
+         for (level = c->options.images_level + 1;
+              level <= c->options.lc_max_level; level++)
+            if (sd->ip_states_state [level] != NULL)
+               Free (sd->ip_states_state [level]);
+         if (sd->images_of_state != NULL)
+            Free (sd->images_of_state);
+         if (sd->inner_products != NULL)
+            Free (sd->inner_products);
       }
       if (states < rec_states)
-	 Free (rec_state_data);
+         Free (rec_state_data);
       c->domain_pool->model_free (rec_domain_model);
       c->d_domain_pool->model_free (rec_d_domain_model);
       c->coeff->model_free (rec_coeff_model);
       c->d_coeff->model_free (rec_d_coeff_model);
 
       costs = (range->tree_bits + range->matrix_bits + range->weights_bits
-	       + range->mv_tree_bits + range->mv_coord_bits
-	       + range->nd_tree_bits + range->nd_weights_bits) * price
-	      + range->err;
+               + range->mv_tree_bits + range->mv_coord_bits
+               + range->nd_tree_bits + range->nd_weights_bits) * price
+              + range->err;
    }
    else
    {
@@ -198,9 +198,9 @@ predict_range (real_t max_costs, real_t price, range_t *range, wfa_t *wfa,
       range->prediction = NO;
 
       if (wfa->states != states)
-	 remove_states (states, wfa);
+         remove_states (states, wfa);
       restore_state_data (states, rec_states - 1, c->options.lc_max_level,
-			  rec_state_data, wfa, c);
+                          rec_state_data, wfa, c);
       costs = MAXCOSTS;
    }
 
@@ -216,8 +216,8 @@ clear_norms_table (unsigned level, const wfa_info_t *wi, motion_t *mt)
  */
 {
    unsigned  range_size = wi->half_pixel
-			  ? square (wi->search_range)
-			  : square (2 * wi->search_range);
+                          ? square (wi->search_range)
+                          : square (2 * wi->search_range);
 
    if (level > wi->p_min_level)
    {
@@ -236,34 +236,34 @@ update_norms_table (unsigned level, const wfa_info_t *wi, motion_t *mt)
  */
 {
    unsigned  range_size = wi->half_pixel
-			  ? square (wi->search_range)
-			  : square (2 * wi->search_range);
+                          ? square (wi->search_range)
+                          : square (2 * wi->search_range);
 
    if (level > wi->p_min_level)
    {
-      unsigned index;			/* index of motion vector */
+      unsigned index;                   /* index of motion vector */
 
       for (index = 0; index < range_size; index++)
-	 mt->mc_forward_norms [level][index]
-	    += mt->mc_forward_norms [level - 1][index];
+         mt->mc_forward_norms [level][index]
+            += mt->mc_forward_norms [level - 1][index];
       if (mt->frame_type == B_FRAME)
-	 for (index = 0; index < range_size; index++)
-	    mt->mc_backward_norms [level][index]
-	       += mt->mc_backward_norms [level - 1][index];
+         for (index = 0; index < range_size; index++)
+            mt->mc_backward_norms [level][index]
+               += mt->mc_backward_norms [level - 1][index];
    }
 }
 
 /*****************************************************************************
 
-				private code
+                                private code
 
 *****************************************************************************/
 
 static real_t
 mc_prediction (real_t max_costs, real_t price, unsigned band, int y_state,
-	       range_t *range, wfa_t *wfa, coding_t *c)
+               range_t *range, wfa_t *wfa, coding_t *c)
 {
-   real_t    costs;		   	/* current approximation costs */
+   real_t    costs;                     /* current approximation costs */
    range_t   prange = *range;
    unsigned  width  = width_of_level (range->level);
    unsigned  height = height_of_level (range->level);
@@ -286,12 +286,12 @@ mc_prediction (real_t max_costs, real_t price, unsigned band, int y_state,
 
    costs = (prange.mv_tree_bits + prange.mv_coord_bits) * price;
 
-   if (costs < max_costs)		/* motion vector not too expensive */
+   if (costs < max_costs)               /* motion vector not too expensive */
    {
-      unsigned  last_state;		/* last WFA state before recursion */
-      real_t   *ipi [MAXSTATES];	/* inner products pointers */
+      unsigned  last_state;             /* last WFA state before recursion */
+      real_t   *ipi [MAXSTATES];        /* inner products pointers */
       unsigned  state;
-      real_t  	mvt, mvc;
+      real_t    mvt, mvc;
 
       c->pixels = Calloc (width * height, sizeof (real_t));
       cut_to_bintree (c->pixels, mcpe, width, height, 0, 0, width, height);
@@ -301,12 +301,12 @@ mc_prediction (real_t max_costs, real_t price, unsigned band, int y_state,
        */
       last_state = wfa->states - 1;
       for (state = 0; state <= last_state; state++)
-	 if (need_image (state, wfa))
-	 {
-	    ipi [state] = c->ip_images_state[state];
-	    c->ip_images_state[state]
-	       = Calloc (size_of_tree (c->products_level), sizeof (real_t));
-	 }
+         if (need_image (state, wfa))
+         {
+            ipi [state] = c->ip_images_state[state];
+            c->ip_images_state[state]
+               = Calloc (size_of_tree (c->products_level), sizeof (real_t));
+         }
 
       mvc = prange.mv_coord_bits;
       mvt = prange.mv_tree_bits;
@@ -322,42 +322,42 @@ mc_prediction (real_t max_costs, real_t price, unsigned band, int y_state,
       prange.nd_tree_bits    = 0;
 
       compute_ip_images_state (prange.image, prange.address, prange.level,
-			       1, 0, wfa, c);
+                               1, 0, wfa, c);
       costs += subdivide (max_costs - costs, band, y_state, &prange,
-			  wfa, c, NO, YES);
+                          wfa, c, NO, YES);
 
-      if (costs < max_costs)		/* use motion compensation */
+      if (costs < max_costs)            /* use motion compensation */
       {
-	 unsigned img, adr;		/* temp. values */
-
-	 img                  = range->image;
-	 adr                  = range->address;
-	 *range               = prange;
-	 range->image         = img;
-	 range->address       = adr;
-	 range->mv_coord_bits = mvc;
-	 range->mv_tree_bits  = mvt;
-	 range->prediction    = YES;
-
-	 for (state = last_state + 1; state < wfa->states; state++)
-	    if (need_image (state, wfa))
-	       memset (c->ip_images_state [state], 0,
-		       size_of_tree (c->products_level) * sizeof (real_t));
-
-	 costs = (range->tree_bits + range->matrix_bits + range->weights_bits
-		  + range->mv_tree_bits + range->mv_coord_bits
-		  + range->nd_tree_bits + range->nd_weights_bits) * price
-		 + range->err;
+         unsigned img, adr;             /* temp. values */
+
+         img                  = range->image;
+         adr                  = range->address;
+         *range               = prange;
+         range->image         = img;
+         range->address       = adr;
+         range->mv_coord_bits = mvc;
+         range->mv_tree_bits  = mvt;
+         range->prediction    = YES;
+
+         for (state = last_state + 1; state < wfa->states; state++)
+            if (need_image (state, wfa))
+               memset (c->ip_images_state [state], 0,
+                       size_of_tree (c->products_level) * sizeof (real_t));
+
+         costs = (range->tree_bits + range->matrix_bits + range->weights_bits
+                  + range->mv_tree_bits + range->mv_coord_bits
+                  + range->nd_tree_bits + range->nd_weights_bits) * price
+                 + range->err;
       }
       else
-	 costs = MAXCOSTS;
+         costs = MAXCOSTS;
 
       for (state = 0; state <= last_state; state++)
-	 if (need_image (state, wfa))
-	 {
-	    Free (c->ip_images_state[state]);
-	    c->ip_images_state[state] = ipi [state];
-	 }
+         if (need_image (state, wfa))
+         {
+            Free (c->ip_images_state[state]);
+            c->ip_images_state[state] = ipi [state];
+         }
       Free (c->pixels);
    }
    else
@@ -370,9 +370,9 @@ mc_prediction (real_t max_costs, real_t price, unsigned band, int y_state,
 
 static real_t
 nd_prediction (real_t max_costs, real_t price, unsigned band, int y_state,
-	       range_t *range, wfa_t *wfa, coding_t *c)
+               range_t *range, wfa_t *wfa, coding_t *c)
 {
-   real_t  costs;			/* current approximation costs */
+   real_t  costs;                       /* current approximation costs */
    range_t lrange = *range;
 
    /*
@@ -380,13 +380,13 @@ nd_prediction (real_t max_costs, real_t price, unsigned band, int y_state,
     */
    {
       real_t x = get_ip_image_state (range->image, range->address,
-				     range->level, 0, c);
+                                     range->level, 0, c);
       real_t y = get_ip_state_state (0, 0, range->level, c);
       real_t w = btor (rtob (x / y, c->coeff->dc_rpf), c->coeff->dc_rpf);
       word_t s [2] = {0, -1};
 
-      lrange.into [0] 	     = 0;
-      lrange.into [1] 	     = NO_EDGE;
+      lrange.into [0]        = 0;
+      lrange.into [1]        = NO_EDGE;
       lrange.weight [0]      = w;
       lrange.mv_coord_bits   = 0;
       lrange.mv_tree_bits    = 0;
@@ -404,10 +404,10 @@ nd_prediction (real_t max_costs, real_t price, unsigned band, int y_state,
    if (costs < max_costs)
    {
       unsigned  state;
-      range_t  	rrange;			/* range: recursive subdivision */
-      unsigned  last_state;		/* last WFA state before recursion */
-      real_t   *ipi [MAXSTATES];	/* inner products pointers */
-      unsigned 	width  = width_of_level (range->level);
+      range_t   rrange;                 /* range: recursive subdivision */
+      unsigned  last_state;             /* last WFA state before recursion */
+      real_t   *ipi [MAXSTATES];        /* inner products pointers */
+      unsigned  width  = width_of_level (range->level);
       unsigned  height = height_of_level (range->level);
       real_t   *pixels;
 
@@ -415,15 +415,15 @@ nd_prediction (real_t max_costs, real_t price, unsigned band, int y_state,
        *  Generate difference image original - approximation
        */
       {
-	 unsigned  n;
-	 real_t *src, *dst;		/* pointers to image data */
-	 real_t w = - lrange.weight [0] * c->images_of_state [0][0];
+         unsigned  n;
+         real_t *src, *dst;             /* pointers to image data */
+         real_t w = - lrange.weight [0] * c->images_of_state [0][0];
 
-	 src = c->pixels + range->address * size_of_level (range->level);
-	 dst = c->pixels = pixels = Calloc (width * height, sizeof (real_t));
+         src = c->pixels + range->address * size_of_level (range->level);
+         dst = c->pixels = pixels = Calloc (width * height, sizeof (real_t));
 
-	 for (n = width * height; n; n--)
-	    *dst++ = *src++ + w;
+         for (n = width * height; n; n--)
+            *dst++ = *src++ + w;
       }
 
       /*
@@ -442,56 +442,56 @@ nd_prediction (real_t max_costs, real_t price, unsigned band, int y_state,
 
       last_state = wfa->states - 1;
       for (state = 0; state <= last_state; state++)
-	 if (need_image (state, wfa))
-	 {
-	    ipi [state] = c->ip_images_state[state];
-	    c->ip_images_state[state]
-	       = Calloc (size_of_tree (c->products_level), sizeof (real_t));
-	 }
+         if (need_image (state, wfa))
+         {
+            ipi [state] = c->ip_images_state[state];
+            c->ip_images_state[state]
+               = Calloc (size_of_tree (c->products_level), sizeof (real_t));
+         }
 
       compute_ip_images_state (rrange.image, rrange.address, rrange.level,
-			       1, 0, wfa, c);
+                               1, 0, wfa, c);
 
       costs += subdivide (max_costs - costs, band, y_state, &rrange, wfa, c,
-			  NO, YES);
+                          NO, YES);
 
       Free (pixels);
 
       if (costs < max_costs && ischild (rrange.tree)) /* use prediction */
       {
-	 unsigned img, adr;
-	 unsigned edge;
-
-	 img                     = range->image;
-	 adr                     = range->address;
-	 *range                  = rrange;
-	 range->image            = img;
-	 range->address          = adr;
-	 range->nd_tree_bits    += lrange.nd_tree_bits;
-	 range->nd_weights_bits += lrange.weights_bits;
-
-	 for (edge = 0; isedge (lrange.into [edge]); edge++)
-	 {
-	    range->into [edge]   = lrange.into [edge];
-	    range->weight [edge] = lrange.weight [edge];
-	 }
-	 range->into [edge] = NO_EDGE;
-	 range->prediction  = edge;
-
-	 for (state = last_state + 1; state < wfa->states; state++)
-	    if (need_image (state, wfa))
-	       memset (c->ip_images_state [state], 0,
-		       size_of_tree (c->products_level) * sizeof (real_t));
+         unsigned img, adr;
+         unsigned edge;
+
+         img                     = range->image;
+         adr                     = range->address;
+         *range                  = rrange;
+         range->image            = img;
+         range->address          = adr;
+         range->nd_tree_bits    += lrange.nd_tree_bits;
+         range->nd_weights_bits += lrange.weights_bits;
+
+         for (edge = 0; isedge (lrange.into [edge]); edge++)
+         {
+            range->into [edge]   = lrange.into [edge];
+            range->weight [edge] = lrange.weight [edge];
+         }
+         range->into [edge] = NO_EDGE;
+         range->prediction  = edge;
+
+         for (state = last_state + 1; state < wfa->states; state++)
+            if (need_image (state, wfa))
+               memset (c->ip_images_state [state], 0,
+                       size_of_tree (c->products_level) * sizeof (real_t));
       }
       else
-	 costs = MAXCOSTS;
+         costs = MAXCOSTS;
 
       for (state = 0; state <= last_state; state++)
-	 if (need_image (state, wfa))
-	 {
-	    Free (c->ip_images_state [state]);
-	    c->ip_images_state [state] = ipi [state];
-	 }
+         if (need_image (state, wfa))
+         {
+            Free (c->ip_images_state [state]);
+            c->ip_images_state [state] = ipi [state];
+         }
    }
    else
       costs = MAXCOSTS;
@@ -501,20 +501,20 @@ nd_prediction (real_t max_costs, real_t price, unsigned band, int y_state,
 
 static state_data_t *
 store_state_data (unsigned from, unsigned to, unsigned max_level,
-		  wfa_t *wfa, coding_t *c)
+                  wfa_t *wfa, coding_t *c)
 /*
  *  Save and remove all states starting from state 'from'.
  *
  *  Return value:
- *	pointer to array of state_data structs
+ *      pointer to array of state_data structs
  */
 {
-   state_data_t *data;			/* array of savestates */
-   state_data_t *sd;			/* pointer to current savestates */
-   unsigned	 state, label, level;
+   state_data_t *data;                  /* array of savestates */
+   state_data_t *sd;                    /* pointer to current savestates */
+   unsigned      state, label, level;
 
    if (to < from)
-      return NULL;			/* nothing to do */
+      return NULL;                      /* nothing to do */
 
    data = Calloc (to - from + 1, sizeof (state_data_t));
 
@@ -534,30 +534,30 @@ store_state_data (unsigned from, unsigned to, unsigned max_level,
 
       for (label = 0; label < MAXLABELS; label++)
       {
-	 sd->tree [label]     	= wfa->tree [state][label];
-	 sd->y_state [label]  	= wfa->y_state [state][label];
-	 sd->y_column [label] 	= wfa->y_column [state][label];
-	 sd->mv_tree [label]  	= wfa->mv_tree [state][label];
-	 sd->x [label]        	= wfa->x [state][label];
-	 sd->y [label]        	= wfa->y [state][label];
-	 sd->prediction [label] = wfa->prediction [state][label];
-
-	 memcpy (sd->weight [label], wfa->weight [state][label],
-		 sizeof (real_t) * (MAXEDGES + 1));
-	 memcpy (sd->int_weight [label], wfa->int_weight [state][label],
-		 sizeof (word_t) * (MAXEDGES + 1));
-	 memcpy (sd->into [label], wfa->into [state][label],
-		 sizeof (word_t) * (MAXEDGES + 1));
-
-	 wfa->into [state][label][0] = NO_EDGE;
-	 wfa->tree [state][label]    = RANGE;
-	 wfa->y_state [state][label] = RANGE;
+         sd->tree [label]       = wfa->tree [state][label];
+         sd->y_state [label]    = wfa->y_state [state][label];
+         sd->y_column [label]   = wfa->y_column [state][label];
+         sd->mv_tree [label]    = wfa->mv_tree [state][label];
+         sd->x [label]          = wfa->x [state][label];
+         sd->y [label]          = wfa->y [state][label];
+         sd->prediction [label] = wfa->prediction [state][label];
+
+         memcpy (sd->weight [label], wfa->weight [state][label],
+                 sizeof (real_t) * (MAXEDGES + 1));
+         memcpy (sd->int_weight [label], wfa->int_weight [state][label],
+                 sizeof (word_t) * (MAXEDGES + 1));
+         memcpy (sd->into [label], wfa->into [state][label],
+                 sizeof (word_t) * (MAXEDGES + 1));
+
+         wfa->into [state][label][0] = NO_EDGE;
+         wfa->tree [state][label]    = RANGE;
+         wfa->y_state [state][label] = RANGE;
       }
       for (level = c->options.images_level + 1; level <= max_level;
-	   level++)
+           level++)
       {
-	 sd->ip_states_state [level]       = c->ip_states_state [state][level];
-	 c->ip_states_state [state][level] = NULL;
+         sd->ip_states_state [level]       = c->ip_states_state [state][level];
+         c->ip_states_state [state][level] = NULL;
       }
    }
 
@@ -566,18 +566,18 @@ store_state_data (unsigned from, unsigned to, unsigned max_level,
 
 static void
 restore_state_data (unsigned from, unsigned to, unsigned max_level,
-		    state_data_t *data, wfa_t *wfa, coding_t *c)
+                    state_data_t *data, wfa_t *wfa, coding_t *c)
 /*
  *  Restore all state data starting from state 'from'.
  *
  *  No return value.
  */
 {
-   state_data_t *sd;			/* pointer to state_data item */
-   unsigned	 state, label, level;
+   state_data_t *sd;                    /* pointer to state_data item */
+   unsigned      state, label, level;
 
    if (to < from)
-      return;				/* nothing to do */
+      return;                           /* nothing to do */
 
    for (state = from; state <= to; state++)
    {
@@ -588,35 +588,35 @@ restore_state_data (unsigned from, unsigned to, unsigned max_level,
       wfa->domain_type [state]        = sd->domain_type;
 
       if (c->images_of_state [state] != NULL)
-	 Free (c->images_of_state [state]);
+         Free (c->images_of_state [state]);
       c->images_of_state [state] = sd->images_of_state;
       if (c->ip_images_state [state] != NULL)
-	 Free (c->ip_images_state [state]);
+         Free (c->ip_images_state [state]);
       c->ip_images_state [state] = sd->inner_products;
 
       for (label = 0; label < MAXLABELS; label++)
       {
-	 wfa->tree [state][label]     	= sd->tree [label];
-	 wfa->y_state [state][label]  	= sd->y_state [label];
-	 wfa->y_column [state][label] 	= sd->y_column [label];
-	 wfa->mv_tree [state][label]  	= sd->mv_tree [label];
-	 wfa->x [state][label]        	= sd->x [label];
-	 wfa->y [state][label]        	= sd->y [label];
-	 wfa->prediction [state][label] = sd->prediction [label];
-
-	 memcpy (wfa->weight [state][label], sd->weight [label],
-		 sizeof(real_t) * (MAXEDGES + 1));
-	 memcpy (wfa->int_weight [state][label], sd->int_weight [label],
-		 sizeof(word_t) * (MAXEDGES + 1));
-	 memcpy (wfa->into [state][label], sd->into [label],
-		 sizeof(word_t) * (MAXEDGES + 1));
+         wfa->tree [state][label]       = sd->tree [label];
+         wfa->y_state [state][label]    = sd->y_state [label];
+         wfa->y_column [state][label]   = sd->y_column [label];
+         wfa->mv_tree [state][label]    = sd->mv_tree [label];
+         wfa->x [state][label]          = sd->x [label];
+         wfa->y [state][label]          = sd->y [label];
+         wfa->prediction [state][label] = sd->prediction [label];
+
+         memcpy (wfa->weight [state][label], sd->weight [label],
+                 sizeof(real_t) * (MAXEDGES + 1));
+         memcpy (wfa->int_weight [state][label], sd->int_weight [label],
+                 sizeof(word_t) * (MAXEDGES + 1));
+         memcpy (wfa->into [state][label], sd->into [label],
+                 sizeof(word_t) * (MAXEDGES + 1));
       }
       for (level = c->options.images_level + 1; level <= max_level;
-	   level++)
+           level++)
       {
-	 if (c->ip_states_state [state][level] != NULL)
-	    Free (c->ip_states_state [state][level]);
-	 c->ip_states_state [state][level] = sd->ip_states_state [level];
+         if (c->ip_states_state [state][level] != NULL)
+            Free (c->ip_states_state [state][level]);
+         c->ip_states_state [state][level] = sd->ip_states_state [level];
       }
    }
 
diff --git a/converter/other/fiasco/codec/prediction.h b/converter/other/fiasco/codec/prediction.h
index 0646dfd8..10b432b3 100644
--- a/converter/other/fiasco/codec/prediction.h
+++ b/converter/other/fiasco/codec/prediction.h
@@ -1,9 +1,9 @@
 /*
  *  prediction.h
  *
- *  Written by:		Ullrich Hafner
- *			Michael Unger
- *		
+ *  Written by:         Ullrich Hafner
+ *                      Michael Unger
+ *              
  *  This file is part of FIASCO (Fractal Image And Sequence COdec)
  *  Copyright (C) 1994-2000 Ullrich Hafner
  */
@@ -23,10 +23,10 @@
 
 real_t
 predict_range (real_t max_costs, real_t price, range_t *range, wfa_t *wfa,
-	       coding_t *c, unsigned band, int y_state, unsigned states,
-	       const tree_t *tree_model, const tree_t *p_tree_model,
-	       const void *domain_model, const void *d_domain_model,
-	       const void *coeff_model, const void *d_coeff_model);
+               coding_t *c, unsigned band, int y_state, unsigned states,
+               const tree_t *tree_model, const tree_t *p_tree_model,
+               const void *domain_model, const void *d_domain_model,
+               const void *coeff_model, const void *d_coeff_model);
 void
 update_norms_table (unsigned level, const wfa_info_t *wi, motion_t *mt);
 void
diff --git a/converter/other/fiasco/codec/subdivide.c b/converter/other/fiasco/codec/subdivide.c
index 3ddf1ffc..7eb951c0 100644
--- a/converter/other/fiasco/codec/subdivide.c
+++ b/converter/other/fiasco/codec/subdivide.c
@@ -1,7 +1,7 @@
 /*
- *  subdivide.c:	Recursive subdivision of range images
+ *  subdivide.c:        Recursive subdivision of range images
  *
- *  Written by:		Ullrich Hafner
+ *  Written by:         Ullrich Hafner
  *
  *  This file is part of FIASCO (Fractal Image And Sequence COdec)
  *  Copyright (C) 1994-2000 Ullrich Hafner
@@ -41,27 +41,27 @@
 
 /*****************************************************************************
 
-				prototypes
+                                prototypes
 
 *****************************************************************************/
 
 static void
 init_new_state (bool_t auxiliary_state, bool_t delta, range_t *range,
-		const range_t *child, const int *y_state,
-		wfa_t *wfa, coding_t *c);
+                const range_t *child, const int *y_state,
+                wfa_t *wfa, coding_t *c);
 static void
 init_range (range_t *range, const image_t *image, unsigned band,
-	    const wfa_t *wfa, coding_t *c);
+            const wfa_t *wfa, coding_t *c);
 
 /*****************************************************************************
 
-				public code
+                                public code
 
 *****************************************************************************/
 
 real_t
 subdivide (real_t max_costs, unsigned band, int y_state, range_t *range,
-	   wfa_t *wfa, coding_t *c, bool_t prediction, bool_t delta)
+           wfa_t *wfa, coding_t *c, bool_t prediction, bool_t delta)
 /*
  *  Subdivide the current 'range' recursively and decide whether
  *  a linear combination, a recursive subdivision, or a prediction is
@@ -73,46 +73,46 @@ subdivide (real_t max_costs, unsigned band, int y_state, range_t *range,
  *  If 'delta' is TRUE then current range is already predicted.
  *
  *  Return value:
- *	costs of the best approximation or MAXCOSTS if costs exceed 'max_costs'
+ *      costs of the best approximation or MAXCOSTS if costs exceed 'max_costs'
  *
  *  Side effects:
- *	'range'	factors and costs of linear combination are modified
- *      'wfa'	new transitions and prediction coefficients are added
- *	'c'	pixels and inner products are updated
+ *      'range' factors and costs of linear combination are modified
+ *      'wfa'   new transitions and prediction coefficients are added
+ *      'c'     pixels and inner products are updated
  */
 {
    real_t    subdivide_costs;        /* Costs arising from approx. the current
-				       range with two children */
+                                       range with two children */
    real_t    lincomb_costs;          /* Costs arising from approx. the current
-				       range with a linear combination */
-   int	     new_y_state [MAXLABELS];	/* Corresponding state of Y */
-   real_t    price;			/* Approximation costs multiplier */
-   bool_t    try_mc;			/* YES: try MC prediction */
-   bool_t    try_nd;			/* YES: try ND prediction */
-   unsigned  states;			/* Number of states before the
-					   recursive subdivision starts */
-   void     *domain_model;		/* copy of domain pool model */
-   void     *d_domain_model;		/* copy of delta domain pool model */
-   void     *lc_domain_model;		/* copy of domain pool model */
-   void     *lc_d_domain_model;		/* copy of delta domain pool model */
-   void	    *coeff_model;	        /* copy of coefficients model */
-   void	    *d_coeff_model;		/* copy of delta coefficients model */
-   void	    *lc_coeff_model;	        /* copy of coefficients model */
-   void	    *lc_d_coeff_model;		/* copy of delta coefficients model */
-   tree_t    tree_model;		/* copy of tree model */
-   tree_t    p_tree_model;		/* copy of pred. tree model */
-   range_t   lrange;			/* range of lin. comb. approx. */
-   range_t   rrange;			/* range of recursive approx. */
-   range_t   child [MAXLABELS];		/* new children of the current range */
-   static unsigned percent = 0;		/* status of progress meter */
+                                       range with a linear combination */
+   int       new_y_state [MAXLABELS];   /* Corresponding state of Y */
+   real_t    price;                     /* Approximation costs multiplier */
+   bool_t    try_mc;                    /* YES: try MC prediction */
+   bool_t    try_nd;                    /* YES: try ND prediction */
+   unsigned  states;                    /* Number of states before the
+                                           recursive subdivision starts */
+   void     *domain_model;              /* copy of domain pool model */
+   void     *d_domain_model;            /* copy of delta domain pool model */
+   void     *lc_domain_model;           /* copy of domain pool model */
+   void     *lc_d_domain_model;         /* copy of delta domain pool model */
+   void     *coeff_model;               /* copy of coefficients model */
+   void     *d_coeff_model;             /* copy of delta coefficients model */
+   void     *lc_coeff_model;            /* copy of coefficients model */
+   void     *lc_d_coeff_model;          /* copy of delta coefficients model */
+   tree_t    tree_model;                /* copy of tree model */
+   tree_t    p_tree_model;              /* copy of pred. tree model */
+   range_t   lrange;                    /* range of lin. comb. approx. */
+   range_t   rrange;                    /* range of recursive approx. */
+   range_t   child [MAXLABELS];         /* new children of the current range */
+   static unsigned percent = 0;         /* status of progress meter */
 
    if (wfa->wfainfo->level == range->level)
       percent = 0;
 
-   range->into [0] = NO_EDGE;		/* default approximation: empty */
+   range->into [0] = NO_EDGE;           /* default approximation: empty */
    range->tree     = RANGE;
 
-   if (range->level < 3)		/* Don't process small ranges */
+   if (range->level < 3)                /* Don't process small ranges */
       return MAXCOSTS;
 
    /*
@@ -122,35 +122,35 @@ subdivide (real_t max_costs, unsigned band, int y_state, range_t *range,
    if (c->tiling->exponent
        && range->level == wfa->wfainfo->level - c->tiling->exponent)
    {
-      unsigned width, height;		/* size of range (dummies)*/
+      unsigned width, height;           /* size of range (dummies)*/
 
       if (c->tiling->vorder [range->global_address] < 0)
-	 return 0;			/* nothing to do */
+         return 0;                      /* nothing to do */
       else
-	 locate_subimage (wfa->wfainfo->level, range->level,
-			  c->tiling->vorder [range->global_address],
-			  &range->x, &range->y, &width, &height);
+         locate_subimage (wfa->wfainfo->level, range->level,
+                          c->tiling->vorder [range->global_address],
+                          &range->x, &range->y, &width, &height);
    }
 
    if (range->x >= c->mt->original->width ||
        range->y >= c->mt->original->height)
-      return 0;				/* range is not visible */
+      return 0;                         /* range is not visible */
 
    /*
     *  Check whether prediction is allowed or not
     *  mc == motion compensation, nd == nondeterminism
     */
    try_mc = (prediction && c->mt->frame_type != I_FRAME
-	     && range->level >= wfa->wfainfo->p_min_level
-	     && range->level <= wfa->wfainfo->p_max_level
-	     && (range->x + width_of_level (range->level)
-		 <= c->mt->original->width)
-	     && (range->y + height_of_level (range->level)
-		 <= c->mt->original->height));
+             && range->level >= wfa->wfainfo->p_min_level
+             && range->level <= wfa->wfainfo->p_max_level
+             && (range->x + width_of_level (range->level)
+                 <= c->mt->original->width)
+             && (range->y + height_of_level (range->level)
+                 <= c->mt->original->height));
 
    try_nd = (prediction && c->mt->frame_type == I_FRAME
-	     && range->level >= wfa->wfainfo->p_min_level
-	     && range->level <= wfa->wfainfo->p_max_level);
+             && range->level >= wfa->wfainfo->p_min_level
+             && range->level <= wfa->wfainfo->p_max_level);
 
    if (try_mc)
       clear_norms_table (range->level, wfa->wfainfo, c->mt);
@@ -171,15 +171,15 @@ subdivide (real_t max_costs, unsigned band, int y_state, range_t *range,
    /*
     *  Compute children of corresponding state in Y band
     */
-   if (band != Y)			/* Cb and Cr bands only */
+   if (band != Y)                       /* Cb and Cr bands only */
    {
       unsigned label;
 
       for (label = 0; label < MAXLABELS; label++)
-	 if (ischild (y_state))
-	    new_y_state [label] = wfa->tree [y_state][label];
-	 else
-	    new_y_state [label] = RANGE;
+         if (ischild (y_state))
+            new_y_state [label] = wfa->tree [y_state][label];
+         else
+            new_y_state [label] = RANGE;
    }
    else
       new_y_state [0] = new_y_state [1] = RANGE;
@@ -210,13 +210,13 @@ subdivide (real_t max_costs, unsigned band, int y_state, range_t *range,
       lrange.mv_coord_bits   = 0;
       lrange.nd_tree_bits    = 0;
       lrange.nd_weights_bits = 0;
-      lrange.prediction	     = NO;
+      lrange.prediction      = NO;
 
       lincomb_costs
-	 = approximate_range (max_costs, price, c->options.max_elements,
-			      y_state, &lrange,
-			      (delta ? c->d_domain_pool : c->domain_pool),
-			      (delta ? c->d_coeff : c->coeff), wfa, c);
+         = approximate_range (max_costs, price, c->options.max_elements,
+                              y_state, &lrange,
+                              (delta ? c->d_domain_pool : c->domain_pool),
+                              (delta ? c->d_coeff : c->coeff), wfa, c);
    }
    else
       lincomb_costs = MAXCOSTS;
@@ -236,7 +236,7 @@ subdivide (real_t max_costs, unsigned band, int y_state, range_t *range,
    c->d_domain_pool->model = c->d_domain_pool->model_duplicate (d_domain_model);
    c->coeff->model         = c->coeff->model_duplicate (c->coeff, coeff_model);
    c->d_coeff->model       = c->d_coeff->model_duplicate (c->d_coeff,
-							  d_coeff_model);
+                                                          d_coeff_model);
 
    /*
     *  Second alternative of range approximation:
@@ -256,122 +256,122 @@ subdivide (real_t max_costs, unsigned band, int y_state, range_t *range,
       rrange.matrix_bits     = 0;
       rrange.weights_bits    = 0;
       rrange.err             = 0;
-      rrange.mv_tree_bits    = try_mc ? 1 : 0;	/* mc allowed but not used */
+      rrange.mv_tree_bits    = try_mc ? 1 : 0;  /* mc allowed but not used */
       rrange.mv_coord_bits   = 0;
       rrange.nd_tree_bits    = try_nd ?
-			       tree_bits (CHILD, lrange.level, &c->p_tree): 0;
+                               tree_bits (CHILD, lrange.level, &c->p_tree): 0;
       rrange.nd_weights_bits = 0;
-      rrange.prediction	     = NO;
+      rrange.prediction      = NO;
 
       /*
        *  Initialize the cost function and subdivide the current range.
        *  Every child is approximated by a recursive call of subdivide()
        */
       subdivide_costs = (rrange.tree_bits + rrange.weights_bits
-			 + rrange.matrix_bits + rrange.mv_tree_bits
-			 + rrange.mv_coord_bits + rrange.nd_tree_bits
-			 + rrange.nd_weights_bits) * price;
+                         + rrange.matrix_bits + rrange.mv_tree_bits
+                         + rrange.mv_coord_bits + rrange.nd_tree_bits
+                         + rrange.nd_weights_bits) * price;
 
       for (label = 0; label < MAXLABELS; label++)
       {
-	 real_t remaining_costs;	/* upper limit for next recursion */
-
-	 child[label].image          = rrange.image * MAXLABELS + label + 1;
-	 child[label].address        = rrange.address * MAXLABELS + label;
-	 child[label].global_address = rrange.global_address * MAXLABELS
-				       + label;
-	 child[label].level          = rrange.level - 1;
-	 child[label].x	= rrange.level & 1
-			  ? rrange.x
-			  : (rrange.x
-			     + label * width_of_level (rrange.level - 1));
-	 child[label].y = rrange.level & 1
-			  ? (rrange.y
-			     + label * height_of_level (rrange.level - 1))
-			  : rrange.y;
-
-	 /*
-	  *  If necessary compute the inner products of the new states
-	  *  (generated during the recursive approximation of child [0])
-	  */
-	 if (label && rrange.level <= c->options.lc_max_level)
-	    compute_ip_images_state (child[label].image, child[label].address,
-				     child[label].level, 1, states, wfa, c);
-	 /*
-	  *  Call subdivide() for both children.
-	  *  Abort the recursion if 'subdivide_costs' exceed 'lincomb_costs'
-	  *  or 'max_costs'.
-	  */
-	 remaining_costs = MIN(lincomb_costs, max_costs) - subdivide_costs;
-
-	 if (remaining_costs > 0)	/* still a way for improvement */
-	 {
-	    subdivide_costs += subdivide (remaining_costs, band,
-					  new_y_state [label], &child [label],
-					  wfa, c, prediction, delta);
-	 }
-	 else if (try_mc && child[label].level >= wfa->wfainfo->p_min_level)
-	 {
-	    fill_norms_table (child[label].x, child[label].y,
-			      child[label].level, wfa->wfainfo, c->mt);
-	 }
-
-	 if (try_mc)
-	    update_norms_table (rrange.level, wfa->wfainfo, c->mt);
-
-	 /*
-	  *  Update of progress meter
-	  */
-	 if (c->options.progress_meter != FIASCO_PROGRESS_NONE)
-	 {
-	    if (c->options.progress_meter == FIASCO_PROGRESS_PERCENT)
-	    {
-	       unsigned	new_percent; 	/* new status of progress meter */
-
-	       new_percent = (child[label].global_address + 1) * 100.0
-			     / (1 << (wfa->wfainfo->level - child[label].level));
-	       if (new_percent > percent)
-	       {
-		  percent = new_percent;
-		  info ("%3d%%  \r", percent);
-	       }
-	    }
-	    else if (c->options.progress_meter == FIASCO_PROGRESS_BAR)
-	    {
-	       unsigned	new_percent;	/* new status of progress meter */
-
-	       new_percent = (child[label].global_address + 1) * 50.0
-			     / (1 << (wfa->wfainfo->level
-				      - child[label].level));
-	       for (; new_percent > percent; percent++)
-	       {
-		  info ("#");
-	       }
-	    }
-	 }
-
-	 /*
-	  *  If costs of subdivision exceed costs of linear combination
-	  *  then abort recursion.
-	  */
-	 if (subdivide_costs >= MIN(lincomb_costs, max_costs))
-	 {
-	    subdivide_costs = MAXCOSTS;
-	    break;
-	 }
-	 rrange.err             += child [label].err;
-	 rrange.tree_bits       += child [label].tree_bits;
-	 rrange.matrix_bits     += child [label].matrix_bits;
-	 rrange.weights_bits    += child [label].weights_bits;
-	 rrange.mv_tree_bits    += child [label].mv_tree_bits;
-	 rrange.mv_coord_bits   += child [label].mv_coord_bits;
-	 rrange.nd_weights_bits += child [label].nd_weights_bits;
-	 rrange.nd_tree_bits    += child [label].nd_tree_bits;
-
-	 tree_update (ischild (child [label].tree) ? CHILD : LEAF,
-		      child [label].level, &c->tree);
-	 tree_update (child [label].prediction ? LEAF : CHILD,
-		      child [label].level, &c->p_tree);
+         real_t remaining_costs;        /* upper limit for next recursion */
+
+         child[label].image          = rrange.image * MAXLABELS + label + 1;
+         child[label].address        = rrange.address * MAXLABELS + label;
+         child[label].global_address = rrange.global_address * MAXLABELS
+                                       + label;
+         child[label].level          = rrange.level - 1;
+         child[label].x = rrange.level & 1
+                          ? rrange.x
+                          : (rrange.x
+                             + label * width_of_level (rrange.level - 1));
+         child[label].y = rrange.level & 1
+                          ? (rrange.y
+                             + label * height_of_level (rrange.level - 1))
+                          : rrange.y;
+
+         /*
+          *  If necessary compute the inner products of the new states
+          *  (generated during the recursive approximation of child [0])
+          */
+         if (label && rrange.level <= c->options.lc_max_level)
+            compute_ip_images_state (child[label].image, child[label].address,
+                                     child[label].level, 1, states, wfa, c);
+         /*
+          *  Call subdivide() for both children.
+          *  Abort the recursion if 'subdivide_costs' exceed 'lincomb_costs'
+          *  or 'max_costs'.
+          */
+         remaining_costs = MIN(lincomb_costs, max_costs) - subdivide_costs;
+
+         if (remaining_costs > 0)       /* still a way for improvement */
+         {
+            subdivide_costs += subdivide (remaining_costs, band,
+                                          new_y_state [label], &child [label],
+                                          wfa, c, prediction, delta);
+         }
+         else if (try_mc && child[label].level >= wfa->wfainfo->p_min_level)
+         {
+            fill_norms_table (child[label].x, child[label].y,
+                              child[label].level, wfa->wfainfo, c->mt);
+         }
+
+         if (try_mc)
+            update_norms_table (rrange.level, wfa->wfainfo, c->mt);
+
+         /*
+          *  Update of progress meter
+          */
+         if (c->options.progress_meter != FIASCO_PROGRESS_NONE)
+         {
+            if (c->options.progress_meter == FIASCO_PROGRESS_PERCENT)
+            {
+               unsigned new_percent;    /* new status of progress meter */
+
+               new_percent = (child[label].global_address + 1) * 100.0
+                             / (1 << (wfa->wfainfo->level - child[label].level));
+               if (new_percent > percent)
+               {
+                  percent = new_percent;
+                  info ("%3d%%  \r", percent);
+               }
+            }
+            else if (c->options.progress_meter == FIASCO_PROGRESS_BAR)
+            {
+               unsigned new_percent;    /* new status of progress meter */
+
+               new_percent = (child[label].global_address + 1) * 50.0
+                             / (1 << (wfa->wfainfo->level
+                                      - child[label].level));
+               for (; new_percent > percent; percent++)
+               {
+                  info ("#");
+               }
+            }
+         }
+
+         /*
+          *  If costs of subdivision exceed costs of linear combination
+          *  then abort recursion.
+          */
+         if (subdivide_costs >= MIN(lincomb_costs, max_costs))
+         {
+            subdivide_costs = MAXCOSTS;
+            break;
+         }
+         rrange.err             += child [label].err;
+         rrange.tree_bits       += child [label].tree_bits;
+         rrange.matrix_bits     += child [label].matrix_bits;
+         rrange.weights_bits    += child [label].weights_bits;
+         rrange.mv_tree_bits    += child [label].mv_tree_bits;
+         rrange.mv_coord_bits   += child [label].mv_coord_bits;
+         rrange.nd_weights_bits += child [label].nd_weights_bits;
+         rrange.nd_tree_bits    += child [label].nd_tree_bits;
+
+         tree_update (ischild (child [label].tree) ? CHILD : LEAF,
+                      child [label].level, &c->tree);
+         tree_update (child [label].prediction ? LEAF : CHILD,
+                      child [label].level, &c->p_tree);
       }
    }
    else
@@ -382,9 +382,9 @@ subdivide (real_t max_costs, unsigned band, int y_state, range_t *range,
     *  Predict range via motion compensation or nondeterminism and
     *  approximate delta image.
     */
-   if (try_mc || try_nd)		/* try prediction */
+   if (try_mc || try_nd)                /* try prediction */
    {
-       real_t prediction_costs;	/* Costs arising from approx. the current
+       real_t prediction_costs; /* Costs arising from approx. the current
                                    range with prediction */
 
        prediction_costs
@@ -393,7 +393,7 @@ subdivide (real_t max_costs, unsigned band, int y_state, range_t *range,
                             price, range, wfa, c, band, y_state, states,
                             &tree_model, &p_tree_model, domain_model,
                             d_domain_model, coeff_model, d_coeff_model);
-       if (prediction_costs < MAXCOSTS)	/* prediction has smallest costs */
+       if (prediction_costs < MAXCOSTS) /* prediction has smallest costs */
        {
            c->domain_pool->model_free (domain_model);
            c->d_domain_pool->model_free (d_domain_model);
@@ -426,13 +426,13 @@ subdivide (real_t max_costs, unsigned band, int y_state, range_t *range,
 
       c->domain_pool->model   = domain_model;
       c->d_domain_pool->model = d_domain_model;
-      c->coeff->model	      = coeff_model;
-      c->d_coeff->model	      = d_coeff_model;
+      c->coeff->model         = coeff_model;
+      c->d_coeff->model       = d_coeff_model;
       c->tree                 = tree_model;
       c->p_tree               = p_tree_model;
 
       if (wfa->states != states)
-	 remove_states (states, wfa);
+         remove_states (states, wfa);
 
       return MAXCOSTS;
    }
@@ -455,15 +455,15 @@ subdivide (real_t max_costs, unsigned band, int y_state, range_t *range,
 
       c->domain_pool->model   = lc_domain_model;
       c->d_domain_pool->model = lc_d_domain_model;
-      c->coeff->model	      = lc_coeff_model;
-      c->d_coeff->model	      = lc_d_coeff_model;
+      c->coeff->model         = lc_coeff_model;
+      c->d_coeff->model       = lc_d_coeff_model;
       c->tree                 = tree_model;
       c->p_tree               = p_tree_model;
 
       *range = lrange;
 
       if (wfa->states != states)
-	 remove_states (states, wfa);
+         remove_states (states, wfa);
 
       return lincomb_costs;
    }
@@ -478,15 +478,15 @@ subdivide (real_t max_costs, unsigned band, int y_state, range_t *range,
        *  - if state is (partially) outside image geometry
        */
       if (band > Y
-	  || (c->tiling->exponent
-	      && rrange.level > wfa->wfainfo->level - c->tiling->exponent)
-	  || (range->x + width_of_level (range->level)
-	      > c->mt->original->width)
-	  || (range->y + height_of_level (range->level)
-	      > c->mt->original->height))
-	 init_new_state (YES, delta, &rrange, child, new_y_state, wfa, c);
+          || (c->tiling->exponent
+              && rrange.level > wfa->wfainfo->level - c->tiling->exponent)
+          || (range->x + width_of_level (range->level)
+              > c->mt->original->width)
+          || (range->y + height_of_level (range->level)
+              > c->mt->original->height))
+         init_new_state (YES, delta, &rrange, child, new_y_state, wfa, c);
       else
-	 init_new_state (NO, delta, &rrange, child, new_y_state, wfa, c);
+         init_new_state (NO, delta, &rrange, child, new_y_state, wfa, c);
 
       *range = rrange;
 
@@ -505,8 +505,8 @@ subdivide (real_t max_costs, unsigned band, int y_state, range_t *range,
 
 void
 cut_to_bintree (real_t *dst, const word_t *src,
-		unsigned src_width, unsigned src_height,
-		unsigned x0, unsigned y0, unsigned width, unsigned height)
+                unsigned src_width, unsigned src_height,
+                unsigned x0, unsigned y0, unsigned width, unsigned height)
 /*
  *  Cut region ('x0', 'y0', 'width', 'height') of the pixel array 'src'.
  *  Size of image is given by 'src_width' x 'src_height'.
@@ -515,15 +515,15 @@ cut_to_bintree (real_t *dst, const word_t *src,
  *  No return value.
  *
  *  Side effects:
- *	'dst []' is filled with corresponding region.
+ *      'dst []' is filled with corresponding region.
  */
 {
    const unsigned mask01      = 0x555555; /* binary ...010101010101 */
    const unsigned mask10      = 0xaaaaaa; /* binary ...101010101010 */
    const unsigned mask01plus1 = mask01 + 1; /* binary ...010101010110 */
    const unsigned mask10plus1 = mask10 + 1; /* binary ...101010101011 */
-   unsigned  	  x, y;			/* pixel coordinates */
-   unsigned  	  xmask, ymask;		/* address conversion */
+   unsigned       x, y;                 /* pixel coordinates */
+   unsigned       xmask, ymask;         /* address conversion */
 
    if (width != height && width != (height >> 1))
       error ("Bintree cutting requires special type of images.");
@@ -534,24 +534,24 @@ cut_to_bintree (real_t *dst, const word_t *src,
       xmask = 0;
       for (x = x0; x < x0 + width; x++, xmask = (xmask + mask01plus1) & mask10)
       {
-	 if (y >= src_height || x >= src_width)
-	    dst [xmask | ymask] = 0;
-	 else
-	    dst [xmask | ymask] = src [y * src_width + x] / 16;
+         if (y >= src_height || x >= src_width)
+            dst [xmask | ymask] = 0;
+         else
+            dst [xmask | ymask] = src [y * src_width + x] / 16;
       }
    }
 }
 
 /*****************************************************************************
 
-				private code
+                                private code
 
 *****************************************************************************/
 
 static void
 init_new_state (bool_t auxiliary_state, bool_t delta, range_t *range,
-		const range_t *child, const int *y_state,
-		wfa_t *wfa, coding_t *c)
+                const range_t *child, const int *y_state,
+                wfa_t *wfa, coding_t *c)
 /*
  *  Initializes a new state with all parameters needed for the encoding step.
  *  If flag 'auxiliary_state' is set then don't insert state into domain pools.
@@ -563,7 +563,7 @@ init_new_state (bool_t auxiliary_state, bool_t delta, range_t *range,
  *  No return value.
  *
  *  Side effects:
- *	New state is appended to 'wfa' (and also its inner products and images
+ *      New state is appended to 'wfa' (and also its inner products and images
  *      are computed and stored in 'c')
  */
 {
@@ -573,13 +573,13 @@ init_new_state (bool_t auxiliary_state, bool_t delta, range_t *range,
    if (!auxiliary_state)
    {
       if (!delta || c->options.delta_domains)
-	 state_is_domain = c->domain_pool->append (wfa->states, range->level,
-						   wfa, c->domain_pool->model);
+         state_is_domain = c->domain_pool->append (wfa->states, range->level,
+                                                   wfa, c->domain_pool->model);
       if (delta || c->options.normal_domains)
-	 state_is_domain = c->d_domain_pool->append (wfa->states, range->level,
-						     wfa,
-						     c->d_domain_pool->model)
-			   || state_is_domain;
+         state_is_domain = c->d_domain_pool->append (wfa->states, range->level,
+                                                     wfa,
+                                                     c->d_domain_pool->model)
+                           || state_is_domain;
    }
    else
       state_is_domain = NO;
@@ -597,7 +597,7 @@ init_new_state (bool_t auxiliary_state, bool_t delta, range_t *range,
       wfa->prediction [wfa->states][label] = child [label].prediction;
 
       append_transitions (wfa->states, label, child [label].weight,
-			  child [label].into, wfa);
+                          child [label].into, wfa);
    }
    wfa->delta_state [wfa->states] = delta;
 
@@ -607,13 +607,13 @@ init_new_state (bool_t auxiliary_state, bool_t delta, range_t *range,
 /*    state_is_domain = YES; */
 
    append_state (!state_is_domain,
-		 compute_final_distribution (wfa->states, wfa),
-		 range->level, wfa, c);
+                 compute_final_distribution (wfa->states, wfa),
+                 range->level, wfa, c);
 }
 
 static void
 init_range (range_t *range, const image_t *image, unsigned band,
-	    const wfa_t *wfa, coding_t *c)
+            const wfa_t *wfa, coding_t *c)
 /*
  *  Read a new 'range' of the image 'image_name' (current color component
  *  is 'band') and compute the new inner product arrays.
@@ -621,9 +621,9 @@ init_range (range_t *range, const image_t *image, unsigned band,
  *  No return value.
  *
  *  Side effects:
- *	'c->pixels' are filled with pixel values of image block
- *	'c->ip_images_state' are computed with respect to new image block
- *	'range->address' and 'range->image' are initialized with zero
+ *      'c->pixels' are filled with pixel values of image block
+ *      'c->ip_images_state' are computed with respect to new image block
+ *      'range->address' and 'range->image' are initialized with zero
  */
 {
    unsigned state;
@@ -633,13 +633,13 @@ init_range (range_t *range, const image_t *image, unsigned band,
     */
    for (state = 0; state < wfa->states; state++)
       if (need_image (state, wfa))
-	 memset (c->ip_images_state[state], 0,
-		 size_of_tree (c->products_level) * sizeof(real_t));
+         memset (c->ip_images_state[state], 0,
+                 size_of_tree (c->products_level) * sizeof(real_t));
 
    cut_to_bintree (c->pixels, image->pixels [band],
-		   image->width, image->height,
-		   range->x, range->y, width_of_level (range->level),
-		   height_of_level (range->level));
+                   image->width, image->height,
+                   range->x, range->y, width_of_level (range->level),
+                   height_of_level (range->level));
 
    range->address = range->image = 0;
    compute_ip_images_state (0, 0, range->level, 1, 0, wfa, c);
diff --git a/converter/other/fiasco/codec/subdivide.h b/converter/other/fiasco/codec/subdivide.h
index bd9cd10e..dbd5620a 100644
--- a/converter/other/fiasco/codec/subdivide.h
+++ b/converter/other/fiasco/codec/subdivide.h
@@ -1,8 +1,8 @@
 /*
  *  subdivide.h
  *
- *  Written by:		Ullrich Hafner
- *		
+ *  Written by:         Ullrich Hafner
+ *
  *  This file is part of FIASCO (Fractal Image And Sequence COdec)
  *  Copyright (C) 1994-2000 Ullrich Hafner
  */
@@ -20,13 +20,13 @@
 #include "types.h"
 #include "cwfa.h"
 
-real_t 
+real_t
 subdivide (real_t max_costs, unsigned band, int y_state, range_t *range,
-	   wfa_t *wfa, coding_t *c, bool_t prediction, bool_t delta);
+           wfa_t *wfa, coding_t *c, bool_t prediction, bool_t delta);
 void
 cut_to_bintree (real_t *dst, const word_t *src,
-		unsigned src_width, unsigned src_height,
-		unsigned x0, unsigned y0, unsigned width, unsigned height);
+                unsigned src_width, unsigned src_height,
+                unsigned x0, unsigned y0, unsigned width, unsigned height);
 
 #endif /* not _SUBDIVIDE_H */
 
diff --git a/converter/other/fiasco/codec/tiling.c b/converter/other/fiasco/codec/tiling.c
index 9af43da0..08423b24 100644
--- a/converter/other/fiasco/codec/tiling.c
+++ b/converter/other/fiasco/codec/tiling.c
@@ -1,8 +1,8 @@
 /*
- *  tiling.c:		Subimage permutation
+ *  tiling.c:           Subimage permutation
+ *
+ *  Written by:         Ullrich Hafner
  *
- *  Written by:		Ullrich Hafner
- *		
  *  This file is part of FIASCO (Fractal Image And Sequence COdec)
  *  Copyright (C) 1994-2000 Ullrich Hafner
  */
@@ -33,8 +33,8 @@
 
 typedef struct var_list
 {
-   int	  address;			/* bintree address */
-   real_t variance;			/* variance of tile */
+   int    address;                      /* bintree address */
+   real_t variance;                     /* variance of tile */
 } var_list_t;
 
 #ifndef LITERAL_FN_DEF_MATCH
@@ -71,17 +71,17 @@ cmpdecvar(const void * const value1,
 
 tiling_t *
 alloc_tiling (fiasco_tiling_e method, unsigned tiling_exponent,
-	      unsigned image_level)
+              unsigned image_level)
 /*
  *  Image tiling constructor.
  *  Allocate memory for the tiling_t structure.
  *  `method' defines the tiling method (spiral or variance,
  *  ascending or descending).
  *  In case of invalid parameters, a structure with tiling.exponent == 0 is
- *  returned. 
+ *  returned.
  *
  *  Return value
- *	pointer to the new tiling structure on success
+ *      pointer to the new tiling structure on success
  */
 {
    tiling_t *tiling = Calloc (1, sizeof (tiling_t));
@@ -90,21 +90,21 @@ alloc_tiling (fiasco_tiling_e method, unsigned tiling_exponent,
    {
       tiling_exponent = 6;
       warning (_("Image tiles must be at least 8x8 pixels large.\n"
-		 "Setting tiling size to 8x8 pixels."));
+                 "Setting tiling size to 8x8 pixels."));
    }
-   
+
    switch (method)
    {
       case FIASCO_TILING_SPIRAL_ASC:
       case FIASCO_TILING_SPIRAL_DSC:
       case FIASCO_TILING_VARIANCE_ASC:
       case FIASCO_TILING_VARIANCE_DSC:
-	 tiling_exponent = tiling_exponent;
-	 break;
+         tiling_exponent = tiling_exponent;
+         break;
       default:
-	 warning (_("Invalid tiling method specified. Disabling tiling."));
-	 tiling_exponent = 0;
-	 break;
+         warning (_("Invalid tiling method specified. Disabling tiling."));
+         tiling_exponent = 0;
+         break;
    }
 
    return tiling;
@@ -119,7 +119,7 @@ free_tiling (tiling_t *tiling)
  *  No return value.
  *
  *  Side effects:
- *	structure 'tiling' is discarded.
+ *      structure 'tiling' is discarded.
  */
 {
    if (tiling->vorder)
@@ -145,88 +145,88 @@ perform_tiling (const image_t *image, tiling_t *tiling)
  *  No return value.
  *
  *  Side effects:
- *	The tiling permutation is stored in 'tiling->vorder'.
+ *      The tiling permutation is stored in 'tiling->vorder'.
  */
 {
    if (tiling->exponent)
    {
-      unsigned 	tiles = 1 << tiling->exponent; /* number of image tiles */
-      bool_t   *tile_valid;		/* tile i is in valid range ? */
-      
+      unsigned  tiles = 1 << tiling->exponent; /* number of image tiles */
+      bool_t   *tile_valid;             /* tile i is in valid range ? */
+
       tiling->vorder = Calloc (tiles, sizeof (int));
       tile_valid     = Calloc (tiles, sizeof (bool_t));
 
       if (tiling->method == FIASCO_TILING_VARIANCE_ASC
-	  || tiling->method == FIASCO_TILING_VARIANCE_DSC)
+          || tiling->method == FIASCO_TILING_VARIANCE_DSC)
       {
-	 unsigned    address;		/* bintree address of tile */
-	 unsigned    number;		/* number of image tiles */
-	 unsigned    lx       = log2 (image->width - 1) + 1; /* x level */
-	 unsigned    ly       = log2 (image->height - 1) + 1; /* y level */
-	 unsigned    level    = MAX(lx, ly) * 2 - ((ly == lx + 1) ? 1 : 0);
-	 var_list_t *var_list = Calloc (tiles, sizeof (var_list_t));
-	 
-	 /*
-	  *  Compute variances of image tiles
-	  */
-	 for (number = 0, address = 0; address < tiles; address++)
-	 {
-	    unsigned width, height;	/* size of image tile */
-	    unsigned x0, y0;		/* NW corner of image tile */
-      
-	    locate_subimage (level, level - tiling->exponent, address,
-			     &x0, &y0, &width, &height);
-	    if (x0 < image->width && y0 < image->height) /* valid range */
-	    {
-	       if (x0 + width > image->width)	/* outside image area */
-		  width = image->width - x0;
-	       if (y0 + height > image->height) /* outside image area */
-		  height = image->height - y0;
-
-	       var_list [number].variance
-		  = variance (image->pixels [GRAY], x0, y0,
-			      width, height, image->width);
-	       var_list [number].address  = address;
-	       number++;
-	       tile_valid [address] = YES;
-	    }
-	    else
-	       tile_valid [address] = NO;
-	 }
-
-	 /*
-	  *  Sort image tiles according to sign of 'tiling->exp'
-	  */
-	 if (tiling->method == FIASCO_TILING_VARIANCE_DSC)
-	    qsort (var_list, number, sizeof (var_list_t), cmpdecvar);
-	 else
-	    qsort (var_list, number, sizeof (var_list_t), cmpincvar);
-
-	 for (number = 0, address = 0; address < tiles; address++)
-	    if (tile_valid [address])
-	    {
-	       tiling->vorder [address] = var_list [number].address;
-	       number++;
-	       debug_message ("tile number %d has original address %d",
-			      number, tiling->vorder [address]);
-	    }
-	    else
-	       tiling->vorder [address] = -1;
-
-	 Free (var_list);
+         unsigned    address;           /* bintree address of tile */
+         unsigned    number;            /* number of image tiles */
+         unsigned    lx       = log2 (image->width - 1) + 1; /* x level */
+         unsigned    ly       = log2 (image->height - 1) + 1; /* y level */
+         unsigned    level    = MAX(lx, ly) * 2 - ((ly == lx + 1) ? 1 : 0);
+         var_list_t *var_list = Calloc (tiles, sizeof (var_list_t));
+
+         /*
+          *  Compute variances of image tiles
+          */
+         for (number = 0, address = 0; address < tiles; address++)
+         {
+            unsigned width, height;     /* size of image tile */
+            unsigned x0, y0;            /* NW corner of image tile */
+
+            locate_subimage (level, level - tiling->exponent, address,
+                             &x0, &y0, &width, &height);
+            if (x0 < image->width && y0 < image->height) /* valid range */
+            {
+               if (x0 + width > image->width)   /* outside image area */
+                  width = image->width - x0;
+               if (y0 + height > image->height) /* outside image area */
+                  height = image->height - y0;
+
+               var_list [number].variance
+                  = variance (image->pixels [GRAY], x0, y0,
+                              width, height, image->width);
+               var_list [number].address  = address;
+               number++;
+               tile_valid [address] = YES;
+            }
+            else
+               tile_valid [address] = NO;
+         }
+
+         /*
+          *  Sort image tiles according to sign of 'tiling->exp'
+          */
+         if (tiling->method == FIASCO_TILING_VARIANCE_DSC)
+            qsort (var_list, number, sizeof (var_list_t), cmpdecvar);
+         else
+            qsort (var_list, number, sizeof (var_list_t), cmpincvar);
+
+         for (number = 0, address = 0; address < tiles; address++)
+            if (tile_valid [address])
+            {
+               tiling->vorder [address] = var_list [number].address;
+               number++;
+               debug_message ("tile number %d has original address %d",
+                              number, tiling->vorder [address]);
+            }
+            else
+               tiling->vorder [address] = -1;
+
+         Free (var_list);
       }
       else if (tiling->method == FIASCO_TILING_SPIRAL_DSC
-	       || tiling->method == FIASCO_TILING_SPIRAL_ASC)
+               || tiling->method == FIASCO_TILING_SPIRAL_ASC)
       {
-	 compute_spiral (tiling->vorder, image->width, image->height,
-			 tiling->exponent,
-			 tiling->method == FIASCO_TILING_SPIRAL_ASC);
+         compute_spiral (tiling->vorder, image->width, image->height,
+                         tiling->exponent,
+                         tiling->method == FIASCO_TILING_SPIRAL_ASC);
       }
       else
       {
-	 warning ("We do not know the tiling method.\n"
-		  "Skipping image tiling step.");
-	 tiling->exponent = 0;
+         warning ("We do not know the tiling method.\n"
+                  "Skipping image tiling step.");
+         tiling->exponent = 0;
       }
    }
 }
diff --git a/converter/other/fiasco/codec/tiling.h b/converter/other/fiasco/codec/tiling.h
index 6668ad8b..ef6d426d 100644
--- a/converter/other/fiasco/codec/tiling.h
+++ b/converter/other/fiasco/codec/tiling.h
@@ -1,8 +1,8 @@
 /*
  *  tiling.h
  *
- *  Written by:		Ullrich Hafner
- *		
+ *  Written by:         Ullrich Hafner
+ *              
  *  This file is part of FIASCO (Fractal Image And Sequence COdec)
  *  Copyright (C) 1994-2000 Ullrich Hafner
  */
@@ -22,17 +22,17 @@
 
 typedef struct tiling
 {
-   unsigned    	    exponent;		/* Image is split in 2^exp tiles */
-   fiasco_tiling_e  method;		/* Method of Image tiling */
-   int	      	   *vorder;		/* Block permutation (size = 2^exp)
-					   -1 indicates empty block */
+   unsigned         exponent;           /* Image is split in 2^exp tiles */
+   fiasco_tiling_e  method;             /* Method of Image tiling */
+   int             *vorder;             /* Block permutation (size = 2^exp)
+                                           -1 indicates empty block */
 } tiling_t;
 
 void
 perform_tiling (const image_t *image, tiling_t *tiling);
 tiling_t *
 alloc_tiling (fiasco_tiling_e method, unsigned tiling_exponent,
-	      unsigned image_level);
+              unsigned image_level);
 void
 free_tiling (tiling_t *tiling);
 
diff --git a/converter/other/fiasco/codec/wfa.h b/converter/other/fiasco/codec/wfa.h
index 4e66ccbd..ae86d216 100644
--- a/converter/other/fiasco/codec/wfa.h
+++ b/converter/other/fiasco/codec/wfa.h
@@ -1,7 +1,7 @@
 /*
  *  wfa.h
  *
- *  Written by:		Ullrich Hafner
+ *  Written by:         Ullrich Hafner
  *
  *  This file is part of FIASCO (Fractal Image And Sequence COdec)
  *  Copyright (C) 1994-2000 Ullrich Hafner
@@ -19,38 +19,38 @@
 
 #define MAXEDGES  5
 #define MAXSTATES 6000
-#define MAXLABELS 2			/* only bintree possible anymore */
+#define MAXLABELS 2                     /* only bintree possible anymore */
 #define MAXLEVEL  22
 
 #define FIASCO_BINFILE_RELEASE   2
-#define FIASCO_MAGIC	         "FIASCO" /* FIASCO magic number */
+#define FIASCO_MAGIC             "FIASCO" /* FIASCO magic number */
 #define FIASCO_BASIS_MAGIC       "Fiasco" /* FIASCO initial basis */
 
-#define NO_EDGE		-1
-#define RANGE		-1
-#define NO_RANGE	 0
+#define NO_EDGE         -1
+#define RANGE           -1
+#define NO_RANGE         0
 
-#define CHILD		 1
-#define LEAF		 0
+#define CHILD            1
+#define LEAF             0
 
-#define MAX_PROB	 9
-#define MIN_PROB	 1
+#define MAX_PROB         9
+#define MIN_PROB         1
 
 /*
  *  WFA state types:
- *	0:		 state is not allowed to be used in an
- *			 approximation and it's image is not needed
- *			 for ip computations.
- *	AUXILIARY_MASK:  state is required for computation of ip's but is not
- *			 allowed to be used in an approximation.
- *	USE_DOMAIN_MASK: state is allowed to be used in an approximation.
+ *      0:               state is not allowed to be used in an
+ *                       approximation and it's image is not needed
+ *                       for ip computations.
+ *      AUXILIARY_MASK:  state is required for computation of ip's but is not
+ *                       allowed to be used in an approximation.
+ *      USE_DOMAIN_MASK: state is allowed to be used in an approximation.
  */
 enum state_types {AUXILIARY_MASK = 1 << 0, USE_DOMAIN_MASK = 1 << 1};
 
-#define isedge(x)	   ((x) != NO_EDGE)
-#define isdomain(x)	   ((x) != NO_EDGE)
-#define isrange(x)	   ((x) == RANGE)
-#define ischild(x)	   ((x) != RANGE)
+#define isedge(x)          ((x) != NO_EDGE)
+#define isdomain(x)        ((x) != NO_EDGE)
+#define isrange(x)         ((x) == RANGE)
+#define ischild(x)         ((x) != RANGE)
 #define isauxiliary(d,wfa) ((wfa)->domain_type[d] & AUXILIARY_MASK)
 #define usedomain(d, wfa)  ((wfa)->domain_type[d] & USE_DOMAIN_MASK)
 #define need_image(d,wfa)  (isauxiliary ((d), (wfa)) || usedomain ((d), (wfa)))
@@ -64,15 +64,15 @@ typedef struct mv
  *  Motion vector components
  */
 {
-   mc_type_e type;			/* motion compensation type */
-   int       fx, fy;			/* forward vector coordinates */
-   int       bx, by;			/* backward vector coordinates */
+   mc_type_e type;                      /* motion compensation type */
+   int       fx, fy;                    /* forward vector coordinates */
+   int       bx, by;                    /* backward vector coordinates */
 } mv_t;
 
 typedef struct range_info
 {
-   unsigned x, y;			/* coordinates of upper left corner */
-   unsigned level;			/* bintree level of range */
+   unsigned x, y;                       /* coordinates of upper left corner */
+   unsigned level;                      /* bintree level of range */
 } range_info_t;
 
 #include "image.h"
@@ -81,32 +81,32 @@ typedef struct range_info
 
 typedef struct wfa_info
 {
-   char	    *wfa_name;			/* filename of the WFA */
-   char	    *basis_name;		/* filename of the initial basis */
-   char     *title;			/* title of FIASCO stream */
-   char     *comment;			/* comment for FIASCO stream */
-
-   unsigned  max_states;		/* max. cardinality of domain pool */
-   unsigned  chroma_max_states;		/* max. cardinality of domain pool for
-					   chroma band coding */
-   bool_t    color;			/* color image */
-   unsigned  width;			/* image width */
-   unsigned  height;			/* image height */
-   unsigned  level;			/* image level */
-   rpf_t    *rpf;			/* Standard reduced precision format */
-   rpf_t    *dc_rpf;			/* DC reduced precision format */
-   rpf_t    *d_rpf;			/* Delta reduced precision format */
-   rpf_t    *d_dc_rpf;			/* Delta DC reduced precision format */
-   unsigned  frames;			/* number of frames in the video */
-   unsigned  fps;			/* number of frames per second */
-   unsigned  p_min_level;		/* min. level of prediction */
-   unsigned  p_max_level;		/* max. level of prediction */
-   unsigned  search_range;		/* motion vector interval */
-   bool_t    half_pixel;		/* usage of half pixel precision */
-   bool_t    cross_B_search;		/* usage of Cross-B-Search */
-   bool_t    B_as_past_ref;		/* usage of B frames as ref's */
-   unsigned  smoothing;			/* smoothing of image along borders */
-   unsigned  release;			/* FIASCO file format release */
+   char     *wfa_name;                  /* filename of the WFA */
+   char     *basis_name;                /* filename of the initial basis */
+   char     *title;                     /* title of FIASCO stream */
+   char     *comment;                   /* comment for FIASCO stream */
+
+   unsigned  max_states;                /* max. cardinality of domain pool */
+   unsigned  chroma_max_states;         /* max. cardinality of domain pool for
+                                           chroma band coding */
+   bool_t    color;                     /* color image */
+   unsigned  width;                     /* image width */
+   unsigned  height;                    /* image height */
+   unsigned  level;                     /* image level */
+   rpf_t    *rpf;                       /* Standard reduced precision format */
+   rpf_t    *dc_rpf;                    /* DC reduced precision format */
+   rpf_t    *d_rpf;                     /* Delta reduced precision format */
+   rpf_t    *d_dc_rpf;                  /* Delta DC reduced precision format */
+   unsigned  frames;                    /* number of frames in the video */
+   unsigned  fps;                       /* number of frames per second */
+   unsigned  p_min_level;               /* min. level of prediction */
+   unsigned  p_max_level;               /* max. level of prediction */
+   unsigned  search_range;              /* motion vector interval */
+   bool_t    half_pixel;                /* usage of half pixel precision */
+   bool_t    cross_B_search;            /* usage of Cross-B-Search */
+   bool_t    B_as_past_ref;             /* usage of B frames as ref's */
+   unsigned  smoothing;                 /* smoothing of image along borders */
+   unsigned  release;                   /* FIASCO file format release */
 } wfa_info_t;
 
 typedef struct wfa
@@ -114,27 +114,27 @@ typedef struct wfa
  *  Used to store all information and data structures of a WFA
  */
 {
-   wfa_info_t	*wfainfo;		/* misc. information about the WFA */
-   frame_type_e frame_type;		/* intra, predicted, bi-directional */
-   unsigned	states;			/* number of states */
-   unsigned	basis_states;		/* number of states in the basis */
-   unsigned	root_state;		/* root of the tree */
-   real_t	*final_distribution;    /* one pixel images */
-   byte_t	*level_of_state;	/* level of the image part which is
-					   represented by the current state */
-   byte_t	*domain_type;		/* Bit_0==1: auxiliary state
-					   Bit_1==1: used for Y compr */
-   mv_t		(*mv_tree)[MAXLABELS];	/* motion vectors */
-   word_t	(*tree)[MAXLABELS];	/* bintree partitioning */
-   u_word_t	(*x)[MAXLABELS];	/* range coordinate */
-   u_word_t	(*y)[MAXLABELS];	/* range coordinate */
-   word_t	(*into)[MAXLABELS][MAXEDGES + 1];   /* domain references */
-   real_t	(*weight)[MAXLABELS][MAXEDGES + 1]; /* lin.comb. coefficients */
-   word_t	(*int_weight)[MAXLABELS][MAXEDGES + 1]; /* bin. representation */
-   word_t	(*y_state)[MAXLABELS];	/* bintree of Y component */
-   byte_t	(*y_column)[MAXLABELS];	/* array for Y component references */
-   byte_t	(*prediction)[MAXLABELS]; /* DC prediction */
-   bool_t	(*delta_state);		/* delta state */
+   wfa_info_t   *wfainfo;               /* misc. information about the WFA */
+   frame_type_e frame_type;             /* intra, predicted, bi-directional */
+   unsigned     states;                 /* number of states */
+   unsigned     basis_states;           /* number of states in the basis */
+   unsigned     root_state;             /* root of the tree */
+   real_t       *final_distribution;    /* one pixel images */
+   byte_t       *level_of_state;        /* level of the image part which is
+                                           represented by the current state */
+   byte_t       *domain_type;           /* Bit_0==1: auxiliary state
+                                           Bit_1==1: used for Y compr */
+   mv_t         (*mv_tree)[MAXLABELS];  /* motion vectors */
+   word_t       (*tree)[MAXLABELS];     /* bintree partitioning */
+   u_word_t     (*x)[MAXLABELS];        /* range coordinate */
+   u_word_t     (*y)[MAXLABELS];        /* range coordinate */
+   word_t       (*into)[MAXLABELS][MAXEDGES + 1];   /* domain references */
+   real_t       (*weight)[MAXLABELS][MAXEDGES + 1]; /* lin.comb. coefficients */
+   word_t       (*int_weight)[MAXLABELS][MAXEDGES + 1]; /* bin. representation */
+   word_t       (*y_state)[MAXLABELS];  /* bintree of Y component */
+   byte_t       (*y_column)[MAXLABELS]; /* array for Y component references */
+   byte_t       (*prediction)[MAXLABELS]; /* DC prediction */
+   bool_t       (*delta_state);         /* delta state */
 } wfa_t;
 
 #endif /* not _WFA_H */
diff --git a/converter/other/fiasco/codec/wfalib.c b/converter/other/fiasco/codec/wfalib.c
index 90420d6f..fd73092f 100644
--- a/converter/other/fiasco/codec/wfalib.c
+++ b/converter/other/fiasco/codec/wfalib.c
@@ -1,8 +1,8 @@
 /*
- *  wfalib.c:		Library functions both for encoding and decoding
+ *  wfalib.c:           Library functions both for encoding and decoding
+ *
+ *  Written by:         Ullrich Hafner
  *
- *  Written by:		Ullrich Hafner
- *		
  *  This file is part of FIASCO (Fractal Image And Sequence COdec)
  *  Copyright (C) 1994-2000 Ullrich Hafner
  */
@@ -35,8 +35,8 @@
 
 /*****************************************************************************
 
-				prototypes
-  
+                                prototypes
+
 *****************************************************************************/
 
 static unsigned
@@ -44,8 +44,8 @@ xy_to_address (unsigned x, unsigned y, unsigned level, unsigned n);
 
 /*****************************************************************************
 
-				public code
-  
+                                public code
+
 *****************************************************************************/
 
 wfa_t *
@@ -56,11 +56,11 @@ alloc_wfa (bool_t coding)
  *  Flag 'coding' indicates whether WFA is used for coding or decoding.
  *
  *  Return value:
- *	pointer to the new WFA structure
+ *      pointer to the new WFA structure
  */
 {
    wfa_t *wfa = Calloc (1, sizeof (wfa_t));
-		 
+
    /*
     *  Allocate memory
     */
@@ -74,17 +74,17 @@ alloc_wfa (bool_t coding)
    wfa->mv_tree            = Calloc (MAXSTATES * MAXLABELS, sizeof (mv_t));
    wfa->y_state            = Calloc (MAXSTATES * MAXLABELS, sizeof (word_t));
    wfa->into               = Calloc (MAXSTATES * MAXLABELS * (MAXEDGES + 1),
-				     sizeof (word_t));
+                                     sizeof (word_t));
    wfa->weight             = Calloc (MAXSTATES * MAXLABELS * (MAXEDGES + 1),
-				     sizeof (real_t));
+                                     sizeof (real_t));
    wfa->int_weight         = Calloc (MAXSTATES * MAXLABELS * (MAXEDGES + 1),
-				     sizeof (word_t));
+                                     sizeof (word_t));
    wfa->wfainfo            = Calloc (1, sizeof (wfa_info_t));;
    wfa->prediction         = Calloc (MAXSTATES * MAXLABELS, sizeof (byte_t));
 
    wfa->wfainfo->wfa_name   = NULL;
    wfa->wfainfo->basis_name = NULL;
-   wfa->wfainfo->title 	    = strdup ("");
+   wfa->wfainfo->title      = strdup ("");
    wfa->wfainfo->comment    = strdup ("");
 
    /*
@@ -96,24 +96,24 @@ alloc_wfa (bool_t coding)
       wfa->states       = 0;
       wfa->basis_states = 0;
       wfa->root_state   = 0;
-      for (state = 0; state < MAXSTATES; state++) 
+      for (state = 0; state < MAXSTATES; state++)
       {
-	 wfa->final_distribution [state] = 0;
-	 wfa->domain_type [state]        = 0;
-	 for (label = 0; label < MAXLABELS; label++)
-	 {
-	    wfa->into [state][label][0] = NO_EDGE;
-	    wfa->tree [state][label]    = RANGE;
-	    wfa->y_state [state][label] = RANGE;
-	 }
+         wfa->final_distribution [state] = 0;
+         wfa->domain_type [state]        = 0;
+         for (label = 0; label < MAXLABELS; label++)
+         {
+            wfa->into [state][label][0] = NO_EDGE;
+            wfa->tree [state][label]    = RANGE;
+            wfa->y_state [state][label] = RANGE;
+         }
       }
    }
 
-   if (coding)				/* initialize additional variables */
+   if (coding)                          /* initialize additional variables */
       wfa->y_column = Calloc (MAXSTATES * MAXLABELS, sizeof (byte_t));
    else
       wfa->y_column = NULL;
-   
+
    return wfa;
 }
 
@@ -126,7 +126,7 @@ free_wfa (wfa_t *wfa)
  *  No return value.
  *
  *  Side effects:
- *	'wfa' struct is discarded.
+ *      'wfa' struct is discarded.
  */
 {
    if (wfa->wfainfo->wfa_name)
@@ -157,14 +157,14 @@ free_wfa (wfa_t *wfa)
    Free (wfa);
 }
 
-real_t 
+real_t
 compute_final_distribution (unsigned state, const wfa_t *wfa)
 /*
  *  Compute the final distribution of the given 'state'.
  *  Uses the fact that the generated 'wfa' is average preserving.
  *
  *  Return value:
- *	final distribution
+ *      final distribution
  */
 {
    unsigned label;
@@ -174,14 +174,14 @@ compute_final_distribution (unsigned state, const wfa_t *wfa)
    {
       unsigned edge;
       int      domain;
-      
+
       if (ischild (domain = wfa->tree [state][label]))
-	 final += wfa->final_distribution [domain];
+         final += wfa->final_distribution [domain];
       for (edge = 0; isedge (domain = wfa->into [state][label][edge]); edge++)
-	 final += wfa->weight [state][label][edge]
-		  * wfa->final_distribution [domain];
+         final += wfa->weight [state][label][edge]
+                  * wfa->final_distribution [domain];
    }
-   
+
    return final / MAXLABELS;
 }
 
@@ -193,10 +193,10 @@ compute_hits (unsigned from, unsigned to, unsigned n, const wfa_t *wfa)
  *  {i | 'from' <= i <= 'to'}. I.e. domains are in {i | from <= i < 'to'}
  *  Always ensure that state 0 is among selected states even though from
  *  may be > 0.
- *  
+ *
  *  Return value:
- *	pointer to array of the most popular state images
- *	sorted by increasing state numbers and terminated by -1
+ *      pointer to array of the most popular state images
+ *      sorted by increasing state numbers and terminated by -1
  */
 {
    word_t   *domains;
@@ -209,12 +209,12 @@ compute_hits (unsigned from, unsigned to, unsigned n, const wfa_t *wfa)
       hits [domain].value = domain;
       hits [domain].key   = 0;
    }
-   
+
    for (state = from; state <= to; state++)
       for (label = 0; label < MAXLABELS; label++)
-	 for (edge = 0; isedge (domain = wfa->into [state][label][edge]);
-	      edge++)
-	    hits [domain].key++;
+         for (edge = 0; isedge (domain = wfa->into [state][label][edge]);
+              edge++)
+            hits [domain].key++;
 
    qsort (hits + 1, to - 1, sizeof (pair_t), sort_desc_pair);
 
@@ -222,23 +222,23 @@ compute_hits (unsigned from, unsigned to, unsigned n, const wfa_t *wfa)
    domains = Calloc (n + 1, sizeof (word_t));
 
    for (domain = 0; domain < (int) n && (!domain || hits [domain].key);
-	domain++)
+        domain++)
       domains [domain] = hits [domain].value;
    if (n != domain)
       debug_message ("Only %d domains have been used in the luminance.",
-		     domain);
+                     domain);
    n = domain;
    qsort (domains, n, sizeof (word_t), sort_asc_word);
    domains [n] = -1;
-   
+
    Free (hits);
-   
+
    return domains;
 }
 
 void
 append_edge (unsigned from, unsigned into, real_t weight,
-	     unsigned label, wfa_t *wfa)
+             unsigned label, wfa_t *wfa)
 /*
  *  Append an edge from state 'from' to state 'into' with
  *  the given 'label' and 'weight' to the 'wfa'.
@@ -246,10 +246,10 @@ append_edge (unsigned from, unsigned into, real_t weight,
  *  No return value.
  *
  *  Side effects:
- *	'wfa' structure is changed.
+ *      'wfa' structure is changed.
  */
 {
-   unsigned new;			/* position of the new edge */
+   unsigned new;                        /* position of the new edge */
    unsigned edge;
 
    /*
@@ -257,7 +257,7 @@ append_edge (unsigned from, unsigned into, real_t weight,
     *  edges are sorted by increasing 'into' values
     */
    for (new = 0; (isedge (wfa->into [from][label][new])
-		  && wfa->into [from][label][new] < (int) into); new++)
+                  && wfa->into [from][label][new] < (int) into); new++)
       ;
    /*
     *  Move the edges 'n' to position 'n+1', for n = max, ..., 'new'
@@ -269,7 +269,7 @@ append_edge (unsigned from, unsigned into, real_t weight,
       wfa->into [from][label][edge]    = wfa->into [from][label][edge - 1];
       wfa->weight [from][label][edge]  = wfa->weight [from][label][edge - 1];
       wfa->int_weight [from][label][edge]
-	 = wfa->int_weight [from][label][edge - 1];
+         = wfa->int_weight [from][label][edge - 1];
    }
    /*
     *  Insert the new edge
@@ -279,15 +279,15 @@ append_edge (unsigned from, unsigned into, real_t weight,
    wfa->int_weight [from][label][edge] = weight * 512 + 0.5;
 }
 
-void 
+void
 remove_states (unsigned from, wfa_t *wfa)
-/* 
+/*
  *  Remove 'wfa' states 'wfa->basis_states',...,'wfa->states' - 1.
  *
  *  No return value.
  *
  *  Side effects:
- *	'wfa' structure is cleared for the given states.
+ *      'wfa' structure is cleared for the given states.
  */
 {
    unsigned state;
@@ -295,18 +295,18 @@ remove_states (unsigned from, wfa_t *wfa)
    for (state = from; state < wfa->states; state++)
    {
       unsigned label;
-      
-      for (label = 0; label < MAXLABELS; label++) 
+
+      for (label = 0; label < MAXLABELS; label++)
       {
-	 wfa->into [state][label][0]      = NO_EDGE;
-	 wfa->tree [state][label]         = RANGE;
-	 wfa->prediction [state][label]   = FALSE;
-	 wfa->y_state [state][label]      = RANGE;
-	 wfa->mv_tree [state][label].type = NONE;
-	 wfa->mv_tree [state][label].fx   = 0;
-	 wfa->mv_tree [state][label].fy   = 0;
-	 wfa->mv_tree [state][label].bx   = 0;
-	 wfa->mv_tree [state][label].by   = 0;
+         wfa->into [state][label][0]      = NO_EDGE;
+         wfa->tree [state][label]         = RANGE;
+         wfa->prediction [state][label]   = FALSE;
+         wfa->y_state [state][label]      = RANGE;
+         wfa->mv_tree [state][label].type = NONE;
+         wfa->mv_tree [state][label].fx   = 0;
+         wfa->mv_tree [state][label].fy   = 0;
+         wfa->mv_tree [state][label].bx   = 0;
+         wfa->mv_tree [state][label].by   = 0;
       }
       wfa->domain_type [state] = 0;
       wfa->delta_state [state] = FALSE;
@@ -323,7 +323,7 @@ copy_wfa (wfa_t *dst, const wfa_t *src)
  *  No return value.
  *
  *  Side effects:
- *	'dst' is filled with same data as 'src'
+ *      'dst' is filled with same data as 'src'
  *
  *  NOTE: size of WFA 'dst' must be at least size of WFA 'src'
  */
@@ -339,11 +339,11 @@ copy_wfa (wfa_t *dst, const wfa_t *src)
    memset (dst->y, 0, MAXSTATES * MAXLABELS * sizeof (word_t));
    memset (dst->y_state, 0, MAXSTATES * MAXLABELS * sizeof (word_t));
    memset (dst->into, NO_EDGE,
-	   MAXSTATES * MAXLABELS * (MAXEDGES + 1) * sizeof (word_t));
+           MAXSTATES * MAXLABELS * (MAXEDGES + 1) * sizeof (word_t));
    memset (dst->weight, 0,
-	   MAXSTATES * MAXLABELS * (MAXEDGES + 1) * sizeof (real_t));
+           MAXSTATES * MAXLABELS * (MAXEDGES + 1) * sizeof (real_t));
    memset (dst->int_weight, 0,
-	   MAXSTATES * MAXLABELS * (MAXEDGES + 1) * sizeof (word_t));
+           MAXSTATES * MAXLABELS * (MAXEDGES + 1) * sizeof (word_t));
    memset (dst->prediction, 0, MAXSTATES * MAXLABELS * sizeof (byte_t));
    memset (dst->delta_state, 0, MAXSTATES * sizeof (bool_t));
    if (dst->y_column)
@@ -352,62 +352,62 @@ copy_wfa (wfa_t *dst, const wfa_t *src)
    for (state = 0; state < MAXSTATES; state++) /* clear WFA struct */
    {
       unsigned label;
-      
+
       for (label = 0; label < MAXLABELS; label++)
       {
-	 dst->into [state][label][0]      = NO_EDGE;
-	 dst->tree [state][label]         = RANGE;
-	 dst->mv_tree [state][label].type = NONE;
-	 dst->y_state[state][label]       = RANGE;
+         dst->into [state][label][0]      = NO_EDGE;
+         dst->tree [state][label]         = RANGE;
+         dst->mv_tree [state][label].type = NONE;
+         dst->y_state[state][label]       = RANGE;
       }
       dst->delta_state [state] = NO;
       dst->domain_type [state] = 0;
    }
-   
+
    dst->frame_type   = src->frame_type;
-   dst->states 	     = src->states;
+   dst->states       = src->states;
    dst->basis_states = src->basis_states;
    dst->root_state   = src->root_state;
 
    memcpy (dst->wfainfo, src->wfainfo, sizeof (wfa_info_t));
 
-   if (dst->states == 0)		/* nothing to do */
+   if (dst->states == 0)                /* nothing to do */
       return;
 
    memcpy (dst->final_distribution, src->final_distribution,
-	   src->states * sizeof (real_t));
+           src->states * sizeof (real_t));
    memcpy (dst->level_of_state, src->level_of_state,
-	   src->states * sizeof (byte_t));
+           src->states * sizeof (byte_t));
    memcpy (dst->domain_type, src->domain_type,
-	   src->states * sizeof (byte_t));
+           src->states * sizeof (byte_t));
    memcpy (dst->delta_state, src->delta_state,
-	   src->states * sizeof (bool_t));
+           src->states * sizeof (bool_t));
    memcpy (dst->mv_tree, src->mv_tree,
-	   src->states * MAXLABELS * sizeof (mv_t));
+           src->states * MAXLABELS * sizeof (mv_t));
    memcpy (dst->tree, src->tree,
-	   src->states * MAXLABELS * sizeof (word_t));
+           src->states * MAXLABELS * sizeof (word_t));
    memcpy (dst->x, src->x,
-	   src->states * MAXLABELS * sizeof (word_t));
+           src->states * MAXLABELS * sizeof (word_t));
    memcpy (dst->y, src->y,
-	   src->states * MAXLABELS * sizeof (word_t));
+           src->states * MAXLABELS * sizeof (word_t));
    memcpy (dst->y_state, src->y_state,
-	   src->states * MAXLABELS * sizeof (word_t));
+           src->states * MAXLABELS * sizeof (word_t));
    memcpy (dst->into, src->into,
-	   src->states * MAXLABELS * (MAXEDGES + 1) * sizeof (word_t));
+           src->states * MAXLABELS * (MAXEDGES + 1) * sizeof (word_t));
    memcpy (dst->weight, src->weight,
-	   src->states * MAXLABELS * (MAXEDGES + 1) * sizeof (real_t));
+           src->states * MAXLABELS * (MAXEDGES + 1) * sizeof (real_t));
    memcpy (dst->int_weight, src->int_weight,
-	   src->states * MAXLABELS * (MAXEDGES + 1) * sizeof (word_t));
+           src->states * MAXLABELS * (MAXEDGES + 1) * sizeof (word_t));
    memcpy (dst->prediction, src->prediction,
-	   src->states * MAXLABELS * sizeof (byte_t));
+           src->states * MAXLABELS * sizeof (byte_t));
    if (dst->y_column)
       memcpy (dst->y_column, src->y_column,
-	      src->states * MAXLABELS * sizeof (byte_t));
+              src->states * MAXLABELS * sizeof (byte_t));
 }
 
 void
 locate_subimage (unsigned orig_level, unsigned level, unsigned bintree,
-		 unsigned *x, unsigned *y, unsigned *width, unsigned *height)
+                 unsigned *x, unsigned *y, unsigned *width, unsigned *height)
 /*
  *  Compute pixel coordinates of the subimage which 'bintree' address is given.
  *  The level of the original image is 'orig_level' and the level of the
@@ -416,14 +416,14 @@ locate_subimage (unsigned orig_level, unsigned level, unsigned bintree,
  *  No return value.
  *
  *  Side effects:
- *	'*x', '*y'		coordinates of the upper left corner
- *      '*width', '*height'	size of image
+ *      '*x', '*y'              coordinates of the upper left corner
+ *      '*width', '*height'     size of image
  */
 {
    /*
     *  Compute coordinates of the subimage
     */
-   *x = *y = 0;				/* start at NW corner */
+   *x = *y = 0;                         /* start at NW corner */
    *width  = width_of_level (level);
    *height = height_of_level (level);
 
@@ -439,31 +439,31 @@ locate_subimage (unsigned orig_level, unsigned level, unsigned bintree,
    }
    else if (level < orig_level)
    {
-      unsigned mask;			/* mask for bintree -> xy conversion */
-      bool_t   hor;			/* 1 next subdivision is horizontal
-					   0 next subdivision is vertical */
-      unsigned l = orig_level - 1;	/* current level */
-      
-      hor = orig_level % 2;		/* start with vertival subdivision
-					   for square image and vice versa */
-   
+      unsigned mask;                    /* mask for bintree -> xy conversion */
+      bool_t   hor;                     /* 1 next subdivision is horizontal
+                                           0 next subdivision is vertical */
+      unsigned l = orig_level - 1;      /* current level */
+
+      hor = orig_level % 2;             /* start with vertival subdivision
+                                           for square image and vice versa */
+
       for (mask = 1 << (orig_level - level - 1); mask; mask >>= 1, hor = !hor)
       {
-	 if (bintree & mask)		/* change coordinates */
-	 {
-	    if (hor)			/* horizontal subdivision */
-	       *y += height_of_level (l);
-	    else			/* vertical subdivision */
-	       *x += width_of_level (l);
-	 }
-	 l--;
+         if (bintree & mask)            /* change coordinates */
+         {
+            if (hor)                    /* horizontal subdivision */
+               *y += height_of_level (l);
+            else                        /* vertical subdivision */
+               *x += width_of_level (l);
+         }
+         l--;
       }
    }
 }
 
 void
 compute_spiral (int *vorder, unsigned image_width, unsigned image_height,
-		unsigned tiling_exp, bool_t inc_spiral)
+                unsigned tiling_exp, bool_t inc_spiral)
 /*
  *  Compute image tiling with spiral order.
  *  'inc_spiral' specifies whether the spiral starts in the middle
@@ -474,28 +474,28 @@ compute_spiral (int *vorder, unsigned image_width, unsigned image_height,
  *  No return value.
  *
  *  Side effects:
- *	vorder[] is filled with tiling permutation
+ *      vorder[] is filled with tiling permutation
  */
 {
-   unsigned x, y;			/* current position */
-   unsigned xmin, xmax, ymin, ymax;	/* boundaries for current line */
-   unsigned width, height;		/* offset for each tile */
-   unsigned lx, ly, level;		/* level x and y */
-   unsigned tiles;			/* total number of tiles */
-   unsigned address;			/* bintree address */
-   
+   unsigned x, y;                       /* current position */
+   unsigned xmin, xmax, ymin, ymax;     /* boundaries for current line */
+   unsigned width, height;              /* offset for each tile */
+   unsigned lx, ly, level;              /* level x and y */
+   unsigned tiles;                      /* total number of tiles */
+   unsigned address;                    /* bintree address */
+
    lx     = log2 (image_width - 1) + 1;
    ly     = log2 (image_height - 1) + 1;
    level  = MAX(lx, ly) * 2 - ((ly == lx + 1) ? 1 : 0);
-   tiles  = 1 << tiling_exp;		/* Number of image tiles */
+   tiles  = 1 << tiling_exp;            /* Number of image tiles */
    width  = width_of_level (level - tiling_exp);
    height = height_of_level (level - tiling_exp);
    for (address = 0; address < tiles; address++)
    {
       unsigned x0, y0, width, height;
-      
+
       locate_subimage (level, level - tiling_exp, address,
-		       &x0, &y0, &width, &height);
+                       &x0, &y0, &width, &height);
       vorder [address] = (x0 < image_width && y0 < image_height) ? 0 : -1;
    }
 
@@ -507,7 +507,7 @@ compute_spiral (int *vorder, unsigned image_width, unsigned image_height,
 
    /*
     *  1234
-    *  CDE5  Traverse image in spiral order 
+    *  CDE5  Traverse image in spiral order
     *  BGF6  starting at the top left corner
     *  A987
     */
@@ -515,59 +515,59 @@ compute_spiral (int *vorder, unsigned image_width, unsigned image_height,
    {
       for (x = xmin, y = ymin; x < xmax; x += width) /* W>E */
       {
-	 while (vorder [address] == -1)
-	    address++;
-	 if (x < image_width && y < image_height) /* valid range */
-	    vorder [address++] = xy_to_address (x, y, level, tiling_exp);
-	 while (address < tiles && vorder [address] == -1)
-	    address++;
+         while (vorder [address] == -1)
+            address++;
+         if (x < image_width && y < image_height) /* valid range */
+            vorder [address++] = xy_to_address (x, y, level, tiling_exp);
+         while (address < tiles && vorder [address] == -1)
+            address++;
       }
       ymin += height;
 
       if (address >= tiles)
-	 break;
-      
+         break;
+
       for (x = xmax - width, y = ymin; y < ymax; y += height) /* N>S  */
       {
-	 while (vorder [address] == -1)
-	    address++;
-	 if (x <= image_width && y <= image_height) /* valid range */
-	    vorder [address++] = xy_to_address (x, y, level, tiling_exp);
-	 while (address < tiles && vorder [address] == -1)
-	    address++;
+         while (vorder [address] == -1)
+            address++;
+         if (x <= image_width && y <= image_height) /* valid range */
+            vorder [address++] = xy_to_address (x, y, level, tiling_exp);
+         while (address < tiles && vorder [address] == -1)
+            address++;
       }
       xmax -= width;
 
       if (address >= tiles)
-	 break;
+         break;
 
       for (x = xmax - width, y = ymax - width; x >= xmin; x -= width) /* E<W */
       {
-	 while (vorder [address] == -1)
-	    address++;
-	 if (x <= image_width && y <= image_height) /* valid range */
-	    vorder [address++] = xy_to_address (x, y, level, tiling_exp);
-	 while (address < tiles && vorder [address] == -1)
-	    address++;
+         while (vorder [address] == -1)
+            address++;
+         if (x <= image_width && y <= image_height) /* valid range */
+            vorder [address++] = xy_to_address (x, y, level, tiling_exp);
+         while (address < tiles && vorder [address] == -1)
+            address++;
       }
       ymax -= height;
 
       if (address >= tiles)
-	 break;
+         break;
 
-      for (x = xmin, y = ymax - height; y >= ymin; y -= height)	/* S>N */
+      for (x = xmin, y = ymax - height; y >= ymin; y -= height) /* S>N */
       {
-	 while (vorder [address] == -1)
-	    address++;
-	 if (x <= image_width && y <= image_height) /* valid range */
-	    vorder [address++] = xy_to_address (x, y, level, tiling_exp);
-	 while (address < tiles && vorder [address] == -1)
-	    address++;
+         while (vorder [address] == -1)
+            address++;
+         if (x <= image_width && y <= image_height) /* valid range */
+            vorder [address++] = xy_to_address (x, y, level, tiling_exp);
+         while (address < tiles && vorder [address] == -1)
+            address++;
       }
       xmin += width;
-	 
+
       if (address >= tiles)
-	 break;
+         break;
    }
 
    if (inc_spiral)
@@ -576,18 +576,18 @@ compute_spiral (int *vorder, unsigned image_width, unsigned image_height,
 
       while (i < j)
       {
-	 int tmp;
-	    
-	 while (vorder [i] == -1)
-	    i++;
-	 while (vorder [j] == -1)
-	    j--;
-	    
-	 tmp 	       = vorder [i];
-	 vorder [i] = vorder [j];
-	 vorder [j] = tmp;
-	 i++;
-	 j--;
+         int tmp;
+
+         while (vorder [i] == -1)
+            i++;
+         while (vorder [j] == -1)
+            j--;
+
+         tmp           = vorder [i];
+         vorder [i] = vorder [j];
+         vorder [j] = tmp;
+         i++;
+         j--;
       }
    }
    /*
@@ -595,109 +595,109 @@ compute_spiral (int *vorder, unsigned image_width, unsigned image_height,
     */
    {
       unsigned number;
-      
+
       for (number = 0, address = 0; address < tiles; address++)
-	 if (vorder [address] != -1)
-	    debug_message ("number %d: address %d",
-			   number++, vorder [address]);
+         if (vorder [address] != -1)
+            debug_message ("number %d: address %d",
+                           number++, vorder [address]);
    }
 }
 
 bool_t
 find_range (unsigned x, unsigned y, unsigned band,
-	    const wfa_t *wfa, unsigned *range_state, unsigned *range_label)
+            const wfa_t *wfa, unsigned *range_state, unsigned *range_label)
 /*
  *  Find a range ('*range_state', '*range_label') that contains
  *  pixel ('x', 'y') in the iven color 'band'.
  *
  *  Return value:
- *	TRUE on success, or FALSE if there is no such range
+ *      TRUE on success, or FALSE if there is no such range
  *
  *  Side effects:
- *	'*range_state' and '*range_label' are modified on success.
+ *      '*range_state' and '*range_label' are modified on success.
  */
 {
    unsigned state, label;
    unsigned first_state, last_state;
    bool_t   success = NO;
-   
+
    first_state = wfa->basis_states;
    last_state  = wfa->states;
    if (wfa->wfainfo->color)
       switch (band)
       {
-	 case Y:
-	    first_state = wfa->basis_states;
-	    last_state  = wfa->tree [wfa->tree [wfa->root_state][0]][0];
-	    break;
-	 case Cb:
-	    first_state = wfa->tree [wfa->tree [wfa->root_state][0]][0] + 1;
-	    last_state  = wfa->tree [wfa->tree [wfa->root_state][0]][1];
-	    break;
-	 case Cr:
-	    first_state = wfa->tree [wfa->tree [wfa->root_state][0]][1] + 1;
-	    last_state  = wfa->states;
-	    break;
-	 default:
-	    error ("unknown color component.");
+         case Y:
+            first_state = wfa->basis_states;
+            last_state  = wfa->tree [wfa->tree [wfa->root_state][0]][0];
+            break;
+         case Cb:
+            first_state = wfa->tree [wfa->tree [wfa->root_state][0]][0] + 1;
+            last_state  = wfa->tree [wfa->tree [wfa->root_state][0]][1];
+            break;
+         case Cr:
+            first_state = wfa->tree [wfa->tree [wfa->root_state][0]][1] + 1;
+            last_state  = wfa->states;
+            break;
+         default:
+            error ("unknown color component.");
       }
 
    for (state = first_state; state < last_state; state++)
       for (label = 0; label < MAXLABELS; label++)
-	 if (isrange (wfa->tree [state][label]))
-	    if (x >= wfa->x [state][label] && y >= wfa->y [state][label]
-		&& x < (unsigned) (wfa->x [state][label]
-			+ width_of_level (wfa->level_of_state [state] - 1))
-		&& y < (unsigned) (wfa->y [state][label]
-			+ height_of_level (wfa->level_of_state [state] - 1))) 
-	    {
-	       success      = YES;
-	       *range_state = state;
-	       *range_label = label;
-
-	       return success;
-	    }
+         if (isrange (wfa->tree [state][label]))
+            if (x >= wfa->x [state][label] && y >= wfa->y [state][label]
+                && x < (unsigned) (wfa->x [state][label]
+                        + width_of_level (wfa->level_of_state [state] - 1))
+                && y < (unsigned) (wfa->y [state][label]
+                        + height_of_level (wfa->level_of_state [state] - 1)))
+            {
+               success      = YES;
+               *range_state = state;
+               *range_label = label;
+
+               return success;
+            }
 
    return success;
 }
 
 void
 sort_ranges (unsigned state, unsigned *domain,
-	     range_sort_t *rs, const wfa_t *wfa)
+             range_sort_t *rs, const wfa_t *wfa)
 /*
  *  Generate list of ranges in coder order.
  *  'state' is the current state of the call tree while 'domain' is the
  *  index of the last added WFA state.
  *
  *  Side effects:
- *	'domain' is incremented after recursion returns
- *	'rs'	 is filled accordingly
+ *      'domain' is incremented after recursion returns
+ *      'rs'     is filled accordingly
  *
  *  No return value.
  */
 {
    unsigned label;
-   
+
    for (label = 0; label < MAXLABELS; label++)
    {
       if (isrange (wfa->tree [state][label]))
-	 rs->range_subdivided [rs->range_no] = NO;
+         rs->range_subdivided [rs->range_no] = NO;
       else
       {
-	 sort_ranges (wfa->tree [state][label], domain, rs, wfa);
-	 rs->range_subdivided [rs->range_no] = YES;
+         sort_ranges (wfa->tree [state][label], domain, rs, wfa);
+         rs->range_subdivided [rs->range_no] = YES;
       }
 
       rs->range_state [rs->range_no]      = state;
       rs->range_label [rs->range_no]      = label;
       rs->range_max_domain [rs->range_no] = *domain;
       while (!usedomain (rs->range_max_domain [rs->range_no], wfa))
-	 rs->range_max_domain [rs->range_no]--;
+         rs->range_max_domain [rs->range_no]--;
 
       if (label == 1 || !rs->range_subdivided [rs->range_no])
-	 rs->range_no++;
+         rs->range_no++;
    }
-   
+
    (*domain)++;
 }
 
@@ -709,11 +709,11 @@ locate_delta_images (wfa_t *wfa)
  *  via MC or ND.
  *
  *  Return value:
- *	TRUE	at least one state is part of a delta approximation
- *	FALSE	no delta approximations in this WFA
+ *      TRUE    at least one state is part of a delta approximation
+ *      FALSE   no delta approximations in this WFA
  *
  *  Side effects:
- *	'wfa->delta [state][label]' is set accordingly.
+ *      'wfa->delta [state][label]' is set accordingly.
  */
 {
    unsigned state, label;
@@ -724,22 +724,22 @@ locate_delta_images (wfa_t *wfa)
 
    for (state = wfa->root_state; state >= wfa->basis_states; state--)
       for (label = 0; label < MAXLABELS; label++)
-	 if (ischild (wfa->tree [state][label]))
-	    if (wfa->mv_tree [state][label].type != NONE
-		|| isedge (wfa->into [state][label][0])
-		|| wfa->delta_state [state])
-	    {
-	       delta = YES;
-	       wfa->delta_state [wfa->tree [state][label]] = YES;
-	    }
+         if (ischild (wfa->tree [state][label]))
+            if (wfa->mv_tree [state][label].type != NONE
+                || isedge (wfa->into [state][label][0])
+                || wfa->delta_state [state])
+            {
+               delta = YES;
+               wfa->delta_state [wfa->tree [state][label]] = YES;
+            }
 
    return delta;
 }
 
 /*****************************************************************************
 
-				private code
-  
+                                private code
+
 ******************************************************************************/
 
 static unsigned
@@ -750,25 +750,25 @@ xy_to_address (unsigned x, unsigned y, unsigned level, unsigned n)
  *  'n' specifies number of iterations.
  *
  *  Return value:
- *	address of subimage
- */ 
-{ 
+ *      address of subimage
+ */
+{
    unsigned address = 0;
 
    while (n--)
    {
       address <<= 1;
-      if (--level % 2) 
+      if (--level % 2)
       {
-	 if (x & width_of_level (level))
-	    address++;
+         if (x & width_of_level (level))
+            address++;
       }
       else
       {
-	 if (y & height_of_level (level))
-	    address++;
+         if (y & height_of_level (level))
+            address++;
       }
    }
-   
+
    return address;
 }
diff --git a/converter/other/fiasco/codec/wfalib.h b/converter/other/fiasco/codec/wfalib.h
index 5c1e0907..63723f30 100644
--- a/converter/other/fiasco/codec/wfalib.h
+++ b/converter/other/fiasco/codec/wfalib.h
@@ -1,8 +1,8 @@
 /*
  *  wfalib.h
  *
- *  Written by:		Ullrich Hafner
- *		
+ *  Written by:         Ullrich Hafner
+ *
  *  This file is part of FIASCO (Fractal Image And Sequence COdec)
  *  Copyright (C) 1994-2000 Ullrich Hafner
  */
@@ -34,26 +34,26 @@ bool_t
 locate_delta_images (wfa_t *wfa);
 void
 sort_ranges (unsigned state, unsigned *domain,
-	     range_sort_t *rs, const wfa_t *wfa);
+             range_sort_t *rs, const wfa_t *wfa);
 bool_t
 find_range (unsigned x, unsigned y, unsigned band,
-	    const wfa_t *wfa, unsigned *range_state, unsigned *range_label);
+            const wfa_t *wfa, unsigned *range_state, unsigned *range_label);
 void
 compute_spiral (int *vorder, unsigned image_width, unsigned image_height,
-		unsigned tiling_exp, bool_t inc_spiral);
+                unsigned tiling_exp, bool_t inc_spiral);
 void
 locate_subimage (unsigned orig_level, unsigned level, unsigned bintree,
-		 unsigned *x, unsigned *y, unsigned *width, unsigned *height);
+                 unsigned *x, unsigned *y, unsigned *width, unsigned *height);
 void
 copy_wfa (wfa_t *dst, const wfa_t *src);
-void 
+void
 remove_states (unsigned from, wfa_t *wfa);
 void
 append_edge (unsigned from, unsigned into, real_t weight,
-	     unsigned label, wfa_t *wfa);
+             unsigned label, wfa_t *wfa);
 word_t *
 compute_hits (unsigned from, unsigned to, unsigned n, const wfa_t *wfa);
-real_t 
+real_t
 compute_final_distribution (unsigned state, const wfa_t *wfa);
 wfa_t *
 alloc_wfa (bool_t coding);
diff --git a/converter/other/fiasco/display.c b/converter/other/fiasco/display.c
deleted file mode 100644
index d8d32fa6..00000000
--- a/converter/other/fiasco/display.c
+++ /dev/null
@@ -1,415 +0,0 @@
-/*
- *  display.c:		X11 display of frames
- *
- *  Written by:		Ullrich Hafner
- *		
- *  This file is part of FIASCO (Fractal Image And Sequence COdec)
- *  Copyright (C) 1994-2000 Ullrich Hafner
- *		
- *  Based on mpeg2decode, (C) 1994, MPEG Software Simulation Group
- *  and      mpeg2play,   (C) 1994 Stefan Eckart
- *                                 <stefan@lis.e-technik.tu-muenchen.de>
- *  and      tmndec       (C) 1995, 1996  Telenor R&D, Norway
- */
-
-/*
- *  $Date: 2000/07/03 19:35:59 $
- *  $Author: hafner $
- *  $Revision: 5.2 $
- *  $State: Exp $
- */
-
-#include "config.h"
-
-#ifndef X_DISPLAY_MISSING
-
-#include <X11/Xlib.h>
-#include <X11/Xutil.h>
-#include <X11/keysym.h>
-
-#include <stdlib.h>
-#include <string.h>
-
-#include "types.h"
-#include "macros.h"
-#include "display.h"
-#include "binerror.h"
-
-/*****************************************************************************
-
-	       shared memory functions (if USE_SHM is defined)
-  
-*****************************************************************************/
-
-#ifdef USE_SHM
-
-#ifdef HAVE_FEATURES_H
-#include <features.h>
-#endif
-
-#include <sys/types.h>
-#include <sys/ipc.h>
-#include <sys/shm.h>
-#include <X11/extensions/XShm.h>
-
-int
-XShmQueryExtension (Display *dpy);
-int
-XShmGetEventBase (Display *dpy);
-
-static int
-HandleXError (Display *dpy, XErrorEvent *event);
-static void
-InstallXErrorHandler (x11_info_t *xinfo);
-static void
-DeInstallXErrorHandler (x11_info_t *xinfo);
-
-static int		shmem_flag;
-static XShmSegmentInfo	shminfo1, shminfo2;
-static int		gXErrorFlag;
-static int		CompletionType = -1;
-
-static int
-HandleXError (Display *dpy, XErrorEvent *event)
-{
-   gXErrorFlag = 1;
-   
-   return 0;
-}
-
-static void
-InstallXErrorHandler (x11_info_t *xinfo)
-{
-   XSetErrorHandler (HandleXError);
-   XFlush (xinfo->display);
-}
-
-static void
-DeInstallXErrorHandler (x11_info_t *xinfo)
-{
-   XSetErrorHandler (NULL);
-   XFlush (xinfo->display);
-}
-
-#endif /* USE_SHM */
-
-/*****************************************************************************
-
-				public code
-  
-*****************************************************************************/
-
-void
-display_image (unsigned x0, unsigned y0, x11_info_t *xinfo)
-/*
- *  Display 'image' at pos ('x0', 'y0') in the current window
- *  (given by 'xinfo->window'). 
- *
- *  No return value.
- */
-{
-   int byte_order_check = 1;
-   
-   /*
-    *  Always work in native bit and byte order. This tells Xlib to
-    *  reverse bit and byte order if necessary when crossing a
-    *  network. Frankly, this part of XImages is somewhat
-    *  underdocumented, so this may not be exactly correct.
-    */
-   if (*(char *) & byte_order_check == 1)
-   {
-      xinfo->ximage->byte_order       = LSBFirst;
-      xinfo->ximage->bitmap_bit_order = LSBFirst;
-   }
-   else
-   {
-      xinfo->ximage->byte_order       = MSBFirst;
-      xinfo->ximage->bitmap_bit_order = MSBFirst;
-   }    
-
-   /* Display dithered image */
-#ifdef USE_SHM
-   if (shmem_flag)
-   {
-      XEvent xev;
-      
-      XShmPutImage (xinfo->display, xinfo->window, xinfo->gc, xinfo->ximage,
-		    0, 0, x0, y0, xinfo->ximage->width, xinfo->ximage->height,
-		    True);
-      XFlush (xinfo->display);
-      
-      while (!XCheckTypedEvent (xinfo->display, CompletionType, &xev))
-	 ;
-   }
-   else 
-#endif /* USE_SHM */
-   {
-      xinfo->ximage->data = (char *) xinfo->pixels; 
-      XPutImage (xinfo->display, xinfo->window, xinfo->gc, xinfo->ximage, 0, 0,
-		 x0, y0, xinfo->ximage->width, xinfo->ximage->height);
-   }
-}
-
-void
-close_window (x11_info_t *xinfo)
-{
-#ifdef USE_SHM
-   if (shmem_flag && xinfo->ximage)
-   {
-      XShmDetach (xinfo->display, &shminfo1);
-      XDestroyImage (xinfo->ximage);
-      xinfo->ximage = NULL;
-      shmdt (shminfo1.shmaddr);
-   }
-   else
-#endif /* USE_SHM */
-   if (xinfo->ximage)
-   {
-      XDestroyImage (xinfo->ximage);
-      xinfo->ximage = NULL;
-   }
-   if (xinfo->display)
-   {
-      XCloseDisplay (xinfo->display);
-      xinfo->display = NULL;
-   }
-}
-
-x11_info_t *
-open_window (const char *titlename, const char *iconname,
-	     unsigned width, unsigned height)
-/*
- *  Open a X11 window of size 'width'x'height'.
- *  If 'color' is false then allocate a colormap with grayscales.
- *  Window and icon titles are given by 'titlename' and 'iconname',
- *  respectively.
- *
- *  Return value:
- *	X11 info struct containing display, gc, window ID and colormap.
- */
-{
-   XVisualInfo		visual_template; /* template for XGetVisualInfo() */
-   XVisualInfo		visual_info;	/* return value of XGetVisualInfo() */
-   int			visual_n;	/* # of matches of XGetVisualInfo */
-   XEvent		xev;		
-   XSizeHints		hint;		
-   XSetWindowAttributes xswa;		
-   unsigned int		fg, bg;		/* foreground and background color */
-   unsigned int		mask;		/* event mask */
-   x11_info_t		*xinfo = calloc (1, sizeof (x11_info_t));
-   long                 visual_mask;
-   
-   if (!xinfo)
-      error ("Out of memory");
-   /*
-    *  Initialization of display
-    */
-   xinfo->display = XOpenDisplay (NULL);
-   if (xinfo->display == NULL)
-      error ("Can't open display.\n"
-	     "Make sure that your environment variable DISPLAY "
-	     "is set correctly.");
-
-   xinfo->screen = DefaultScreen (xinfo->display);
-   xinfo->gc     = DefaultGC (xinfo->display, xinfo->screen);
-
-   {
-      unsigned   depth [] 	= {32, 24, 16};
-      int        class [] 	= {TrueColor, PseudoColor};
-      const char *class_text [] = {"TrueColor", "PseudoColor"};
-      Status     found 		= 0;
-      unsigned   d, c;
-
-      for (d = 0; !found && d < sizeof (depth) / sizeof (unsigned); d++)
-	 for (c = 0; !found && c < sizeof (class) / sizeof (int); c++)
-	 {
-	    found = XMatchVisualInfo (xinfo->display, xinfo->screen,
-				      depth [d], class [c], &visual_info);
-	    if (found)
-	       fprintf (stderr, "%s : %d bit colordepth.\n",
-			class_text [c], depth [d]);
-	 }
-      if (!found && fiasco_get_verbosity ())
-	 error ("Can't find a 16/24/32 bit TrueColor/DirectColor display");
-   }
-   
-   /* Width and height of the display window */
-   hint.x = hint.y = 0;
-   hint.min_width  = hint.max_width  = hint.width  = width;
-   hint.min_height = hint.max_height = hint.height = height;
-   hint.flags = PSize | PMinSize | PMaxSize;
-
-   /* Get some colors */
-   bg = WhitePixel (xinfo->display, xinfo->screen);
-   fg = BlackPixel (xinfo->display, xinfo->screen);
-
-   /* Make the window */
-   mask = CWBackPixel | CWBorderPixel;
-   if (visual_info.depth >= 16)
-   {
-      mask |= CWColormap;
-      xswa.colormap = XCreateColormap (xinfo->display,
-				       DefaultRootWindow (xinfo->display),
-				       visual_info.visual, AllocNone);
-   }
-   xswa.background_pixel = bg;
-   xswa.border_pixel     = fg;
-   xinfo->window = XCreateWindow (xinfo->display,
-				  DefaultRootWindow (xinfo->display), 0, 0,
-				  width, height, 1, visual_info.depth,
-				  InputOutput, visual_info.visual,
-				  mask, &xswa);
-
-   XSelectInput (xinfo->display, xinfo->window, StructureNotifyMask);
-
-   /* Tell other applications about this window */
-   XSetStandardProperties (xinfo->display, xinfo->window, titlename, iconname,
-			   None, NULL, 0, &hint);
-
-   /* Map window. */
-   XMapWindow (xinfo->display, xinfo->window);
-
-   /* Wait for map. */
-   do
-   {
-      XNextEvent (xinfo->display, &xev);
-   }
-   while (xev.type != MapNotify || xev.xmap.event != xinfo->window);
-
-   /* Allocate colors */
-
-   return xinfo;
-}
-
-void
-alloc_ximage (x11_info_t *xinfo, unsigned width, unsigned height)
-/*
- *  Allocate ximage of size 'width'x'height'.
- *  If USE_SHM is defined then use shared memory extensions.
- *
- *  No return value.
- *
- *  Side effects:
- *	'ximage->ximage' and 'ximage->pixels' are set to useful values.
- */
-{
-   char dummy;
-   
-#ifdef USE_SHM
-   if (XShmQueryExtension(xinfo->display))
-   {
-      if (fiasco_get_verbosity ())
-	 fprintf (stderr, "Trying shared memory.\n");
-      shmem_flag = 1;
-   }
-   else
-   {
-      shmem_flag = 0;
-      if (fiasco_get_verbosity ())
-	 fprintf (stderr,
-              "Shared memory does not work on this system\n"
-              "Reverting to normal Xlib.\n");
-   }
-
-   if (shmem_flag)
-      CompletionType = XShmGetEventBase (xinfo->display) + ShmCompletion;
-
-   InstallXErrorHandler (xinfo);
-
-   if (shmem_flag)
-   {
-      xinfo->ximage = XShmCreateImage (xinfo->display,
-				       DefaultVisual (xinfo->display,
-						      xinfo->screen),
-				       DefaultDepth (xinfo->display,
-						     xinfo->screen), ZPixmap,
-				       NULL, &shminfo1, width, height);
-
-      /* If no go, then revert to normal Xlib calls. */
-
-      if (xinfo->ximage == NULL)
-      {
-	 if (fiasco_get_verbosity ())
-	    fprintf (stderr,
-		     "Shared memory error, disabling (Ximage error).\n");
-	 goto shmemerror;
-      }
-
-      /* Success here, continue. */
-
-      shminfo1.shmid = shmget (IPC_PRIVATE, xinfo->ximage->bytes_per_line
-			       * xinfo->ximage->height, IPC_CREAT | 0777);
-
-      if (shminfo1.shmid < 0)
-      {
-	 XDestroyImage (xinfo->ximage);
-	 if (fiasco_get_verbosity ())
-	    fprintf (stderr,
-		     "Shared memory error, disabling (seg id error).\n");
-	 goto shmemerror;
-      }
-
-      shminfo1.shmaddr = (char *) shmat (shminfo1.shmid, 0, 0);
-      shminfo2.shmaddr = (char *) shmat (shminfo2.shmid, 0, 0);
-
-      if (shminfo1.shmaddr == ((char *) -1))
-      {
-	 XDestroyImage (xinfo->ximage);
-	 if (shminfo1.shmaddr != ((char *) -1))
-	    shmdt (shminfo1.shmaddr);
-	 if (fiasco_get_verbosity ())
-	    fprintf (stderr,
-		     "Shared memory error, disabling (address error).\n");
-	 goto shmemerror;
-      }
-
-      xinfo->ximage->data = shminfo1.shmaddr;
-      xinfo->pixels       = (byte_t *) xinfo->ximage->data;
-      shminfo1.readOnly   = False;
-
-      XShmAttach (xinfo->display, &shminfo1);
-      XSync (xinfo->display, False);
-
-      if (gXErrorFlag)
-      {
-	 /* Ultimate failure here. */
-	 XDestroyImage (xinfo->ximage);
-	 shmdt (shminfo1.shmaddr);
-	 if (fiasco_get_verbosity ())
-	    fprintf (stderr, "Shared memory error, disabling.\n");
-	 gXErrorFlag = 0;
-	 goto shmemerror;
-      }
-      else
-	 shmctl (shminfo1.shmid, IPC_RMID, 0);
-      if (fiasco_get_verbosity ())
-	 fprintf (stderr, "Sharing memory.\n");
-   }
-   else
-   {
-     shmemerror:
-      shmem_flag = 0;
-#endif /* USE_SHM */
-
-      xinfo->ximage = XCreateImage (xinfo->display,
-				    DefaultVisual (xinfo->display,
-						   xinfo->screen),
-				    DefaultDepth (xinfo->display,
-						  xinfo->screen),
-				    ZPixmap, 0, &dummy, width, height, 8, 0);
-      xinfo->pixels = calloc (width * height,
-			      xinfo->ximage->depth <= 8
-			      ? sizeof (byte_t)
-			      : (xinfo->ximage->depth <= 16
-				 ? sizeof (u_word_t) : sizeof (unsigned int)));
-      if (!xinfo->pixels)
-	 error ("Out of memory.");
-    
-#ifdef USE_SHM
-   }
-
-   DeInstallXErrorHandler (xinfo);
-#endif /* USE_SHM */
-}
-
-#endif /* not X_DISPLAY_MISSING */
diff --git a/converter/other/fiasco/display.h b/converter/other/fiasco/display.h
deleted file mode 100644
index 8049456a..00000000
--- a/converter/other/fiasco/display.h
+++ /dev/null
@@ -1,49 +0,0 @@
-/*
- *  display.h
- *
- *  Written by:		Ullrich Hafner
- *		
- *  This file is part of FIASCO (Fractal Image And Sequence COdec)
- *  Copyright (C) 1994-2000 Ullrich Hafner
- */
-
-/*
- *  $Date: 2000/06/14 20:51:17 $
- *  $Author: hafner $
- *  $Revision: 5.1 $
- *  $State: Exp $
- */
-
-#ifndef _DISPLAY_H
-#define _DISPLAY_H
-
-#ifndef X_DISPLAY_MISSING
-
-#include <X11/Xlib.h>
-
-#include "types.h"
-#include "image.h"
-
-typedef struct x11_info
-{
-   Display *display;
-   int	    screen;			/* default screen number */
-   Window   window;			
-   XImage  *ximage;
-   GC	    gc;
-   byte_t  *pixels;
-} x11_info_t;
-
-void
-display_image (unsigned x0, unsigned y0, x11_info_t *xinfo);
-void
-close_window (x11_info_t *xinfo);
-x11_info_t *
-open_window (const char *titlename, const char *iconname,
-	     unsigned width, unsigned height);
-void
-alloc_ximage (x11_info_t *xinfo, unsigned width, unsigned height);
-
-#endif /* X_DISPLAY_MISSING */
-
-#endif /* not _DISPLAY_H */
diff --git a/converter/other/fiasco/fiasco.h b/converter/other/fiasco/fiasco.h
index 88f999fc..48226c47 100644
--- a/converter/other/fiasco/fiasco.h
+++ b/converter/other/fiasco/fiasco.h
@@ -1,8 +1,8 @@
 /*
- *  fiasco.h		
+ *  fiasco.h
+ *
+ *  Written by:         Ullrich Hafner
  *
- *  Written by:		Ullrich Hafner
- *		
  *  This file is part of FIASCO (Fractal Image And Sequence COdec)
  *  Copyright (C) 1994-2000 Ullrich Hafner
  *
@@ -46,7 +46,7 @@
 __BEGIN_DECLS
 
 /****************************************************************************
-			  FIASCO data types
+                          FIASCO data types
 ****************************************************************************/
 
 /*
@@ -56,9 +56,9 @@ __BEGIN_DECLS
  *  FIASCO_ULTIMATE_VERBOSITY: Show debugging output
  */
 typedef enum {FIASCO_NO_VERBOSITY,
-	      FIASCO_SOME_VERBOSITY,
-	      FIASCO_ULTIMATE_VERBOSITY} fiasco_verbosity_e;
-  
+              FIASCO_SOME_VERBOSITY,
+              FIASCO_ULTIMATE_VERBOSITY} fiasco_verbosity_e;
+
 /*
  *  Image tiling methods:
  *  VARIANCE_ASC:  Tiles are sorted by variance.
@@ -71,9 +71,9 @@ typedef enum {FIASCO_NO_VERBOSITY,
  *                 in the upper left corner.
  */
 typedef enum {FIASCO_TILING_SPIRAL_ASC,
-	      FIASCO_TILING_SPIRAL_DSC,
-	      FIASCO_TILING_VARIANCE_ASC,
-	      FIASCO_TILING_VARIANCE_DSC} fiasco_tiling_e;
+              FIASCO_TILING_SPIRAL_DSC,
+              FIASCO_TILING_VARIANCE_ASC,
+              FIASCO_TILING_VARIANCE_DSC} fiasco_tiling_e;
 
 /*
  *  Range of reduced precision format:
@@ -83,29 +83,29 @@ typedef enum {FIASCO_TILING_SPIRAL_ASC,
  *  FIASCO_RPF_RANGE_2_00: use interval [-2.00,2.00]
  */
 typedef enum {FIASCO_RPF_RANGE_0_75,
-	      FIASCO_RPF_RANGE_1_00,
-	      FIASCO_RPF_RANGE_1_50,
-	      FIASCO_RPF_RANGE_2_00} fiasco_rpf_range_e;
+              FIASCO_RPF_RANGE_1_00,
+              FIASCO_RPF_RANGE_1_50,
+              FIASCO_RPF_RANGE_2_00} fiasco_rpf_range_e;
 
 /*
  *  Type of progress meter to be used during coding
  *  FIASCO_PROGRESS_NONE:    no output at all
- *  FIASCO_PROGRESS_BAR:     RPM style progress bar using 50 hash marks ###### 
- *  FIASCO_PROGRESS_PERCENT: percentage meter 50% 
+ *  FIASCO_PROGRESS_BAR:     RPM style progress bar using 50 hash marks ######
+ *  FIASCO_PROGRESS_PERCENT: percentage meter 50%
  */
 typedef enum {FIASCO_PROGRESS_NONE,
-	      FIASCO_PROGRESS_BAR,
-	      FIASCO_PROGRESS_PERCENT} fiasco_progress_e;
+              FIASCO_PROGRESS_BAR,
+              FIASCO_PROGRESS_PERCENT} fiasco_progress_e;
 
 /*
  * Class to encapsulate FIASCO images.
  */
 typedef struct fiasco_image
 {
-   void		(*delete)	(struct fiasco_image *image);
-   unsigned	(*get_width)	(struct fiasco_image *image);
-   unsigned	(*get_height)	(struct fiasco_image *image);
-   int		(*is_color)	(struct fiasco_image *image);
+   void         (*delete)       (struct fiasco_image *image);
+   unsigned     (*get_width)    (struct fiasco_image *image);
+   unsigned     (*get_height)   (struct fiasco_image *image);
+   int          (*is_color)     (struct fiasco_image *image);
    void *private;
 } fiasco_image_t;
 
@@ -114,17 +114,17 @@ typedef struct fiasco_image
  */
 typedef struct fiasco_decoder
 {
-   int			(*delete)	 (struct fiasco_decoder *decoder);
-   int			(*write_frame)   (struct fiasco_decoder *decoder,
-					  const char *filename);
-   fiasco_image_t *	(*get_frame)     (struct fiasco_decoder *decoder);
-   unsigned		(*get_length)    (struct fiasco_decoder *decoder);
-   unsigned		(*get_rate)	 (struct fiasco_decoder *decoder);
-   unsigned		(*get_width)	 (struct fiasco_decoder *decoder);
-   unsigned		(*get_height)	 (struct fiasco_decoder *decoder);
-   const char *		(*get_title)	 (struct fiasco_decoder *decoder);
-   const char *		(*get_comment)	 (struct fiasco_decoder *decoder);
-   int			(*is_color)	 (struct fiasco_decoder *decoder);
+   int                  (*delete)        (struct fiasco_decoder *decoder);
+   int                  (*write_frame)   (struct fiasco_decoder *decoder,
+                                          const char *filename);
+   fiasco_image_t *     (*get_frame)     (struct fiasco_decoder *decoder);
+   unsigned             (*get_length)    (struct fiasco_decoder *decoder);
+   unsigned             (*get_rate)      (struct fiasco_decoder *decoder);
+   unsigned             (*get_width)     (struct fiasco_decoder *decoder);
+   unsigned             (*get_height)    (struct fiasco_decoder *decoder);
+   const char *         (*get_title)     (struct fiasco_decoder *decoder);
+   const char *         (*get_comment)   (struct fiasco_decoder *decoder);
+   int                  (*is_color)      (struct fiasco_decoder *decoder);
    void *private;
 } fiasco_decoder_t;
 
@@ -135,43 +135,43 @@ typedef struct fiasco_c_options
 {
    void (*delete)            (struct fiasco_c_options *options);
    int (*set_tiling)         (struct fiasco_c_options *options,
-			      fiasco_tiling_e method,
-			      unsigned exponent);
+                              fiasco_tiling_e method,
+                              unsigned exponent);
    int (*set_frame_pattern)  (struct fiasco_c_options *options,
-			      const char *pattern);
+                              const char *pattern);
    int (*set_basisfile)      (struct fiasco_c_options *options,
-			      const char *filename);
+                              const char *filename);
    int (*set_chroma_quality) (struct fiasco_c_options *options,
-			      float quality_factor,
-			      unsigned dictionary_size);
+                              float quality_factor,
+                              unsigned dictionary_size);
    int (*set_optimizations)  (struct fiasco_c_options *options,
-			      unsigned min_block_level,
-			      unsigned max_block_level,
-			      unsigned max_elements,
-			      unsigned dictionary_size,
-			      unsigned optimization_level);
+                              unsigned min_block_level,
+                              unsigned max_block_level,
+                              unsigned max_elements,
+                              unsigned dictionary_size,
+                              unsigned optimization_level);
    int (*set_prediction)     (struct fiasco_c_options *options,
-			      int intra_prediction,
-			      unsigned min_block_level,
-			      unsigned max_block_level);
+                              int intra_prediction,
+                              unsigned min_block_level,
+                              unsigned max_block_level);
    int (*set_video_param)    (struct fiasco_c_options *options,
-			      unsigned frames_per_second,
-			      int half_pixel_prediction,
-			      int cross_B_search,
-			      int B_as_past_ref);
+                              unsigned frames_per_second,
+                              int half_pixel_prediction,
+                              int cross_B_search,
+                              int B_as_past_ref);
    int (*set_quantization)   (struct fiasco_c_options *options,
-			      unsigned mantissa,
-			      fiasco_rpf_range_e range,
-			      unsigned dc_mantissa,
-			      fiasco_rpf_range_e dc_range);
+                              unsigned mantissa,
+                              fiasco_rpf_range_e range,
+                              unsigned dc_mantissa,
+                              fiasco_rpf_range_e dc_range);
    int (*set_progress_meter) (struct fiasco_c_options *options,
-			      fiasco_progress_e type);
+                              fiasco_progress_e type);
    int (*set_smoothing)      (struct fiasco_c_options *options,
-			      int smoothing);
+                              int smoothing);
    int (*set_comment)        (struct fiasco_c_options *options,
-			      const char *comment);
+                              const char *comment);
    int (*set_title)          (struct fiasco_c_options *options,
-			      const char *title);
+                              const char *title);
    void *private;
 } fiasco_c_options_t;
 
@@ -182,32 +182,32 @@ typedef struct fiasco_d_options
 {
    void (*delete)            (struct fiasco_d_options *options);
    int (*set_smoothing)      (struct fiasco_d_options *options,
-			      int smoothing);
+                              int smoothing);
    int (*set_magnification)  (struct fiasco_d_options *options,
-			      int level);
+                              int level);
    int (*set_4_2_0_format)   (struct fiasco_d_options *options,
-			      int format);
+                              int format);
    void *private;
 } fiasco_d_options_t;
 
 /*
  * Class to convert internal FIASCO image structure to a XImage structure.
- * Method `renderer()' is used to convert internal image to XImage. 
- * Method `delete()' is used to delete and free internal image. 
+ * Method `renderer()' is used to convert internal image to XImage.
+ * Method `delete()' is used to delete and free internal image.
  */
 typedef struct fiasco_renderer
 {
    int  (*render) (const struct fiasco_renderer *this,
-		   unsigned char *data,
-		   const fiasco_image_t *fiasco_image);
+                   unsigned char *data,
+                   const fiasco_image_t *fiasco_image);
    void (*delete) (struct fiasco_renderer *this);
    void *private;
 } fiasco_renderer_t;
 
 /****************************************************************************
-		       miscellaneous functions
+                       miscellaneous functions
 ****************************************************************************/
-  
+
 /* Get last error message of FIASCO library */
 const char *fiasco_get_error_message (void);
 
@@ -218,19 +218,19 @@ void fiasco_set_verbosity (fiasco_verbosity_e level);
 fiasco_verbosity_e fiasco_get_verbosity (void);
 
 /****************************************************************************
-			  decoder functions
+                          decoder functions
 ****************************************************************************/
 
 /* Decode FIASCO image or sequence */
 fiasco_decoder_t *fiasco_decoder_new (const char *filename,
-				      const fiasco_d_options_t *options);
+                                      const fiasco_d_options_t *options);
 
 /* Flush and discard FIASCO decoder */
 int fiasco_decoder_delete (fiasco_decoder_t *decoder);
 
 /* Decode next FIASCO frame and write to PNM image 'filename' */
 int fiasco_decoder_write_frame (fiasco_decoder_t *decoder,
-				const char *filename);
+                                const char *filename);
 
 /* Decode next FIASCO frame to FIASCO image structure */
 fiasco_image_t *fiasco_decoder_get_frame (fiasco_decoder_t *decoder);
@@ -259,7 +259,7 @@ const char *
 fiasco_decoder_get_comment (fiasco_decoder_t *decoder);
 
 /****************************************************************************
-			  image functions
+                          image functions
 ****************************************************************************/
 
 /* Create FIASCO image (from PNM image file) */
@@ -275,7 +275,7 @@ fiasco_image_new_stream(FILE *       const ifP,
                         int          const format);
 
 /* Discard FIASCO image */
-void fiasco_image_delete (fiasco_image_t *image); 
+void fiasco_image_delete (fiasco_image_t *image);
 
 /* Get width of FIASCO image or sequence */
 unsigned fiasco_image_get_width (fiasco_image_t *image);
@@ -287,14 +287,14 @@ unsigned fiasco_image_get_height (fiasco_image_t *image);
 int fiasco_image_is_color (fiasco_image_t *image);
 
 /****************************************************************************
-			  renderer functions
+                          renderer functions
 ****************************************************************************/
 
 /* Constructor of FIASCO image structure to a XImage renderer */
 fiasco_renderer_t *
 fiasco_renderer_new (unsigned long red_mask, unsigned long green_mask,
-		     unsigned long blue_mask, unsigned bpp,
-		     int double_resolution);
+                     unsigned long blue_mask, unsigned bpp,
+                     int double_resolution);
 
 /* Destructor of FIASCO image structure to a XImage renderer */
 void
@@ -303,21 +303,21 @@ fiasco_renderer_delete (fiasco_renderer_t *renderer);
 /* FIASCO image structure to a XImage renderer */
 int
 fiasco_renderer_render (const fiasco_renderer_t *renderer,
-			unsigned char *ximage,
-			const fiasco_image_t *fiasco_image);
+                        unsigned char *ximage,
+                        const fiasco_image_t *fiasco_image);
 
 /****************************************************************************
-			   coder functions
+                           coder functions
 ****************************************************************************/
 
 /* Encode image or sequence by FIASCO */
 int fiasco_coder (char const * const *inputname,
-		  const char *outputname,
-		  float quality,
-		  const fiasco_c_options_t *options);
+                  const char *outputname,
+                  float quality,
+                  const fiasco_c_options_t *options);
 
 /****************************************************************************
-		 coder options functions
+                 coder options functions
 ****************************************************************************/
 
 /* FIASCO additional options constructor */
@@ -328,25 +328,25 @@ void fiasco_c_options_delete (fiasco_c_options_t *options);
 
 /* Define `smoothing'-percentage along partitioning borders.*/
 int fiasco_c_options_set_smoothing (fiasco_c_options_t *options,
-				    int smoothing);
+                                    int smoothing);
 
 /* Set type of frame prediction for sequence of frames */
 int fiasco_c_options_set_frame_pattern (fiasco_c_options_t *options,
-					const char *pattern);
+                                        const char *pattern);
 
 /* Set method and number of tiles for image tiling */
 int fiasco_c_options_set_tiling (fiasco_c_options_t *options,
-				 fiasco_tiling_e method,
-				 unsigned exponent);
+                                 fiasco_tiling_e method,
+                                 unsigned exponent);
 
 /* Set FIASCO initial basis file */
 int fiasco_c_options_set_basisfile (fiasco_c_options_t *options,
-				    const char *filename);
+                                    const char *filename);
 
 /* Set quality and dictionary size of chroma compression */
 int fiasco_c_options_set_chroma_quality (fiasco_c_options_t *options,
-					 float quality_factor,
-					 unsigned dictionary_size);
+                                         float quality_factor,
+                                         unsigned dictionary_size);
 
 /*
  *  Since FIASCO internally works with binary trees, all functions
@@ -354,62 +354,62 @@ int fiasco_c_options_set_chroma_quality (fiasco_c_options_t *options,
  *  the corresponding binary tree than the traditional `width' and
  *  `height' arguments.  Refer to following table to convert these
  *  values:
- *  
+ *
  *  level | width | height
  *  ------+-------+--------
- *    0   |    1  |    1  
- *    1   |    1  |    2  
- *    2   |    2  |    2  
- *    3   |    2  |    4  
- *    4   |    4  |    4  
- *    5   |    4  |    8  
- *    6   |    8  |    8  
+ *    0   |    1  |    1
+ *    1   |    1  |    2
+ *    2   |    2  |    2
+ *    3   |    2  |    4
+ *    4   |    4  |    4
+ *    5   |    4  |    8
+ *    6   |    8  |    8
  *    7   |    8  |   16
  *
  */
-   
+
 /* Set various optimization parameters. */
 int fiasco_c_options_set_optimizations (fiasco_c_options_t *options,
-					unsigned min_block_level,
-					unsigned max_block_level,
-					unsigned max_elements,
-					unsigned dictionary_size,
-					unsigned optimization_level);
+                                        unsigned min_block_level,
+                                        unsigned max_block_level,
+                                        unsigned max_elements,
+                                        unsigned dictionary_size,
+                                        unsigned optimization_level);
 
 /* Set minimum and maximum size of image block prediction */
 int fiasco_c_options_set_prediction (fiasco_c_options_t *options,
-				     int intra_prediction,
-				     unsigned min_block_level,
-				     unsigned max_block_level);
+                                     int intra_prediction,
+                                     unsigned min_block_level,
+                                     unsigned max_block_level);
 
 /*  Set various parameters used for video compensation */
 int fiasco_c_options_set_video_param (fiasco_c_options_t *options,
-				      unsigned frames_per_second,
-				      int half_pixel_prediction,
-				      int cross_B_search,
-				      int B_as_past_ref);
+                                      unsigned frames_per_second,
+                                      int half_pixel_prediction,
+                                      int cross_B_search,
+                                      int B_as_past_ref);
 
 /* Set accuracy of coefficients quantization */
 int fiasco_c_options_set_quantization (fiasco_c_options_t *options,
-				       unsigned mantissa,
-				       fiasco_rpf_range_e range,
-				       unsigned dc_mantissa,
-				       fiasco_rpf_range_e dc_range);
+                                       unsigned mantissa,
+                                       fiasco_rpf_range_e range,
+                                       unsigned dc_mantissa,
+                                       fiasco_rpf_range_e dc_range);
 
 /* Set type of progress meter */
 int fiasco_c_options_set_progress_meter (fiasco_c_options_t *options,
-					 fiasco_progress_e type);
+                                         fiasco_progress_e type);
 
 /*  Set comment of FIASCO stream */
 int fiasco_c_options_set_comment (fiasco_c_options_t *options,
-				  const char *comment);
+                                  const char *comment);
 
 /*  Set title of FIASCO stream */
 int fiasco_c_options_set_title (fiasco_c_options_t *options,
-				const char *title);
+                                const char *title);
 
 /****************************************************************************
-		 decoder options functions
+                 decoder options functions
 ****************************************************************************/
 
 /* FIASCO additional options constructor */
@@ -421,15 +421,15 @@ void fiasco_d_options_delete (fiasco_d_options_t *options);
 
 /* Define `smoothing'-percentage along partitioning borders.*/
 int fiasco_d_options_set_smoothing (fiasco_d_options_t *options,
-				  int smoothing);
+                                  int smoothing);
 
 /* Set magnification-'level' of decoded image */
 int fiasco_d_options_set_magnification (fiasco_d_options_t *options,
-				      int level);
+                                      int level);
 
 /* Set image format to 4:2:0 or 4:4:4 */
 int fiasco_d_options_set_4_2_0_format (fiasco_d_options_t *options,
-				     int format);
+                                     int format);
 
 __END_DECLS
 
diff --git a/converter/other/fiasco/fiascotopnm.c b/converter/other/fiasco/fiascotopnm.c
index e95e27fc..340f9d4e 100644
--- a/converter/other/fiasco/fiascotopnm.c
+++ b/converter/other/fiasco/fiascotopnm.c
@@ -1,13 +1,13 @@
 /*
- *  dwfa.c:     Decoding of WFA-files
+ *  Decode WFA-files
  *
  *  Written by:     Ullrich Hafner
  *          Michael Unger
- *      
+ *
  *  This file is part of FIASCO (Fractal Image And Sequence COdec)
  *  Copyright (C) 1994-2000 Ullrich Hafner
  */
- 
+
 /*
  *  $Date: 2000/10/28 17:39:29 $
  *  $Author: hafner $
@@ -25,99 +25,65 @@
 #include <stdlib.h>
 #include <string.h>
 #include <math.h>
+#include <getopt.h>
 
+#include "mallocvar.h"
 #include "nstring.h"
 
 #include "types.h"
 #include "macros.h"
 
-#include <getopt.h>
-
-#include "binerror.h"
 #include "misc.h"
 #include "params.h"
 #include "fiasco.h"
 
-#ifndef X_DISPLAY_MISSING
-
-#   include "display.h"
-#   include "buttons.h"
-
-static x11_info_t *xinfo = NULL;
-
-#endif /* not X_DISPLAY_MISSING */
-
-/*****************************************************************************
 
-                prototypes
-  
-*****************************************************************************/
 
-static int 
-checkargs (int argc, char **argv, bool_t *double_resolution, bool_t *panel,
-           int *fps, char **image_name, fiasco_d_options_t **options);
 static void
-video_decoder (const char *wfa_name, const char *image_name, bool_t panel,
-               bool_t double_resolution, int fps, fiasco_d_options_t *options);
-static void
-get_output_template (const char *image_name, const char *wfa_name,
-                     bool_t color, char **basename, char **suffix);
+getOutputTemplate(const char *  const imageName,
+                  const char *  const wfaName,
+                  bool_t        const color,
+                  const char ** const basename,
+                  const char ** const suffixP) {
+/*----------------------------------------------------------------------------
+
+  Generate image filename template for output of image sequences.
+  'wfa_name' is the filename of the WFA stream.
+  Images are either saved with filename 'basename'.'suffix' (still images)
+  or 'basename'.%03d.'suffix' (videos).
+-----------------------------------------------------------------------------*/
+    char * suffixLoc;
+
+    /* Generate filename template */
+    if (!imageName || streq(imageName, "") || streq(imageName, "-")) {
+        if (!wfaName || streq(wfaName, "-"))
+            *basename = strdup("stdin");
+        else
+            *basename = strdup(wfaName);
+        suffixLoc = NULL;
+    } else {
+        *basename = strdup(imageName);
+        suffixLoc = strrchr(*basename, '.');
+    }
 
-#ifndef X_DISPLAY_MISSING
+    if (suffixLoc) {
+        /* found name 'basename.suffix' */
 
-static void
-show_stored_frames (unsigned char * const *frame_buffer, int last_frame,
-                    x11_info_t *xinfo, binfo_t *binfo, size_t size,
-                    unsigned frame_time);
-
-#endif /* not X_DISPLAY_MISSING */
-
-/*****************************************************************************
-
-                public code
-  
-*****************************************************************************/
-
-int 
-main (int argc, char **argv)
-{
-    char               *image_name        = NULL; /* output filename */
-    bool_t              double_resolution = NO; /* double resolution of image */
-    bool_t              panel             = NO; /* control panel */
-    int             fps               = -1; /* frame display rate */
-    fiasco_d_options_t *options           = NULL; /* additional coder options */
-    int                 last_arg;    /* last processed cmdline parameter */
-
-    init_error_handling (argv[0]);
-
-    last_arg = checkargs (argc, argv, &double_resolution, &panel, &fps,
-                          &image_name, &options);
-   
-    if (last_arg >= argc)
-        video_decoder ("-", image_name, panel, double_resolution, fps, options);
-    else
-        while (last_arg++ < argc)
-            video_decoder (argv [last_arg - 1], image_name, panel,
-                           double_resolution, fps, options);
+        *suffixLoc = '\0';         /* remove dot from *basename*/
 
-    return 0;
+        if (*(suffixLoc+1) == '\0')
+            *suffixP = strdup(color ? "ppm" : "pgm");
+        else
+            *suffixP = strdup(suffixLoc + 1);
+    } else             /* no suffix found, generate one */
+        *suffixP = strdup(color ? "ppm" : "pgm");
 }
 
-/*****************************************************************************
 
-                private code
-  
-*****************************************************************************/
 
-static param_t params [] =
-{
-#ifdef X_DISPLAY_MISSING
+static param_t params [] = {
     {"output", "FILE", 'o', PSTR, {0}, "-",
      "Write raw PNM frame(s) to `%s'."},
-#else  /* not X_DISPLAY_MISSING */
-    {"output", "FILE", 'o', POSTR, {0}, NULL,
-     "Write raw PNM frame(s) to INPUT.ppm/pgm [or `%s']."},
-#endif /* not X_DISPLAY_MISSING */
     {"double", NULL, 'd', PFLAG, {0}, "FALSE",
      "Interpolate images to double size before display."},
     {"fast", NULL, 'r', PFLAG, {0}, "FALSE",
@@ -133,350 +99,166 @@ static param_t params [] =
     {NULL, NULL, 0, 0, {0}, NULL, NULL }
 };
 
-static int 
-checkargs (int argc, char **argv, bool_t *double_resolution, bool_t *panel,
-           int *fps, char **image_name, fiasco_d_options_t **options)
-/*
- *  Check validness of command line parameters and of the parameter files.
- *
- *  Return value.
- *  index in argv of the first argv-element that is not an option.
- *
- *  Side effects:
- *  'double_resolution', 'panel', 'fps', 'image_name' and 'options'
- *      are modified.
- */
-{
+static int
+checkargs(int                         argc,
+          const char **         const argv,
+          bool_t *              const double_resolution,
+          bool_t *              const panel,
+          int *                 const fps,
+          const char **         const image_name,
+          fiasco_d_options_t ** const options) {
+/*----------------------------------------------------------------------------
+  Check validness of command line parameters and of the parameter files.
+
+  Return value: index in argv of the first argv-element that is not an option.
+
+  Side effects:
+-----------------------------------------------------------------------------*/
     int optind;              /* last processed commandline param */
 
-    optind = parseargs (params, argc, argv,
-#ifdef X_DISPLAY_MISSING
-                        "Decode FIASCO-FILEs and write frame(s) to disk.",
-#else  /* not X_DISPLAY_MISSING */
-                        "Decode and display FIASCO-FILEs using X11.",
-#endif /* not X_DISPLAY_MISSING */
-                        "With no FIASCO-FILE, or if FIASCO-FILE is -, "
-                        "read standard input.\n"
-#ifndef X_DISPLAY_MISSING
-                        "With --output=[FILE] specified, "
-                        "write frames without displaying them.\n\n"
-#endif  /* not X_DISPLAY_MISSING */
-                        "Environment:\n"
-                        "FIASCO_DATA   Search path for automata files. "
-                        "Default: ./\n"
-                        "FIASCO_IMAGES Save path for image files. "
+    optind = parseargs(params, argc, argv,
+                       "Decode FIASCO-FILEs and write frame(s) to disk.",
+                       "With no FIASCO-FILE, or if FIASCO-FILE is -, "
+                       "read standard input.\n"
+                       "Environment:\n"
+                       "FIASCO_DATA   Search path for automata files. "
+                       "Default: ./\n"
+                       "FIASCO_IMAGES Save path for image files. "
                         "Default: ./", " [FIASCO-FILE]...",
-                        FIASCO_SHARE, "system.fiascorc", ".fiascorc");
+                       FIASCO_SHARE, "system.fiascorc", ".fiascorc");
 
     *image_name        =   (char *)   parameter_value (params, "output");
     *double_resolution = *((bool_t *) parameter_value (params, "double"));
     *panel             = *((bool_t *) parameter_value (params, "panel"));
-    *fps           = *((int *)    parameter_value (params, "framerate"));
+    *fps               = *((int *)    parameter_value (params, "framerate"));
 
-    /*
-     *  Additional options ... (have to be set with the fiasco_set_... methods)
+    /* Additional options ... (have to be set with the fiasco_set_... methods)
      */
-    *options = fiasco_d_options_new ();
+    *options = fiasco_d_options_new();
 
     {
-        int const n = *((int *) parameter_value (params, "smoothing"));
-      
-        if (!fiasco_d_options_set_smoothing (*options, MAX(-1, n)))
-            error (fiasco_get_error_message ());
+        int const n = *((int *)parameter_value(params, "smoothing"));
+
+        if (!fiasco_d_options_set_smoothing(*options, MAX(-1, n)))
+            pm_error("%s", fiasco_get_error_message());
     }
 
     {
-        int const n = *((int *) parameter_value (params, "magnify"));
-      
-        if (!fiasco_d_options_set_magnification (*options, n))
-            error (fiasco_get_error_message ());
+        int const n = *((int *)parameter_value(params, "magnify"));
+
+        if (!fiasco_d_options_set_magnification(*options, n))
+            pm_error("%s", fiasco_get_error_message());
     }
-   
+
     {
-        bool_t const n = *((bool_t *) parameter_value (params, "fast"));
-      
-        if (!fiasco_d_options_set_4_2_0_format (*options, n > 0 ? YES : NO))
-            error (fiasco_get_error_message ());
+        bool_t const n = *((bool_t *)parameter_value(params, "fast"));
+
+        if (!fiasco_d_options_set_4_2_0_format(*options, n > 0 ? YES : NO))
+            pm_error("%s", fiasco_get_error_message ());
     }
 
     return optind;
 }
 
+
+
 static void
-video_decoder (const char *wfa_name, const char *image_name, bool_t panel,
-               bool_t double_resolution, int fps, fiasco_d_options_t *options)
-{
-#ifndef X_DISPLAY_MISSING
-    fiasco_renderer_t  *renderer     = NULL;
-    unsigned char     **frame_buffer = NULL;
-    binfo_t            *binfo        = NULL; /* buttons info */
-#endif /* not X_DISPLAY_MISSING */
-   
-    do
-    {
-        unsigned      width, height, frames, n;
-        fiasco_decoder_t *decoder_state;
-        char             *filename;
-        char             *basename;   /* basename of decoded frame */
-        char             *suffix;     /* suffix of decoded frame */
-        unsigned      frame_time;
-      
-        if (!(decoder_state = fiasco_decoder_new (wfa_name, options)))
-            error (fiasco_get_error_message ());
-   
-        if (fps <= 0)         /* then use value of FIASCO file */ 
-            fps = fiasco_decoder_get_rate (decoder_state);
+video_decoder(const char *         const wfa_name,
+              const char *         const image_name,
+              bool_t               const panel,
+              bool_t               const double_resolution,
+              int                  const fpsArg,
+              fiasco_d_options_t * const options) {
+    do {
+        int                fps;
+        unsigned int       width, height;
+        unsigned int       frames;
+        unsigned int       n;
+        fiasco_decoder_t * decoder_state;
+        char *             filename;
+        const char *       basename;   /* basename of decoded frame */
+        const char *       suffix;     /* suffix of decoded frame */
+        unsigned int       frame_time;
+
+        if (!(decoder_state = fiasco_decoder_new(wfa_name, options)))
+            pm_error("%s", fiasco_get_error_message ());
+
+        if (fpsArg <= 0)         /* then use value of FIASCO file */
+            fps = fiasco_decoder_get_rate(decoder_state);
+        else
+            fps = fpsArg;
+
         frame_time = fps ? (1000 / fps) : (1000 / 25);
 
-        if (!(width = fiasco_decoder_get_width (decoder_state)))
-            error (fiasco_get_error_message ());
-      
-        if (!(height = fiasco_decoder_get_height (decoder_state)))
-            error (fiasco_get_error_message ());
-
-        if (!(frames = fiasco_decoder_get_length (decoder_state)))
-            error (fiasco_get_error_message ());
-      
-        get_output_template (image_name, wfa_name,
-                             fiasco_decoder_is_color (decoder_state),
-                             &basename, &suffix);
-
-        filename = calloc (strlen (basename) + strlen (suffix) + 2
-                           + 10 + (int) (log10 (frames) + 1), sizeof (char));
-        if (!filename)
-            error ("Out of memory.");
-
-        for (n = 0; n < frames; n++)
-        {
+        if (!(width = fiasco_decoder_get_width(decoder_state)))
+            pm_error("%s", fiasco_get_error_message ());
+
+        if (!(height = fiasco_decoder_get_height(decoder_state)))
+            pm_error("%s", fiasco_get_error_message ());
+
+        if (!(frames = fiasco_decoder_get_length(decoder_state)))
+            pm_error("%s", fiasco_get_error_message ());
+
+        getOutputTemplate(image_name, wfa_name,
+                          fiasco_decoder_is_color(decoder_state),
+                          &basename, &suffix);
+
+        MALLOCARRAY_NOFAIL(filename,
+                           strlen (basename) + strlen (suffix) + 2
+                           + 10 + (int) (log10 (frames) + 1));
+
+        for (n = 0; n < frames; ++n) {
             clock_t fps_timer;     /* frames per second timer struct */
-     
-            prg_timer (&fps_timer, START);
-     
-            if (image_name)        /* just write frame to disk */
-            {
-                if (frames == 1)        /* just one image */
-                {
-                    if (streq (image_name, "-"))
-                        strcpy (filename, "-");
+
+            prg_timer(&fps_timer, START);
+
+            if (image_name) {
+                /* just write frame to disk */
+                if (frames == 1) {
+                    if (streq(image_name, "-"))
+                        strcpy(filename, "-");
                     else
-                        sprintf (filename, "%s.%s", basename, suffix);
-                }
-                else
-                {
-                    fprintf (stderr, "Decoding frame %d to file `%s.%0*d.%s\n",
-                             n, basename, (int) (log10 (frames - 1) + 1),
-                             n, suffix);
-                    sprintf (filename, "%s.%0*d.%s", basename,
-                             (int) (log10 (frames - 1) + 1), n, suffix);
+                        sprintf(filename, "%s.%s", basename, suffix);
+                } else {
+                    pm_message("Decoding frame %d to file `%s.%0*d.%s",
+                               n, basename, (int) (log10 (frames - 1) + 1),
+                               n, suffix);
+                    sprintf(filename, "%s.%0*d.%s", basename,
+                            (int) (log10 (frames - 1) + 1), n, suffix);
                 }
 
                 if (!fiasco_decoder_write_frame (decoder_state, filename))
-                    error (fiasco_get_error_message ());
+                    pm_error("%s", fiasco_get_error_message ());
             }
-#ifndef X_DISPLAY_MISSING
-            else
-            {
-                fiasco_image_t *frame;
-        
-                if (!(frame = fiasco_decoder_get_frame (decoder_state)))
-                    error (fiasco_get_error_message ());
-        
-                if (frames == 1)
-                    panel = NO;
-
-                if (xinfo == NULL)      /* initialize X11 window */
-                {
-                    const char * const title = 
-                        fiasco_decoder_get_title (decoder_state);
-                    char        titlename [MAXSTRLEN];
-
-           
-                    sprintf (titlename, "dfiasco " VERSION ": %s",
-                             strlen (title) > 0 ? title : wfa_name);
-                    xinfo = 
-                        open_window (titlename, "dfiasco",
-                                     (width  << (double_resolution ? 1 : 0)),
-                                     (height << (double_resolution ? 1 : 0))
-                                     + (panel ? 30 : 0));
-                    alloc_ximage (xinfo, width  << (double_resolution ? 1 : 0),
-                                  height << (double_resolution ? 1 : 0));
-                    if (panel)       /* initialize button panel */
-                        binfo = init_buttons (xinfo, n, frames, 30, 10);
-                    renderer = 
-                        fiasco_renderer_new (xinfo->ximage->red_mask,
-                                             xinfo->ximage->green_mask,
-                                             xinfo->ximage->blue_mask,
-                                             xinfo->ximage->bits_per_pixel,
-                                             double_resolution);
-                    if (!renderer)
-                        error (fiasco_get_error_message ());
-                }
-                renderer->render (renderer, xinfo->pixels, frame);
-                frame->delete (frame);
-        
-                if (frame_buffer != NULL) /* store next frame */
-                {
-                    size_t size = (width  << (double_resolution ? 1 : 0))
-                        * (height << (double_resolution ? 1 : 0))
-                        * (xinfo->ximage->depth <= 8
-                           ? sizeof (byte_t)
-                           : (xinfo->ximage->depth <= 16
-                              ? sizeof (u_word_t)
-                              : sizeof (unsigned int)));
-
-                    frame_buffer [n] = malloc (size);
-                    if (!frame_buffer [n])
-                        error ("Out of memory.");
-                    memcpy (frame_buffer [n], xinfo->pixels, size);
-
-                    if (n == frames - 1)
-                    {
-                        show_stored_frames (frame_buffer, frames - 1,
-                                            xinfo, binfo, size, frame_time);
-                        break;
-                    }
-                }
-
-                display_image (0, 0, xinfo);
-                if (frames == 1)
-                    wait_for_input (xinfo);
-                else if (panel)
-                {
-                    check_events (xinfo, binfo, n, frames);
-                    if (binfo->pressed [QUIT_BUTTON]) 
-                        /* start from beginning */
-                        break;
-                    if (binfo->pressed [STOP_BUTTON]) 
-                        /* start from beginning */
-                        n = frames;
-           
-                    if (binfo->pressed [RECORD_BUTTON] && frame_buffer == NULL)
-                    {
-                        n = frames;
-                        frame_buffer = 
-                            calloc (frames, sizeof (unsigned char *));
-                        if (!frame_buffer)
-                            error ("Out of memory.");
-                    }
-                }
-                while (prg_timer (&fps_timer, STOP) < frame_time) /* wait */
-                    ;
-            }
-#else
             if (frame_time) {/* defeat compiler warning */}
-#endif /* not X_DISPLAY_MISSING */   
         }
-        free (filename);
-   
-        fiasco_decoder_delete (decoder_state);
-    } while (panel
-
-#ifndef X_DISPLAY_MISSING
-             && !binfo->pressed [QUIT_BUTTON]
-#endif /* not X_DISPLAY_MISSING */
-        
-        );
-
-#ifndef X_DISPLAY_MISSING
-    if (renderer)
-        renderer->delete (renderer);
-
-    if (!image_name)
-    {
-        close_window (xinfo);
-        free (xinfo);
-        xinfo = NULL;
-        if (binfo)
-            free (binfo);
-    }
-#endif /* not X_DISPLAY_MISSING */
-}
+        free(filename);
 
-static void
-get_output_template (const char *image_name, const char *wfa_name,
-                     bool_t color, char **basename, char **suffix)
-/*
- *  Generate image filename template for output of image sequences.
- *  'wfa_name' is the filename of the WFA stream.
- *  Images are either saved with filename 'basename'.'suffix' (still images)
- *  or 'basename'.%03d.'suffix' (videos).
- *
- *  No return value.
- *
- *  Side effects:
- *  '*basename' and '*suffix' is set.
- */
-{
-    if (!wfa_name || streq (wfa_name, "-"))
-        wfa_name = "stdin";       
-    /*
-     *  Generate filename template
-     */
-    if (!image_name || streq (image_name, "") || streq (image_name, "-"))
-    {
-        *basename = strdup (wfa_name);
-        *suffix   = NULL;
-    }
-    else
-    {
-        *basename = strdup (image_name);
-        *suffix   = strrchr (*basename, '.');
-    }
-    
-    if (*suffix)         /* found name 'basename.suffix' */
-    {
-        **suffix = 0;         /* remove dot */
-        (*suffix)++;
-        if (**suffix == 0)
-            *suffix = strdup (color ? "ppm" : "pgm");
-    }
-    else             /* no suffix found, generate one */
-        *suffix = strdup (color ? "ppm" : "pgm");
+        fiasco_decoder_delete(decoder_state);
+    } while (panel);
 }
 
-#ifndef X_DISPLAY_MISSING
+int
+main(int argc, const char **argv) {
 
-static void
-show_stored_frames (unsigned char * const *frame_buffer, int last_frame,
-                    x11_info_t *xinfo, binfo_t *binfo, size_t size,
-                    unsigned frame_time)
-/*
- *  After a WFA video stream has been saved, all frames have been
- *  decoded and stored in memory. These frames are then displayed
- *  in an endless loop.
- *
- *  This function never returns, the program is terminated if the
- *  STOP button is pressed.
- */
-{
-    int n = last_frame;          /* frame number */
-   
-    while (1)
-    {
-        clock_t fps_timer;        /* frames per second timer struct */
-      
-        prg_timer (&fps_timer, START);
-      
-        display_image (0, 0, xinfo);
-        check_events (xinfo, binfo, n, last_frame + 1);
-
-        if (binfo->pressed [STOP_BUTTON])
-            n = 0;
-        else if (binfo->pressed [QUIT_BUTTON])
-            break;
-        else if (binfo->pressed [PLAY_BUTTON])
-            n++;
-        else if (binfo->pressed [RECORD_BUTTON]) /* REWIND is mapped RECORD */
-            n--;
-        if (n < 0)
-            n = last_frame;
-        if (n > last_frame)
-            n = 0;
-
-        memcpy (xinfo->pixels, frame_buffer [n], size);
-        while (prg_timer (&fps_timer, STOP) < frame_time) /* wait */
-            ;
-    };
+    const char *         imageName; /* output filename */
+    bool_t               doubleResolution;/* double resolution of image */
+    bool_t               panel; /* control panel */
+    int                  fps; /* frame display rate */
+    fiasco_d_options_t * options;/* additional coder options */
+    unsigned int         lastArg;    /* last processed cmdline parameter */
+
+    lastArg = checkargs(argc, argv, &doubleResolution, &panel, &fps,
+                        &imageName, &options);
+
+    if (lastArg >= argc)
+        video_decoder("-", imageName, panel, doubleResolution, fps, options);
+    else
+        while (lastArg++ < argc)
+            video_decoder(argv [lastArg - 1], imageName, panel,
+                          doubleResolution, fps, options);
+
+    return 0;
 }
 
-#endif /* not X_DISPLAY_MISSING */
+
diff --git a/converter/other/fiasco/getopt.c b/converter/other/fiasco/getopt.c
index 2f45c7cc..44fd03e6 100644
--- a/converter/other/fiasco/getopt.c
+++ b/converter/other/fiasco/getopt.c
@@ -66,12 +66,12 @@
 
 /* This needs to come after some library #include
    to get __GNU_LIBRARY__ defined.  */
-#ifdef	__GNU_LIBRARY__
+#ifdef  __GNU_LIBRARY__
 /* Don't include stdlib.h for non-GNU C libraries because some of them
    contain conflicting prototypes for getopt.  */
 #include <stdlib.h>
 #include <unistd.h>
-#endif	/* GNU C library.  */
+#endif  /* GNU C library.  */
 
 #if MSVCRT
 #include <windows.h>
@@ -83,9 +83,9 @@
    When compiling libc, the _ macro is predefined.  */
 #ifdef HAVE_LIBINTL_H
 # include <libintl.h>
-# define _(msgid)	gettext (msgid)
+# define _(msgid)       gettext (msgid)
 #else
-# define _(msgid)	(msgid)
+# define _(msgid)       (msgid)
 #endif
 #endif
 
@@ -191,13 +191,13 @@ static enum
 /* Value of POSIXLY_CORRECT environment variable.  */
 static char *posixly_correct;
 
-#ifdef	__GNU_LIBRARY__
+#ifdef  __GNU_LIBRARY__
 /* We want to avoid inclusion of string.h with non-GNU libraries
    because there are many ways it can cause trouble.
    On some systems, it contains special magic macros that don't work
    in GCC.  */
 #include <string.h>
-#define	my_index	strchr
+#define my_index        strchr
 #else
 
 /* Avoid depending on library functions or files
@@ -213,7 +213,7 @@ my_index (str, chr)
   while (*str)
     {
       if (*str == chr)
-	return (char *) str;
+        return (char *) str;
       str++;
     }
   return 0;
@@ -297,37 +297,37 @@ exchange (argv)
   while (top > middle && middle > bottom)
     {
       if (top - middle > middle - bottom)
-	{
-	  /* Bottom segment is the short one.  */
-	  int len = middle - bottom;
-	  register int i;
-
-	  /* Swap it with the top part of the top segment.  */
-	  for (i = 0; i < len; i++)
-	    {
-	      tem = argv[bottom + i];
-	      argv[bottom + i] = argv[top - (middle - bottom) + i];
-	      argv[top - (middle - bottom) + i] = tem;
-	    }
-	  /* Exclude the moved bottom segment from further swapping.  */
-	  top -= len;
-	}
+        {
+          /* Bottom segment is the short one.  */
+          int len = middle - bottom;
+          register int i;
+
+          /* Swap it with the top part of the top segment.  */
+          for (i = 0; i < len; i++)
+            {
+              tem = argv[bottom + i];
+              argv[bottom + i] = argv[top - (middle - bottom) + i];
+              argv[top - (middle - bottom) + i] = tem;
+            }
+          /* Exclude the moved bottom segment from further swapping.  */
+          top -= len;
+        }
       else
-	{
-	  /* Top segment is the short one.  */
-	  int len = top - middle;
-	  register int i;
-
-	  /* Swap it with the bottom part of the bottom segment.  */
-	  for (i = 0; i < len; i++)
-	    {
-	      tem = argv[bottom + i];
-	      argv[bottom + i] = argv[middle + i];
-	      argv[middle + i] = tem;
-	    }
-	  /* Exclude the moved top segment from further swapping.  */
-	  bottom += len;
-	}
+        {
+          /* Top segment is the short one.  */
+          int len = top - middle;
+          register int i;
+
+          /* Swap it with the bottom part of the bottom segment.  */
+          for (i = 0; i < len; i++)
+            {
+              tem = argv[bottom + i];
+              argv[bottom + i] = argv[middle + i];
+              argv[middle + i] = tem;
+            }
+          /* Exclude the moved top segment from further swapping.  */
+          bottom += len;
+        }
     }
 
   /* Update records for the slots the non-options now occupy.  */
@@ -379,16 +379,16 @@ _getopt_initialize (argc, argv, optstring)
       && argc == original_argc && argv == original_argv)
     {
       /* Bash 2.0 puts a special variable in the environment for each
-	 command it runs, specifying which ARGV elements are the results of
-	 file name wildcard expansion and therefore should not be
-	 considered as options.  */
+         command it runs, specifying which ARGV elements are the results of
+         file name wildcard expansion and therefore should not be
+         considered as options.  */
       char var[100];
       sprintf (var, "_%d_GNU_nonoption_argv_flags_", getpid ());
       nonoption_flags = getenv (var);
       if (nonoption_flags == NULL)
-	nonoption_flags_len = 0;
+        nonoption_flags_len = 0;
       else
-	nonoption_flags_len = strlen (nonoption_flags);
+        nonoption_flags_len = strlen (nonoption_flags);
     }
   else
     nonoption_flags_len = 0;
@@ -467,7 +467,7 @@ _getopt_internal (argc, argv, optstring, longopts, longind, long_only)
   if (!__getopt_initialized || optind == 0)
     {
       optstring = _getopt_initialize (argc, argv, optstring);
-      optind = 1;		/* Don't scan ARGV[0], the program name.  */
+      optind = 1;               /* Don't scan ARGV[0], the program name.  */
       __getopt_initialized = 1;
     }
 
@@ -476,9 +476,9 @@ _getopt_internal (argc, argv, optstring, longopts, longind, long_only)
      from the shell indicating it is not an option.  The later information
      is only used when the used in the GNU libc.  */
 #ifdef _LIBC
-#define NONOPTION_P (argv[optind][0] != '-' || argv[optind][1] == '\0'	      \
-		     || (optind < nonoption_flags_len			      \
-			 && nonoption_flags[optind] == '1'))
+#define NONOPTION_P (argv[optind][0] != '-' || argv[optind][1] == '\0'        \
+                     || (optind < nonoption_flags_len                         \
+                         && nonoption_flags[optind] == '1'))
 #else
 #define NONOPTION_P (argv[optind][0] != '-' || argv[optind][1] == '\0')
 #endif
@@ -488,76 +488,76 @@ _getopt_internal (argc, argv, optstring, longopts, longind, long_only)
       /* Advance to the next ARGV-element.  */
 
       /* Give FIRST_NONOPT & LAST_NONOPT rational values if OPTIND has been
-	 moved back by the user (who may also have changed the arguments).  */
+         moved back by the user (who may also have changed the arguments).  */
       if (last_nonopt > optind)
-	last_nonopt = optind;
+        last_nonopt = optind;
       if (first_nonopt > optind)
-	first_nonopt = optind;
+        first_nonopt = optind;
 
       if (ordering == PERMUTE)
-	{
-	  /* If we have just processed some options following some non-options,
-	     exchange them so that the options come first.  */
+        {
+          /* If we have just processed some options following some non-options,
+             exchange them so that the options come first.  */
 
-	  if (first_nonopt != last_nonopt && last_nonopt != optind)
-	    exchange ((char **) argv);
-	  else if (last_nonopt != optind)
-	    first_nonopt = optind;
+          if (first_nonopt != last_nonopt && last_nonopt != optind)
+            exchange ((char **) argv);
+          else if (last_nonopt != optind)
+            first_nonopt = optind;
 
-	  /* Skip any additional non-options
-	     and extend the range of non-options previously skipped.  */
+          /* Skip any additional non-options
+             and extend the range of non-options previously skipped.  */
 
-	  while (optind < argc && NONOPTION_P)
-	    optind++;
-	  last_nonopt = optind;
-	}
+          while (optind < argc && NONOPTION_P)
+            optind++;
+          last_nonopt = optind;
+        }
 
       /* The special ARGV-element `--' means premature end of options.
-	 Skip it like a null option,
-	 then exchange with previous non-options as if it were an option,
-	 then skip everything else like a non-option.  */
+         Skip it like a null option,
+         then exchange with previous non-options as if it were an option,
+         then skip everything else like a non-option.  */
 
       if (optind != argc && !strcmp (argv[optind], "--"))
-	{
-	  optind++;
+        {
+          optind++;
 
-	  if (first_nonopt != last_nonopt && last_nonopt != optind)
-	    exchange ((char **) argv);
-	  else if (first_nonopt == last_nonopt)
-	    first_nonopt = optind;
-	  last_nonopt = argc;
+          if (first_nonopt != last_nonopt && last_nonopt != optind)
+            exchange ((char **) argv);
+          else if (first_nonopt == last_nonopt)
+            first_nonopt = optind;
+          last_nonopt = argc;
 
-	  optind = argc;
-	}
+          optind = argc;
+        }
 
       /* If we have done all the ARGV-elements, stop the scan
-	 and back over any non-options that we skipped and permuted.  */
+         and back over any non-options that we skipped and permuted.  */
 
       if (optind == argc)
-	{
-	  /* Set the next-arg-index to point at the non-options
-	     that we previously skipped, so the caller will digest them.  */
-	  if (first_nonopt != last_nonopt)
-	    optind = first_nonopt;
-	  return -1;
-	}
+        {
+          /* Set the next-arg-index to point at the non-options
+             that we previously skipped, so the caller will digest them.  */
+          if (first_nonopt != last_nonopt)
+            optind = first_nonopt;
+          return -1;
+        }
 
       /* If we have come to a non-option and did not permute it,
-	 either stop the scan or describe it to the caller and pass it by.  */
+         either stop the scan or describe it to the caller and pass it by.  */
 
       if (NONOPTION_P)
-	{
-	  if (ordering == REQUIRE_ORDER)
-	    return -1;
-	  optarg = argv[optind++];
-	  return 1;
-	}
+        {
+          if (ordering == REQUIRE_ORDER)
+            return -1;
+          optarg = argv[optind++];
+          return 1;
+        }
 
       /* We have found another option-ARGV-element.
-	 Skip the initial punctuation.  */
+         Skip the initial punctuation.  */
 
       nextchar = (argv[optind] + 1
-		  + (longopts != NULL && argv[optind][1] == '-'));
+                  + (longopts != NULL && argv[optind][1] == '-'));
     }
 
   /* Decode the current option-ARGV-element.  */
@@ -577,7 +577,7 @@ _getopt_internal (argc, argv, optstring, longopts, longind, long_only)
 
   if (longopts != NULL
       && (argv[optind][1] == '-'
-	  || (long_only && (argv[optind][2] || !my_index (optstring, argv[optind][1])))))
+          || (long_only && (argv[optind][2] || !my_index (optstring, argv[optind][1])))))
     {
       char *nameend;
       const struct option *p;
@@ -588,124 +588,124 @@ _getopt_internal (argc, argv, optstring, longopts, longind, long_only)
       int option_index;
 
       for (nameend = nextchar; *nameend && *nameend != '='; nameend++)
-	/* Do nothing.  */ ;
+        /* Do nothing.  */ ;
 
       /* Test all long options for either exact match
-	 or abbreviated matches.  */
+         or abbreviated matches.  */
       for (p = longopts, option_index = 0; p->name; p++, option_index++)
-	if (!strncmp (p->name, nextchar, nameend - nextchar))
-	  {
-	    if ((unsigned int) (nameend - nextchar)
-		== (unsigned int) strlen (p->name))
-	      {
-		/* Exact match found.  */
-		pfound = p;
-		indfound = option_index;
-		exact = 1;
-		break;
-	      }
-	    else if (pfound == NULL)
-	      {
-		/* First nonexact match found.  */
-		pfound = p;
-		indfound = option_index;
-	      }
-	    else
-	      /* Second or later nonexact match found.  */
-	      ambig = 1;
-	  }
+        if (!strncmp (p->name, nextchar, nameend - nextchar))
+          {
+            if ((unsigned int) (nameend - nextchar)
+                == (unsigned int) strlen (p->name))
+              {
+                /* Exact match found.  */
+                pfound = p;
+                indfound = option_index;
+                exact = 1;
+                break;
+              }
+            else if (pfound == NULL)
+              {
+                /* First nonexact match found.  */
+                pfound = p;
+                indfound = option_index;
+              }
+            else
+              /* Second or later nonexact match found.  */
+              ambig = 1;
+          }
 
       if (ambig && !exact)
-	{
-	  if (opterr)
-	    fprintf (stderr, _("%s: option `%s' is ambiguous\n"),
-		     argv[0], argv[optind]);
-	  nextchar += strlen (nextchar);
-	  optind++;
-	  optopt = 0;
-	  return '?';
-	}
+        {
+          if (opterr)
+            fprintf (stderr, _("%s: option `%s' is ambiguous\n"),
+                     argv[0], argv[optind]);
+          nextchar += strlen (nextchar);
+          optind++;
+          optopt = 0;
+          return '?';
+        }
 
       if (pfound != NULL)
-	{
-	  option_index = indfound;
-	  optind++;
-	  if (*nameend)
-	    {
-	      /* Don't test has_arg with >, because some C compilers don't
-		 allow it to be used on enums.  */
-	      if (pfound->has_arg)
-		optarg = nameend + 1;
-	      else
-		{
+        {
+          option_index = indfound;
+          optind++;
+          if (*nameend)
+            {
+              /* Don't test has_arg with >, because some C compilers don't
+                 allow it to be used on enums.  */
+              if (pfound->has_arg)
+                optarg = nameend + 1;
+              else
+                {
             if (opterr) {
-		   if (argv[optind - 1][1] == '-')
-		    /* --option */
-		    fprintf (stderr,
-		     _("%s: option `--%s' doesn't allow an argument\n"),
-		     argv[0], pfound->name);
-		   else
-		    /* +option or -option */
-		    fprintf (stderr,
-		     _("%s: option `%c%s' doesn't allow an argument\n"),
-		     argv[0], argv[optind - 1][0], pfound->name);
+                   if (argv[optind - 1][1] == '-')
+                    /* --option */
+                    fprintf (stderr,
+                     _("%s: option `--%s' doesn't allow an argument\n"),
+                     argv[0], pfound->name);
+                   else
+                    /* +option or -option */
+                    fprintf (stderr,
+                     _("%s: option `%c%s' doesn't allow an argument\n"),
+                     argv[0], argv[optind - 1][0], pfound->name);
             }
 
-		  nextchar += strlen (nextchar);
-
-		  optopt = pfound->val;
-		  return '?';
-		}
-	    }
-	  else if (pfound->has_arg == 1)
-	    {
-	      if (optind < argc)
-		optarg = argv[optind++];
-	      else
-		{
-		  if (opterr)
-		    fprintf (stderr,
-			   _("%s: option `%s' requires an argument\n"),
-			   argv[0], argv[optind - 1]);
-		  nextchar += strlen (nextchar);
-		  optopt = pfound->val;
-		  return optstring[0] == ':' ? ':' : '?';
-		}
-	    }
-	  nextchar += strlen (nextchar);
-	  if (longind != NULL)
-	    *longind = option_index;
-	  if (pfound->flag)
-	    {
-	      *(pfound->flag) = pfound->val;
-	      return 0;
-	    }
-	  return pfound->val;
-	}
+                  nextchar += strlen (nextchar);
+
+                  optopt = pfound->val;
+                  return '?';
+                }
+            }
+          else if (pfound->has_arg == 1)
+            {
+              if (optind < argc)
+                optarg = argv[optind++];
+              else
+                {
+                  if (opterr)
+                    fprintf (stderr,
+                           _("%s: option `%s' requires an argument\n"),
+                           argv[0], argv[optind - 1]);
+                  nextchar += strlen (nextchar);
+                  optopt = pfound->val;
+                  return optstring[0] == ':' ? ':' : '?';
+                }
+            }
+          nextchar += strlen (nextchar);
+          if (longind != NULL)
+            *longind = option_index;
+          if (pfound->flag)
+            {
+              *(pfound->flag) = pfound->val;
+              return 0;
+            }
+          return pfound->val;
+        }
 
       /* Can't find it as a long option.  If this is not getopt_long_only,
-	 or the option starts with '--' or is not a valid short
-	 option, then it's an error.
-	 Otherwise interpret it as a short option.  */
+         or the option starts with '--' or is not a valid short
+         option, then it's an error.
+         Otherwise interpret it as a short option.  */
       if (!long_only || argv[optind][1] == '-'
-	  || my_index (optstring, *nextchar) == NULL)
-	{
-	  if (opterr)
-	    {
-	      if (argv[optind][1] == '-')
-		/* --option */
-		fprintf (stderr, _("%s: unrecognized option `--%s'\n"),
-			 argv[0], nextchar);
-	      else
-		/* +option or -option */
-		fprintf (stderr, _("%s: unrecognized option `%c%s'\n"),
-			 argv[0], argv[optind][0], nextchar);
-	    }
-	  nextchar = (char *) "";
-	  optind++;
-	  optopt = 0;
-	  return '?';
-	}
+          || my_index (optstring, *nextchar) == NULL)
+        {
+          if (opterr)
+            {
+              if (argv[optind][1] == '-')
+                /* --option */
+                fprintf (stderr, _("%s: unrecognized option `--%s'\n"),
+                         argv[0], nextchar);
+              else
+                /* +option or -option */
+                fprintf (stderr, _("%s: unrecognized option `%c%s'\n"),
+                         argv[0], argv[optind][0], nextchar);
+            }
+          nextchar = (char *) "";
+          optind++;
+          optopt = 0;
+          return '?';
+        }
     }
 
   /* Look at and handle the next short option-character.  */
@@ -720,188 +720,188 @@ _getopt_internal (argc, argv, optstring, longopts, longind, long_only)
 
     if (temp == NULL || c == ':')
       {
-	if (opterr)
-	  {
-	    if (posixly_correct)
-	      /* 1003.2 specifies the format of this message.  */
-	      fprintf (stderr, _("%s: illegal option -- %c\n"),
-		       argv[0], c);
-	    else
-	      fprintf (stderr, _("%s: invalid option -- %c\n"),
-		       argv[0], c);
-	  }
-	optopt = c;
-	return '?';
+        if (opterr)
+          {
+            if (posixly_correct)
+              /* 1003.2 specifies the format of this message.  */
+              fprintf (stderr, _("%s: illegal option -- %c\n"),
+                       argv[0], c);
+            else
+              fprintf (stderr, _("%s: invalid option -- %c\n"),
+                       argv[0], c);
+          }
+        optopt = c;
+        return '?';
       }
     /* Convenience. Treat POSIX -W foo same as long option --foo */
     if (temp[0] == 'W' && temp[1] == ';')
       {
-	char *nameend;
-	const struct option *p;
-	const struct option *pfound = NULL;
-	int exact = 0;
-	int ambig = 0;
-	int indfound = 0;
-	int option_index;
-
-	/* This is an option that requires an argument.  */
-	if (*nextchar != '\0')
-	  {
-	    optarg = nextchar;
-	    /* If we end this ARGV-element by taking the rest as an arg,
-	       we must advance to the next element now.  */
-	    optind++;
-	  }
-	else if (optind == argc)
-	  {
-	    if (opterr)
-	      {
-		/* 1003.2 specifies the format of this message.  */
-		fprintf (stderr, _("%s: option requires an argument -- %c\n"),
-			 argv[0], c);
-	      }
-	    optopt = c;
-	    if (optstring[0] == ':')
-	      c = ':';
-	    else
-	      c = '?';
-	    return c;
-	  }
-	else
-	  /* We already incremented `optind' once;
-	     increment it again when taking next ARGV-elt as argument.  */
-	  optarg = argv[optind++];
-
-	/* optarg is now the argument, see if it's in the
-	   table of longopts.  */
-
-	for (nextchar = nameend = optarg; *nameend && *nameend != '='; nameend++)
-	  /* Do nothing.  */ ;
-
-	/* Test all long options for either exact match
-	   or abbreviated matches.  */
-	for (p = longopts, option_index = 0; p->name; p++, option_index++)
-	  if (!strncmp (p->name, nextchar, nameend - nextchar))
-	    {
-	      if ((unsigned int) (nameend - nextchar) == strlen (p->name))
-		{
-		  /* Exact match found.  */
-		  pfound = p;
-		  indfound = option_index;
-		  exact = 1;
-		  break;
-		}
-	      else if (pfound == NULL)
-		{
-		  /* First nonexact match found.  */
-		  pfound = p;
-		  indfound = option_index;
-		}
-	      else
-		/* Second or later nonexact match found.  */
-		ambig = 1;
-	    }
-	if (ambig && !exact)
-	  {
-	    if (opterr)
-	      fprintf (stderr, _("%s: option `-W %s' is ambiguous\n"),
-		       argv[0], argv[optind]);
-	    nextchar += strlen (nextchar);
-	    optind++;
-	    return '?';
-	  }
-	if (pfound != NULL)
-	  {
-	    option_index = indfound;
-	    if (*nameend)
-	      {
-		/* Don't test has_arg with >, because some C compilers don't
-		   allow it to be used on enums.  */
-		if (pfound->has_arg)
-		  optarg = nameend + 1;
-		else
-		  {
-		    if (opterr)
-		      fprintf (stderr, _("\
+        char *nameend;
+        const struct option *p;
+        const struct option *pfound = NULL;
+        int exact = 0;
+        int ambig = 0;
+        int indfound = 0;
+        int option_index;
+
+        /* This is an option that requires an argument.  */
+        if (*nextchar != '\0')
+          {
+            optarg = nextchar;
+            /* If we end this ARGV-element by taking the rest as an arg,
+               we must advance to the next element now.  */
+            optind++;
+          }
+        else if (optind == argc)
+          {
+            if (opterr)
+              {
+                /* 1003.2 specifies the format of this message.  */
+                fprintf (stderr, _("%s: option requires an argument -- %c\n"),
+                         argv[0], c);
+              }
+            optopt = c;
+            if (optstring[0] == ':')
+              c = ':';
+            else
+              c = '?';
+            return c;
+          }
+        else
+          /* We already incremented `optind' once;
+             increment it again when taking next ARGV-elt as argument.  */
+          optarg = argv[optind++];
+
+        /* optarg is now the argument, see if it's in the
+           table of longopts.  */
+
+        for (nextchar = nameend = optarg; *nameend && *nameend != '='; nameend++)
+          /* Do nothing.  */ ;
+
+        /* Test all long options for either exact match
+           or abbreviated matches.  */
+        for (p = longopts, option_index = 0; p->name; p++, option_index++)
+          if (!strncmp (p->name, nextchar, nameend - nextchar))
+            {
+              if ((unsigned int) (nameend - nextchar) == strlen (p->name))
+                {
+                  /* Exact match found.  */
+                  pfound = p;
+                  indfound = option_index;
+                  exact = 1;
+                  break;
+                }
+              else if (pfound == NULL)
+                {
+                  /* First nonexact match found.  */
+                  pfound = p;
+                  indfound = option_index;
+                }
+              else
+                /* Second or later nonexact match found.  */
+                ambig = 1;
+            }
+        if (ambig && !exact)
+          {
+            if (opterr)
+              fprintf (stderr, _("%s: option `-W %s' is ambiguous\n"),
+                       argv[0], argv[optind]);
+            nextchar += strlen (nextchar);
+            optind++;
+            return '?';
+          }
+        if (pfound != NULL)
+          {
+            option_index = indfound;
+            if (*nameend)
+              {
+                /* Don't test has_arg with >, because some C compilers don't
+                   allow it to be used on enums.  */
+                if (pfound->has_arg)
+                  optarg = nameend + 1;
+                else
+                  {
+                    if (opterr)
+                      fprintf (stderr, _("\
 %s: option `-W %s' doesn't allow an argument\n"),
-			       argv[0], pfound->name);
-
-		    nextchar += strlen (nextchar);
-		    return '?';
-		  }
-	      }
-	    else if (pfound->has_arg == 1)
-	      {
-		if (optind < argc)
-		  optarg = argv[optind++];
-		else
-		  {
-		    if (opterr)
-		      fprintf (stderr,
-			       _("%s: option `%s' requires an argument\n"),
-			       argv[0], argv[optind - 1]);
-		    nextchar += strlen (nextchar);
-		    return optstring[0] == ':' ? ':' : '?';
-		  }
-	      }
-	    nextchar += strlen (nextchar);
-	    if (longind != NULL)
-	      *longind = option_index;
-	    if (pfound->flag)
-	      {
-		*(pfound->flag) = pfound->val;
-		return 0;
-	      }
-	    return pfound->val;
-	  }
-	  nextchar = NULL;
-	  return 'W';	/* Let the application handle it.   */
+                               argv[0], pfound->name);
+
+                    nextchar += strlen (nextchar);
+                    return '?';
+                  }
+              }
+            else if (pfound->has_arg == 1)
+              {
+                if (optind < argc)
+                  optarg = argv[optind++];
+                else
+                  {
+                    if (opterr)
+                      fprintf (stderr,
+                               _("%s: option `%s' requires an argument\n"),
+                               argv[0], argv[optind - 1]);
+                    nextchar += strlen (nextchar);
+                    return optstring[0] == ':' ? ':' : '?';
+                  }
+              }
+            nextchar += strlen (nextchar);
+            if (longind != NULL)
+              *longind = option_index;
+            if (pfound->flag)
+              {
+                *(pfound->flag) = pfound->val;
+                return 0;
+              }
+            return pfound->val;
+          }
+          nextchar = NULL;
+          return 'W';   /* Let the application handle it.   */
       }
     if (temp[1] == ':')
       {
-	if (temp[2] == ':')
-	  {
-	    /* This is an option that accepts an argument optionally.  */
-	    if (*nextchar != '\0')
-	      {
-		optarg = nextchar;
-		optind++;
-	      }
-	    else
-	      optarg = NULL;
-	    nextchar = NULL;
-	  }
-	else
-	  {
-	    /* This is an option that requires an argument.  */
-	    if (*nextchar != '\0')
-	      {
-		optarg = nextchar;
-		/* If we end this ARGV-element by taking the rest as an arg,
-		   we must advance to the next element now.  */
-		optind++;
-	      }
-	    else if (optind == argc)
-	      {
-		if (opterr)
-		  {
-		    /* 1003.2 specifies the format of this message.  */
-		    fprintf (stderr,
-			   _("%s: option requires an argument -- %c\n"),
-			   argv[0], c);
-		  }
-		optopt = c;
-		if (optstring[0] == ':')
-		  c = ':';
-		else
-		  c = '?';
-	      }
-	    else
-	      /* We already incremented `optind' once;
-		 increment it again when taking next ARGV-elt as argument.  */
-	      optarg = argv[optind++];
-	    nextchar = NULL;
-	  }
+        if (temp[2] == ':')
+          {
+            /* This is an option that accepts an argument optionally.  */
+            if (*nextchar != '\0')
+              {
+                optarg = nextchar;
+                optind++;
+              }
+            else
+              optarg = NULL;
+            nextchar = NULL;
+          }
+        else
+          {
+            /* This is an option that requires an argument.  */
+            if (*nextchar != '\0')
+              {
+                optarg = nextchar;
+                /* If we end this ARGV-element by taking the rest as an arg,
+                   we must advance to the next element now.  */
+                optind++;
+              }
+            else if (optind == argc)
+              {
+                if (opterr)
+                  {
+                    /* 1003.2 specifies the format of this message.  */
+                    fprintf (stderr,
+                           _("%s: option requires an argument -- %c\n"),
+                           argv[0], c);
+                  }
+                optopt = c;
+                if (optstring[0] == ':')
+                  c = ':';
+                else
+                  c = '?';
+              }
+            else
+              /* We already incremented `optind' once;
+                 increment it again when taking next ARGV-elt as argument.  */
+              optarg = argv[optind++];
+            nextchar = NULL;
+          }
       }
     return c;
   }
@@ -914,12 +914,12 @@ getopt (argc, argv, optstring)
      const char *optstring;
 {
   return _getopt_internal (argc, argv, optstring,
-			   (const struct option *) 0,
-			   (int *) 0,
-			   0);
+                           (const struct option *) 0,
+                           (int *) 0,
+                           0);
 }
 
-#endif	/* Not ELIDE_CODE.  */
+#endif  /* Not ELIDE_CODE.  */
 
 #ifdef TEST
 
@@ -940,51 +940,51 @@ main (argc, argv)
 
       c = getopt (argc, argv, "abc:d:0123456789");
       if (c == -1)
-	break;
+        break;
 
       switch (c)
-	{
-	case '0':
-	case '1':
-	case '2':
-	case '3':
-	case '4':
-	case '5':
-	case '6':
-	case '7':
-	case '8':
-	case '9':
-	  if (digit_optind != 0 && digit_optind != this_option_optind)
-	    printf ("digits occur in two different argv-elements.\n");
-	  digit_optind = this_option_optind;
-	  printf ("option %c\n", c);
-	  break;
-
-	case 'a':
-	  printf ("option a\n");
-	  break;
-
-	case 'b':
-	  printf ("option b\n");
-	  break;
-
-	case 'c':
-	  printf ("option c with value `%s'\n", optarg);
-	  break;
-
-	case '?':
-	  break;
-
-	default:
-	  printf ("?? getopt returned character code 0%o ??\n", c);
-	}
+        {
+        case '0':
+        case '1':
+        case '2':
+        case '3':
+        case '4':
+        case '5':
+        case '6':
+        case '7':
+        case '8':
+        case '9':
+          if (digit_optind != 0 && digit_optind != this_option_optind)
+            printf ("digits occur in two different argv-elements.\n");
+          digit_optind = this_option_optind;
+          printf ("option %c\n", c);
+          break;
+
+        case 'a':
+          printf ("option a\n");
+          break;
+
+        case 'b':
+          printf ("option b\n");
+          break;
+
+        case 'c':
+          printf ("option c with value `%s'\n", optarg);
+          break;
+
+        case '?':
+          break;
+
+        default:
+          printf ("?? getopt returned character code 0%o ??\n", c);
+        }
     }
 
   if (optind < argc)
     {
       printf ("non-option ARGV-elements: ");
       while (optind < argc)
-	printf ("%s ", argv[optind++]);
+        printf ("%s ", argv[optind++]);
       printf ("\n");
     }
 
diff --git a/converter/other/fiasco/getopt.h b/converter/other/fiasco/getopt.h
index 9acca708..3c735e3d 100644
--- a/converter/other/fiasco/getopt.h
+++ b/converter/other/fiasco/getopt.h
@@ -22,7 +22,7 @@
 #ifndef _GETOPT_H
 #define _GETOPT_H 1
 
-#ifdef	__cplusplus
+#ifdef  __cplusplus
 extern "C" {
 #endif
 
@@ -63,9 +63,9 @@ extern int optopt;
    zero.
 
    The field `has_arg' is:
-   no_argument		(or 0) if the option does not take an argument,
-   required_argument	(or 1) if the option requires an argument,
-   optional_argument 	(or 2) if the option takes an optional argument.
+   no_argument          (or 0) if the option does not take an argument,
+   required_argument    (or 1) if the option requires an argument,
+   optional_argument    (or 2) if the option takes an optional argument.
 
    If the field `flag' is not NULL, it points to a variable that is set
    to the value given in the field `val' when the option is found, but
@@ -90,9 +90,9 @@ struct option
 
 /* Names for the values of the `has_arg' field of `struct option'.  */
 
-#define	no_argument		0
-#define required_argument	1
-#define optional_argument	2
+#define no_argument             0
+#define required_argument       1
+#define optional_argument       2
 
 #if defined (__STDC__) && __STDC__
 #ifdef __GNU_LIBRARY__
@@ -104,16 +104,16 @@ extern int getopt (int argc, char *const *argv, const char *shortopts);
 extern int getopt ();
 #endif /* __GNU_LIBRARY__ */
 extern int getopt_long (int argc, char *const *argv, const char *shortopts,
-		        const struct option *longopts, int *longind);
+                        const struct option *longopts, int *longind);
 extern int getopt_long_only (int argc, char *const *argv,
-			     const char *shortopts,
-		             const struct option *longopts, int *longind);
+                             const char *shortopts,
+                             const struct option *longopts, int *longind);
 
 /* Internal only.  Users should not call this directly.  */
 extern int _getopt_internal (int argc, char *const *argv,
-			     const char *shortopts,
-		             const struct option *longopts, int *longind,
-			     int long_only);
+                             const char *shortopts,
+                             const struct option *longopts, int *longind,
+                             int long_only);
 #else /* not __STDC__ */
 extern int getopt ();
 extern int getopt_long ();
@@ -122,7 +122,7 @@ extern int getopt_long_only ();
 extern int _getopt_internal ();
 #endif /* __STDC__ */
 
-#ifdef	__cplusplus
+#ifdef  __cplusplus
 }
 #endif
 
diff --git a/converter/other/fiasco/getopt1.c b/converter/other/fiasco/getopt1.c
index 8347bb13..4ed64b8b 100644
--- a/converter/other/fiasco/getopt1.c
+++ b/converter/other/fiasco/getopt1.c
@@ -60,7 +60,7 @@
 #include <stdlib.h>
 #endif
 
-#ifndef	NULL
+#ifndef NULL
 #define NULL 0
 #endif
 
@@ -92,7 +92,7 @@ getopt_long_only (argc, argv, options, long_options, opt_index)
 }
 
 
-#endif	/* Not ELIDE_CODE.  */
+#endif  /* Not ELIDE_CODE.  */
 
 #ifdef TEST
 
@@ -112,74 +112,74 @@ main (argc, argv)
       int option_index = 0;
       static struct option long_options[] =
       {
-	{"add", 1, 0, 0},
-	{"append", 0, 0, 0},
-	{"delete", 1, 0, 0},
-	{"verbose", 0, 0, 0},
-	{"create", 0, 0, 0},
-	{"file", 1, 0, 0},
-	{0, 0, 0, 0}
+        {"add", 1, 0, 0},
+        {"append", 0, 0, 0},
+        {"delete", 1, 0, 0},
+        {"verbose", 0, 0, 0},
+        {"create", 0, 0, 0},
+        {"file", 1, 0, 0},
+        {0, 0, 0, 0}
       };
 
       c = getopt_long (argc, argv, "abc:d:0123456789",
-		       long_options, &option_index);
+                       long_options, &option_index);
       if (c == -1)
-	break;
+        break;
 
       switch (c)
-	{
-	case 0:
-	  printf ("option %s", long_options[option_index].name);
-	  if (optarg)
-	    printf (" with arg %s", optarg);
-	  printf ("\n");
-	  break;
-
-	case '0':
-	case '1':
-	case '2':
-	case '3':
-	case '4':
-	case '5':
-	case '6':
-	case '7':
-	case '8':
-	case '9':
-	  if (digit_optind != 0 && digit_optind != this_option_optind)
-	    printf ("digits occur in two different argv-elements.\n");
-	  digit_optind = this_option_optind;
-	  printf ("option %c\n", c);
-	  break;
-
-	case 'a':
-	  printf ("option a\n");
-	  break;
-
-	case 'b':
-	  printf ("option b\n");
-	  break;
-
-	case 'c':
-	  printf ("option c with value `%s'\n", optarg);
-	  break;
-
-	case 'd':
-	  printf ("option d with value `%s'\n", optarg);
-	  break;
-
-	case '?':
-	  break;
-
-	default:
-	  printf ("?? getopt returned character code 0%o ??\n", c);
-	}
+        {
+        case 0:
+          printf ("option %s", long_options[option_index].name);
+          if (optarg)
+            printf (" with arg %s", optarg);
+          printf ("\n");
+          break;
+
+        case '0':
+        case '1':
+        case '2':
+        case '3':
+        case '4':
+        case '5':
+        case '6':
+        case '7':
+        case '8':
+        case '9':
+          if (digit_optind != 0 && digit_optind != this_option_optind)
+            printf ("digits occur in two different argv-elements.\n");
+          digit_optind = this_option_optind;
+          printf ("option %c\n", c);
+          break;
+
+        case 'a':
+          printf ("option a\n");
+          break;
+
+        case 'b':
+          printf ("option b\n");
+          break;
+
+        case 'c':
+          printf ("option c with value `%s'\n", optarg);
+          break;
+
+        case 'd':
+          printf ("option d with value `%s'\n", optarg);
+          break;
+
+        case '?':
+          break;
+
+        default:
+          printf ("?? getopt returned character code 0%o ??\n", c);
+        }
     }
 
   if (optind < argc)
     {
       printf ("non-option ARGV-elements: ");
       while (optind < argc)
-	printf ("%s ", argv[optind++]);
+        printf ("%s ", argv[optind++]);
       printf ("\n");
     }
 
diff --git a/converter/other/fiasco/input/basis.c b/converter/other/fiasco/input/basis.c
index e5ced0d0..4be7f4ed 100644
--- a/converter/other/fiasco/input/basis.c
+++ b/converter/other/fiasco/input/basis.c
@@ -1,7 +1,7 @@
 /*
- *  basis.c:		WFA initial basis files
+ *  basis.c:            WFA initial basis files
  *
- *  Written by:		Ullrich Hafner
+ *  Written by:         Ullrich Hafner
  *
  *  This file is part of FIASCO (Fractal Image And Sequence COdec)
  *  Copyright (C) 1994-2000 Ullrich Hafner
@@ -43,7 +43,7 @@ typedef struct
 
 /*****************************************************************************
 
-				prototypes
+                                prototypes
 
 *****************************************************************************/
 
@@ -58,7 +58,7 @@ static basis_file_t const basis_files[] = {
 
 /*****************************************************************************
 
-				public code
+                                public code
 
 *****************************************************************************/
 
@@ -70,69 +70,69 @@ get_linked_basis (const char *basis_name, wfa_t *wfa)
  *  according to the stored data, otherwise print a warning message.
  *
  *  Return value:
- *	true on success, false if basis is not available yet.
+ *      true on success, false if basis is not available yet.
  *
  *  Side effects:
- *	'wfa' struct is filled on success.
+ *      'wfa' struct is filled on success.
  */
 {
-   bool_t	  success = NO;		/* indicates if basis is found */
-   unsigned	  n;			/* counter */
-   basis_values_t bv;			/* basis values */
+   bool_t         success = NO;         /* indicates if basis is found */
+   unsigned       n;                    /* counter */
+   basis_values_t bv;                   /* basis values */
 
    for (n = 0; basis_files [n].filename != NULL; n++)
-      if (streq (basis_files [n].filename, basis_name))	/* basis is stored */
+      if (streq (basis_files [n].filename, basis_name)) /* basis is stored */
       {
-	 unsigned state, edge;
-
-	 (*basis_files [n].function) (&bv); /* initialize local variables */
-	 /*
-	  *  Generate WFA
-	  */
-	 wfa->basis_states = wfa->states = bv.states + 1;
-	 wfa->domain_type[0]             = USE_DOMAIN_MASK;
-	 wfa->final_distribution[0]      = 128;
-	 append_edge (0, 0, 1.0, 0, wfa);
-	 append_edge (0, 0, 1.0, 1, wfa);
-	 for (state = 1; state < wfa->basis_states; state++)
-	 {
-	    wfa->final_distribution [state] = bv.final [state - 1];
-	    wfa->domain_type [state]        = bv.use_domain [state - 1]
-					      ? USE_DOMAIN_MASK
-					      : AUXILIARY_MASK;
-	 }
-	 for (edge = 0; isedge (bv.transitions [edge][0]); edge++)
-	    append_edge (bv.transitions [edge][0], bv.transitions [edge][1],
-			 bv.transitions [edge][2], bv.transitions [edge][3],
-			 wfa);
-
-	 success = YES;
-	 break;
+         unsigned state, edge;
+
+         (*basis_files [n].function) (&bv); /* initialize local variables */
+         /*
+          *  Generate WFA
+          */
+         wfa->basis_states = wfa->states = bv.states + 1;
+         wfa->domain_type[0]             = USE_DOMAIN_MASK;
+         wfa->final_distribution[0]      = 128;
+         append_edge (0, 0, 1.0, 0, wfa);
+         append_edge (0, 0, 1.0, 1, wfa);
+         for (state = 1; state < wfa->basis_states; state++)
+         {
+            wfa->final_distribution [state] = bv.final [state - 1];
+            wfa->domain_type [state]        = bv.use_domain [state - 1]
+                                              ? USE_DOMAIN_MASK
+                                              : AUXILIARY_MASK;
+         }
+         for (edge = 0; isedge (bv.transitions [edge][0]); edge++)
+            append_edge (bv.transitions [edge][0], bv.transitions [edge][1],
+                         bv.transitions [edge][2], bv.transitions [edge][3],
+                         wfa);
+
+         success = YES;
+         break;
       }
 
    if (!success)
       warning ("WFA initial basis '%s' isn't linked with the executable yet."
-	       "\nLoading basis from disk instead.", basis_name);
+               "\nLoading basis from disk instead.", basis_name);
 
    return success;
 }
 
 /*****************************************************************************
 
-				private code
+                                private code
 
 *****************************************************************************/
 
 /*****************************************************************************
-				basis "small.wfa"
+                                basis "small.wfa"
 *****************************************************************************/
 
-static unsigned	states_small           = 2;
-static bool_t	use_domain_small[]     = {YES, YES};
-static real_t 	final_small[]          = {64, 64};
-static real_t 	transitions_small[][4] = {{1, 2, 0.5, 0}, {1, 2, 0.5, 1},
-				      	 {1, 0, 0.5, 1}, {2, 1, 1.0, 0},
-				      	 {2, 1, 1.0, 1}, {-1, 0, 0, 0}};
+static unsigned states_small           = 2;
+static bool_t   use_domain_small[]     = {YES, YES};
+static real_t   final_small[]          = {64, 64};
+static real_t   transitions_small[][4] = {{1, 2, 0.5, 0}, {1, 2, 0.5, 1},
+                                         {1, 0, 0.5, 1}, {2, 1, 1.0, 0},
+                                         {2, 1, 1.0, 1}, {-1, 0, 0, 0}};
 static void
 small_init (basis_values_t *bv)
 {
diff --git a/converter/other/fiasco/input/basis.h b/converter/other/fiasco/input/basis.h
index e2242198..d6d2f8b3 100644
--- a/converter/other/fiasco/input/basis.h
+++ b/converter/other/fiasco/input/basis.h
@@ -1,8 +1,8 @@
 /*
  *  basis.h
  *
- *  Written by:		Ullrich Hafner
- *		
+ *  Written by:         Ullrich Hafner
+ *              
  *  This file is part of FIASCO (Fractal Image And Sequence COdec)
  *  Copyright (C) 1994-2000 Ullrich Hafner
  */
diff --git a/converter/other/fiasco/input/matrices.c b/converter/other/fiasco/input/matrices.c
index d20a27eb..f59b5a30 100644
--- a/converter/other/fiasco/input/matrices.c
+++ b/converter/other/fiasco/input/matrices.c
@@ -1,7 +1,7 @@
 /*
- *  matrices.c:		Input of transition matrices
+ *  matrices.c:         Input of transition matrices
  *
- *  Written by:		Ullrich Hafner
+ *  Written by:         Ullrich Hafner
  *
  *  This file is part of FIASCO (Fractal Image And Sequence COdec)
  *  Copyright (C) 1994-2000 Ullrich Hafner
@@ -28,12 +28,12 @@
 #include "matrices.h"
 
 #if STDC_HEADERS
-#	include <stdlib.h>
+#       include <stdlib.h>
 #endif /* not STDC_HEADERS */
 
 /*****************************************************************************
 
-				prototypes
+                                prototypes
 
 *****************************************************************************/
 
@@ -48,7 +48,7 @@ compute_y_state (int state, int y_state, wfa_t *wfa);
 
 /*****************************************************************************
 
-				public code
+                                public code
 
 *****************************************************************************/
 
@@ -58,16 +58,16 @@ read_matrices (wfa_t *wfa, bitfile_t *input)
  *  Read transitions of WFA given from the stream 'input'.
  *
  *  Return value:
- *	number of edges
+ *      number of edges
  *
  *  Side effects:
- *	'wfa->into' is filled with decoded values
+ *      'wfa->into' is filled with decoded values
  */
 {
-   unsigned total;			/* total number of edges in the WFA */
+   unsigned total;                      /* total number of edges in the WFA */
    unsigned root_state = wfa->wfainfo->color
-			 ? wfa->tree [wfa->tree [wfa->root_state][0]][0]
-			 : wfa->root_state;
+                         ? wfa->tree [wfa->tree [wfa->root_state][0]][0]
+                         : wfa->root_state;
 
    total  = column_0_decoding (wfa, root_state, input);
    total += delta_decoding (wfa, root_state, input);
@@ -79,7 +79,7 @@ read_matrices (wfa_t *wfa, bitfile_t *input)
 
 /*****************************************************************************
 
-				private code
+                                private code
 
 *****************************************************************************/
 
@@ -91,34 +91,34 @@ delta_decoding (wfa_t *wfa, unsigned last_domain, bitfile_t *input)
  *  'last_domain' is the maximum state number used as domain image.
  *
  *  Return value:
- *	number of non-zero matrix elements (WFA edges)
+ *      number of non-zero matrix elements (WFA edges)
  *
  *  Side effects:
- *	'wfa->into' is filled with decoded values
+ *      'wfa->into' is filled with decoded values
  */
 {
-   range_sort_t	 rs;			/* ranges are sorted as in the coder */
-   unsigned	 max_domain;		/* dummy used for recursion */
-   unsigned	 range;
-   unsigned	 count [MAXEDGES + 1];
-   unsigned 	 state, label;
-   unsigned	*n_edges;		/* number of elements per row */
-   unsigned	 total = 0;		/* total number of decoded edges */
+   range_sort_t  rs;                    /* ranges are sorted as in the coder */
+   unsigned      max_domain;            /* dummy used for recursion */
+   unsigned      range;
+   unsigned      count [MAXEDGES + 1];
+   unsigned      state, label;
+   unsigned     *n_edges;               /* number of elements per row */
+   unsigned      total = 0;             /* total number of decoded edges */
 
    /*
     *  Generate a list of range blocks.
     *  The order is the same as in the coder.
     */
    rs.range_state      = Calloc ((last_domain + 1) * MAXLABELS,
-				 sizeof (u_word_t));
+                                 sizeof (u_word_t));
    rs.range_label      = Calloc ((last_domain + 1) * MAXLABELS,
-				 sizeof (byte_t));
+                                 sizeof (byte_t));
    rs.range_max_domain = Calloc ((last_domain + 1) * MAXLABELS,
-				 sizeof (u_word_t));
+                                 sizeof (u_word_t));
    rs.range_subdivided = Calloc ((last_domain + 1) * MAXLABELS,
-				 sizeof (bool_t));
-   rs.range_no	       = 0;
-   max_domain 	       = wfa->basis_states - 1;
+                                 sizeof (bool_t));
+   rs.range_no         = 0;
+   max_domain          = wfa->basis_states - 1;
    sort_ranges (last_domain, &max_domain, &rs, wfa);
 
    /*
@@ -127,42 +127,42 @@ delta_decoding (wfa_t *wfa, unsigned last_domain, bitfile_t *input)
    {
       arith_t  *decoder;
       model_t  *elements;
-      unsigned 	max_edges = read_rice_code (3, input);
+      unsigned  max_edges = read_rice_code (3, input);
 
       /*
        *  Get the probability array of the number of edges distribution
        *  and allocate the corresponding model.
        */
       {
-	 unsigned edge;
+         unsigned edge;
 
-	 for (edge = 0; edge <= max_edges; edge++)
-	    count [edge] = read_rice_code ((int) log2 (last_domain) - 2,
-					   input);
-	 elements = alloc_model (max_edges + 1, 0, 0, count);
+         for (edge = 0; edge <= max_edges; edge++)
+            count [edge] = read_rice_code ((int) log2 (last_domain) - 2,
+                                           input);
+         elements = alloc_model (max_edges + 1, 0, 0, count);
       }
 
       /*
        *  Get number of elements per matrix row
        */
       {
-	 unsigned row;
-
-	 n_edges = Calloc (wfa->states, sizeof (unsigned));
-	 decoder = alloc_decoder (input);
-	 for (row = range = 0; range < rs.range_no; range++)
-	    if (!rs.range_subdivided [range])
-	    {
-	       state = rs.range_state [range];
-	       label = rs.range_label [range];
-
-	       n_edges [row++]
-		  = decode_symbol (decoder, elements)
-		  - (isedge (wfa->into [state][label][0]) ? 1 : 0);
-	    }
-
-	 free_decoder (decoder);
-	 free_model (elements);
+         unsigned row;
+
+         n_edges = Calloc (wfa->states, sizeof (unsigned));
+         decoder = alloc_decoder (input);
+         for (row = range = 0; range < rs.range_no; range++)
+            if (!rs.range_subdivided [range])
+            {
+               state = rs.range_state [range];
+               label = rs.range_label [range];
+
+               n_edges [row++]
+                  = decode_symbol (decoder, elements)
+                  - (isedge (wfa->into [state][label][0]) ? 1 : 0);
+            }
+
+         free_decoder (decoder);
+         free_model (elements);
       }
    }
 
@@ -175,8 +175,8 @@ delta_decoding (wfa_t *wfa, unsigned last_domain, bitfile_t *input)
       u_word_t *mapping_coder1     = Calloc (wfa->states, sizeof (word_t));
       u_word_t *mapping2           = Calloc (wfa->states, sizeof (word_t));
       u_word_t *mapping_coder2     = Calloc (wfa->states, sizeof (word_t));
-      bool_t	use_normal_domains = get_bit (input);
-      bool_t	use_delta_domains  = get_bit (input);
+      bool_t    use_normal_domains = get_bit (input);
+      bool_t    use_delta_domains  = get_bit (input);
 
       /*
        *  Generate array of states which are admitted domains.
@@ -187,63 +187,63 @@ delta_decoding (wfa_t *wfa, unsigned last_domain, bitfile_t *input)
        *             coding the motion compensated prediction error
        */
       {
-	 unsigned n1, n2, state;
-
-	 for (n1 = n2 = state = 0; state < wfa->states; state++)
-	 {
-	    mapping1 [n1] = state;
-	    mapping_coder1 [state] = n1;
-	    if (usedomain (state, wfa)
-		&& (state < wfa->basis_states
-		    || use_delta_domains || !wfa->delta_state [state]))
-	       n1++;
-
-	    mapping2 [n2] = state;
-	    mapping_coder2 [state] = n2;
-	    if (usedomain (state, wfa)
-		&& (state < wfa->basis_states || use_normal_domains
-		    || wfa->delta_state [state]))
-	       n2++;
-	 }
+         unsigned n1, n2, state;
+
+         for (n1 = n2 = state = 0; state < wfa->states; state++)
+         {
+            mapping1 [n1] = state;
+            mapping_coder1 [state] = n1;
+            if (usedomain (state, wfa)
+                && (state < wfa->basis_states
+                    || use_delta_domains || !wfa->delta_state [state]))
+               n1++;
+
+            mapping2 [n2] = state;
+            mapping_coder2 [state] = n2;
+            if (usedomain (state, wfa)
+                && (state < wfa->basis_states || use_normal_domains
+                    || wfa->delta_state [state]))
+               n2++;
+         }
       }
 
       for (row = 0, range = 0; range < rs.range_no; range++)
-	 if (!rs.range_subdivided [range])
-	 {
-	    u_word_t *mapping;
-	    u_word_t *mapping_coder;
-	    unsigned  max_value;
-	    unsigned  edge;
-	    unsigned  state = rs.range_state [range];
-	    unsigned  label = rs.range_label [range];
-	    unsigned  last  = 1;
-
-	    if (wfa->delta_state [state] ||
-		wfa->mv_tree [state][label].type != NONE)
-	    {
-	       mapping 	     = mapping2;
-	       mapping_coder = mapping_coder2;
-	    }
-	    else
-	    {
-	       mapping 	     = mapping1;
-	       mapping_coder = mapping_coder1;
-	    }
-	    max_value = mapping_coder [rs.range_max_domain [range]];
-	    for (edge = n_edges [row]; edge; edge--)
-	    {
-	       unsigned domain;
-
-	       if (max_value - last)
-		  domain = read_bin_code (max_value - last, input) + last;
-	       else
-		  domain = max_value;
-	       append_edge (state, mapping [domain], -1, label, wfa);
-	       last = domain + 1;
-	       total++;
-	    }
-	    row++;
-	 }
+         if (!rs.range_subdivided [range])
+         {
+            u_word_t *mapping;
+            u_word_t *mapping_coder;
+            unsigned  max_value;
+            unsigned  edge;
+            unsigned  state = rs.range_state [range];
+            unsigned  label = rs.range_label [range];
+            unsigned  last  = 1;
+
+            if (wfa->delta_state [state] ||
+                wfa->mv_tree [state][label].type != NONE)
+            {
+               mapping       = mapping2;
+               mapping_coder = mapping_coder2;
+            }
+            else
+            {
+               mapping       = mapping1;
+               mapping_coder = mapping_coder1;
+            }
+            max_value = mapping_coder [rs.range_max_domain [range]];
+            for (edge = n_edges [row]; edge; edge--)
+            {
+               unsigned domain;
+
+               if (max_value - last)
+                  domain = read_bin_code (max_value - last, input) + last;
+               else
+                  domain = max_value;
+               append_edge (state, mapping [domain], -1, label, wfa);
+               last = domain + 1;
+               total++;
+            }
+            row++;
+         }
       Free (mapping1);
       Free (mapping_coder1);
       Free (mapping2);
@@ -267,23 +267,23 @@ column_0_decoding (wfa_t *wfa, unsigned last_row, bitfile_t *input)
  *  All rows from 'wfa->basis_states' up to 'last_row' are decoded.
  *
  *  Return value:
- *	number of non-zero matrix elements (WFA edges)
+ *      number of non-zero matrix elements (WFA edges)
  *
  *  Side effects:
- *	'wfa->into' is filled with decoded values
+ *      'wfa->into' is filled with decoded values
  */
 {
-   unsigned  row;			/* current matrix row */
-   unsigned  total = 0;			/* total number of edges in col 0 */
-   unsigned *prob_ptr;			/* pointer to current probability */
-   unsigned *last;			/* pointer to minimum probability */
-   unsigned *first;			/* pointer to maximum probability */
-   unsigned *new_prob_ptr;		/* ptr to probability of last domain */
-   unsigned *prob;			/* probability array */
-   u_word_t  high;			/* Start of the current code range */
-   u_word_t  low;			/* End of the current code range */
-   u_word_t  code;			/* The present input code value */
-   word_t   *is_leaf;			/* pointer to the tree structure */
+   unsigned  row;                       /* current matrix row */
+   unsigned  total = 0;                 /* total number of edges in col 0 */
+   unsigned *prob_ptr;                  /* pointer to current probability */
+   unsigned *last;                      /* pointer to minimum probability */
+   unsigned *first;                     /* pointer to maximum probability */
+   unsigned *new_prob_ptr;              /* ptr to probability of last domain */
+   unsigned *prob;                      /* probability array */
+   u_word_t  high;                      /* Start of the current code range */
+   u_word_t  low;                       /* End of the current code range */
+   u_word_t  code;                      /* The present input code value */
+   word_t   *is_leaf;                   /* pointer to the tree structure */
 
    /*
     *  Compute the asymmetric probability array
@@ -292,14 +292,14 @@ column_0_decoding (wfa_t *wfa, unsigned last_row, bitfile_t *input)
     */
    {
       unsigned n;
-      unsigned index;			/* probability index */
-      unsigned exp;			/* current exponent */
+      unsigned index;                   /* probability index */
+      unsigned exp;                     /* current exponent */
 
       prob = Calloc (1 << (MAX_PROB + 1), sizeof (unsigned));
 
       for (index = 0, n = MIN_PROB; n <= MAX_PROB; n++)
-	 for (exp = 0; exp < 1U << n; exp++, index++)
-	    prob [index] = n;
+         for (exp = 0; exp < 1U << n; exp++, index++)
+            prob [index] = n;
    }
 
    first = prob_ptr = new_prob_ptr = prob;
@@ -307,8 +307,8 @@ column_0_decoding (wfa_t *wfa, unsigned last_row, bitfile_t *input)
 
    is_leaf = wfa->tree [wfa->basis_states]; /* use pointer arithmetics ... */
 
-   high = HIGH;				/* 1.0 */
-   low  = LOW;				/* 0.0 */
+   high = HIGH;                         /* 1.0 */
+   low  = LOW;                          /* 0.0 */
    code = get_bits (input, 16);
 
    /*
@@ -324,73 +324,73 @@ column_0_decoding (wfa_t *wfa, unsigned last_row, bitfile_t *input)
     */
    for (row = wfa->basis_states; row <= last_row; row++)
    {
-      unsigned count;			/* value in the current interval */
+      unsigned count;                   /* value in the current interval */
 
       /*
        *  Read label 0 element
        */
-      if (isrange (*is_leaf++))		/* valid matrix index */
+      if (isrange (*is_leaf++))         /* valid matrix index */
       {
-	 count = high - ((high - low) >> *prob_ptr);
-	 if (code < count)
-	 {
-	    if (prob_ptr < last)	/* model update */
-	       prob_ptr++;
-	    /*
-	     *  Decode the MPS '0'
-	     */
-	    high = count - 1;
-
-	    RESCALE_INPUT_INTERVAL;
-	 }
-	 else
-	 {
-	    prob_ptr = ((prob_ptr - first) >> 1) + first; /* model update */
-	    /*
-	     *  Decode the LPS '1'
-	     */
-	    low = count;
-
-	    RESCALE_INPUT_INTERVAL;
-	    /*
-	     *  Restore the transition (weight = -1)
-	     */
-	    append_edge (row, 0, -1, 0, wfa);
-	    total++;
-	 }
+         count = high - ((high - low) >> *prob_ptr);
+         if (code < count)
+         {
+            if (prob_ptr < last)        /* model update */
+               prob_ptr++;
+            /*
+             *  Decode the MPS '0'
+             */
+            high = count - 1;
+
+            RESCALE_INPUT_INTERVAL;
+         }
+         else
+         {
+            prob_ptr = ((prob_ptr - first) >> 1) + first; /* model update */
+            /*
+             *  Decode the LPS '1'
+             */
+            low = count;
+
+            RESCALE_INPUT_INTERVAL;
+            /*
+             *  Restore the transition (weight = -1)
+             */
+            append_edge (row, 0, -1, 0, wfa);
+            total++;
+         }
       }
       /*
        *  Read label 1 element
        */
       if (isrange (*is_leaf++)) /* valid matrix index */
       {
-	 count = high - ((high - low) >> *prob_ptr);
-	 if (code < count)
-	 {
-	    if (prob_ptr < last)
-	       prob_ptr++;		/* model update */
-	    /*
-	     *  Decode the MPS '0'
-	     */
-	    high = count - 1;
-
-	    RESCALE_INPUT_INTERVAL;
-	 }
-	 else
-	 {
-	    prob_ptr = ((prob_ptr - first) >> 1) + first; /* model update */
-	    /*
-	     *  Decode the LPS '1'
-	     */
-	    low = count;
-
-	    RESCALE_INPUT_INTERVAL;
-	    /*
-	     *  Restore the transition (weight = -1)
-	     */
-	    append_edge (row, 0, -1, 1, wfa);
-	    total++;
-	 }
+         count = high - ((high - low) >> *prob_ptr);
+         if (code < count)
+         {
+            if (prob_ptr < last)
+               prob_ptr++;              /* model update */
+            /*
+             *  Decode the MPS '0'
+             */
+            high = count - 1;
+
+            RESCALE_INPUT_INTERVAL;
+         }
+         else
+         {
+            prob_ptr = ((prob_ptr - first) >> 1) + first; /* model update */
+            /*
+             *  Decode the LPS '1'
+             */
+            low = count;
+
+            RESCALE_INPUT_INTERVAL;
+            /*
+             *  Restore the transition (weight = -1)
+             */
+            append_edge (row, 0, -1, 1, wfa);
+            total++;
+         }
       }
    }
 
@@ -408,24 +408,24 @@ chroma_decoding (wfa_t *wfa, bitfile_t *input)
  *  chroma channels Cb and Cr from stream 'input'.
  *
  *  Return value:
- *	number of non-zero matrix elements (WFA edges)
+ *      number of non-zero matrix elements (WFA edges)
  *
  *  Side effects:
- *	'wfa->into' is filled with decoded values
+ *      'wfa->into' is filled with decoded values
  */
 {
-   unsigned  domain;			/* current domain, counter */
-   unsigned  total = 0;			/* total number of chroma edges */
-   unsigned *prob_ptr;			/* pointer to current probability */
-   unsigned *last;			/* pointer to minimum probability */
-   unsigned *first;			/* pointer to maximum probability */
-   unsigned *new_prob_ptr;		/* ptr to probability of last domain */
-   unsigned *prob;			/* probability array */
-   u_word_t  high;			/* Start of the current code range */
-   u_word_t  low;			/* End of the current code range */
-   u_word_t  code;			/* The present input code value */
-   word_t   *y_domains;			/* domain images corresponding to Y */
-   int	     save_index;		/* YES: store current probability */
+   unsigned  domain;                    /* current domain, counter */
+   unsigned  total = 0;                 /* total number of chroma edges */
+   unsigned *prob_ptr;                  /* pointer to current probability */
+   unsigned *last;                      /* pointer to minimum probability */
+   unsigned *first;                     /* pointer to maximum probability */
+   unsigned *new_prob_ptr;              /* ptr to probability of last domain */
+   unsigned *prob;                      /* probability array */
+   u_word_t  high;                      /* Start of the current code range */
+   u_word_t  low;                       /* End of the current code range */
+   u_word_t  code;                      /* The present input code value */
+   word_t   *y_domains;                 /* domain images corresponding to Y */
+   int       save_index;                /* YES: store current probability */
 
    /*
     *  Compute the asymmetric probability array
@@ -434,26 +434,26 @@ chroma_decoding (wfa_t *wfa, bitfile_t *input)
     */
    {
       unsigned n;
-      unsigned index;			/* probability index */
-      unsigned exp;			/* current exponent */
+      unsigned index;                   /* probability index */
+      unsigned exp;                     /* current exponent */
 
       prob = Calloc (1 << (MAX_PROB + 1), sizeof (unsigned));
 
       for (index = 0, n = MIN_PROB; n <= MAX_PROB; n++)
-	 for (exp = 0; exp < 1U << n; exp++, index++)
-	    prob [index] = n;
+         for (exp = 0; exp < 1U << n; exp++, index++)
+            prob [index] = n;
    }
 
-   high = HIGH;				/* 1.0 */
-   low  = LOW;				/* 0.0 */
+   high = HIGH;                         /* 1.0 */
+   low  = LOW;                          /* 0.0 */
    code = get_bits (input, 16);
 
    /*
     *  Compute list of admitted domains
     */
    y_domains = compute_hits (wfa->basis_states,
-			     wfa->tree [wfa->tree [wfa->root_state][0]][0],
-			     wfa->wfainfo->chroma_max_states, wfa);
+                             wfa->tree [wfa->tree [wfa->root_state][0]][0],
+                             wfa->wfainfo->chroma_max_states, wfa);
 
    first = prob_ptr = new_prob_ptr = prob;
    last  = first + 1020;
@@ -465,7 +465,7 @@ chroma_decoding (wfa_t *wfa, bitfile_t *input)
     */
    for (domain = 0; y_domains [domain] != -1; domain++)
    {
-      unsigned 	row	= wfa->tree [wfa->tree [wfa->root_state][0]][0] + 1;
+      unsigned  row     = wfa->tree [wfa->tree [wfa->root_state][0]][0] + 1;
       word_t   *is_leaf = wfa->tree [row];
 
       prob_ptr   = new_prob_ptr;
@@ -473,87 +473,87 @@ chroma_decoding (wfa_t *wfa, bitfile_t *input)
 
       for (; row < wfa->states; row++)
       {
-	 unsigned count;		/* value in the current interval */
-	 /*
-	  *  Read label 0 element
-	  */
-	 if (isrange (*is_leaf++)) 	/* valid matrix index */
-	 {
-	    count = high - ((high - low) >> *prob_ptr);
-	    if (code < count)
-	    {
-	       if (prob_ptr < last)
-		  prob_ptr++;
-	       /*
-		*  Decode the MPS '0'
-		*/
-	       high = count - 1;
-
-	       RESCALE_INPUT_INTERVAL;
-	    }
-	    else
-	    {
-	       prob_ptr = ((prob_ptr - first) >> 1) + first;
-	       /*
-		*  Decode the LPS '1'
-		*/
-	       low = count;
-
-	       RESCALE_INPUT_INTERVAL;
-	       /*
-		*  Restore the transition (weight = -1)
-		*/
-	       append_edge (row, y_domains [domain], -1, 0, wfa);
-	       total++;
-	    }
-	 }
-	 /*
-	  *  Read label 1 element
-	  */
-	 if (isrange (*is_leaf++)) /* valid matrix index */
-	 {
-	    count = high - ((high - low) >> *prob_ptr);
-	    if (code < count)
-	    {
-	       if (prob_ptr < last)
-		  prob_ptr++;
-	       /*
-		*  Decode the MPS '0'
-		*/
-	       high = count - 1;
-
-	       RESCALE_INPUT_INTERVAL;
-	    }
-	    else
-	    {
-	       prob_ptr = ((prob_ptr - first) >> 1) + first;
-	       /*
-		*  Decode the LPS '1'
-		*/
-	       low = count;
-
-	       RESCALE_INPUT_INTERVAL;
-	       /*
-		*  Restore the transition (weight = -1)
-		*/
-	       append_edge (row, y_domains [domain], -1, 1, wfa);
-	       total++;
-	    }
-	 }
-	 if (save_index)
-	 {
-	    save_index 	 = NO;
-	    new_prob_ptr = prob_ptr;
-	 }
+         unsigned count;                /* value in the current interval */
+         /*
+          *  Read label 0 element
+          */
+         if (isrange (*is_leaf++))      /* valid matrix index */
+         {
+            count = high - ((high - low) >> *prob_ptr);
+            if (code < count)
+            {
+               if (prob_ptr < last)
+                  prob_ptr++;
+               /*
+                *  Decode the MPS '0'
+                */
+               high = count - 1;
+
+               RESCALE_INPUT_INTERVAL;
+            }
+            else
+            {
+               prob_ptr = ((prob_ptr - first) >> 1) + first;
+               /*
+                *  Decode the LPS '1'
+                */
+               low = count;
+
+               RESCALE_INPUT_INTERVAL;
+               /*
+                *  Restore the transition (weight = -1)
+                */
+               append_edge (row, y_domains [domain], -1, 0, wfa);
+               total++;
+            }
+         }
+         /*
+          *  Read label 1 element
+          */
+         if (isrange (*is_leaf++)) /* valid matrix index */
+         {
+            count = high - ((high - low) >> *prob_ptr);
+            if (code < count)
+            {
+               if (prob_ptr < last)
+                  prob_ptr++;
+               /*
+                *  Decode the MPS '0'
+                */
+               high = count - 1;
+
+               RESCALE_INPUT_INTERVAL;
+            }
+            else
+            {
+               prob_ptr = ((prob_ptr - first) >> 1) + first;
+               /*
+                *  Decode the LPS '1'
+                */
+               low = count;
+
+               RESCALE_INPUT_INTERVAL;
+               /*
+                *  Restore the transition (weight = -1)
+                */
+               append_edge (row, y_domains [domain], -1, 1, wfa);
+               total++;
+            }
+         }
+         if (save_index)
+         {
+            save_index   = NO;
+            new_prob_ptr = prob_ptr;
+         }
       }
    }
 
    Free (y_domains);
 
    compute_y_state (wfa->tree [wfa->tree [wfa->root_state][0]][1],
-		    wfa->tree [wfa->tree [wfa->root_state][0]][0], wfa);
+                    wfa->tree [wfa->tree [wfa->root_state][0]][0], wfa);
    compute_y_state (wfa->tree [wfa->tree [wfa->root_state][1]][0],
-		    wfa->tree [wfa->tree [wfa->root_state][0]][0], wfa);
+                    wfa->tree [wfa->tree [wfa->root_state][0]][0], wfa);
 
    first = prob_ptr = new_prob_ptr = prob;
 
@@ -565,44 +565,44 @@ chroma_decoding (wfa_t *wfa, bitfile_t *input)
     *  Again, quasi arithmetic decoding is used for this task.
     */
    {
-      unsigned 	row;
+      unsigned  row;
 
       for (row = wfa->tree [wfa->tree [wfa->root_state][0]][0] + 1;
-	   row < wfa->states; row++)
+           row < wfa->states; row++)
       {
-	 int label;			/* current label */
-
-	 for (label = 0; label < MAXLABELS; label++)
-	 {
-	    u_word_t count = high - ((high - low) >> *prob_ptr);
-
-	    if (code < count)
-	    {
-	       if (prob_ptr < last)
-		  prob_ptr++;
-	       /*
-		*  Decode the MPS '0'
-		*/
-	       high = count - 1;
-
-	       RESCALE_INPUT_INTERVAL;
-	    }
-	    else
-	    {
-	       prob_ptr = ((prob_ptr - first) >> 1) + first;
-	       /*
-		*  Decode the LPS '1'
-		*/
-	       low = count;
-
-	       RESCALE_INPUT_INTERVAL;
-	       /*
-		*  Restore the transition (weight = -1)
-		*/
-	       append_edge (row, wfa->y_state [row][label], -1, label, wfa);
-	       total++;
-	    }
-	 }
+         int label;                     /* current label */
+
+         for (label = 0; label < MAXLABELS; label++)
+         {
+            u_word_t count = high - ((high - low) >> *prob_ptr);
+
+            if (code < count)
+            {
+               if (prob_ptr < last)
+                  prob_ptr++;
+               /*
+                *  Decode the MPS '0'
+                */
+               high = count - 1;
+
+               RESCALE_INPUT_INTERVAL;
+            }
+            else
+            {
+               prob_ptr = ((prob_ptr - first) >> 1) + first;
+               /*
+                *  Decode the LPS '1'
+                */
+               low = count;
+
+               RESCALE_INPUT_INTERVAL;
+               /*
+                *  Restore the transition (weight = -1)
+                */
+               append_edge (row, wfa->y_state [row][label], -1, label, wfa);
+               total++;
+            }
+         }
       }
    }
 
@@ -625,20 +625,20 @@ compute_y_state (int state, int y_state, wfa_t *wfa)
  *  No return value.
  *
  *  Side effects:
- *	'wfa->y_state' is filled with the generated tree structure.
+ *      'wfa->y_state' is filled with the generated tree structure.
  */
 {
    unsigned label;
 
    for (label = 0; label < MAXLABELS; label++)
       if (isrange (y_state))
-	 wfa->y_state [state][label] = RANGE;
+         wfa->y_state [state][label] = RANGE;
       else
       {
-	 wfa->y_state [state][label] = wfa->tree [y_state][label];
-	 if (!isrange (wfa->tree [state][label]))
-	    compute_y_state (wfa->tree [state][label],
-			     wfa->y_state [state][label], wfa);
+         wfa->y_state [state][label] = wfa->tree [y_state][label];
+         if (!isrange (wfa->tree [state][label]))
+            compute_y_state (wfa->tree [state][label],
+                             wfa->y_state [state][label], wfa);
       }
 
 }
diff --git a/converter/other/fiasco/input/matrices.h b/converter/other/fiasco/input/matrices.h
index 6d1cef15..193bc6a7 100644
--- a/converter/other/fiasco/input/matrices.h
+++ b/converter/other/fiasco/input/matrices.h
@@ -1,8 +1,8 @@
 /*
  *  matrices.h
  *
- *  Written by:		Ullrich Hafner
- *		
+ *  Written by:         Ullrich Hafner
+ *              
  *  This file is part of FIASCO (Fractal Image And Sequence COdec)
  *  Copyright (C) 1994-2000 Ullrich Hafner
  */
diff --git a/converter/other/fiasco/input/mc.c b/converter/other/fiasco/input/mc.c
index afc0c1c3..8d93d931 100644
--- a/converter/other/fiasco/input/mc.c
+++ b/converter/other/fiasco/input/mc.c
@@ -1,8 +1,8 @@
 /*
- *  mc.c:	Input of motion compensation
+ *  mc.c:       Input of motion compensation
  *
  *  written by: Michael Unger
- *		Ullrich Hafner
+ *              Ullrich Hafner
  *
  *  This file is part of FIASCO (Fractal Image And Sequence COdec)
  *  Copyright (C) 1994-2000 Ullrich Hafner
@@ -31,27 +31,27 @@
 
 /*****************************************************************************
 
-			     local variables
+                             local variables
 
 *****************************************************************************/
 
 typedef struct huff_node
 {
-   int		     code_index;	/* leaf if index >= 0 */
-   struct huff_node *left;		/* follow if '0' bit read */
-   struct huff_node *right;		/* follow if '1' bit read */
-   int		     index_set [34];
+   int               code_index;        /* leaf if index >= 0 */
+   struct huff_node *left;              /* follow if '0' bit read */
+   struct huff_node *right;             /* follow if '1' bit read */
+   int               index_set [34];
 } huff_node_t;
 
 /*****************************************************************************
 
-				prototypes
+                                prototypes
 
 *****************************************************************************/
 
 static void
 decode_mc_tree (frame_type_e frame_type, unsigned max_state,
-		wfa_t *wfa, bitfile_t *input);
+                wfa_t *wfa, bitfile_t *input);
 static void
 decode_mc_coords (unsigned max_state, wfa_t *wfa, bitfile_t *input);
 static int
@@ -63,7 +63,7 @@ create_huff_node (huff_node_t *hn, int bits_processed);
 
 /*****************************************************************************
 
-				public code
+                                public code
 
 *****************************************************************************/
 
@@ -76,12 +76,12 @@ read_mc (frame_type_e frame_type, wfa_t *wfa, bitfile_t *input)
  *  No return value.
  *
  *  Side effects:
- *	'wfa->mv_tree' is filled with the decoded values.
+ *      'wfa->mv_tree' is filled with the decoded values.
  */
 {
    unsigned max_state = wfa->wfainfo->color
-			? wfa->tree [wfa->tree [wfa->root_state][0]][0]
-			: wfa->states;
+                        ? wfa->tree [wfa->tree [wfa->root_state][0]][0]
+                        : wfa->states;
 
    decode_mc_tree (frame_type, max_state, wfa, input);
    decode_mc_coords (max_state, wfa, input);
@@ -89,13 +89,13 @@ read_mc (frame_type_e frame_type, wfa_t *wfa, bitfile_t *input)
 
 /*****************************************************************************
 
-				private code
+                                private code
 
 *****************************************************************************/
 
 static void
 decode_mc_tree (frame_type_e frame_type, unsigned max_state,
-		wfa_t *wfa, bitfile_t *input)
+                wfa_t *wfa, bitfile_t *input)
 /*
  *  Read tree of motion compensation decisions of the 'input' stream.
  *  Depending on 'frame_type' different decoding methods are used.
@@ -104,13 +104,13 @@ decode_mc_tree (frame_type_e frame_type, unsigned max_state,
  *  No return value.
  *
  *  Side effects:
- *	'wfa->mv_tree' is filled with decoded values.
+ *      'wfa->mv_tree' is filled with decoded values.
  */
 {
-   unsigned  state;			/* current state */
-   unsigned *queue;			/* states in breadth first order */
-   unsigned  last;			/* last node
-					   (update for each new node) */
+   unsigned  state;                     /* current state */
+   unsigned *queue;                     /* states in breadth first order */
+   unsigned  last;                      /* last node
+                                           (update for each new node) */
 
    /*
     *  Traverse tree in breadth first order (starting at level
@@ -120,68 +120,68 @@ decode_mc_tree (frame_type_e frame_type, unsigned max_state,
    queue = Calloc (MAXSTATES, sizeof (unsigned));
    for (last = 0, state = wfa->basis_states; state < max_state; state++)
       if (wfa->level_of_state [state] - 1 == (int) wfa->wfainfo->p_max_level)
-	 queue [last++] = state;	/* init level 'p_max_level' */
+         queue [last++] = state;        /* init level 'p_max_level' */
 
    if (frame_type == P_FRAME)
    {
-      unsigned label;			/* current label */
-      unsigned current;			/* current node to process */
+      unsigned label;                   /* current label */
+      unsigned current;                 /* current node to process */
 
       for (current = 0; current < last; current++)
-	 for (label = 0; label < MAXLABELS; label++)
-	 {
-	    state = queue[current];
-	    if (wfa->x [state][label]	/* process visible states only */
-		+  width_of_level (wfa->level_of_state [state] - 1)
-		<= wfa->wfainfo->width
-		&&
-		wfa->y [state][label]
-		+  height_of_level (wfa->level_of_state [state] - 1)
-		<= wfa->wfainfo->height)
-	    {
-	       wfa->mv_tree [state][label].type
-		  = get_bit (input) ? NONE : FORWARD;
-	    }
-	    else
-	       wfa->mv_tree [state][label].type = NONE;
-	    if (wfa->mv_tree [state][label].type == NONE &&
-		!isrange (wfa->tree [state][label]) &&
-		wfa->level_of_state [state] - 1 >=
-		(int) wfa->wfainfo->p_min_level)
-	       queue [last++] = wfa->tree [state][label]; /* append child  */
-	 }
+         for (label = 0; label < MAXLABELS; label++)
+         {
+            state = queue[current];
+            if (wfa->x [state][label]   /* process visible states only */
+                +  width_of_level (wfa->level_of_state [state] - 1)
+                <= wfa->wfainfo->width
+                &&
+                wfa->y [state][label]
+                +  height_of_level (wfa->level_of_state [state] - 1)
+                <= wfa->wfainfo->height)
+            {
+               wfa->mv_tree [state][label].type
+                  = get_bit (input) ? NONE : FORWARD;
+            }
+            else
+               wfa->mv_tree [state][label].type = NONE;
+            if (wfa->mv_tree [state][label].type == NONE &&
+                !isrange (wfa->tree [state][label]) &&
+                wfa->level_of_state [state] - 1 >=
+                (int) wfa->wfainfo->p_min_level)
+               queue [last++] = wfa->tree [state][label]; /* append child  */
+         }
    }
    else
    {
-      unsigned label;			/* current label */
-      unsigned current;			/* current node to process */
+      unsigned label;                   /* current label */
+      unsigned current;                 /* current node to process */
 
       for (current = 0; current < last; current++)
-	 for (label = 0; label < MAXLABELS; label++)
-	 {
-	    state = queue[current];
-	    if (wfa->x [state][label]	/* process visible states only */
-		+ width_of_level (wfa->level_of_state [state] - 1)
-		> wfa->wfainfo->width
-		||
-		wfa->y [state][label]
-		+ height_of_level (wfa->level_of_state [state] - 1)
-		> wfa->wfainfo->height)
-	       wfa->mv_tree[state][label].type = NONE;
-	    else if (get_bit (input))	/* 1   */
-	       wfa->mv_tree[state][label].type = NONE;
-	    else if (get_bit (input))	/* 01  */
-	       wfa->mv_tree[state][label].type = INTERPOLATED;
-	    else if (get_bit (input))	/* 001 */
-	       wfa->mv_tree[state][label].type = BACKWARD;
-	    else			/* 000 */
-	       wfa->mv_tree[state][label].type = FORWARD;
-	    if (wfa->mv_tree[state][label].type == NONE &&
-		!isrange (wfa->tree[state][label]) &&
-		wfa->level_of_state[state] - 1
-		>= (int) wfa->wfainfo->p_min_level)
-	       queue[last++] = wfa->tree[state][label]; /* append child  */
-	 }
+         for (label = 0; label < MAXLABELS; label++)
+         {
+            state = queue[current];
+            if (wfa->x [state][label]   /* process visible states only */
+                + width_of_level (wfa->level_of_state [state] - 1)
+                > wfa->wfainfo->width
+                ||
+                wfa->y [state][label]
+                + height_of_level (wfa->level_of_state [state] - 1)
+                > wfa->wfainfo->height)
+               wfa->mv_tree[state][label].type = NONE;
+            else if (get_bit (input))   /* 1   */
+               wfa->mv_tree[state][label].type = NONE;
+            else if (get_bit (input))   /* 01  */
+               wfa->mv_tree[state][label].type = INTERPOLATED;
+            else if (get_bit (input))   /* 001 */
+               wfa->mv_tree[state][label].type = BACKWARD;
+            else                        /* 000 */
+               wfa->mv_tree[state][label].type = FORWARD;
+            if (wfa->mv_tree[state][label].type == NONE &&
+                !isrange (wfa->tree[state][label]) &&
+                wfa->level_of_state[state] - 1
+                >= (int) wfa->wfainfo->p_min_level)
+               queue[last++] = wfa->tree[state][label]; /* append child  */
+         }
    }
 
    INPUT_BYTE_ALIGN (input);
@@ -198,12 +198,12 @@ decode_mc_coords (unsigned max_state, wfa_t *wfa, bitfile_t *input)
  *  No return value.
  *
  *  Side effects:
- *	'wfa->mv_tree' is filled with decoded values.
+ *      'wfa->mv_tree' is filled with decoded values.
  */
 {
-   unsigned	       label;		/* current label */
-   unsigned	       state;		/* current state */
-   mv_t		      *mv;		/* current motion vector */
+   unsigned            label;           /* current label */
+   unsigned            state;           /* current state */
+   mv_t               *mv;              /* current motion vector */
    static huff_node_t *huff_mv_root = NULL; /* root of huffman tree */
 
    if (huff_mv_root == NULL)
@@ -212,26 +212,26 @@ decode_mc_coords (unsigned max_state, wfa_t *wfa, bitfile_t *input)
    for (state = wfa->basis_states; state < max_state; state++)
       for (label = 0; label < MAXLABELS; label++)
       {
-	 mv = &wfa->mv_tree[state][label];
-	 switch (mv->type)
-	 {
-	    case NONE:
-	       break;
-	    case FORWARD:
-	       mv->fx = get_mv (1, huff_mv_root, input);
-	       mv->fy = get_mv (1, huff_mv_root, input);
-	       break;
-	    case BACKWARD:
-	       mv->bx = get_mv (1, huff_mv_root, input);
-	       mv->by = get_mv (1, huff_mv_root, input);
-	       break;
-	    case INTERPOLATED:
-	       mv->fx = get_mv (1, huff_mv_root, input);
-	       mv->fy = get_mv (1, huff_mv_root, input);
-	       mv->bx = get_mv (1, huff_mv_root, input);
-	       mv->by = get_mv (1, huff_mv_root, input);
-	       break;
-	 }
+         mv = &wfa->mv_tree[state][label];
+         switch (mv->type)
+         {
+            case NONE:
+               break;
+            case FORWARD:
+               mv->fx = get_mv (1, huff_mv_root, input);
+               mv->fy = get_mv (1, huff_mv_root, input);
+               break;
+            case BACKWARD:
+               mv->bx = get_mv (1, huff_mv_root, input);
+               mv->by = get_mv (1, huff_mv_root, input);
+               break;
+            case INTERPOLATED:
+               mv->fx = get_mv (1, huff_mv_root, input);
+               mv->fy = get_mv (1, huff_mv_root, input);
+               mv->bx = get_mv (1, huff_mv_root, input);
+               mv->by = get_mv (1, huff_mv_root, input);
+               break;
+         }
       }
 
    INPUT_BYTE_ALIGN (input);
@@ -249,11 +249,11 @@ get_mv (int f_code, huff_node_t *hn, bitfile_t *input)
    while (hn->code_index < 0)
    {
       if (hn->code_index == -2)
-	 error ("wrong huffman code !");
+         error ("wrong huffman code !");
       if (get_bit (input))
-	 hn = hn->right;
+         hn = hn->right;
       else
-	 hn = hn->left;
+         hn = hn->left;
    }
    vlc_code = hn->code_index - 16;
    if (vlc_code == 0 || f_code == 1)
@@ -275,7 +275,7 @@ create_huff_tree (void)
  *  Construct huffman tree from code table
  */
 {
-   unsigned	i;
+   unsigned     i;
    huff_node_t *huff_root = Calloc (1, sizeof (huff_node_t));
 
    /*
@@ -286,7 +286,7 @@ create_huff_tree (void)
 
    for (i = 0; i < 33; i++)
       huff_root->index_set [i] = i;
-   huff_root->index_set [i] = -1;	/* end marker */
+   huff_root->index_set [i] = -1;       /* end marker */
 
    create_huff_node (huff_root, 0);
 
@@ -299,14 +299,14 @@ create_huff_node (huff_node_t *hn, int bits_processed)
  *  Create one node in the huffman tree
  */
 {
-   int lind = 0;			/* next index of left huff_node */
-   int rind = 0;			/* next index of right huff_node */
+   int lind = 0;                        /* next index of left huff_node */
+   int rind = 0;                        /* next index of right huff_node */
    int code_len, i, ind;
 
    hn->code_index = -1;
-   if (hn->index_set [0] < 0)		/* empty index set ? */
+   if (hn->index_set [0] < 0)           /* empty index set ? */
    {
-      hn->code_index = -2;		/* error */
+      hn->code_index = -2;              /* error */
       return;
    }
    hn->left  = Calloc (1, sizeof (huff_node_t));
@@ -315,19 +315,19 @@ create_huff_node (huff_node_t *hn, int bits_processed)
    for (i = 0; (ind = hn->index_set[i]) >= 0; i++)
    {
       code_len = mv_code_table[ind][1];
-      if (code_len == bits_processed)	/* generate leaf */
+      if (code_len == bits_processed)   /* generate leaf */
       {
-	 hn->code_index = ind;
-	 Free (hn->left);
-	 Free (hn->right);
-	 return;
+         hn->code_index = ind;
+         Free (hn->left);
+         Free (hn->right);
+         return;
       }
       if (mv_code_table[ind][0] & (1 << (code_len - 1 - bits_processed)))
-	 hn->right->index_set[rind++] = ind;
+         hn->right->index_set[rind++] = ind;
       else
-	 hn->left->index_set[lind++] = ind;
+         hn->left->index_set[lind++] = ind;
    }
-   hn->right->index_set[rind] = -1;	/* set end markers */
+   hn->right->index_set[rind] = -1;     /* set end markers */
    hn->left->index_set[lind]  = -1;
    create_huff_node (hn->left, bits_processed + 1);
    create_huff_node (hn->right, bits_processed + 1);
diff --git a/converter/other/fiasco/input/mc.h b/converter/other/fiasco/input/mc.h
index 9d9d714d..a61f7e4a 100644
--- a/converter/other/fiasco/input/mc.h
+++ b/converter/other/fiasco/input/mc.h
@@ -2,8 +2,8 @@
  *  mc.h
  *
  *  written by: Michael Unger
- *		Ullrich Hafner
- 
+ *              Ullrich Hafner
+
  *  This file is part of FIASCO (Fractal Image And Sequence COdec)
  *  Copyright (C) 1994-2000 Ullrich Hafner
  */
diff --git a/converter/other/fiasco/input/nd.c b/converter/other/fiasco/input/nd.c
index 129a150e..0317073a 100644
--- a/converter/other/fiasco/input/nd.c
+++ b/converter/other/fiasco/input/nd.c
@@ -1,7 +1,7 @@
 /*
- *  nd.c:		Input of prediction tree
+ *  nd.c:               Input of prediction tree
  *
- *  Written by:		Ullrich Hafner
+ *  Written by:         Ullrich Hafner
  *
  *  This file is part of FIASCO (Fractal Image And Sequence COdec)
  *  Copyright (C) 1994-2000 Ullrich Hafner
@@ -30,7 +30,7 @@
 
 /*****************************************************************************
 
-				prototypes
+                                prototypes
 
 *****************************************************************************/
 
@@ -41,7 +41,7 @@ decode_nd_tree (wfa_t *wfa, bitfile_t *input);
 
 /*****************************************************************************
 
-				public code
+                                public code
 
 *****************************************************************************/
 
@@ -52,7 +52,7 @@ read_nd (wfa_t *wfa, bitfile_t *input)
  *  ND is used only at levels {'wfa->p_min_level', ... , 'wfa->p_max_level'}.
  *
  *  Side effects:
- *	'wfa->into' and 'wfa->weights' are filled with the decoded values
+ *      'wfa->into' and 'wfa->weights' are filled with the decoded values
  */
 {
    unsigned total = decode_nd_tree (wfa, input);
@@ -63,7 +63,7 @@ read_nd (wfa_t *wfa, bitfile_t *input)
 
 /*****************************************************************************
 
-				private code
+                                private code
 
 *****************************************************************************/
 
@@ -75,16 +75,16 @@ decode_nd_tree (wfa_t *wfa, bitfile_t *input)
  *  No return value.
  *
  *  Side effects:
- *	'wfa->into' is filled with the decoded values
+ *      'wfa->into' is filled with the decoded values
  */
 {
-   lqueue_t *queue;			/* queue of states */
-   int       next, state;		/* state and its current child */
-   unsigned  total = 0;			/* total number of predicted states */
-   u_word_t  sum0, sum1;		/* Probability model */
-   u_word_t  code;			/* The present input code value */
-   u_word_t  low;			/* Start of the current code range */
-   u_word_t  high;			/* End of the current code range */
+   lqueue_t *queue;                     /* queue of states */
+   int       next, state;               /* state and its current child */
+   unsigned  total = 0;                 /* total number of predicted states */
+   u_word_t  sum0, sum1;                /* Probability model */
+   u_word_t  code;                      /* The present input code value */
+   u_word_t  low;                       /* Start of the current code range */
+   u_word_t  high;                      /* End of the current code range */
 
    /*
     *  Initialize arithmetic decoder
@@ -108,78 +108,78 @@ decode_nd_tree (wfa_t *wfa, bitfile_t *input)
 
       if (wfa->level_of_state [next] > wfa->wfainfo->p_max_level + 1)
       {
-	 /*
-	  *  Nondetermismn is not allowed at levels larger than
-	  *  'wfa->wfainfo->p_max_level'.
-	  */
-	 for (label = 0; label < MAXLABELS; label++)
-	    if (ischild (state = wfa->tree [next][label]))
-	       queue_append (queue, &state); /* continue with children */
+         /*
+          *  Nondetermismn is not allowed at levels larger than
+          *  'wfa->wfainfo->p_max_level'.
+          */
+         for (label = 0; label < MAXLABELS; label++)
+            if (ischild (state = wfa->tree [next][label]))
+               queue_append (queue, &state); /* continue with children */
       }
       else if (wfa->level_of_state [next] > wfa->wfainfo->p_min_level)
       {
-	 for (label = 0; label < MAXLABELS; label++)
-	    if (ischild (state = wfa->tree [next][label]))
-	    {
-	       unsigned count;		/* Current interval count */
-	       unsigned range;		/* Current interval range */
-
-	       count = (((code - low) + 1) * sum1 - 1) / ((high - low) + 1);
-	       if (count < sum0)
-	       {
-		  /*
-		   *  Decode a '0' symbol
-		   *  First, the range is expanded to account for the
-		   *  symbol removal.
-		   */
-		  range = (high - low) + 1;
-		  high = low + (u_word_t) ((range * sum0) / sum1 - 1 );
-		  RESCALE_INPUT_INTERVAL;
-		  /*
-		   *  Update the frequency counts
-		   */
-		  sum0++;
-		  sum1++;
-		  if (sum1 > 50) /* scale the symbol frequencies */
-		  {
-		     sum0 >>= 1;
-		     sum1 >>= 1;
-		     if (!sum0)
-			sum0 = 1;
-		     if (sum0 >= sum1)
-			sum1 = sum0 + 1;
-		  }
-		  if (wfa->level_of_state [state] > wfa->wfainfo->p_min_level)
-		     queue_append (queue, &state);
-	       }
-	       else
-	       {
-		  /*
-		   *  Decode a '1' symbol
-		   *  First, the range is expanded to account for the
-		   *  symbol removal.
-		   */
-		  range = (high - low) + 1;
-		  high = low + (u_word_t) ((range * sum1) / sum1 - 1);
-		  low  = low + (u_word_t) ((range * sum0) / sum1);
-		  RESCALE_INPUT_INTERVAL;
-		  /*
-		   *  Update the frequency counts
-		   */
-		  sum1++;
-		  if (sum1 > 50) /* scale the symbol frequencies */
-		  {
-		     sum0 >>= 1;
-		     sum1 >>= 1;
-		     if (!sum0)
-			sum0 = 1;
-		     if (sum0 >= sum1)
-			sum1 = sum0 + 1;
-		  }
-		  append_edge (next, 0, -1, label, wfa);
-		  total++;
-	       }
-	    }
+         for (label = 0; label < MAXLABELS; label++)
+            if (ischild (state = wfa->tree [next][label]))
+            {
+               unsigned count;          /* Current interval count */
+               unsigned range;          /* Current interval range */
+
+               count = (((code - low) + 1) * sum1 - 1) / ((high - low) + 1);
+               if (count < sum0)
+               {
+                  /*
+                   *  Decode a '0' symbol
+                   *  First, the range is expanded to account for the
+                   *  symbol removal.
+                   */
+                  range = (high - low) + 1;
+                  high = low + (u_word_t) ((range * sum0) / sum1 - 1 );
+                  RESCALE_INPUT_INTERVAL;
+                  /*
+                   *  Update the frequency counts
+                   */
+                  sum0++;
+                  sum1++;
+                  if (sum1 > 50) /* scale the symbol frequencies */
+                  {
+                     sum0 >>= 1;
+                     sum1 >>= 1;
+                     if (!sum0)
+                        sum0 = 1;
+                     if (sum0 >= sum1)
+                        sum1 = sum0 + 1;
+                  }
+                  if (wfa->level_of_state [state] > wfa->wfainfo->p_min_level)
+                     queue_append (queue, &state);
+               }
+               else
+               {
+                  /*
+                   *  Decode a '1' symbol
+                   *  First, the range is expanded to account for the
+                   *  symbol removal.
+                   */
+                  range = (high - low) + 1;
+                  high = low + (u_word_t) ((range * sum1) / sum1 - 1);
+                  low  = low + (u_word_t) ((range * sum0) / sum1);
+                  RESCALE_INPUT_INTERVAL;
+                  /*
+                   *  Update the frequency counts
+                   */
+                  sum1++;
+                  if (sum1 > 50) /* scale the symbol frequencies */
+                  {
+                     sum0 >>= 1;
+                     sum1 >>= 1;
+                     if (!sum0)
+                        sum0 = 1;
+                     if (sum0 >= sum1)
+                        sum1 = sum0 + 1;
+                  }
+                  append_edge (next, 0, -1, label, wfa);
+                  total++;
+               }
+            }
       }
    }
    free_queue (queue);
@@ -199,21 +199,21 @@ decode_nd_coefficients (unsigned total, wfa_t *wfa, bitfile_t *input)
  *  No return value.
  *
  *  Side effects:
- *	'wfa->weights' is filled with the decoded values.
+ *      'wfa->weights' is filled with the decoded values.
  */
 {
-   unsigned *coefficients;		/* array of factors to encode */
-   unsigned *ptr;			/* pointer to current factor */
+   unsigned *coefficients;              /* array of factors to encode */
+   unsigned *ptr;                       /* pointer to current factor */
 
    /*
     *  Decode array of coefficients stored with arithmetic coding
     */
    {
-      const int	scaling  = 50;		/* scaling factor of prob. model */
+      const int scaling  = 50;          /* scaling factor of prob. model */
       unsigned  c_symbols = 1 << (wfa->wfainfo->dc_rpf->mantissa_bits + 1);
 
       ptr = coefficients = decode_array (input, NULL, &c_symbols, 1,
-					 total, scaling);
+                                         total, scaling);
    }
 
    /*
@@ -223,15 +223,15 @@ decode_nd_coefficients (unsigned total, wfa_t *wfa, bitfile_t *input)
       unsigned state, label;
 
       for (state = wfa->basis_states; state < wfa->states; state++)
-	 for (label = 0; label < MAXLABELS; label++)
-	    if (ischild (wfa->tree [state][label])
-		&& isedge (wfa->into [state][label][0]))
-	    {
-	       wfa->weight [state][label][0] = btor (*ptr++,
-						     wfa->wfainfo->dc_rpf);
-	       wfa->int_weight [state][label][0]
-		  = wfa->weight [state][label][0] * 512 + 0.5;
-	    }
+         for (label = 0; label < MAXLABELS; label++)
+            if (ischild (wfa->tree [state][label])
+                && isedge (wfa->into [state][label][0]))
+            {
+               wfa->weight [state][label][0] = btor (*ptr++,
+                                                     wfa->wfainfo->dc_rpf);
+               wfa->int_weight [state][label][0]
+                  = wfa->weight [state][label][0] * 512 + 0.5;
+            }
    }
    Free (coefficients);
 }
diff --git a/converter/other/fiasco/input/nd.h b/converter/other/fiasco/input/nd.h
index 0fe06cf1..57f46440 100644
--- a/converter/other/fiasco/input/nd.h
+++ b/converter/other/fiasco/input/nd.h
@@ -1,8 +1,8 @@
 /*
  *  nd.h
  *
- *  Written by:		Ullrich Hafner
- *		
+ *  Written by:         Ullrich Hafner
+ *              
  *  This file is part of FIASCO (Fractal Image And Sequence COdec)
  *  Copyright (C) 1994-2000 Ullrich Hafner
  */
diff --git a/converter/other/fiasco/input/read.c b/converter/other/fiasco/input/read.c
index c3aa77a8..50e271e5 100644
--- a/converter/other/fiasco/input/read.c
+++ b/converter/other/fiasco/input/read.c
@@ -1,7 +1,7 @@
 /*
- *  read.c:		Input of WFA files
+ *  read.c:             Input of WFA files
  *
- *  Written by:		Ullrich Hafner
+ *  Written by:         Ullrich Hafner
  *
  *  This file is part of FIASCO (Fractal Image And Sequence COdec)
  *  Copyright (C) 1994-2000 Ullrich Hafner
@@ -46,17 +46,17 @@
 
 /*****************************************************************************
 
-				prototypes
+                                prototypes
 
 *****************************************************************************/
 
 static void
 read_tiling (tiling_t *tiling, unsigned image_width, unsigned image_height,
-	     unsigned image_level, bitfile_t *input);
+             unsigned image_level, bitfile_t *input);
 
 /*****************************************************************************
 
-				public code
+                                public code
 
 *****************************************************************************/
 
@@ -66,14 +66,14 @@ open_wfa (const char *filename, wfa_info_t *wi)
  *  Open WFA file 'filename' and read header information.
  *
  *  Return value:
- *	Pointer to input stream (fileposition: first WFA frame)
+ *      Pointer to input stream (fileposition: first WFA frame)
  *
  *  Side effects:
- *	The values of the header of 'filename' are copied to 'wfainfo'.
+ *      The values of the header of 'filename' are copied to 'wfainfo'.
  *
  */
 {
-   bitfile_t *input;			/* pointer to WFA bitfile */
+   bitfile_t *input;                    /* pointer to WFA bitfile */
 
    assert (filename && wi);
 
@@ -83,7 +83,7 @@ open_wfa (const char *filename, wfa_info_t *wi)
     *  Check whether 'filename' is a regular WFA file
     */
    {
-      unsigned 	n;
+      unsigned  n;
       const char     *str;
 
       if (!(input = open_bitfile (filename, "FIASCO_DATA", READ_ACCESS)))
@@ -92,57 +92,57 @@ open_wfa (const char *filename, wfa_info_t *wi)
       for (str = FIASCO_MAGIC, n = strlen (FIASCO_MAGIC); n; n--)
           if (get_bits (input, 8) != (unsigned) *str++)
               error ("Input file %s is not a valid FIASCO file!", filename);
-      get_bits (input, 8);		/* fetch newline */
+      get_bits (input, 8);              /* fetch newline */
    }
 
    /*
     *  Read WFA header information
     */
    {
-      char	      basis_name [MAXSTRLEN]; /* temp. buffer */
-      const unsigned  rice_k = 8; 	/* parameter of Rice Code */
-      char     	     *str    = basis_name;
+      char            basis_name [MAXSTRLEN]; /* temp. buffer */
+      const unsigned  rice_k = 8;       /* parameter of Rice Code */
+      char           *str    = basis_name;
 
       while ((*str++ = get_bits (input, 8)) != 0
-	     && str < basis_name + MAXSTRLEN)
-	 ;
+             && str < basis_name + MAXSTRLEN)
+         ;
       if (str == basis_name + MAXSTRLEN)
-	 error ("Input file %s is not a valid FIASCO file!", filename);
+         error ("Input file %s is not a valid FIASCO file!", filename);
 
       {
-	 wi->release = read_rice_code (rice_k, input);
+         wi->release = read_rice_code (rice_k, input);
 
-	 if (wi->release > FIASCO_BINFILE_RELEASE)
-	    error ("Can't decode FIASCO files of file format release `%d'."
-		   "\nCurrent file format release is `%d'.", wi->release,
-		   FIASCO_BINFILE_RELEASE);
+         if (wi->release > FIASCO_BINFILE_RELEASE)
+            error ("Can't decode FIASCO files of file format release `%d'."
+                   "\nCurrent file format release is `%d'.", wi->release,
+                   FIASCO_BINFILE_RELEASE);
       }
 
       if (wi->release > 1)
       {
-	 header_type_e type;
-
-	 while ((type = read_rice_code (rice_k, input)) != HEADER_END)
-	 {
-	    char     buffer [MAXSTRLEN];
-	    unsigned n = 0;
-
-	    switch (type)
-	    {
-	       case HEADER_TITLE:
-		  while ((buffer [n++] = get_bits (input, 8)))
-		     ;
-		  wi->title = strdup (buffer);
-		  break;
-	       case HEADER_COMMENT:
-		  while ((buffer [n++] = get_bits (input, 8)))
-		     ;
-		  wi->comment = strdup (buffer);
-		  break;
-	       default:			/* should not happen */
-		  break;
-	    }
-	 }
+         header_type_e type;
+
+         while ((type = read_rice_code (rice_k, input)) != HEADER_END)
+         {
+            char     buffer [MAXSTRLEN];
+            unsigned n = 0;
+
+            switch (type)
+            {
+               case HEADER_TITLE:
+                  while ((buffer [n++] = get_bits (input, 8)))
+                     ;
+                  wi->title = strdup (buffer);
+                  break;
+               case HEADER_COMMENT:
+                  while ((buffer [n++] = get_bits (input, 8)))
+                     ;
+                  wi->comment = strdup (buffer);
+                  break;
+               default:                 /* should not happen */
+                  break;
+            }
+         }
       }
 
       wi->basis_name = strdup (basis_name);
@@ -155,65 +155,65 @@ open_wfa (const char *filename, wfa_info_t *wi)
        *  Compute bintree level
        */
       {
-	 unsigned lx = log2 (wi->width - 1) + 1;
-	 unsigned ly = log2 (wi->height - 1) + 1;
+         unsigned lx = log2 (wi->width - 1) + 1;
+         unsigned ly = log2 (wi->height - 1) + 1;
 
-	 wi->level = MAX(lx, ly) * 2 - ((ly == lx + 1) ? 1 : 0);
+         wi->level = MAX(lx, ly) * 2 - ((ly == lx + 1) ? 1 : 0);
       }
       wi->chroma_max_states = wi->color ? read_rice_code (rice_k, input) : -1;
       wi->p_min_level       = read_rice_code (rice_k, input);
       wi->p_max_level       = read_rice_code (rice_k, input);
       wi->frames            = read_rice_code (rice_k, input);
-      wi->smoothing	    = read_rice_code (rice_k, input);
+      wi->smoothing         = read_rice_code (rice_k, input);
 
       /*
        *  Read RPF models from disk
        */
       {
-	 unsigned 	    mantissa;
-	 fiasco_rpf_range_e range;
-
-	 mantissa = get_bits (input, 3) + 2;
-	 range    = get_bits (input, 2);
-	 wi->rpf  = alloc_rpf (mantissa, range);
-
-	 if (get_bit (input))		/* different DC model */
-	 {
-	    mantissa   = get_bits (input, 3) + 2;
-	    range      = get_bits (input, 2);
-	    wi->dc_rpf = alloc_rpf (mantissa, range);
-	 }
-	 else				/* use same model for DC coefficients */
-	    wi->dc_rpf = alloc_rpf (wi->rpf->mantissa_bits,
-				    wi->rpf->range_e);
-
-	 if (get_bit (input))		/* different delta model */
-	 {
-	    mantissa  = get_bits (input, 3) + 2;
-	    range     = get_bits (input, 2);
-	    wi->d_rpf = alloc_rpf (mantissa, range);
-	 }
-	 else
-	    wi->d_rpf = alloc_rpf (wi->rpf->mantissa_bits,
-				   wi->rpf->range_e);
-
-	 if (get_bit (input))		/* different DC delta model */
-	 {
-	    mantissa  	 = get_bits (input, 3) + 2;
-	    range     	 = get_bits (input, 2);
-	    wi->d_dc_rpf = alloc_rpf (mantissa, range);
-	 }
-	 else
-	    wi->d_dc_rpf = alloc_rpf (wi->dc_rpf->mantissa_bits,
-				      wi->dc_rpf->range_e);
+         unsigned           mantissa;
+         fiasco_rpf_range_e range;
+
+         mantissa = get_bits (input, 3) + 2;
+         range    = get_bits (input, 2);
+         wi->rpf  = alloc_rpf (mantissa, range);
+
+         if (get_bit (input))           /* different DC model */
+         {
+            mantissa   = get_bits (input, 3) + 2;
+            range      = get_bits (input, 2);
+            wi->dc_rpf = alloc_rpf (mantissa, range);
+         }
+         else                           /* use same model for DC coefficients */
+            wi->dc_rpf = alloc_rpf (wi->rpf->mantissa_bits,
+                                    wi->rpf->range_e);
+
+         if (get_bit (input))           /* different delta model */
+         {
+            mantissa  = get_bits (input, 3) + 2;
+            range     = get_bits (input, 2);
+            wi->d_rpf = alloc_rpf (mantissa, range);
+         }
+         else
+            wi->d_rpf = alloc_rpf (wi->rpf->mantissa_bits,
+                                   wi->rpf->range_e);
+
+         if (get_bit (input))           /* different DC delta model */
+         {
+            mantissa     = get_bits (input, 3) + 2;
+            range        = get_bits (input, 2);
+            wi->d_dc_rpf = alloc_rpf (mantissa, range);
+         }
+         else
+            wi->d_dc_rpf = alloc_rpf (wi->dc_rpf->mantissa_bits,
+                                      wi->dc_rpf->range_e);
       }
 
-      if (wi->frames > 1)		/* motion compensation stuff */
+      if (wi->frames > 1)               /* motion compensation stuff */
       {
-	 wi->fps           = read_rice_code (rice_k, input);
-	 wi->search_range  = read_rice_code (rice_k, input);
-	 wi->half_pixel    = get_bit (input) ? YES : NO;
-	 wi->B_as_past_ref = get_bit (input) ? YES : NO;
+         wi->fps           = read_rice_code (rice_k, input);
+         wi->search_range  = read_rice_code (rice_k, input);
+         wi->half_pixel    = get_bit (input) ? YES : NO;
+         wi->B_as_past_ref = get_bit (input) ? YES : NO;
       }
    }
 
@@ -230,12 +230,12 @@ read_basis (const char *filename, wfa_t *wfa)
  *  No return value.
  *
  *  Side effects:
- *	wfa->into, wfa->weights, wfa->final_distribution, wfa->basis_states
- *	wfa->domain_type wfa->wfainfo->basis_name, are filled with the
- *	values of the WFA basis.
+ *      wfa->into, wfa->weights, wfa->final_distribution, wfa->basis_states
+ *      wfa->domain_type wfa->wfainfo->basis_name, are filled with the
+ *      values of the WFA basis.
  */
 {
-   FILE	*input;				/* ASCII WFA initial basis file */
+   FILE *input;                         /* ASCII WFA initial basis file */
 
    assert (filename && wfa);
 
@@ -243,27 +243,27 @@ read_basis (const char *filename, wfa_t *wfa)
        !streq (wfa->wfainfo->basis_name, filename))
    {
       if (wfa->wfainfo->basis_name)
-	 Free (wfa->wfainfo->basis_name);
+         Free (wfa->wfainfo->basis_name);
       wfa->wfainfo->basis_name = strdup (filename);
    }
 
    if (get_linked_basis (filename, wfa))
-      return;				/* basis is linked with executable */
+      return;                           /* basis is linked with executable */
 
    /*
     *  Check whether 'wfa_name' is a regular ASCII WFA initial basis file
     */
    {
-      char magic [MAXSTRLEN];		/* WFA magic number */
+      char magic [MAXSTRLEN];           /* WFA magic number */
 
       if (!(input = open_file (filename, "FIASCO_DATA", READ_ACCESS)))
-	 file_error(filename);
+         file_error(filename);
 
       if (fscanf (input, MAXSTRLEN_SCANF, magic) != 1)
-	 error ("Format error: ASCII FIASCO initial basis file %s", filename);
+         error ("Format error: ASCII FIASCO initial basis file %s", filename);
       else if (!streq (FIASCO_BASIS_MAGIC, magic))
-	 error ("Input file %s is not an ASCII FIASCO initial basis!",
-		filename);
+         error ("Input file %s is not an ASCII FIASCO initial basis!",
+                filename);
    }
 
    /*
@@ -273,74 +273,74 @@ read_basis (const char *filename, wfa_t *wfa)
     *        Don't define any transitions of state 0 in an initial basis.
     *
     *  Header:
-    *   type		|description
-    *	----------------+-----------
-    *   string		|MAGIC Number "Wfa"
-    *	int		|Number of basis states 'N'
-    *	bool_t-array[N]	|use vector in linear combinations,
-    *			|0: don't use vector (auxiliary state)
-    *			|1: use vector in linear combinations
-    *	float-array[N]	|final distribution of every state
+    *   type            |description
+    *   ----------------+-----------
+    *   string          |MAGIC Number "Wfa"
+    *   int             |Number of basis states 'N'
+    *   bool_t-array[N] |use vector in linear combinations,
+    *                   |0: don't use vector (auxiliary state)
+    *                   |1: use vector in linear combinations
+    *   float-array[N]  |final distribution of every state
     *
     *  Transitions:
     *
-    *      <state 1>			current state
-    *      <label> <into> <weight>	transition 1 of current state
-    *      <label> <into> <weight>	transition 2 of current state
+    *      <state 1>                    current state
+    *      <label> <into> <weight>      transition 1 of current state
+    *      <label> <into> <weight>      transition 2 of current state
     *      ...
-    *      <-1>				last transition marker
+    *      <-1>                         last transition marker
     *      <state 2>
     *      ...
-    *      <-1>				last transition marker
+    *      <-1>                         last transition marker
     *      <state N>
     *      ...
     *
-    *      <-1>				last transition marker
-    *      <-1>				last state marker
+    *      <-1>                         last transition marker
+    *      <-1>                         last state marker
     */
    {
       unsigned state;
 
       if (fscanf (input ,"%u", &wfa->basis_states) != 1)
-	 error ("Format error: ASCII FIASCO initial basis file %s", filename);
+         error ("Format error: ASCII FIASCO initial basis file %s", filename);
 
       /*
        *  State 0 is assumed to be the constant function f(x, y) = 128.
        */
       wfa->domain_type [0]        = USE_DOMAIN_MASK;
       wfa->final_distribution [0] = 128;
-      wfa->states 		  = wfa->basis_states;
+      wfa->states                 = wfa->basis_states;
       wfa->basis_states++;
 
       append_edge (0, 0, 1.0, 0, wfa);
       append_edge (0, 0, 1.0, 1, wfa);
 
       for (state = 1; state < wfa->basis_states; state++)
-	 wfa->domain_type [state]
-	    = read_int (input) ? USE_DOMAIN_MASK : AUXILIARY_MASK;
+         wfa->domain_type [state]
+            = read_int (input) ? USE_DOMAIN_MASK : AUXILIARY_MASK;
 
       for (state = 1; state < wfa->basis_states; state++)
-	 wfa->final_distribution[state] = read_real (input);
+         wfa->final_distribution[state] = read_real (input);
 
       /*
        *  Read transitions
        */
       for (state = 1; state < wfa->basis_states; state++)
       {
-	 unsigned domain;
-	 int      label;
-	 real_t   weight;
-
-	 if (read_int (input) != (int) state)
-	    error ("Format error: ASCII FIASCO initial basis file %s",
-		   filename);
-
-	 while((label = read_int (input)) != -1)
-	 {
-	    domain = read_int (input);
-	    weight = read_real (input);
-	    append_edge (state, domain, weight, label, wfa);
-	 }
+         unsigned domain;
+         int      label;
+         real_t   weight;
+
+         if (read_int (input) != (int) state)
+            error ("Format error: ASCII FIASCO initial basis file %s",
+                   filename);
+
+         while((label = read_int (input)) != -1)
+         {
+            domain = read_int (input);
+            weight = read_real (input);
+            append_edge (state, domain, weight, label, wfa);
+         }
       }
    }
 
@@ -357,13 +357,13 @@ read_next_wfa (wfa_t *wfa, bitfile_t *input)
  *  No return value.
  *
  *  Side effects:
- *	wfa->into, wfa->weights, wfa->final_distribution, wfa->states
- *	wfa->x, wfa->y, wfa->level_of_state, wfa->domain_type
+ *      wfa->into, wfa->weights, wfa->final_distribution, wfa->states
+ *      wfa->x, wfa->y, wfa->level_of_state, wfa->domain_type
  *      mt->type, mt->number are filled with the values of the WFA file.
  */
 {
-   tiling_t tiling;			/* tiling information */
-   unsigned frame_number;		/* current frame number */
+   tiling_t tiling;                     /* tiling information */
+   unsigned frame_number;               /* current frame number */
 
    assert (wfa && input);
 
@@ -371,14 +371,14 @@ read_next_wfa (wfa_t *wfa, bitfile_t *input)
     *  Frame header information
     */
    {
-      const unsigned rice_k = 8;	/* parameter of Rice Code */
+      const unsigned rice_k = 8;        /* parameter of Rice Code */
 
       wfa->states     = read_rice_code (rice_k, input);
       wfa->frame_type = read_rice_code (rice_k, input);
       frame_number    = read_rice_code (rice_k, input);
    }
 
-   if (wfa->wfainfo->release > 1)	/* no alignment in version 1 */
+   if (wfa->wfainfo->release > 1)       /* no alignment in version 1 */
    {
       INPUT_BYTE_ALIGN (input);
    }
@@ -386,9 +386,9 @@ read_next_wfa (wfa_t *wfa, bitfile_t *input)
    /*
     *  Read image tiling info
     */
-   if (get_bit (input))			/* tiling performed ? */
+   if (get_bit (input))                 /* tiling performed ? */
       read_tiling (&tiling, wfa->wfainfo->width, wfa->wfainfo->height,
-		   wfa->wfainfo->level, input);
+                   wfa->wfainfo->level, input);
    else
       tiling.exponent = 0;
 
@@ -404,30 +404,30 @@ read_next_wfa (wfa_t *wfa, bitfile_t *input)
       unsigned state;
 
       for (state = wfa->basis_states; state < wfa->states; state++)
-	 if ((!wfa->wfainfo->color
-	      || (int) state <= wfa->tree [wfa->tree [wfa->root_state][0]][0])
-	     &&
-	     (!tiling.exponent ||
-	      wfa->level_of_state [state] <= (wfa->wfainfo->level
-					      - tiling.exponent))
-	     && ((wfa->x [state][0]
-		 + width_of_level (wfa->level_of_state [state]))
-		 <= wfa->wfainfo->width)
-	     && ((wfa->y [state][0]
-		 + height_of_level (wfa->level_of_state [state]))
-		 <= wfa->wfainfo->height))
-	    wfa->domain_type [state] = USE_DOMAIN_MASK;
-	 else
-	    wfa->domain_type [state] = 0;
+         if ((!wfa->wfainfo->color
+              || (int) state <= wfa->tree [wfa->tree [wfa->root_state][0]][0])
+             &&
+             (!tiling.exponent ||
+              wfa->level_of_state [state] <= (wfa->wfainfo->level
+                                              - tiling.exponent))
+             && ((wfa->x [state][0]
+                 + width_of_level (wfa->level_of_state [state]))
+                 <= wfa->wfainfo->width)
+             && ((wfa->y [state][0]
+                 + height_of_level (wfa->level_of_state [state]))
+                 <= wfa->wfainfo->height))
+            wfa->domain_type [state] = USE_DOMAIN_MASK;
+         else
+            wfa->domain_type [state] = 0;
    }
 
    if (tiling.exponent)
       Free (tiling.vorder);
 
-   if (get_bit (input))			/* nondeterministic prediction used */
+   if (get_bit (input))                 /* nondeterministic prediction used */
       read_nd (wfa, input);
 
-   if (wfa->frame_type != I_FRAME)	/* motion compensation used */
+   if (wfa->frame_type != I_FRAME)      /* motion compensation used */
       read_mc (wfa->frame_type, wfa, input);
 
    locate_delta_images (wfa);
@@ -439,7 +439,7 @@ read_next_wfa (wfa_t *wfa, bitfile_t *input)
       unsigned edges = read_matrices (wfa, input);
 
       if (edges)
-	 read_weights (edges, wfa, input);
+         read_weights (edges, wfa, input);
    }
 
    /*
@@ -449,8 +449,8 @@ read_next_wfa (wfa_t *wfa, bitfile_t *input)
       unsigned state;
 
       for (state = wfa->basis_states; state <= wfa->states; state++)
-	 wfa->final_distribution[state]
-	    = compute_final_distribution (state, wfa);
+         wfa->final_distribution[state]
+            = compute_final_distribution (state, wfa);
    }
 
    return frame_number;
@@ -458,13 +458,13 @@ read_next_wfa (wfa_t *wfa, bitfile_t *input)
 
 /*****************************************************************************
 
-				private code
+                                private code
 
 *****************************************************************************/
 
 static void
 read_tiling (tiling_t *tiling, unsigned image_width, unsigned image_height,
-	     unsigned image_level, bitfile_t *input)
+             unsigned image_level, bitfile_t *input)
 /*
  *  Read image tiling information from the given file 'input'
  *  and store parameters in struct 'tiling'.
@@ -472,32 +472,32 @@ read_tiling (tiling_t *tiling, unsigned image_width, unsigned image_height,
  *  No return value.
  */
 {
-   const unsigned rice_k = 8;		/* parameter of Rice Code */
+   const unsigned rice_k = 8;           /* parameter of Rice Code */
 
    tiling->exponent = read_rice_code (rice_k, input);
 
-   if (get_bit (input))			/* variance order */
+   if (get_bit (input))                 /* variance order */
    {
-      unsigned tile;			/* current image tile */
-      unsigned x0, y0;			/* NW corner of image tile */
-      unsigned width, height;		/* size of image tile */
+      unsigned tile;                    /* current image tile */
+      unsigned x0, y0;                  /* NW corner of image tile */
+      unsigned width, height;           /* size of image tile */
 
       tiling->vorder = Calloc (1 << tiling->exponent, sizeof (int));
       for (tile = 0; tile <  1U << tiling->exponent; tile++)
       {
-	 locate_subimage (image_level, image_level - tiling->exponent, tile,
-			  &x0, &y0, &width, &height);
-	 if (x0 < image_width && y0 < image_height)
-	    tiling->vorder [tile] = get_bits (input, tiling->exponent);
-	 else
-	    tiling->vorder [tile] = -1;
+         locate_subimage (image_level, image_level - tiling->exponent, tile,
+                          &x0, &y0, &width, &height);
+         if (x0 < image_width && y0 < image_height)
+            tiling->vorder [tile] = get_bits (input, tiling->exponent);
+         else
+            tiling->vorder [tile] = -1;
       }
    }
-   else					/* spiral order */
+   else                                 /* spiral order */
    {
       tiling->vorder = Calloc (1 << tiling->exponent, sizeof (int));
       compute_spiral (tiling->vorder, image_width, image_height,
-		      tiling->exponent, get_bit (input) ? YES : NO);
+                      tiling->exponent, get_bit (input) ? YES : NO);
    }
 }
 
diff --git a/converter/other/fiasco/input/read.h b/converter/other/fiasco/input/read.h
index 1f59f103..f41cb874 100644
--- a/converter/other/fiasco/input/read.h
+++ b/converter/other/fiasco/input/read.h
@@ -1,8 +1,8 @@
 /*
  *  read.h
  *
- *  Written by:		Ullrich Hafner
- *  
+ *  Written by:         Ullrich Hafner
+ *
  *  This file is part of FIASCO (Fractal Image And Sequence COdec)
  *  Copyright (C) 1994-2000 Ullrich Hafner
  */
diff --git a/converter/other/fiasco/input/tree.c b/converter/other/fiasco/input/tree.c
index 74ceeb68..8d81ae1b 100644
--- a/converter/other/fiasco/input/tree.c
+++ b/converter/other/fiasco/input/tree.c
@@ -1,7 +1,7 @@
 /*
- *  tree.c:		Input of bintree partitioning
+ *  tree.c:             Input of bintree partitioning
  *
- *  Written by:		Ullrich Hafner
+ *  Written by:         Ullrich Hafner
  *
  *  This file is part of FIASCO (Fractal Image And Sequence COdec)
  *  Copyright (C) 1994-2000 Ullrich Hafner
@@ -30,22 +30,22 @@
 
 /*****************************************************************************
 
-				prototypes
+                                prototypes
 
 *****************************************************************************/
 
 static unsigned
 restore_depth_first_order (unsigned src_state, unsigned level, unsigned x,
-			   unsigned y, unsigned *dst_state,
-			   word_t (*bfo_tree)[MAXLABELS],
-			   wfa_t *wfa, tiling_t *tiling);
+                           unsigned y, unsigned *dst_state,
+                           word_t (*bfo_tree)[MAXLABELS],
+                           wfa_t *wfa, tiling_t *tiling);
 static void
 decode_tree (bitfile_t *input, byte_t *data, unsigned n_data, unsigned scaling,
-	     u_word_t sum0, u_word_t sum1);
+             u_word_t sum0, u_word_t sum1);
 
 /*****************************************************************************
 
-				public code
+                                public code
 
 *****************************************************************************/
 
@@ -58,12 +58,12 @@ read_tree (wfa_t *wfa, tiling_t *tiling, bitfile_t *input)
  *  No return value.
  *
  *  Side effects:
- *	'wfa->tree', 'wfa->x', 'wfa->y', 'wfa->level_of_state'
+ *      'wfa->tree', 'wfa->x', 'wfa->y', 'wfa->level_of_state'
  *      are filled with decoded values.
  */
 {
-   byte_t *bitstring;			/* the encoded data */
-   word_t (*bfo_tree)[MAXLABELS];	/* node numbers in BFO */
+   byte_t *bitstring;                   /* the encoded data */
+   word_t (*bfo_tree)[MAXLABELS];       /* node numbers in BFO */
 
    /*
     *  Read WFA tree stored in breadth first order
@@ -80,15 +80,15 @@ read_tree (wfa_t *wfa, tiling_t *tiling, bitfile_t *input)
     *  Generate tree using a breadth first traversal
     */
    {
-      unsigned 	next;			/* next free node number of the tree */
-      unsigned 	state;
-      unsigned 	label;
-      byte_t   *buffer = bitstring;	/* pointer to decoded data */
+      unsigned  next;                   /* next free node number of the tree */
+      unsigned  state;
+      unsigned  label;
+      byte_t   *buffer = bitstring;     /* pointer to decoded data */
 
       bfo_tree = Calloc (wfa->states * MAXLABELS, sizeof (word_t));
       for (state = 0, next = 1; state < next; state++)
-	 for (label = 0; label < MAXLABELS; label++)
-	    bfo_tree [state][label] = *buffer++ ? next++ : RANGE;
+         for (label = 0; label < MAXLABELS; label++)
+            bfo_tree [state][label] = *buffer++ ? next++ : RANGE;
    }
 
    /*
@@ -98,9 +98,9 @@ read_tree (wfa_t *wfa, tiling_t *tiling, bitfile_t *input)
       unsigned dst_state = wfa->basis_states;
 
       wfa->root_state
-	 = restore_depth_first_order (0, (wfa->wfainfo->level
-					  + (wfa->wfainfo->color ? 2 : 0)),
-				      0, 0, &dst_state, bfo_tree, wfa, tiling);
+         = restore_depth_first_order (0, (wfa->wfainfo->level
+                                          + (wfa->wfainfo->color ? 2 : 0)),
+                                      0, 0, &dst_state, bfo_tree, wfa, tiling);
    }
 
    Free (bitstring);
@@ -109,15 +109,15 @@ read_tree (wfa_t *wfa, tiling_t *tiling, bitfile_t *input)
 
 /*****************************************************************************
 
-				private code
+                                private code
 
 *****************************************************************************/
 
 static unsigned
 restore_depth_first_order (unsigned src_state, unsigned level, unsigned x,
-			   unsigned y, unsigned *dst_state,
-			   word_t (*bfo_tree)[MAXLABELS],
-			   wfa_t *wfa, tiling_t *tiling)
+                           unsigned y, unsigned *dst_state,
+                           word_t (*bfo_tree)[MAXLABELS],
+                           wfa_t *wfa, tiling_t *tiling)
 /*
  *  Map state 'src_state' (breadth first order)
  *  to state '*dst_state' (depth first order)
@@ -127,17 +127,17 @@ restore_depth_first_order (unsigned src_state, unsigned level, unsigned x,
  *  of size 'image_level'. 'tiling' defines the image partitioning.
  *
  *  Return value:
- *	new node number in depth first order
+ *      new node number in depth first order
  *
  *  Side effects:
- *	'wfa->tree', 'wfa->x', 'wfa->y', 'wfa->level_of_state'
+ *      'wfa->tree', 'wfa->x', 'wfa->y', 'wfa->level_of_state'
  *      are filled with decoded values.
  */
 {
-   unsigned newx [MAXLABELS];		/* x coordinate of children */
-   unsigned newy [MAXLABELS];		/* y coordinate of children */
-   unsigned x0, y0;			/* NW corner of image tile */
-   unsigned width, height;		/* size of image tile */
+   unsigned newx [MAXLABELS];           /* x coordinate of children */
+   unsigned newy [MAXLABELS];           /* y coordinate of children */
+   unsigned x0, y0;                     /* NW corner of image tile */
+   unsigned width, height;              /* size of image tile */
 
    /*
     *  If tiling is performed then replace current coordinates
@@ -148,14 +148,14 @@ restore_depth_first_order (unsigned src_state, unsigned level, unsigned x,
 
       for (tile = 0; tile < 1U << tiling->exponent; tile++)
       {
-	 locate_subimage (wfa->wfainfo->level, level, tile,
-			  &x0, &y0, &width, &height);
-	 if (x0 == x && y0 == y) /* matched ! */
-	 {
-	    locate_subimage (wfa->wfainfo->level, level, tiling->vorder[tile],
-			     &x, &y, &width, &height);
-	    break;
-	 }
+         locate_subimage (wfa->wfainfo->level, level, tile,
+                          &x0, &y0, &width, &height);
+         if (x0 == x && y0 == y) /* matched ! */
+         {
+            locate_subimage (wfa->wfainfo->level, level, tiling->vorder[tile],
+                             &x, &y, &width, &height);
+            break;
+         }
       }
    }
    /*
@@ -175,24 +175,24 @@ restore_depth_first_order (unsigned src_state, unsigned level, unsigned x,
     *  Remap node numbers
     */
    {
-      int      child [MAXLABELS];	/* children of current node (state) */
-      int      domain;			/* current domain */
+      int      child [MAXLABELS];       /* children of current node (state) */
+      int      domain;                  /* current domain */
       unsigned label;
 
       for (label = 0; label < MAXLABELS; label++)
-	 if (!isrange (domain = bfo_tree [src_state][label]))
-	    child [label] = restore_depth_first_order (domain, level - 1,
-						       newx [label],
-						       newy [label], dst_state,
-						       bfo_tree, wfa, tiling);
-	 else
-	    child [label] = RANGE;
+         if (!isrange (domain = bfo_tree [src_state][label]))
+            child [label] = restore_depth_first_order (domain, level - 1,
+                                                       newx [label],
+                                                       newy [label], dst_state,
+                                                       bfo_tree, wfa, tiling);
+         else
+            child [label] = RANGE;
 
       for (label = 0; label < MAXLABELS; label++)
       {
-	 wfa->tree [*dst_state][label] = child [label];
-	 wfa->x [*dst_state][label]    = newx [label];
-	 wfa->y [*dst_state][label]    = newy [label];
+         wfa->tree [*dst_state][label] = child [label];
+         wfa->x [*dst_state][label]    = newx [label];
+         wfa->y [*dst_state][label]    = newy [label];
       }
       wfa->level_of_state [*dst_state] = level;
    }
@@ -208,26 +208,26 @@ restore_depth_first_order (unsigned src_state, unsigned level, unsigned x,
 
 static void
 decode_tree (bitfile_t *input, byte_t *data, unsigned n_data, unsigned scaling,
-	     u_word_t sum0, u_word_t sum1)
+             u_word_t sum0, u_word_t sum1)
 /*
  *  Decode bintree partitioning using adaptive binary arithmetic decoding.
- *  'input'	input stream,
- *  'data'	buffer for decoded szmbols,
- *  'n_data'	number of symbols to decode,
- *  'scaling'	rescale probability models if range > 'scaling'
- *  'sum0'	initial totals of symbol '0'
- *  'sum1'	initial totals of symbol '1'
+ *  'input'     input stream,
+ *  'data'      buffer for decoded szmbols,
+ *  'n_data'    number of symbols to decode,
+ *  'scaling'   rescale probability models if range > 'scaling'
+ *  'sum0'      initial totals of symbol '0'
+ *  'sum1'      initial totals of symbol '1'
  *
  *  No return value.
  *
  *  Side effects:
- *	'data []' is filled with the decoded bitstring
+ *      'data []' is filled with the decoded bitstring
  */
 {
-   u_word_t code;			/* The present input code value */
-   u_word_t low;			/* Start of the current code range */
-   u_word_t high;			/* End of the current code range */
-   unsigned n;				/* Data counter */
+   u_word_t code;                       /* The present input code value */
+   u_word_t low;                        /* Start of the current code range */
+   u_word_t high;                       /* End of the current code range */
+   unsigned n;                          /* Data counter */
 
    assert (data);
 
@@ -237,64 +237,64 @@ decode_tree (bitfile_t *input, byte_t *data, unsigned n_data, unsigned scaling,
 
    for (n = n_data; n; n--)
    {
-      unsigned count;			/* Current interval count */
-      unsigned range;			/* Current interval range */
+      unsigned count;                   /* Current interval count */
+      unsigned range;                   /* Current interval range */
 
       count = (((code - low) + 1) * sum1 - 1) / ((high - low) + 1);
       if (count < sum0)
       {
-	 /*
-	  *  Decode a '0' symbol
-	  *  First, the range is expanded to account for the symbol removal.
-	  */
-	 range = (high - low) + 1;
-	 high = low + (u_word_t) ((range * sum0) / sum1 - 1 );
-
-	 RESCALE_INPUT_INTERVAL;
-
-	 *data++ = 0;
-	 /*
-	  *  Update the frequency counts
-	  */
-	 sum0++;
-	 sum1++;
-	 if (sum1 > scaling) /* scale the symbol frequencies */
-	 {
-	    sum0 >>= 1;
-	    sum1 >>= 1;
-	    if (!sum0)
-	       sum0 = 1;
-	    if (sum0 >= sum1)
-	       sum1 = sum0 + 1;
-	 }
+         /*
+          *  Decode a '0' symbol
+          *  First, the range is expanded to account for the symbol removal.
+          */
+         range = (high - low) + 1;
+         high = low + (u_word_t) ((range * sum0) / sum1 - 1 );
+
+         RESCALE_INPUT_INTERVAL;
+
+         *data++ = 0;
+         /*
+          *  Update the frequency counts
+          */
+         sum0++;
+         sum1++;
+         if (sum1 > scaling) /* scale the symbol frequencies */
+         {
+            sum0 >>= 1;
+            sum1 >>= 1;
+            if (!sum0)
+               sum0 = 1;
+            if (sum0 >= sum1)
+               sum1 = sum0 + 1;
+         }
 
       }
       else
       {
-	 /*
-	  *  Decode a '1' symbol
-	  *  First, the range is expanded to account for the symbol removal.
-	  */
-	 range = (high - low) + 1;
-	 high = low + (u_word_t) ((range * sum1) / sum1 - 1);
-	 low  = low + (u_word_t) ((range * sum0) / sum1);
-
-	 RESCALE_INPUT_INTERVAL;
-
-	 *data++ = 1;
-	 /*
-	  *  Update the frequency counts
-	  */
-	 sum1++;
-	 if (sum1 > scaling) /* scale the symbol frequencies */
-	 {
-	    sum0 >>= 1;
-	    sum1 >>= 1;
-	    if (!sum0)
-	       sum0 = 1;
-	    if (sum0 >= sum1)
-	       sum1 = sum0 + 1;
-	 }
+         /*
+          *  Decode a '1' symbol
+          *  First, the range is expanded to account for the symbol removal.
+          */
+         range = (high - low) + 1;
+         high = low + (u_word_t) ((range * sum1) / sum1 - 1);
+         low  = low + (u_word_t) ((range * sum0) / sum1);
+
+         RESCALE_INPUT_INTERVAL;
+
+         *data++ = 1;
+         /*
+          *  Update the frequency counts
+          */
+         sum1++;
+         if (sum1 > scaling) /* scale the symbol frequencies */
+         {
+            sum0 >>= 1;
+            sum1 >>= 1;
+            if (!sum0)
+               sum0 = 1;
+            if (sum0 >= sum1)
+               sum1 = sum0 + 1;
+         }
       }
    }
    INPUT_BYTE_ALIGN (input);
diff --git a/converter/other/fiasco/input/tree.h b/converter/other/fiasco/input/tree.h
index f743ee98..31b73fa5 100644
--- a/converter/other/fiasco/input/tree.h
+++ b/converter/other/fiasco/input/tree.h
@@ -1,8 +1,8 @@
 /*
  *  tree.h
  *
- *  Written by:		Ullrich Hafner
- *		
+ *  Written by:         Ullrich Hafner
+ *              
  *  This file is part of FIASCO (Fractal Image And Sequence COdec)
  *  Copyright (C) 1994-2000 Ullrich Hafner
  */
diff --git a/converter/other/fiasco/input/weights.c b/converter/other/fiasco/input/weights.c
index 8a1e8899..debf38ad 100644
--- a/converter/other/fiasco/input/weights.c
+++ b/converter/other/fiasco/input/weights.c
@@ -2,7 +2,7 @@
  *  weights.c:          Input of weights
  *
  *  Written by:         Ullrich Hafner
- *              
+ *
  *  This file is part of FIASCO (Fractal Image And Sequence COdec)
  *  Copyright (C) 1994-2000 Ullrich Hafner
  */
@@ -32,7 +32,7 @@
 /*****************************************************************************
 
                                 public code
-  
+
 *****************************************************************************/
 
 void
@@ -55,7 +55,7 @@ read_weights (unsigned total, wfa_t *wfa, bitfile_t *input)
    unsigned         offset1, offset2;   /* prob. model offsets. */
    unsigned         offset3, offset4;   /* prob. model offsets. */
    bool_t           delta_approx = NO;  /* true if delta has been used */
-   
+
    /*
     *  Check whether delta approximation has been used
     */
@@ -65,7 +65,7 @@ read_weights (unsigned total, wfa_t *wfa, bitfile_t *input)
          delta_approx = YES;
          break;
       }
-  
+
    /*
     *  Generate array of corresponding levels (context of probability model)
     */
@@ -82,7 +82,7 @@ read_weights (unsigned total, wfa_t *wfa, bitfile_t *input)
       min_level = d_min_level = MAXLEVEL;
       max_level = d_max_level = 0;
       dc        = d_dc     = NO;
-   
+
       for (state = wfa->basis_states; state < wfa->states; state++)
           for (label = 0; label < MAXLABELS; label++)
               if (isrange (wfa->tree [state][label]))
@@ -156,7 +156,7 @@ read_weights (unsigned total, wfa_t *wfa, bitfile_t *input)
          c_symbols [i] = 1 << (wfa->wfainfo->rpf->mantissa_bits + 1);
       for (; i < offset4; i++)
          c_symbols [i] = 1 << (wfa->wfainfo->d_rpf->mantissa_bits + 1);
-      
+
       weights_array = decode_array (input, level_array, c_symbols,
                                     offset4, total, scale);
       Free (c_symbols);
@@ -198,7 +198,7 @@ read_weights (unsigned total, wfa_t *wfa, bitfile_t *input)
                      = wfa->weight [state][label][edge] * 512 + 0.5;
                }
    }
-   
+
    Free (weights_array);
 }
- 
+
diff --git a/converter/other/fiasco/input/weights.h b/converter/other/fiasco/input/weights.h
index 36cea5c2..4a6bdf0a 100644
--- a/converter/other/fiasco/input/weights.h
+++ b/converter/other/fiasco/input/weights.h
@@ -1,8 +1,8 @@
 /*
  *  weights.h
  *
- *  Written by:		Ullrich Hafner
- *		
+ *  Written by:         Ullrich Hafner
+ *              
  *  This file is part of FIASCO (Fractal Image And Sequence COdec)
  *  Copyright (C) 1994-2000 Ullrich Hafner
  */
diff --git a/converter/other/fiasco/lib/arith.c b/converter/other/fiasco/lib/arith.c
index e61e753e..7fac0c6d 100644
--- a/converter/other/fiasco/lib/arith.c
+++ b/converter/other/fiasco/lib/arith.c
@@ -1,7 +1,7 @@
 /*
- *  arith.c:		Adaptive arithmetic coding and decoding
+ *  arith.c:            Adaptive arithmetic coding and decoding
  *
- *  Written by:		Ullrich Hafner
+ *  Written by:         Ullrich Hafner
  *
  *  This file is part of FIASCO (Fractal Image And Sequence COdec)
  *  Copyright (C) 1994-2000 Ullrich Hafner
@@ -26,7 +26,7 @@
 
 /******************************************************************************
 
-				public code
+                                public code
 
 ******************************************************************************/
 
@@ -37,7 +37,7 @@ alloc_encoder (bitfile_t *output)
  *  Initialize the arithmetic coder.
  *
  *  Return value:
- *	A pointer to the new coder structure
+ *      A pointer to the new coder structure
  */
 {
    arith_t *arith = Calloc (1, sizeof (arith_t));
@@ -47,7 +47,7 @@ alloc_encoder (bitfile_t *output)
    arith->low       = LOW;
    arith->high      = HIGH;
    arith->underflow = 0;
-   arith->file 	    = output;
+   arith->file      = output;
 
    return arith;
 }
@@ -62,9 +62,9 @@ free_encoder (arith_t *arith)
  *  No return value.
  */
 {
-   u_word_t   low;			/* start of the current code range  */
-   u_word_t   high;			/* end of the current code range    */
-   u_word_t   underflow;		/* number of underflow bits pending */
+   u_word_t   low;                      /* start of the current code range  */
+   u_word_t   high;                     /* end of the current code range    */
+   u_word_t   underflow;                /* number of underflow bits pending */
    bitfile_t *output;
 
    assert (arith);
@@ -94,22 +94,22 @@ encode_symbol (unsigned symbol, arith_t *arith, model_t *model)
  *  symbol counts are rescaled).
  *
  *  Return value:
- *	information content of the encoded symbol.
+ *      information content of the encoded symbol.
  *
  *  Side effects:
- *	'model' is updated (probability distribution)
- *	'arith' is updated (coder state)
+ *      'model' is updated (probability distribution)
+ *      'arith' is updated (coder state)
  */
 {
-   u_word_t   low_count;		/* lower bound of 'symbol' interval */
-   u_word_t   high_count;		/* upper bound of 'symbol' interval */
-   u_word_t   scale;			/* range of all 'm' symbol intervals */
-   unsigned   range;			/* range of current interval */
-   unsigned   index;			/* index of probability model */
-   u_word_t   low;			/* start of the current code range  */
-   u_word_t   high;			/* end of the current code range    */
-   u_word_t   underflow;		/* number of underflow bits pending */
-   bitfile_t *output;			/* output file */
+   u_word_t   low_count;                /* lower bound of 'symbol' interval */
+   u_word_t   high_count;               /* upper bound of 'symbol' interval */
+   u_word_t   scale;                    /* range of all 'm' symbol intervals */
+   unsigned   range;                    /* range of current interval */
+   unsigned   index;                    /* index of probability model */
+   u_word_t   low;                      /* start of the current code range  */
+   u_word_t   high;                     /* end of the current code range    */
+   u_word_t   underflow;                /* number of underflow bits pending */
+   bitfile_t *output;                   /* output file */
 
    assert (model && arith);
 
@@ -123,28 +123,28 @@ encode_symbol (unsigned symbol, arith_t *arith, model_t *model)
 
    assert (high > low);
 
-   if (model->order > 0)		/* order-'n' model*/
+   if (model->order > 0)                /* order-'n' model*/
    {
-      unsigned power;			/* multiplicator */
+      unsigned power;                   /* multiplicator */
       unsigned i;
 
       /*
        *  Compute index of the probability model to use.
        *  See init_model() for more details.
        */
-      power = 1;			/* multiplicator */
-      index = 0;			/* address of prob. model */
+      power = 1;                        /* multiplicator */
+      index = 0;                        /* address of prob. model */
 
       for (i = 0; i < model->order; i++) /* generate a M-nary number */
       {
-	 index += model->context [i] * power;
-	 power *= model->symbols;
+         index += model->context [i] * power;
+         power *= model->symbols;
       }
 
-      index *= model->symbols + 1;	/* we need space for M + 1 elements */
+      index *= model->symbols + 1;      /* we need space for M + 1 elements */
 
       for (i = 0; i < model->order - 1; i++)
-	 model->context [i] = model->context [i + 1];
+         model->context [i] = model->context [i + 1];
       model->context [i] = symbol;
    }
    else
@@ -163,7 +163,7 @@ encode_symbol (unsigned symbol, arith_t *arith, model_t *model)
 
    RESCALE_OUTPUT_INTERVAL;
 
-   if (model->scale > 0)		/* adaptive model */
+   if (model->scale > 0)                /* adaptive model */
    {
       unsigned i;
 
@@ -171,23 +171,23 @@ encode_symbol (unsigned symbol, arith_t *arith, model_t *model)
        *  Update probability model
        */
       for (i = symbol + 1; i <= model->symbols; i++)
-	 model->totals [index + i]++;
+         model->totals [index + i]++;
       if (model->totals [index + model->symbols] > model->scale) /* scaling */
       {
-	 for (i = 1; i <= model->symbols; i++)
-	 {
-	    model->totals [index + i] >>= 1;
-	    if (model->totals [index + i] <= model->totals [index + i - 1])
-	       model->totals [index + i] = model->totals [index + i - 1] + 1;
-	 }
+         for (i = 1; i <= model->symbols; i++)
+         {
+            model->totals [index + i] >>= 1;
+            if (model->totals [index + i] <= model->totals [index + i - 1])
+               model->totals [index + i] = model->totals [index + i - 1] + 1;
+         }
       }
    }
 
    /*
     *  Store interval values
     */
-   arith->low  	    = low;
-   arith->high 	    = high;
+   arith->low       = low;
+   arith->high      = high;
    arith->underflow = underflow;
 
    return - log2 ((high_count - low_count) / (real_t) scale);
@@ -195,8 +195,8 @@ encode_symbol (unsigned symbol, arith_t *arith, model_t *model)
 
 void
 encode_array (bitfile_t *output, const unsigned *data, const unsigned *context,
-	      const unsigned *c_symbols, unsigned n_context, unsigned n_data,
-	      unsigned scaling)
+              const unsigned *c_symbols, unsigned n_context, unsigned n_data,
+              unsigned scaling)
 /*
  *  Arithmetic coding of #'n_data' symbols given in the array 'data'.
  *  If 'n_context' > 1 then a number (context [n]) is assigned to every
@@ -207,10 +207,10 @@ encode_array (bitfile_t *output, const unsigned *data, const unsigned *context,
  *  No return value.
  */
 {
-   u_word_t **totals;			/* probability model */
+   u_word_t **totals;                   /* probability model */
 
    if (!n_context)
-      n_context = 1;			/* always use one context */
+      n_context = 1;                    /* always use one context */
 
    assert (output && c_symbols && data);
    assert (n_context == 1 || context);
@@ -224,13 +224,13 @@ encode_array (bitfile_t *output, const unsigned *data, const unsigned *context,
 
       for (c = 0; c < n_context; c++)
       {
-	 unsigned i;
+         unsigned i;
 
-	 totals [c]    = Calloc (c_symbols [c] + 1, sizeof (u_word_t));
-	 totals [c][0] = 0;
+         totals [c]    = Calloc (c_symbols [c] + 1, sizeof (u_word_t));
+         totals [c][0] = 0;
 
-	 for (i = 0; i < c_symbols [c]; i++)
-	    totals [c][i + 1] = totals [c][i] + 1;
+         for (i = 0; i < c_symbols [c]; i++)
+            totals [c][i + 1] = totals [c][i] + 1;
       }
    }
 
@@ -238,52 +238,52 @@ encode_array (bitfile_t *output, const unsigned *data, const unsigned *context,
     *  Encode array elements
     */
    {
-      u_word_t low  	 = 0;		/* Start of the current code range */
-      u_word_t high 	 = 0xffff;	/* End of the current code range */
-      u_word_t underflow = 0;		/* Number of underflow bits pending */
+      u_word_t low       = 0;           /* Start of the current code range */
+      u_word_t high      = 0xffff;      /* End of the current code range */
+      u_word_t underflow = 0;           /* Number of underflow bits pending */
       unsigned n;
 
       for (n = 0; n < n_data; n++)
       {
-	 u_word_t low_count;		/* lower bound of 'symbol' interval */
-	 u_word_t high_count;		/* upper bound of 'symbol' interval */
-	 u_word_t scale;		/* range of all 'm' symbol intervals */
-	 unsigned range;		/* current range */
-	 int	  d;			/* current data symbol */
-	 int	  c;			/* context of current data symbol */
-
-	 d = data [n];
-	 c = n_context > 1 ? context [n] : 0;
-
-	 scale	    = totals [c][c_symbols [c]];
-	 low_count  = totals [c][d];
-	 high_count = totals [c][d + 1];
-
-	 /*
-	  * Rescale high and low for the new symbol.
-	  */
-	 range = (high - low) + 1;
-	 high  = low + (u_word_t) ((range * high_count) / scale - 1);
-	 low   = low + (u_word_t) ((range * low_count) / scale);
-	 RESCALE_OUTPUT_INTERVAL;
-
-	 /*
-	  *  Update probability models
-	  */
-	 {
-	    unsigned i;
-
-	    for (i = d + 1; i < c_symbols [c] + 1; i++)
-	       totals [c][i]++;
-
-	    if (totals [c][c_symbols [c]] > scaling) /* scaling */
-	       for (i = 1; i < c_symbols [c] + 1; i++)
-	       {
-		  totals [c][i] >>= 1;
-		  if (totals [c][i] <= totals [c][i - 1])
-		     totals [c][i] = totals [c][i - 1] + 1;
-	       }
-	 }
+         u_word_t low_count;            /* lower bound of 'symbol' interval */
+         u_word_t high_count;           /* upper bound of 'symbol' interval */
+         u_word_t scale;                /* range of all 'm' symbol intervals */
+         unsigned range;                /* current range */
+         int      d;                    /* current data symbol */
+         int      c;                    /* context of current data symbol */
+
+         d = data [n];
+         c = n_context > 1 ? context [n] : 0;
+
+         scale      = totals [c][c_symbols [c]];
+         low_count  = totals [c][d];
+         high_count = totals [c][d + 1];
+
+         /*
+          * Rescale high and low for the new symbol.
+          */
+         range = (high - low) + 1;
+         high  = low + (u_word_t) ((range * high_count) / scale - 1);
+         low   = low + (u_word_t) ((range * low_count) / scale);
+         RESCALE_OUTPUT_INTERVAL;
+
+         /*
+          *  Update probability models
+          */
+         {
+            unsigned i;
+
+            for (i = d + 1; i < c_symbols [c] + 1; i++)
+               totals [c][i]++;
+
+            if (totals [c][c_symbols [c]] > scaling) /* scaling */
+               for (i = 1; i < c_symbols [c] + 1; i++)
+               {
+                  totals [c][i] >>= 1;
+                  if (totals [c][i] <= totals [c][i - 1])
+                     totals [c][i] = totals [c][i - 1] + 1;
+               }
+         }
       }
       /*
        *  Flush arithmetic encoder
@@ -299,7 +299,7 @@ encode_array (bitfile_t *output, const unsigned *data, const unsigned *context,
    {
       unsigned c;
       for (c = 0; c < n_context; c++)
-	 Free (totals [c]);
+         Free (totals [c]);
       Free (totals);
    }
 }
@@ -312,7 +312,7 @@ alloc_decoder (bitfile_t *input)
  *  16 input bits from the stream 'input'.
  *
  *  Return value:
- *	A pointer to the new decoder structure
+ *      A pointer to the new decoder structure
  */
 
 {
@@ -338,7 +338,7 @@ free_decoder (arith_t *arith)
  *  No return value.
  *
  *  Side effects:
- *	structure 'arith' is discarded.
+ *      structure 'arith' is discarded.
  */
 {
    assert (arith);
@@ -357,22 +357,22 @@ decode_symbol (arith_t *arith, model_t *model)
  *  decoding the symbol (if necessary also rescale the symbol counts).
  *
  *  Return value:
- *	decoded symbol
+ *      decoded symbol
  *
  *  Side effects:
- *	'model' is updated (probability distribution)
- *	'arith' is updated (decoder state)
+ *      'model' is updated (probability distribution)
+ *      'arith' is updated (decoder state)
  */
 {
-   unsigned   range;			/* range of current interval */
-   unsigned   count;			/* value in the current interval */
-   unsigned   index;			/* index of probability model */
-   unsigned   symbol;			/* decoded symbol */
-   u_word_t   scale;			/* range of all 'm' symbol intervals */
-   u_word_t   low;			/* start of the current code range  */
-   u_word_t   high;			/* end of the current code range    */
-   u_word_t   code;			/* the present input code value */
-   bitfile_t *input;			/* input file */
+   unsigned   range;                    /* range of current interval */
+   unsigned   count;                    /* value in the current interval */
+   unsigned   index;                    /* index of probability model */
+   unsigned   symbol;                   /* decoded symbol */
+   u_word_t   scale;                    /* range of all 'm' symbol intervals */
+   u_word_t   low;                      /* start of the current code range  */
+   u_word_t   high;                     /* end of the current code range    */
+   u_word_t   code;                     /* the present input code value */
+   bitfile_t *input;                    /* input file */
 
    assert (arith && model);
 
@@ -386,25 +386,25 @@ decode_symbol (arith_t *arith, model_t *model)
 
    assert (high > low);
 
-   if (model->order > 0)		/* order-'n' model */
+   if (model->order > 0)                /* order-'n' model */
    {
-      unsigned power;			/* multiplicator */
+      unsigned power;                   /* multiplicator */
       unsigned i;
 
       /*
        *  Compute index of the probability model to use.
        *  See init_model() for more details.
        */
-      power = 1;			/* multiplicator */
-      index = 0;			/* address of prob. model */
+      power = 1;                        /* multiplicator */
+      index = 0;                        /* address of prob. model */
 
       for (i = 0; i < model->order; i++) /* generate a m-nary number */
       {
-	 index += model->context[i] * power;
-	 power *= model->symbols;
+         index += model->context[i] * power;
+         power *= model->symbols;
       }
 
-      index *= model->symbols + 1;	/* we need space for m + 1 elements */
+      index *= model->symbols + 1;      /* we need space for m + 1 elements */
    }
    else
       index = 0;
@@ -414,15 +414,15 @@ decode_symbol (arith_t *arith, model_t *model)
    count = ((code - low + 1) * scale - 1) / range;
 
    for (symbol = model->symbols; count < model->totals [index + symbol];
-	symbol--)
+        symbol--)
       ;
 
-   if (model->order > 0)		/* order-'n' model */
+   if (model->order > 0)                /* order-'n' model */
    {
       unsigned i;
 
       for (i = 0; i < model->order - 1; i++)
-	 model->context [i] = model->context [i + 1];
+         model->context [i] = model->context [i + 1];
       model->context [i] = symbol;
    }
 
@@ -430,8 +430,8 @@ decode_symbol (arith_t *arith, model_t *model)
     *  Compute interval boundaries
     */
    {
-      u_word_t low_count;		/* lower bound of 'symbol' interval */
-      u_word_t high_count;		/* upper bound of 'symbol' interval */
+      u_word_t low_count;               /* lower bound of 'symbol' interval */
+      u_word_t high_count;              /* upper bound of 'symbol' interval */
 
       low_count  = model->totals [index + symbol];
       high_count = model->totals [index + symbol + 1];
@@ -441,7 +441,7 @@ decode_symbol (arith_t *arith, model_t *model)
 
    RESCALE_INPUT_INTERVAL;
 
-   if (model->scale > 0)		/* adaptive model */
+   if (model->scale > 0)                /* adaptive model */
    {
       unsigned i;
 
@@ -449,15 +449,15 @@ decode_symbol (arith_t *arith, model_t *model)
        *  Update probability model
        */
       for (i = symbol + 1; i <= model->symbols; i++)
-	 model->totals [index + i]++;
+         model->totals [index + i]++;
       if (model->totals [index + model->symbols] > model->scale) /* scaling */
       {
-	 for (i = 1; i <= model->symbols; i++)
-	 {
-	    model->totals [index + i] >>= 1;
-	    if (model->totals [index + i] <= model->totals [index + i - 1])
-	       model->totals [index + i] = model->totals [index + i - 1] + 1;
-	 }
+         for (i = 1; i <= model->symbols; i++)
+         {
+            model->totals [index + i] >>= 1;
+            if (model->totals [index + i] <= model->totals [index + i - 1])
+               model->totals [index + i] = model->totals [index + i - 1] + 1;
+         }
       }
    }
 
@@ -473,8 +473,8 @@ decode_symbol (arith_t *arith, model_t *model)
 
 unsigned *
 decode_array (bitfile_t *input, const unsigned *context,
-	      const unsigned *c_symbols, unsigned n_context,
-	      unsigned n_data, unsigned scaling)
+              const unsigned *c_symbols, unsigned n_context,
+              unsigned n_data, unsigned scaling)
 /*
  *  Arithmetic decoding of #'n_data' symbols.
  *  If 'n_context' > 1 then a number (context [n]) is assigned to every
@@ -483,14 +483,14 @@ decode_array (bitfile_t *input, const unsigned *context,
  *  Rescale probability models if range > 'scaling'.
  *
  *  Return value:
- *	pointer to array containing the decoded symbols
+ *      pointer to array containing the decoded symbols
  */
 {
-   unsigned  *data;			/* array to store decoded symbols */
-   u_word_t **totals;			/* probability model */
+   unsigned  *data;                     /* array to store decoded symbols */
+   u_word_t **totals;                   /* probability model */
 
    if (n_context < 1)
-      n_context = 1;			/* always use one context */
+      n_context = 1;                    /* always use one context */
    assert (input && c_symbols);
    assert (n_context == 1 || context);
 
@@ -505,13 +505,13 @@ decode_array (bitfile_t *input, const unsigned *context,
 
       for (c = 0; c < n_context; c++)
       {
-	 unsigned i;
+         unsigned i;
 
-	 totals [c]    = Calloc (c_symbols [c] + 1, sizeof (u_word_t));
-	 totals [c][0] = 0;
+         totals [c]    = Calloc (c_symbols [c] + 1, sizeof (u_word_t));
+         totals [c][0] = 0;
 
-	 for (i = 0; i < c_symbols [c]; i++)
-	    totals [c][i + 1] = totals [c][i] + 1;
+         for (i = 0; i < c_symbols [c]; i++)
+            totals [c][i + 1] = totals [c][i] + 1;
       }
    }
 
@@ -520,54 +520,54 @@ decode_array (bitfile_t *input, const unsigned *context,
     */
    {
       u_word_t code = get_bits (input, 16); /* The present input code value */
-      u_word_t low  = 0;		/* Start of the current code range */
-      u_word_t high = 0xffff;		/* End of the current code range */
+      u_word_t low  = 0;                /* Start of the current code range */
+      u_word_t high = 0xffff;           /* End of the current code range */
       unsigned n;
 
       for (n = 0; n < n_data; n++)
       {
-	 u_word_t scale;		/* range of all 'm' symbol intervals */
-	 u_word_t low_count;		/* lower bound of 'symbol' interval */
-	 u_word_t high_count;		/* upper bound of 'symbol' interval */
-	 unsigned count;		/* value in the current interval */
-	 unsigned range;		/* current interval range */
-	 unsigned d;			/* current data symbol */
-	 unsigned c;			/* context of current data symbol */
-
-	 c = n_context > 1 ? context [n] : 0;
-
-	 assert (high > low);
-	 scale = totals [c][c_symbols [c]];
-	 range = (high - low) + 1;
-	 count = (((code - low) + 1 ) * scale - 1) / range;
-
-	 for (d = c_symbols [c]; count < totals [c][d]; d--) /* next symbol */
-	    ;
-	 low_count  = totals [c][d];
-	 high_count = totals [c][d + 1];
-
-	 high = low + (u_word_t) ((range * high_count) / scale - 1 );
-	 low  = low + (u_word_t) ((range * low_count) / scale );
-	 RESCALE_INPUT_INTERVAL;
-
-	 /*
-	  *  Updata probability models
-	  */
-	 {
-	    unsigned i;
-
-	    for (i = d + 1; i < c_symbols [c] + 1; i++)
-	       totals [c][i]++;
-
-	    if (totals [c][c_symbols [c]] > scaling) /* scaling */
-	       for (i = 1; i < c_symbols [c] + 1; i++)
-	       {
-		  totals [c][i] >>= 1;
-		  if (totals [c][i] <= totals [c][i - 1])
-		     totals [c][i] = totals [c][i - 1] + 1;
-	       }
-	 }
-	 data [n] = d;
+         u_word_t scale;                /* range of all 'm' symbol intervals */
+         u_word_t low_count;            /* lower bound of 'symbol' interval */
+         u_word_t high_count;           /* upper bound of 'symbol' interval */
+         unsigned count;                /* value in the current interval */
+         unsigned range;                /* current interval range */
+         unsigned d;                    /* current data symbol */
+         unsigned c;                    /* context of current data symbol */
+
+         c = n_context > 1 ? context [n] : 0;
+
+         assert (high > low);
+         scale = totals [c][c_symbols [c]];
+         range = (high - low) + 1;
+         count = (((code - low) + 1 ) * scale - 1) / range;
+
+         for (d = c_symbols [c]; count < totals [c][d]; d--) /* next symbol */
+            ;
+         low_count  = totals [c][d];
+         high_count = totals [c][d + 1];
+
+         high = low + (u_word_t) ((range * high_count) / scale - 1 );
+         low  = low + (u_word_t) ((range * low_count) / scale );
+         RESCALE_INPUT_INTERVAL;
+
+         /*
+          *  Updata probability models
+          */
+         {
+            unsigned i;
+
+            for (i = d + 1; i < c_symbols [c] + 1; i++)
+               totals [c][i]++;
+
+            if (totals [c][c_symbols [c]] > scaling) /* scaling */
+               for (i = 1; i < c_symbols [c] + 1; i++)
+               {
+                  totals [c][i] >>= 1;
+                  if (totals [c][i] <= totals [c][i - 1])
+                     totals [c][i] = totals [c][i - 1] + 1;
+               }
+         }
+         data [n] = d;
       }
       INPUT_BYTE_ALIGN (input);
    }
@@ -579,7 +579,7 @@ decode_array (bitfile_t *input, const unsigned *context,
       unsigned c;
 
       for (c = 0; c < n_context; c++)
-	 Free (totals [c]);
+         Free (totals [c]);
       Free (totals);
    }
 
@@ -599,17 +599,17 @@ alloc_model (unsigned m, unsigned scale, unsigned n, unsigned *totals)
  *  the initial counts.
  *
  *  Return value:
- *	a pointer to the new probability model structure.
+ *      a pointer to the new probability model structure.
  *
  *  Note: We recommend a small size of the alphabet because no escape codes
  *  are used to encode/decode previously unseen symbols.
  *
  */
 {
-   model_t  *model;			/* new probability model */
-   unsigned  num;			/* number of contexts to allocate */
-   bool_t    cont;			/* continue flag */
-   bool_t    dec;			/* next order flag */
+   model_t  *model;                     /* new probability model */
+   unsigned  num;                       /* number of contexts to allocate */
+   bool_t    cont;                      /* continue flag */
+   bool_t    dec;                       /* next order flag */
    unsigned  i;
 
    /*
@@ -630,56 +630,56 @@ alloc_model (unsigned m, unsigned scale, unsigned n, unsigned *totals)
    model->totals = Calloc (num * (model->symbols + 1), sizeof (unsigned));
 
    for (i = 0; i < model->order; i++)
-      model->context[i] = 0;		/* start with context 0,0, .. ,0 */
+      model->context[i] = 0;            /* start with context 0,0, .. ,0 */
    cont = YES;
-   while (cont)				/* repeat while context != M ... M */
+   while (cont)                         /* repeat while context != M ... M */
    {
-      int	power;			/* multiplicator */
-      int	index;			/* index of probability model */
+      int       power;                  /* multiplicator */
+      int       index;                  /* index of probability model */
       /*
        *  There are m^n different contexts:
        *  Let "context_1 context_2 ... context_n symbol" be the current input
        *  stream then the index of the probability model is given by:
        *  index = context_1 * M^0 + context_2 * M^1 + ... + context_n * M^(n-1)
        */
-      power = 1;			/* multiplicator */
-      index = 0;			/* address of prob. model */
+      power = 1;                        /* multiplicator */
+      index = 0;                        /* address of prob. model */
 
-      for (i = 0; i < model->order; i++)	/* generate a m-nary number */
+      for (i = 0; i < model->order; i++)        /* generate a m-nary number */
       {
-	 index += model->context[i] * power;
-	 power *= model->symbols;
+         index += model->context[i] * power;
+         power *= model->symbols;
       }
 
-      index *= model->symbols + 1;	/* size of each model is m + 1 */
+      index *= model->symbols + 1;      /* size of each model is m + 1 */
 
-      model->totals [index + 0] = 0;	/* always zero */
+      model->totals [index + 0] = 0;    /* always zero */
 
       for (i = 1; i <= model->symbols; i++) /* prob of each symbol is 1/m or
-					       as given in totals */
-	 model->totals[index + i] = model->totals [index + i - 1]
-				    + (totals ? totals [i - 1] : 1);
-
-      if (model->order == 0)		/* order-0 model */
-	 cont = NO;
-      else				/* try next context */
-	 for (i = model->order - 1, dec = YES; dec; i--)
-	 {
-	    dec = NO;
-	    model->context[i]++;
-	    if (model->context[i] >= model->symbols)
-	    {
-	       /* change previous context */
-	       model->context[i] = 0;
-	       if (i > 0)		/* there's still a context remaining */
-		  dec = YES;
-	       else
-		  cont = NO;		/* all context models initialized */
-	    }
-	 }
+                                               as given in totals */
+         model->totals[index + i] = model->totals [index + i - 1]
+                                    + (totals ? totals [i - 1] : 1);
+
+      if (model->order == 0)            /* order-0 model */
+         cont = NO;
+      else                              /* try next context */
+         for (i = model->order - 1, dec = YES; dec; i--)
+         {
+            dec = NO;
+            model->context[i]++;
+            if (model->context[i] >= model->symbols)
+            {
+               /* change previous context */
+               model->context[i] = 0;
+               if (i > 0)               /* there's still a context remaining */
+                  dec = YES;
+               else
+                  cont = NO;            /* all context models initialized */
+            }
+         }
    }
    for (i = 0; i < model->order; i++)
-      model->context[i] = 0;		/* start with context 0,0, .. ,0 */
+      model->context[i] = 0;            /* start with context 0,0, .. ,0 */
 
    return model;
 }
@@ -693,13 +693,13 @@ free_model (model_t *model)
  *  No return value.
  *
  *  Side effects:
- *	struct 'model' is discarded
+ *      struct 'model' is discarded
  */
 {
    if (model != NULL)
    {
       if (model->context != NULL)
-	 Free (model->context);
+         Free (model->context);
       Free (model->totals);
       Free (model);
    }
diff --git a/converter/other/fiasco/lib/arith.h b/converter/other/fiasco/lib/arith.h
index 04297eb5..152dabab 100644
--- a/converter/other/fiasco/lib/arith.h
+++ b/converter/other/fiasco/lib/arith.h
@@ -20,24 +20,24 @@
 
 typedef struct model
 {
-   unsigned  symbols;			/* number of symbols in the alphabet */
-   unsigned  scale;			/* if totals > scale rescale totals */
-   unsigned  order;			/* order of the probability model */
-   unsigned *context;			/* context of the model */
-   unsigned *totals;			/* the totals */
+   unsigned  symbols;                   /* number of symbols in the alphabet */
+   unsigned  scale;                     /* if totals > scale rescale totals */
+   unsigned  order;                     /* order of the probability model */
+   unsigned *context;                   /* context of the model */
+   unsigned *totals;                    /* the totals */
 } model_t;
 
 typedef struct arith
 {
-   u_word_t   low;			/* start of the current code range */
-   u_word_t   high;			/* end of the current code range */
-   u_word_t   underflow;		/* number of underflow bits pending */
-   u_word_t   code;			/* the present input code value */
-   bitfile_t *file;			/* I/O stream */
+   u_word_t   low;                      /* start of the current code range */
+   u_word_t   high;                     /* end of the current code range */
+   u_word_t   underflow;                /* number of underflow bits pending */
+   u_word_t   code;                     /* the present input code value */
+   bitfile_t *file;                     /* I/O stream */
 } arith_t;
 
 enum interval {LOW = 0x0000, FIRST_QUARTER = 0x4000, HALF = 0x8000,
-	       THIRD_QUARTER = 0xc000, HIGH = 0xffff};
+               THIRD_QUARTER = 0xc000, HIGH = 0xffff};
 
 arith_t *
 alloc_encoder (bitfile_t *file);
@@ -47,8 +47,8 @@ real_t
 encode_symbol (unsigned symbol, arith_t *arith, model_t *model);
 void
 encode_array (bitfile_t *output, const unsigned *data, const unsigned *context,
-	      const unsigned *c_symbols, unsigned n_context, unsigned n_data,
-	      unsigned scaling);
+              const unsigned *c_symbols, unsigned n_context, unsigned n_data,
+              unsigned scaling);
 arith_t *
 alloc_decoder (bitfile_t *input);
 void
@@ -57,8 +57,8 @@ unsigned
 decode_symbol (arith_t *arith, model_t *model);
 unsigned *
 decode_array (bitfile_t *input, const unsigned *context,
-	      const unsigned *c_symbols, unsigned n_context,
-	      unsigned n_data, unsigned scaling);
+              const unsigned *c_symbols, unsigned n_context,
+              unsigned n_data, unsigned scaling);
 model_t *
 alloc_model (unsigned m, unsigned scale, unsigned n, unsigned *totals);
 void
@@ -67,7 +67,7 @@ free_model (model_t *model);
 #define RESCALE_INPUT_INTERVAL  for (;;)                                      \
                                    if ((high >= HALF) && (low < HALF) &&      \
                                       ((low & FIRST_QUARTER) != FIRST_QUARTER \
-				       || (high & FIRST_QUARTER) != 0))       \
+                                       || (high & FIRST_QUARTER) != 0))       \
                                    {                                          \
                                       break;                                  \
                                    }                                          \
@@ -88,8 +88,8 @@ free_model (model_t *model);
                                       high  |= HALF + 1;                      \
                                       code <<= 1;                             \
                                       code  += get_bit (input);               \
-                                   }                                          
-        								   
+                                   }
+
 #define RESCALE_OUTPUT_INTERVAL  for (;;)                                     \
                                  {                                            \
                                     if (high < HALF)                          \
@@ -116,7 +116,7 @@ free_model (model_t *model);
                                     high <<= 1;                               \
                                     high  |= 1;                               \
                                     low  <<= 1;                               \
-                                 }                                             
-					 
+                                 }
+
 #endif /* not _ARITH_H */
 
diff --git a/converter/other/fiasco/lib/bit-io.h b/converter/other/fiasco/lib/bit-io.h
index 08029824..6de7e396 100644
--- a/converter/other/fiasco/lib/bit-io.h
+++ b/converter/other/fiasco/lib/bit-io.h
@@ -1,7 +1,7 @@
 /*
  *  bit-io.h
  *
- *  Written by:		Ullrich Hafner
+ *  Written by:         Ullrich Hafner
  *
  *  This file is part of FIASCO (Fractal Image And Sequence COdec)
  *  Copyright (C) 1994-2000 Ullrich Hafner
@@ -27,14 +27,14 @@ typedef enum {READ_ACCESS, WRITE_ACCESS} openmode_e;
 
 typedef struct bitfile
 {
-   FILE	      *file;			/* associated filepointer */
-   char	      *filename;		/* corresponding filename */
-   byte_t     *buffer;			/* stream buffer */
-   byte_t     *ptr;			/* pointer to current buffer pos */
-   unsigned    bytepos;			/* current I/O byte */
-   unsigned    bitpos;			/* current I/O bit */
-   unsigned    bits_processed;		/* number of bits already processed */
-   openmode_e  mode;			/* access mode */
+   FILE       *file;                    /* associated filepointer */
+   char       *filename;                /* corresponding filename */
+   byte_t     *buffer;                  /* stream buffer */
+   byte_t     *ptr;                     /* pointer to current buffer pos */
+   unsigned    bytepos;                 /* current I/O byte */
+   unsigned    bitpos;                  /* current I/O bit */
+   unsigned    bits_processed;          /* number of bits already processed */
+   openmode_e  mode;                    /* access mode */
 } bitfile_t;
 
 FILE *
@@ -47,7 +47,7 @@ void
 put_bits (bitfile_t *bitfile, unsigned value, unsigned bits);
 bool_t
 get_bit (bitfile_t *bitfile);
-unsigned 
+unsigned
 get_bits (bitfile_t *bitfile, unsigned bits);
 void
 close_bitfile (bitfile_t *bitfile);
diff --git a/converter/other/fiasco/lib/dither.c b/converter/other/fiasco/lib/dither.c
index 669bb16c..c394f5ec 100644
--- a/converter/other/fiasco/lib/dither.c
+++ b/converter/other/fiasco/lib/dither.c
@@ -1,8 +1,8 @@
 /*
- *  dither.c:		Various dithering routines 	
+ *  dither.c:           Various dithering routines
+ *
+ *  Adapted by:         Ullrich Hafner
  *
- *  Adapted by:		Ullrich Hafner
- *		
  *  This file is part of FIASCO (Fractal Image And Sequence COdec)
  *  Copyright (C) 1994-2000 Ullrich Hafner
  */
@@ -10,17 +10,17 @@
 /*
  * Copyright (c) 1995 Erik Corry
  * All rights reserved.
- * 
+ *
  * Permission to use, copy, modify, and distribute this software and its
  * documentation for any purpose, without fee, and without written agreement is
  * hereby granted, provided that the above copyright notice and the following
  * two paragraphs appear in all copies of this software.
- * 
+ *
  * IN NO EVENT SHALL ERIK CORRY BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT,
  * SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OF
  * THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF ERIK CORRY HAS BEEN ADVISED
  * OF THE POSSIBILITY OF SUCH DAMAGE.
- * 
+ *
  * ERIK CORRY SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING, BUT NOT
  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
  * PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS ON AN "AS IS"
@@ -52,25 +52,25 @@
 
 /*****************************************************************************
 
-				prototypes
-  
+                                prototypes
+
 *****************************************************************************/
 
-static int 
+static int
 display_16_bit (const struct fiasco_renderer *this, unsigned char *ximage,
-		const fiasco_image_t *fiasco_image);
+                const fiasco_image_t *fiasco_image);
 
-static int 
+static int
 display_24_bit_bgr (const struct fiasco_renderer *this, unsigned char *ximage,
-		    const fiasco_image_t *fiasco_image);
+                    const fiasco_image_t *fiasco_image);
 
-static int 
+static int
 display_24_bit_rgb (const struct fiasco_renderer *this, unsigned char *ximage,
-		    const fiasco_image_t *fiasco_image);
+                    const fiasco_image_t *fiasco_image);
 
-static int 
+static int
 display_32_bit (const struct fiasco_renderer *this, unsigned char *ximage,
-		const fiasco_image_t *fiasco_image);
+                const fiasco_image_t *fiasco_image);
 
 static int
 free_bits_at_bottom (unsigned long a);
@@ -80,26 +80,26 @@ number_of_bits_set (unsigned long a);
 
 /*****************************************************************************
 
-				public code
-  
+                                public code
+
 *****************************************************************************/
 
 fiasco_renderer_t *
 fiasco_renderer_new (unsigned long red_mask, unsigned long green_mask,
-		     unsigned long blue_mask, unsigned bpp,
-		     int double_resolution)
+                     unsigned long blue_mask, unsigned bpp,
+                     int double_resolution)
 /*
  *  FIASCO renderer constructor.
  *  Allocate memory for the FIASCO renderer structure and
  *  initialize values.
  *  `red_mask', `green_mask', and `blue_mask' are the corresponding masks
- *  of the X11R6 XImage structure. 
+ *  of the X11R6 XImage structure.
  *  `bpp' gives the depth of the image in bits per pixel (16, 24, or 32).
  *  If `double_resolution' is not 0 the the image width and height is doubled.
  *  (fast pixel doubling, no interpolation!)
  *
  *  Return value:
- *	pointer to the new structure or NULL on error
+ *      pointer to the new structure or NULL on error
  */
 {
    if (bpp != 16 && bpp != 24 && bpp !=32)
@@ -111,30 +111,30 @@ fiasco_renderer_new (unsigned long red_mask, unsigned long green_mask,
    {
       fiasco_renderer_t  *render    = calloc (1, sizeof (fiasco_renderer_t));
       renderer_private_t *private   = calloc (1, sizeof (renderer_private_t));
-      bool_t 	       	  twopixels = (bpp == 16 && double_resolution);
-      int 		  crval, cbval, i; /* counter */
+      bool_t              twopixels = (bpp == 16 && double_resolution);
+      int                 crval, cbval, i; /* counter */
 
       if (!render || !private)
       {
-	 set_error (_("Out of memory."));
-	 return NULL;
+         set_error (_("Out of memory."));
+         return NULL;
       }
       switch (bpp)
       {
-	 case 16:
-	    render->render = display_16_bit;
-	    break;
-	 case 24:
-	    if (red_mask > green_mask)
-	       render->render = display_24_bit_rgb;
-	    else
-	       render->render = display_24_bit_bgr;
-	    break;
-	 case 32:
-	    render->render = display_32_bit;
-	    break;
-	 default:
-	    break;			/* does not happen */
+         case 16:
+            render->render = display_16_bit;
+            break;
+         case 24:
+            if (red_mask > green_mask)
+               render->render = display_24_bit_rgb;
+            else
+               render->render = display_24_bit_bgr;
+            break;
+         case 32:
+            render->render = display_32_bit;
+            break;
+         default:
+            break;                      /* does not happen */
       }
       render->private = private;
       render->delete  = fiasco_renderer_delete;
@@ -146,42 +146,42 @@ fiasco_renderer_new (unsigned long red_mask, unsigned long green_mask,
       private->Cb_b_tab = calloc (256 + 2 * 1024, sizeof (int));
 
       if (!private->Cr_r_tab || !private->Cr_g_tab
-	  || !private->Cb_b_tab || !private->Cb_g_tab)
+          || !private->Cb_b_tab || !private->Cb_g_tab)
       {
-	 set_error (_("Out of memory."));
-	 return NULL;
+         set_error (_("Out of memory."));
+         return NULL;
       }
-      
+
       for (i = 1024; i < 1024 + 256; i++)
       {
-	 cbval = crval  = i - 128 - 1024;
+         cbval = crval  = i - 128 - 1024;
 
-	 private->Cr_r_tab [i] =  1.4022 * crval + 0.5;
-	 private->Cr_g_tab [i] = -0.7145 * crval + 0.5;
-	 private->Cb_g_tab [i] = -0.3456 * cbval + 0.5; 
-	 private->Cb_b_tab [i] =  1.7710 * cbval + 0.5;
+         private->Cr_r_tab [i] =  1.4022 * crval + 0.5;
+         private->Cr_g_tab [i] = -0.7145 * crval + 0.5;
+         private->Cb_g_tab [i] = -0.3456 * cbval + 0.5;
+         private->Cb_b_tab [i] =  1.7710 * cbval + 0.5;
       }
       for (i = 0; i < 1024; i++)
       {
-	 private->Cr_r_tab [i] = private->Cr_r_tab [1024];
-	 private->Cr_g_tab [i] = private->Cr_g_tab [1024];
-	 private->Cb_g_tab [i] = private->Cb_g_tab [1024]; 
-	 private->Cb_b_tab [i] = private->Cb_b_tab [1024];
+         private->Cr_r_tab [i] = private->Cr_r_tab [1024];
+         private->Cr_g_tab [i] = private->Cr_g_tab [1024];
+         private->Cb_g_tab [i] = private->Cb_g_tab [1024];
+         private->Cb_b_tab [i] = private->Cb_b_tab [1024];
       }
       for (i = 1024 + 256; i < 2048 + 256; i++)
       {
-	 private->Cr_r_tab [i] = private->Cr_r_tab [1024 + 255];
-	 private->Cr_g_tab [i] = private->Cr_g_tab [1024 + 255];
-	 private->Cb_g_tab [i] = private->Cb_g_tab [1024 + 255]; 
-	 private->Cb_b_tab [i] = private->Cb_b_tab [1024 + 255];
+         private->Cr_r_tab [i] = private->Cr_r_tab [1024 + 255];
+         private->Cr_g_tab [i] = private->Cr_g_tab [1024 + 255];
+         private->Cb_g_tab [i] = private->Cb_g_tab [1024 + 255];
+         private->Cb_b_tab [i] = private->Cb_b_tab [1024 + 255];
       }
 
       private->Cr_r_tab += 1024 + 128;
       private->Cr_g_tab += 1024 + 128;
       private->Cb_g_tab += 1024 + 128;
       private->Cb_b_tab += 1024 + 128;
-   
-      /* 
+
+      /*
        *  Set up entries 0-255 in rgb-to-pixel value tables.
        */
       private->r_table = calloc (256 + 2 * 1024, sizeof (unsigned int));
@@ -190,38 +190,38 @@ fiasco_renderer_new (unsigned long red_mask, unsigned long green_mask,
       private->y_table = calloc (256 + 2 * 1024, sizeof (unsigned int));
 
       if (!private->r_table || !private->g_table
-	  || !private->b_table || !private->y_table)
+          || !private->b_table || !private->y_table)
       {
-	 set_error (_("Out of memory."));
-	 return NULL;
+         set_error (_("Out of memory."));
+         return NULL;
       }
-      
+
       for (i = 0; i < 256; i++)
       {
-	 private->r_table [i + 1024]
-	    = i >> (8 - number_of_bits_set(red_mask));
-	 private->r_table [i + 1024]
-	    <<= free_bits_at_bottom (red_mask);
-	 private->g_table [i + 1024]
-	    = i >> (8 - number_of_bits_set (green_mask));
-	 private->g_table [i + 1024]
-	    <<= free_bits_at_bottom (green_mask);
-	 private->b_table [i + 1024]
-	    <<= free_bits_at_bottom (blue_mask);
-	 private->b_table [i + 1024]
-	    = i >> (8 - number_of_bits_set (blue_mask));
-	 if (twopixels)
-	 {
-	    private->r_table [i + 1024] = ((private->r_table [i + 1024] << 16)
-					   | private->r_table [i + 1024]);
-	    private->g_table [i + 1024] = ((private->g_table [i + 1024] << 16)
-					   | private->g_table [i + 1024]);
-	    private->b_table [i + 1024] = ((private->b_table [i + 1024] << 16)
-					   | private->b_table [i + 1024]);
-	 }
-	 private->y_table [i + 1024] = (private->r_table [i + 1024]
-					| private->g_table [i + 1024]
-					| private->b_table [i + 1024]);
+         private->r_table [i + 1024]
+            = i >> (8 - number_of_bits_set(red_mask));
+         private->r_table [i + 1024]
+            <<= free_bits_at_bottom (red_mask);
+         private->g_table [i + 1024]
+            = i >> (8 - number_of_bits_set (green_mask));
+         private->g_table [i + 1024]
+            <<= free_bits_at_bottom (green_mask);
+         private->b_table [i + 1024]
+            <<= free_bits_at_bottom (blue_mask);
+         private->b_table [i + 1024]
+            = i >> (8 - number_of_bits_set (blue_mask));
+         if (twopixels)
+         {
+            private->r_table [i + 1024] = ((private->r_table [i + 1024] << 16)
+                                           | private->r_table [i + 1024]);
+            private->g_table [i + 1024] = ((private->g_table [i + 1024] << 16)
+                                           | private->g_table [i + 1024]);
+            private->b_table [i + 1024] = ((private->b_table [i + 1024] << 16)
+                                           | private->b_table [i + 1024]);
+         }
+         private->y_table [i + 1024] = (private->r_table [i + 1024]
+                                        | private->g_table [i + 1024]
+                                        | private->b_table [i + 1024]);
       }
 
       /*
@@ -230,14 +230,14 @@ fiasco_renderer_new (unsigned long red_mask, unsigned long green_mask,
        */
       for (i = 0; i < 1024; i++)
       {
-	 private->r_table [i]              = private->r_table [1024];
-	 private->r_table [i + 1024 + 256] = private->r_table [1024 + 255];
-	 private->g_table [i]              = private->g_table [1024];
-	 private->g_table [i + 1024 + 256] = private->g_table [1024 + 255];
-	 private->b_table [i]              = private->b_table [1024];
-	 private->b_table [i + 1024 + 256] = private->b_table [1024 + 255];
-	 private->y_table [i]              = private->y_table [1024];
-	 private->y_table [i + 1024 + 256] = private->y_table [1024 + 255];
+         private->r_table [i]              = private->r_table [1024];
+         private->r_table [i + 1024 + 256] = private->r_table [1024 + 255];
+         private->g_table [i]              = private->g_table [1024];
+         private->g_table [i + 1024 + 256] = private->g_table [1024 + 255];
+         private->b_table [i]              = private->b_table [1024];
+         private->b_table [i + 1024 + 256] = private->b_table [1024 + 255];
+         private->y_table [i]              = private->y_table [1024];
+         private->y_table [i + 1024 + 256] = private->y_table [1024 + 255];
       }
 
       private->r_table += 1024;
@@ -247,7 +247,7 @@ fiasco_renderer_new (unsigned long red_mask, unsigned long green_mask,
 
       return render;
    }
-   
+
 }
 
 void
@@ -259,7 +259,7 @@ fiasco_renderer_delete (fiasco_renderer_t *renderer)
  *  No return value.
  *
  *  Side effects:
- *	structure 'renderer' is discarded.
+ *      structure 'renderer' is discarded.
  */
 {
    if (!renderer)
@@ -284,8 +284,8 @@ fiasco_renderer_delete (fiasco_renderer_t *renderer)
 
 int
 fiasco_renderer_render (const fiasco_renderer_t *renderer,
-			unsigned char *ximage,
-			const fiasco_image_t *fiasco_image)
+                        unsigned char *ximage,
+                        const fiasco_image_t *fiasco_image)
 {
    if (!renderer)
    {
@@ -298,8 +298,8 @@ fiasco_renderer_render (const fiasco_renderer_t *renderer,
 
 /*****************************************************************************
 
-				private code
-  
+                                private code
+
 *****************************************************************************/
 
 /*
@@ -313,7 +313,7 @@ fiasco_renderer_render (const fiasco_renderer_t *renderer,
  *  mode, since this involves getting down to byte level again. It is
  *  assumed that the bits for each color are contiguous in the
  *  longword.
- * 
+ *
  *  Writing to memory is done in shorts or ints. (Unfortunately, short
  *  is not very fast on Alpha, so there is room for improvement
  *  here). There is no dither time check for overflow - instead the
@@ -357,9 +357,9 @@ free_bits_at_bottom (unsigned long a)
       return 1 + free_bits_at_bottom ( a >> 1);
 }
 
-static int 
+static int
 display_16_bit (const struct fiasco_renderer *this, unsigned char *ximage,
-		const fiasco_image_t *fiasco_image)
+                const fiasco_image_t *fiasco_image)
 /*
  *  Convert 'image' to 16 bit color bitmap.
  *  If 'double_resolution' is true then double image size in both directions.
@@ -367,13 +367,13 @@ display_16_bit (const struct fiasco_renderer *this, unsigned char *ximage,
  *  No return value.
  *
  *  Side effects:
- *	'out[]'	is filled with dithered image
+ *      'out[]' is filled with dithered image
  */
 {
    const image_t      *image;
    renderer_private_t *private;
-   byte_t	      *out;
-   
+   byte_t             *out;
+
    if (!this)
    {
       set_error (_("Parameter `%s' not defined (NULL)."), "this");
@@ -390,21 +390,21 @@ display_16_bit (const struct fiasco_renderer *this, unsigned char *ximage,
       return 0;
    }
 
-   out 	   = (byte_t *) ximage;
+   out     = (byte_t *) ximage;
    image   = cast_image ((fiasco_image_t *) fiasco_image);
    if (!image)
       return 0;
    private = (renderer_private_t *) this->private;
-   
+
    if (image->color)
    {
-      word_t 	   *cbptr, *crptr;	/* pointer to chroma bands */
-      word_t 	   *yptr;		/* pointers to lumincance band */
-      int     	    yval, crval, cbval;	/* pixel value in YCbCr color space */
-      int     	    R, G, B;		/* pixel value in RGB color space */
-      int     	    n;			/* pixel counter */
-      int     	    x, y;		/* pixel coordinates */
-      int 	   *Cr_r_tab, *Cr_g_tab, *Cb_g_tab, *Cb_b_tab;
+      word_t       *cbptr, *crptr;      /* pointer to chroma bands */
+      word_t       *yptr;               /* pointers to lumincance band */
+      int           yval, crval, cbval; /* pixel value in YCbCr color space */
+      int           R, G, B;            /* pixel value in RGB color space */
+      int           n;                  /* pixel counter */
+      int           x, y;               /* pixel coordinates */
+      int          *Cr_r_tab, *Cr_g_tab, *Cb_g_tab, *Cb_b_tab;
       unsigned int *r_table, *g_table, *b_table;
 
       Cr_g_tab = private->Cr_g_tab;
@@ -420,245 +420,245 @@ display_16_bit (const struct fiasco_renderer *this, unsigned char *ximage,
 
       if (image->format == FORMAT_4_2_0)
       {
-	 u_word_t *dst, *dst2;		/* pointers to dithered pixels */
-	 word_t	  *yptr2;		/* pointers to lumincance band */
-
-	 if (private->double_resolution)
-	 {
-	    yptr2 = yptr + image->width;
-	    dst   = (u_word_t *) out;
-	    dst2  = dst + 4 * image->width;
-	    for (y = image->height / 2; y; y--)
-	    {
-	       for (x = image->width / 2; x; x--)
-	       {
+         u_word_t *dst, *dst2;          /* pointers to dithered pixels */
+         word_t   *yptr2;               /* pointers to lumincance band */
+
+         if (private->double_resolution)
+         {
+            yptr2 = yptr + image->width;
+            dst   = (u_word_t *) out;
+            dst2  = dst + 4 * image->width;
+            for (y = image->height / 2; y; y--)
+            {
+               for (x = image->width / 2; x; x--)
+               {
 #ifdef HAVE_SIGNED_SHIFT
-		  crval = *crptr++ >> 4;
-		  cbval = *cbptr++ >> 4;
-		  yval  = (*yptr++ >> 4) + 128;
+                  crval = *crptr++ >> 4;
+                  cbval = *cbptr++ >> 4;
+                  yval  = (*yptr++ >> 4) + 128;
 #else /* not HAVE_SIGNED_SHIFT */
-		  crval = *crptr++ / 16;
-		  cbval = *cbptr++ / 16;
-		  yval  = *yptr++  / 16 + 128;
+                  crval = *crptr++ / 16;
+                  cbval = *cbptr++ / 16;
+                  yval  = *yptr++  / 16 + 128;
 #endif /* not HAVE_SIGNED_SHIFT */
-		  R = yval + Cr_r_tab [crval];
-		  G = yval + Cr_g_tab [crval] + Cb_g_tab [cbval];
-		  B = yval + Cb_b_tab [cbval];
-		  *dst++ = r_table [R] | g_table [G] | b_table [B];
-		  *dst++ = r_table [R] | g_table [G] | b_table [B];
-	       
+                  R = yval + Cr_r_tab [crval];
+                  G = yval + Cr_g_tab [crval] + Cb_g_tab [cbval];
+                  B = yval + Cb_b_tab [cbval];
+                  *dst++ = r_table [R] | g_table [G] | b_table [B];
+                  *dst++ = r_table [R] | g_table [G] | b_table [B];
+
 #ifdef HAVE_SIGNED_SHIFT
-		  yval  = (*yptr++ >> 4) + 128;
+                  yval  = (*yptr++ >> 4) + 128;
 #else /* not HAVE_SIGNED_SHIFT */
-		  yval  = *yptr++  / 16 + 128;
+                  yval  = *yptr++  / 16 + 128;
 #endif /* not HAVE_SIGNED_SHIFT */
-		  R = yval + Cr_r_tab [crval];
-		  G = yval + Cr_g_tab [crval] + Cb_g_tab [cbval];
-		  B = yval + Cb_b_tab [cbval];
-		  *dst++ = r_table [R] | g_table [G] | b_table [B];
-		  *dst++ = r_table [R] | g_table [G] | b_table [B];
+                  R = yval + Cr_r_tab [crval];
+                  G = yval + Cr_g_tab [crval] + Cb_g_tab [cbval];
+                  B = yval + Cb_b_tab [cbval];
+                  *dst++ = r_table [R] | g_table [G] | b_table [B];
+                  *dst++ = r_table [R] | g_table [G] | b_table [B];
 
 #ifdef HAVE_SIGNED_SHIFT
-		  yval  = (*yptr2++ >> 4) + 128;
+                  yval  = (*yptr2++ >> 4) + 128;
 #else /* not HAVE_SIGNED_SHIFT */
-		  yval  = *yptr2++  / 16 + 128;
+                  yval  = *yptr2++  / 16 + 128;
 #endif /* not HAVE_SIGNED_SHIFT */
-		  R = yval + Cr_r_tab [crval];
-		  G = yval + Cr_g_tab [crval] + Cb_g_tab [cbval];
-		  B = yval + Cb_b_tab [cbval];
-		  *dst2++ = r_table [R] | g_table [G] | b_table [B];
-		  *dst2++ = r_table [R] | g_table [G] | b_table [B];
+                  R = yval + Cr_r_tab [crval];
+                  G = yval + Cr_g_tab [crval] + Cb_g_tab [cbval];
+                  B = yval + Cb_b_tab [cbval];
+                  *dst2++ = r_table [R] | g_table [G] | b_table [B];
+                  *dst2++ = r_table [R] | g_table [G] | b_table [B];
 
 #ifdef HAVE_SIGNED_SHIFT
-		  yval  = (*yptr2++ >> 4) + 128;
+                  yval  = (*yptr2++ >> 4) + 128;
 #else /* not HAVE_SIGNED_SHIFT */
-		  yval  = *yptr2++  / 16 + 128;
+                  yval  = *yptr2++  / 16 + 128;
 #endif /* not HAVE_SIGNED_SHIFT */
-		  R = yval + Cr_r_tab [crval];
-		  G = yval + Cr_g_tab [crval] + Cb_g_tab [cbval];
-		  B = yval + Cb_b_tab [cbval];
-		  *dst2++ = r_table [R] | g_table [G] | b_table [B];
-		  *dst2++ = r_table [R] | g_table [G] | b_table [B];
-	       }
-	       memcpy (dst, dst - 2 * image->width,
-		       2 * image->width * sizeof (u_word_t));
-	       memcpy (dst2, dst2 - 2 * image->width,
-		       2 * image->width * sizeof (u_word_t));
-	       yptr  += image->width;
-	       yptr2 += image->width;
-	       dst   += 3 * image->width * 2;
-	       dst2  += 3 * image->width * 2;
-	    }
-	 }
-	 else
-	 {
-	    yptr2 = yptr + image->width;
-	    dst  = (u_word_t *) out;
-	    dst2 = dst + image->width;
-	    
-	    for (y = image->height / 2; y; y--)
-	    {
-	       for (x = image->width / 2; x; x--)
-	       {
+                  R = yval + Cr_r_tab [crval];
+                  G = yval + Cr_g_tab [crval] + Cb_g_tab [cbval];
+                  B = yval + Cb_b_tab [cbval];
+                  *dst2++ = r_table [R] | g_table [G] | b_table [B];
+                  *dst2++ = r_table [R] | g_table [G] | b_table [B];
+               }
+               memcpy (dst, dst - 2 * image->width,
+                       2 * image->width * sizeof (u_word_t));
+               memcpy (dst2, dst2 - 2 * image->width,
+                       2 * image->width * sizeof (u_word_t));
+               yptr  += image->width;
+               yptr2 += image->width;
+               dst   += 3 * image->width * 2;
+               dst2  += 3 * image->width * 2;
+            }
+         }
+         else
+         {
+            yptr2 = yptr + image->width;
+            dst  = (u_word_t *) out;
+            dst2 = dst + image->width;
+
+            for (y = image->height / 2; y; y--)
+            {
+               for (x = image->width / 2; x; x--)
+               {
 #ifdef HAVE_SIGNED_SHIFT
-		  crval = *crptr++ >> 4;
-		  cbval = *cbptr++ >> 4;
-		  yval  = (*yptr++ >> 4) + 128;
+                  crval = *crptr++ >> 4;
+                  cbval = *cbptr++ >> 4;
+                  yval  = (*yptr++ >> 4) + 128;
 #else /* not HAVE_SIGNED_SHIFT */
-		  crval = *crptr++ / 16;
-		  cbval = *cbptr++ / 16;
-		  yval  = *yptr++  / 16 + 128;
+                  crval = *crptr++ / 16;
+                  cbval = *cbptr++ / 16;
+                  yval  = *yptr++  / 16 + 128;
 #endif /* not HAVE_SIGNED_SHIFT */
-		  R = yval + Cr_r_tab [crval];
-		  G = yval + Cr_g_tab [crval] + Cb_g_tab [cbval];
-		  B = yval + Cb_b_tab [cbval];
-		  *dst++ = r_table [R] | g_table [G] | b_table [B];
-	       
+                  R = yval + Cr_r_tab [crval];
+                  G = yval + Cr_g_tab [crval] + Cb_g_tab [cbval];
+                  B = yval + Cb_b_tab [cbval];
+                  *dst++ = r_table [R] | g_table [G] | b_table [B];
+
 #ifdef HAVE_SIGNED_SHIFT
-		  yval  = (*yptr++ >> 4) + 128;
+                  yval  = (*yptr++ >> 4) + 128;
 #else /* not HAVE_SIGNED_SHIFT */
-		  yval  = *yptr++  / 16 + 128;
+                  yval  = *yptr++  / 16 + 128;
 #endif /* not HAVE_SIGNED_SHIFT */
-		  R = yval + Cr_r_tab [crval];
-		  G = yval + Cr_g_tab [crval] + Cb_g_tab [cbval];
-		  B = yval + Cb_b_tab [cbval];
-		  *dst++ = r_table [R] | g_table [G] | b_table [B];
+                  R = yval + Cr_r_tab [crval];
+                  G = yval + Cr_g_tab [crval] + Cb_g_tab [cbval];
+                  B = yval + Cb_b_tab [cbval];
+                  *dst++ = r_table [R] | g_table [G] | b_table [B];
 
 #ifdef HAVE_SIGNED_SHIFT
-		  yval  = (*yptr2++ >> 4) + 128;
+                  yval  = (*yptr2++ >> 4) + 128;
 #else /* not HAVE_SIGNED_SHIFT */
-		  yval  = *yptr2++  / 16 + 128;
+                  yval  = *yptr2++  / 16 + 128;
 #endif /* not HAVE_SIGNED_SHIFT */
-		  R = yval + Cr_r_tab [crval];
-		  G = yval + Cr_g_tab [crval] + Cb_g_tab [cbval];
-		  B = yval + Cb_b_tab [cbval];
-		  *dst2++ = r_table [R] | g_table [G] | b_table [B];
+                  R = yval + Cr_r_tab [crval];
+                  G = yval + Cr_g_tab [crval] + Cb_g_tab [cbval];
+                  B = yval + Cb_b_tab [cbval];
+                  *dst2++ = r_table [R] | g_table [G] | b_table [B];
 
 #ifdef HAVE_SIGNED_SHIFT
-		  yval  = (*yptr2++ >> 4) + 128;
+                  yval  = (*yptr2++ >> 4) + 128;
 #else /* not HAVE_SIGNED_SHIFT */
-		  yval  = *yptr2++  / 16 + 128;
+                  yval  = *yptr2++  / 16 + 128;
 #endif /* not HAVE_SIGNED_SHIFT */
-		  R = yval + Cr_r_tab [crval];
-		  G = yval + Cr_g_tab [crval] + Cb_g_tab [cbval];
-		  B = yval + Cb_b_tab [cbval];
-		  *dst2++ = r_table [R] | g_table [G] | b_table [B];
-	       }
-	       yptr  += image->width;
-	       yptr2 += image->width;
-	       dst   += image->width;
-	       dst2  += image->width;
-	    }
-	 }
+                  R = yval + Cr_r_tab [crval];
+                  G = yval + Cr_g_tab [crval] + Cb_g_tab [cbval];
+                  B = yval + Cb_b_tab [cbval];
+                  *dst2++ = r_table [R] | g_table [G] | b_table [B];
+               }
+               yptr  += image->width;
+               yptr2 += image->width;
+               dst   += image->width;
+               dst2  += image->width;
+            }
+         }
       }
-      else				/* 4:4:4 format */
+      else                              /* 4:4:4 format */
       {
-	 if (private->double_resolution)
-	 {
-	    unsigned int *dst;		/* pointer to dithered pixels */
-	    
-	    dst  = (unsigned int *) out;
-	    
-	    for (y = image->height; y; y--)
-	    {
-	       for (x = image->width; x; x--)
-	       {
+         if (private->double_resolution)
+         {
+            unsigned int *dst;          /* pointer to dithered pixels */
+
+            dst  = (unsigned int *) out;
+
+            for (y = image->height; y; y--)
+            {
+               for (x = image->width; x; x--)
+               {
 #ifdef HAVE_SIGNED_SHIFT
-		  crval = *crptr++ >> 4;
-		  cbval = *cbptr++ >> 4;
-		  yval  = (*yptr++ >> 4) + 128;
+                  crval = *crptr++ >> 4;
+                  cbval = *cbptr++ >> 4;
+                  yval  = (*yptr++ >> 4) + 128;
 #else /* not HAVE_SIGNED_SHIFT */
-		  crval = *crptr++ / 16;
-		  cbval = *cbptr++ / 16;
-		  yval  = *yptr++  / 16 + 128;
+                  crval = *crptr++ / 16;
+                  cbval = *cbptr++ / 16;
+                  yval  = *yptr++  / 16 + 128;
 #endif /* not HAVE_SIGNED_SHIFT */
-		  R = yval + Cr_r_tab [crval];
-		  G = yval + Cr_g_tab [crval] + Cb_g_tab [cbval];
-		  B = yval + Cb_b_tab [cbval];
-		  
-		  *dst++ = r_table [R] | g_table [G] | b_table [B];
-	       }
-	       memcpy (dst, dst - image->width,
-		       image->width * sizeof (unsigned int));
-	       dst += image->width;
-	    }
-	 }
-	 else
-	 {
-	    u_word_t *dst;		/* pointer to dithered pixels */
-
-	    dst  = (u_word_t *) out;
-	    
-	    for (n = image->width * image->height; n; n--)
-	    {
+                  R = yval + Cr_r_tab [crval];
+                  G = yval + Cr_g_tab [crval] + Cb_g_tab [cbval];
+                  B = yval + Cb_b_tab [cbval];
+
+                  *dst++ = r_table [R] | g_table [G] | b_table [B];
+               }
+               memcpy (dst, dst - image->width,
+                       image->width * sizeof (unsigned int));
+               dst += image->width;
+            }
+         }
+         else
+         {
+            u_word_t *dst;              /* pointer to dithered pixels */
+
+            dst  = (u_word_t *) out;
+
+            for (n = image->width * image->height; n; n--)
+            {
 #ifdef HAVE_SIGNED_SHIFT
-	       crval = *crptr++ >> 4;
-	       cbval = *cbptr++ >> 4;
-	       yval  = (*yptr++ >> 4) + 128;
+               crval = *crptr++ >> 4;
+               cbval = *cbptr++ >> 4;
+               yval  = (*yptr++ >> 4) + 128;
 #else /* not HAVE_SIGNED_SHIFT */
-	       crval = *crptr++ / 16;
-	       cbval = *cbptr++ / 16;
-	       yval  = *yptr++  / 16 + 128;
+               crval = *crptr++ / 16;
+               cbval = *cbptr++ / 16;
+               yval  = *yptr++  / 16 + 128;
 #endif /* not HAVE_SIGNED_SHIFT */
-	       R = yval + Cr_r_tab [crval];
-	       G = yval + Cr_g_tab [crval] + Cb_g_tab [cbval];
-	       B = yval + Cb_b_tab [cbval];
+               R = yval + Cr_r_tab [crval];
+               G = yval + Cr_g_tab [crval] + Cb_g_tab [cbval];
+               B = yval + Cb_b_tab [cbval];
 
-	       *dst++ = r_table [R] | g_table [G] | b_table [B];
-	    }
-	 }
+               *dst++ = r_table [R] | g_table [G] | b_table [B];
+            }
+         }
       }
    }
    else
    {
-      unsigned int *dst;		/* pointer to dithered pixels */
-      word_t	   *src;		/* current pixel of frame */
+      unsigned int *dst;                /* pointer to dithered pixels */
+      word_t       *src;                /* current pixel of frame */
       unsigned int *y_table;
 
       y_table = private->y_table;
       dst     = (unsigned int *) out;
       src     = image->pixels [GRAY];
-      
+
       if (private->double_resolution)
       {
-	 int x, y;			/* pixel coordinates */
-  	    
-	 for (y = image->height; y; y--)
-	 {
-	    for (x = image->width; x; x--)
-	    {
-	       int value;
-	       
+         int x, y;                      /* pixel coordinates */
+
+         for (y = image->height; y; y--)
+         {
+            for (x = image->width; x; x--)
+            {
+               int value;
+
 #ifdef HAVE_SIGNED_SHIFT
-	       value = y_table [*src++ >> 4];
+               value = y_table [*src++ >> 4];
 #else /* not HAVE_SIGNED_SHIFT */
-	       value = y_table [*src++ / 16];
+               value = y_table [*src++ / 16];
 #endif /* not HAVE_SIGNED_SHIFT */
-	       *dst++ = (value << 16) | value;
-	    }
-	    
-	    memcpy (dst, dst - image->width,
-		    image->width * sizeof (unsigned int));
-	    dst += image->width;
-	 }
+               *dst++ = (value << 16) | value;
+            }
+
+            memcpy (dst, dst - image->width,
+                    image->width * sizeof (unsigned int));
+            dst += image->width;
+         }
       }
       else
       {
-	 int n;				/* pixel counter */
-	 
-	 for (n = image->width * image->height / 2; n; n--, src += 2)
+         int n;                         /* pixel counter */
+
+         for (n = image->width * image->height / 2; n; n--, src += 2)
 #ifdef HAVE_SIGNED_SHIFT
-#	if BYTE_ORDER == LITTLE_ENDIAN
-	    *dst++ = (y_table [src [1] >> 4] << 16) | y_table [src [0] >> 4];
-#	else
-	    *dst++ = (y_table [src [0] >> 4] << 16) | y_table [src [1] >> 4];
-#	endif
+#       if BYTE_ORDER == LITTLE_ENDIAN
+            *dst++ = (y_table [src [1] >> 4] << 16) | y_table [src [0] >> 4];
+#       else
+            *dst++ = (y_table [src [0] >> 4] << 16) | y_table [src [1] >> 4];
+#       endif
 #else /* not HAVE_SIGNED_SHIFT */
-#	if BYTE_ORDER == LITTLE_ENDIAN
-	    *dst++ = (y_table [src [1] / 16] << 16) | y_table [src [0] / 16];
-#	else
-	    *dst++ = (y_table [src [0] / 16] << 16) | y_table [src [1] / 16];
-#	endif
+#       if BYTE_ORDER == LITTLE_ENDIAN
+            *dst++ = (y_table [src [1] / 16] << 16) | y_table [src [0] / 16];
+#       else
+            *dst++ = (y_table [src [0] / 16] << 16) | y_table [src [1] / 16];
+#       endif
 #endif /* not HAVE_SIGNED_SHIFT */
       }
    }
@@ -666,9 +666,9 @@ display_16_bit (const struct fiasco_renderer *this, unsigned char *ximage,
    return 1;
 }
 
-static int 
+static int
 display_24_bit_bgr (const struct fiasco_renderer *this, unsigned char *ximage,
-		    const fiasco_image_t *fiasco_image)
+                    const fiasco_image_t *fiasco_image)
 /*
  *  Convert 'image' to 16 bit color bitmap.
  *  If 'double_resolution' is true then double image size in both directions.
@@ -676,13 +676,13 @@ display_24_bit_bgr (const struct fiasco_renderer *this, unsigned char *ximage,
  *  No return value.
  *
  *  Side effects:
- *	'out[]'	is filled with dithered image
+ *      'out[]' is filled with dithered image
  */
 {
-   unsigned 	      *gray_clip = init_clipping ();
+   unsigned           *gray_clip = init_clipping ();
    const image_t      *image;
    renderer_private_t *private;
-   byte_t	      *out;
+   byte_t             *out;
 
    if (!gray_clip)
       return 0;
@@ -702,17 +702,17 @@ display_24_bit_bgr (const struct fiasco_renderer *this, unsigned char *ximage,
       return 0;
    }
 
-   out 	   = (byte_t *) ximage;
+   out     = (byte_t *) ximage;
    image   = cast_image ((fiasco_image_t *) fiasco_image);
    if (!image)
       return 0;
    private = (renderer_private_t *) this->private;
-   
+
    if (image->color)
    {
-      word_t 	   *cbptr, *crptr;	/* pointer to chroma bands */
-      word_t 	   *yptr;		/* pointers to lumincance band */
-      int 	   *Cr_r_tab, *Cr_g_tab, *Cb_g_tab, *Cb_b_tab;
+      word_t       *cbptr, *crptr;      /* pointer to chroma bands */
+      word_t       *yptr;               /* pointers to lumincance band */
+      int          *Cr_r_tab, *Cr_g_tab, *Cb_g_tab, *Cb_b_tab;
 
       Cr_g_tab = private->Cr_g_tab;
       Cr_r_tab = private->Cr_r_tab;
@@ -724,396 +724,396 @@ display_24_bit_bgr (const struct fiasco_renderer *this, unsigned char *ximage,
 
       if (image->format == FORMAT_4_2_0)
       {
-	 if (private->double_resolution)
-	 {
-	    int		  yval1;	/* lumincance pixel */
-	    int 	  crval1, cbval1; /* chroma pixels */
-	    int		  yval2;	/* pixel in YCbCr color space */
-	    unsigned int  R1, G1, B1;	/* pixel in RGB color space */
-	    unsigned int  R2, G2, B2;	/* pixel in RGB color space */
-	    int		  x, y;		/* pixel counter */
-	    unsigned int *dst;		/* pointer to dithered pixels */
-	    unsigned int *dst2;		/* pointers to dithered pixels */
-	    word_t	 *yptr2;	/* pointers to lumincance band */
-	    
-	    dst   = (unsigned int *) out;
-	    dst2  = dst + (image->width >> 1) * 3 * 2;
-	    yptr2 = yptr + image->width;
-	    
-	    for (y = image->height >> 1; y; y--)
-	    {
-	       for (x = image->width >> 1; x; x--)
-	       {
+         if (private->double_resolution)
+         {
+            int           yval1;        /* lumincance pixel */
+            int           crval1, cbval1; /* chroma pixels */
+            int           yval2;        /* pixel in YCbCr color space */
+            unsigned int  R1, G1, B1;   /* pixel in RGB color space */
+            unsigned int  R2, G2, B2;   /* pixel in RGB color space */
+            int           x, y;         /* pixel counter */
+            unsigned int *dst;          /* pointer to dithered pixels */
+            unsigned int *dst2;         /* pointers to dithered pixels */
+            word_t       *yptr2;        /* pointers to lumincance band */
+
+            dst   = (unsigned int *) out;
+            dst2  = dst + (image->width >> 1) * 3 * 2;
+            yptr2 = yptr + image->width;
+
+            for (y = image->height >> 1; y; y--)
+            {
+               for (x = image->width >> 1; x; x--)
+               {
 #ifdef HAVE_SIGNED_SHIFT
-		  yval1  = (*yptr++ >> 4) + 128;
-		  yval2  = (*yptr++ >> 4) + 128;
-		  crval1 = *crptr++ >> 4;
-		  cbval1 = *cbptr++ >> 4;
+                  yval1  = (*yptr++ >> 4) + 128;
+                  yval2  = (*yptr++ >> 4) + 128;
+                  crval1 = *crptr++ >> 4;
+                  cbval1 = *cbptr++ >> 4;
 #else /* not HAVE_SIGNED_SHIFT */
-		  yval1  = *yptr++  / 16 + 128;
-		  yval2  = *yptr++  / 16 + 128;
-		  crval1 = *crptr++ / 16;
-		  cbval1 = *cbptr++ / 16;
+                  yval1  = *yptr++  / 16 + 128;
+                  yval2  = *yptr++  / 16 + 128;
+                  crval1 = *crptr++ / 16;
+                  cbval1 = *cbptr++ / 16;
 #endif /* not HAVE_SIGNED_SHIFT */
 
-		  R1 = gray_clip [yval1 + Cr_r_tab [crval1]];
-		  G1 = gray_clip [yval1 + Cr_g_tab [crval1]
-				 + Cb_g_tab [cbval1]];
-		  B1 = gray_clip [yval1 + Cb_b_tab [cbval1]];
-		  R2 = gray_clip [yval2 + Cr_r_tab [crval1]];
-		  G2 = gray_clip [yval2 + Cr_g_tab [crval1]
-				 + Cb_g_tab [cbval1]];
-		  B2 = gray_clip [yval2 + Cb_b_tab [cbval1]];
+                  R1 = gray_clip [yval1 + Cr_r_tab [crval1]];
+                  G1 = gray_clip [yval1 + Cr_g_tab [crval1]
+                                 + Cb_g_tab [cbval1]];
+                  B1 = gray_clip [yval1 + Cb_b_tab [cbval1]];
+                  R2 = gray_clip [yval2 + Cr_r_tab [crval1]];
+                  G2 = gray_clip [yval2 + Cr_g_tab [crval1]
+                                 + Cb_g_tab [cbval1]];
+                  B2 = gray_clip [yval2 + Cb_b_tab [cbval1]];
 
-		  *dst++ = B1 | (G1 << 8) | (R1 << 16) | (B1 << 24);
-		  *dst++ = G1 | (R1 << 8) | (B2 << 16) | (G2 << 24);
-		  *dst++ = R2 | (B2 << 8) | (G2 << 16) | (R2 << 24);
+                  *dst++ = B1 | (G1 << 8) | (R1 << 16) | (B1 << 24);
+                  *dst++ = G1 | (R1 << 8) | (B2 << 16) | (G2 << 24);
+                  *dst++ = R2 | (B2 << 8) | (G2 << 16) | (R2 << 24);
 
 #ifdef HAVE_SIGNED_SHIFT
-		  yval1  = (*yptr2++ >> 4) + 128;
-		  yval2  = (*yptr2++ >> 4) + 128;
+                  yval1  = (*yptr2++ >> 4) + 128;
+                  yval2  = (*yptr2++ >> 4) + 128;
 #else /* not HAVE_SIGNED_SHIFT */
-		  yval1  = *yptr2++  / 16 + 128;
-		  yval2  = *yptr2++  / 16 + 128;
+                  yval1  = *yptr2++  / 16 + 128;
+                  yval2  = *yptr2++  / 16 + 128;
 #endif /* not HAVE_SIGNED_SHIFT */
 
-		  R1 = gray_clip [yval1 + Cr_r_tab [crval1]];
-		  G1 = gray_clip [yval1 + Cr_g_tab [crval1]
-				 + Cb_g_tab [cbval1]];
-		  B1 = gray_clip [yval1 + Cb_b_tab [cbval1]];
-		  R2 = gray_clip [yval2 + Cr_r_tab [crval1]];
-		  G2 = gray_clip [yval2 + Cr_g_tab [crval1]
-				 + Cb_g_tab [cbval1]];
-		  B2 = gray_clip [yval2 + Cb_b_tab [cbval1]];
-
-		  *dst2++ = B1 | (G1 << 8) | (R1 << 16) | (B1 << 24);
-		  *dst2++ = G1 | (R1 << 8) | (B2 << 16) | (G2 << 24);
-		  *dst2++ = R2 | (B2 << 8) | (G2 << 16) | (R2 << 24);
-	       }
-	       memcpy (dst, dst - (image->width >> 1) * 3,
-		       (image->width >> 1) * 3 * sizeof (unsigned int));
-	       memcpy (dst2, dst2 - (image->width >> 1) * 3, 
-		       (image->width >> 1) * 3 * sizeof (unsigned int));
-	       dst   += (image->width >> 1) * 3 * 3;
-	       dst2  += (image->width >> 1) * 3 * 3;
-	       yptr  += image->width;
-	       yptr2 += image->width;
-	    }
-	 }
-	 else
-	 {
-	    int		  yval1;	/* lumincance pixel */
-	    int 	  crval1, cbval1; /* chroma pixels */
-	    int		  yval2;	/* pixel in YCbCr color space */
-	    unsigned int  R1, G1, B1;	/* pixel in RGB color space */
-	    unsigned int  R2, G2, B2;	/* pixel in RGB color space */
-	    int		  x, y;		/* pixel counter */
-	    unsigned int *dst;		/* pointer to dithered pixels */
-	    unsigned int *dst2;		/* pointers to dithered pixels */
-	    word_t	 *yptr2;	/* pointers to lumincance band */
-	    
-	    dst   = (unsigned int *) out;
-	    dst2  = dst + (image->width >> 2) * 3;
-	    yptr2 = yptr + image->width;
-	    
-	    for (y = image->height >> 1; y; y--)
-	    {
-	       for (x = image->width >> 2; x; x--)
-	       {
+                  R1 = gray_clip [yval1 + Cr_r_tab [crval1]];
+                  G1 = gray_clip [yval1 + Cr_g_tab [crval1]
+                                 + Cb_g_tab [cbval1]];
+                  B1 = gray_clip [yval1 + Cb_b_tab [cbval1]];
+                  R2 = gray_clip [yval2 + Cr_r_tab [crval1]];
+                  G2 = gray_clip [yval2 + Cr_g_tab [crval1]
+                                 + Cb_g_tab [cbval1]];
+                  B2 = gray_clip [yval2 + Cb_b_tab [cbval1]];
+
+                  *dst2++ = B1 | (G1 << 8) | (R1 << 16) | (B1 << 24);
+                  *dst2++ = G1 | (R1 << 8) | (B2 << 16) | (G2 << 24);
+                  *dst2++ = R2 | (B2 << 8) | (G2 << 16) | (R2 << 24);
+               }
+               memcpy (dst, dst - (image->width >> 1) * 3,
+                       (image->width >> 1) * 3 * sizeof (unsigned int));
+               memcpy (dst2, dst2 - (image->width >> 1) * 3,
+                       (image->width >> 1) * 3 * sizeof (unsigned int));
+               dst   += (image->width >> 1) * 3 * 3;
+               dst2  += (image->width >> 1) * 3 * 3;
+               yptr  += image->width;
+               yptr2 += image->width;
+            }
+         }
+         else
+         {
+            int           yval1;        /* lumincance pixel */
+            int           crval1, cbval1; /* chroma pixels */
+            int           yval2;        /* pixel in YCbCr color space */
+            unsigned int  R1, G1, B1;   /* pixel in RGB color space */
+            unsigned int  R2, G2, B2;   /* pixel in RGB color space */
+            int           x, y;         /* pixel counter */
+            unsigned int *dst;          /* pointer to dithered pixels */
+            unsigned int *dst2;         /* pointers to dithered pixels */
+            word_t       *yptr2;        /* pointers to lumincance band */
+
+            dst   = (unsigned int *) out;
+            dst2  = dst + (image->width >> 2) * 3;
+            yptr2 = yptr + image->width;
+
+            for (y = image->height >> 1; y; y--)
+            {
+               for (x = image->width >> 2; x; x--)
+               {
 #ifdef HAVE_SIGNED_SHIFT
-		  yval1  = (*yptr++ >> 4) + 128;
-		  yval2  = (*yptr++ >> 4) + 128;
-		  crval1 = *crptr++ >> 4;
-		  cbval1 = *cbptr++ >> 4;
+                  yval1  = (*yptr++ >> 4) + 128;
+                  yval2  = (*yptr++ >> 4) + 128;
+                  crval1 = *crptr++ >> 4;
+                  cbval1 = *cbptr++ >> 4;
 #else /* not HAVE_SIGNED_SHIFT */
-		  yval1  = *yptr++  / 16 + 128;
-		  yval2  = *yptr++  / 16 + 128;
-		  crval1 = *crptr++ / 16;
-		  cbval1 = *cbptr++ / 16;
+                  yval1  = *yptr++  / 16 + 128;
+                  yval2  = *yptr++  / 16 + 128;
+                  crval1 = *crptr++ / 16;
+                  cbval1 = *cbptr++ / 16;
 #endif /* not HAVE_SIGNED_SHIFT */
 
-		  R1 = gray_clip [yval1 + Cr_r_tab [crval1]];
-		  G1 = gray_clip [yval1 + Cr_g_tab [crval1]
-				 + Cb_g_tab [cbval1]];
-		  B1 = gray_clip [yval1 + Cb_b_tab [cbval1]];
-		  R2 = gray_clip [yval2 + Cr_r_tab [crval1]];
-		  G2 = gray_clip [yval2 + Cr_g_tab [crval1]
-				 + Cb_g_tab [cbval1]];
-		  B2 = gray_clip [yval2 + Cb_b_tab [cbval1]];
+                  R1 = gray_clip [yval1 + Cr_r_tab [crval1]];
+                  G1 = gray_clip [yval1 + Cr_g_tab [crval1]
+                                 + Cb_g_tab [cbval1]];
+                  B1 = gray_clip [yval1 + Cb_b_tab [cbval1]];
+                  R2 = gray_clip [yval2 + Cr_r_tab [crval1]];
+                  G2 = gray_clip [yval2 + Cr_g_tab [crval1]
+                                 + Cb_g_tab [cbval1]];
+                  B2 = gray_clip [yval2 + Cb_b_tab [cbval1]];
 
-		  *dst++ = B1 | (G1 << 8) | (R1 << 16) | (B2 << 24);
-		  *dst   = G2 | (R2 << 8);
+                  *dst++ = B1 | (G1 << 8) | (R1 << 16) | (B2 << 24);
+                  *dst   = G2 | (R2 << 8);
 
 #ifdef HAVE_SIGNED_SHIFT
-		  yval1  = (*yptr2++ >> 4) + 128;
-		  yval2  = (*yptr2++ >> 4) + 128;
+                  yval1  = (*yptr2++ >> 4) + 128;
+                  yval2  = (*yptr2++ >> 4) + 128;
 #else /* not HAVE_SIGNED_SHIFT */
-		  yval1  = *yptr2++  / 16 + 128;
-		  yval2  = *yptr2++  / 16 + 128;
+                  yval1  = *yptr2++  / 16 + 128;
+                  yval2  = *yptr2++  / 16 + 128;
 #endif /* not HAVE_SIGNED_SHIFT */
 
-		  R1 = gray_clip [yval1 + Cr_r_tab [crval1]];
-		  G1 = gray_clip [yval1 + Cr_g_tab [crval1]
-				 + Cb_g_tab [cbval1]];
-		  B1 = gray_clip [yval1 + Cb_b_tab [cbval1]];
-		  R2 = gray_clip [yval2 + Cr_r_tab [crval1]];
-		  G2 = gray_clip [yval2 + Cr_g_tab [crval1]
-				 + Cb_g_tab [cbval1]];
-		  B2 = gray_clip [yval2 + Cb_b_tab [cbval1]];
-
-		  *dst2++ = B1 | (G1 << 8) | (R1 << 16) | (B2 << 24);
-		  *dst2   = G2 | (R2 << 8);
-	       
+                  R1 = gray_clip [yval1 + Cr_r_tab [crval1]];
+                  G1 = gray_clip [yval1 + Cr_g_tab [crval1]
+                                 + Cb_g_tab [cbval1]];
+                  B1 = gray_clip [yval1 + Cb_b_tab [cbval1]];
+                  R2 = gray_clip [yval2 + Cr_r_tab [crval1]];
+                  G2 = gray_clip [yval2 + Cr_g_tab [crval1]
+                                 + Cb_g_tab [cbval1]];
+                  B2 = gray_clip [yval2 + Cb_b_tab [cbval1]];
+
+                  *dst2++ = B1 | (G1 << 8) | (R1 << 16) | (B2 << 24);
+                  *dst2   = G2 | (R2 << 8);
+
 #ifdef HAVE_SIGNED_SHIFT
-		  yval1  = (*yptr++ >> 4) + 128;
-		  yval2  = (*yptr++ >> 4) + 128;
-		  crval1 = *crptr++ >> 4;
-		  cbval1 = *cbptr++ >> 4;
+                  yval1  = (*yptr++ >> 4) + 128;
+                  yval2  = (*yptr++ >> 4) + 128;
+                  crval1 = *crptr++ >> 4;
+                  cbval1 = *cbptr++ >> 4;
 #else /* not HAVE_SIGNED_SHIFT */
-		  yval1  = *yptr++  / 16 + 128;
-		  yval2  = *yptr++  / 16 + 128;
-		  crval1 = *crptr++ / 16;
-		  crval2 = *crptr++ / 16;
-		  cbval1 = *cbptr++ / 16;
-		  cbval2 = *cbptr++ / 16;
+                  yval1  = *yptr++  / 16 + 128;
+                  yval2  = *yptr++  / 16 + 128;
+                  crval1 = *crptr++ / 16;
+                  crval2 = *crptr++ / 16;
+                  cbval1 = *cbptr++ / 16;
+                  cbval2 = *cbptr++ / 16;
 #endif /* not HAVE_SIGNED_SHIFT */
 
-		  R1 = gray_clip [yval1 + Cr_r_tab [crval1]];
-		  G1 = gray_clip [yval1 + Cr_g_tab [crval1]
-				 + Cb_g_tab [cbval1]];
-		  B1 = gray_clip [yval1 + Cb_b_tab [cbval1]];
-		  R2 = gray_clip [yval2 + Cr_r_tab [crval1]];
-		  G2 = gray_clip [yval2 + Cr_g_tab [crval1]
-				 + Cb_g_tab [cbval1]];
-		  B2 = gray_clip [yval2 + Cb_b_tab [cbval1]];
+                  R1 = gray_clip [yval1 + Cr_r_tab [crval1]];
+                  G1 = gray_clip [yval1 + Cr_g_tab [crval1]
+                                 + Cb_g_tab [cbval1]];
+                  B1 = gray_clip [yval1 + Cb_b_tab [cbval1]];
+                  R2 = gray_clip [yval2 + Cr_r_tab [crval1]];
+                  G2 = gray_clip [yval2 + Cr_g_tab [crval1]
+                                 + Cb_g_tab [cbval1]];
+                  B2 = gray_clip [yval2 + Cb_b_tab [cbval1]];
 
-		  *dst++ |= (B1 << 16) | (G1 << 24);
-		  *dst++ = R1 | (B2 << 8) | (G2 << 16) | (R2 << 24);
+                  *dst++ |= (B1 << 16) | (G1 << 24);
+                  *dst++ = R1 | (B2 << 8) | (G2 << 16) | (R2 << 24);
 
 #ifdef HAVE_SIGNED_SHIFT
-		  yval1  = (*yptr2++ >> 4) + 128;
-		  yval2  = (*yptr2++ >> 4) + 128;
+                  yval1  = (*yptr2++ >> 4) + 128;
+                  yval2  = (*yptr2++ >> 4) + 128;
 #else /* not HAVE_SIGNED_SHIFT */
-		  yval1  = *yptr2++  / 16 + 128;
-		  yval2  = *yptr2++  / 16 + 128;
+                  yval1  = *yptr2++  / 16 + 128;
+                  yval2  = *yptr2++  / 16 + 128;
 #endif /* not HAVE_SIGNED_SHIFT */
 
-		  R1 = gray_clip [yval1 + Cr_r_tab [crval1]];
-		  G1 = gray_clip [yval1 + Cr_g_tab [crval1]
-				 + Cb_g_tab [cbval1]];
-		  B1 = gray_clip [yval1 + Cb_b_tab [cbval1]];
-		  R2 = gray_clip [yval2 + Cr_r_tab [crval1]];
-		  G2 = gray_clip [yval2 + Cr_g_tab [crval1]
-				 + Cb_g_tab [cbval1]];
-		  B2 = gray_clip [yval2 + Cb_b_tab [cbval1]];
-
-		  *dst2++ |= (B1 << 16) | (G1 << 24);
-		  *dst2++ = R1 | (B2 << 8) | (G2 << 16) | (R2 << 24);
-	       }
-	       dst   += (image->width >> 2) * 3;
-	       dst2  += (image->width >> 2) * 3;
-	       yptr  += image->width;
-	       yptr2 += image->width;
-	    }
-	 }
+                  R1 = gray_clip [yval1 + Cr_r_tab [crval1]];
+                  G1 = gray_clip [yval1 + Cr_g_tab [crval1]
+                                 + Cb_g_tab [cbval1]];
+                  B1 = gray_clip [yval1 + Cb_b_tab [cbval1]];
+                  R2 = gray_clip [yval2 + Cr_r_tab [crval1]];
+                  G2 = gray_clip [yval2 + Cr_g_tab [crval1]
+                                 + Cb_g_tab [cbval1]];
+                  B2 = gray_clip [yval2 + Cb_b_tab [cbval1]];
+
+                  *dst2++ |= (B1 << 16) | (G1 << 24);
+                  *dst2++ = R1 | (B2 << 8) | (G2 << 16) | (R2 << 24);
+               }
+               dst   += (image->width >> 2) * 3;
+               dst2  += (image->width >> 2) * 3;
+               yptr  += image->width;
+               yptr2 += image->width;
+            }
+         }
       }
-      else				/* 4:4:4 format */
+      else                              /* 4:4:4 format */
       {
-	 if (private->double_resolution)
-	 {
-	    unsigned int R1, G1, B1;		/* pixel1 in RGB color space */
-	    unsigned int R2, G2, B2;		/* pixel2 in RGB color space */
-	    int		 yval1, crval1, cbval1;	/* pixel1 in YCbCr space */
-	    int		 yval2, crval2, cbval2;	/* pixel2 in YCbCr space */
-	    int		 x, y;			/* pixel counter */
-	    unsigned int *dst;		        /* dithered pixel pointer */
-	    
-	    dst = (unsigned int *) out;
-	    
-	    for (y = image->height; y; y--)
-	    {
-	       for (x = image->width >> 1; x; x--)
-	       {
+         if (private->double_resolution)
+         {
+            unsigned int R1, G1, B1;            /* pixel1 in RGB color space */
+            unsigned int R2, G2, B2;            /* pixel2 in RGB color space */
+            int          yval1, crval1, cbval1; /* pixel1 in YCbCr space */
+            int          yval2, crval2, cbval2; /* pixel2 in YCbCr space */
+            int          x, y;                  /* pixel counter */
+            unsigned int *dst;                  /* dithered pixel pointer */
+
+            dst = (unsigned int *) out;
+
+            for (y = image->height; y; y--)
+            {
+               for (x = image->width >> 1; x; x--)
+               {
 #ifdef HAVE_SIGNED_SHIFT
-		  yval1  = (*yptr++ >> 4) + 128;
-		  yval2  = (*yptr++ >> 4) + 128;
-		  crval1 = *crptr++ >> 4;
-		  crval2 = *crptr++ >> 4;
-		  cbval1 = *cbptr++ >> 4;
-		  cbval2 = *cbptr++ >> 4;
+                  yval1  = (*yptr++ >> 4) + 128;
+                  yval2  = (*yptr++ >> 4) + 128;
+                  crval1 = *crptr++ >> 4;
+                  crval2 = *crptr++ >> 4;
+                  cbval1 = *cbptr++ >> 4;
+                  cbval2 = *cbptr++ >> 4;
 #else /* not HAVE_SIGNED_SHIFT */
-		  yval1  = *yptr++  / 16 + 128;
-		  yval2  = *yptr++  / 16 + 128;
-		  crval1 = *crptr++ / 16;
-		  crval2 = *crptr++ / 16;
-		  cbval1 = *cbptr++ / 16;
-		  cbval2 = *cbptr++ / 16;
+                  yval1  = *yptr++  / 16 + 128;
+                  yval2  = *yptr++  / 16 + 128;
+                  crval1 = *crptr++ / 16;
+                  crval2 = *crptr++ / 16;
+                  cbval1 = *cbptr++ / 16;
+                  cbval2 = *cbptr++ / 16;
 #endif /* not HAVE_SIGNED_SHIFT */
-		  
-		  R1 = gray_clip [yval1 + Cr_r_tab [crval1]];
-		  G1 = gray_clip [yval1 + Cr_g_tab [crval1]
-				 + Cb_g_tab [cbval1]];
-		  B1 = gray_clip [yval1 + Cb_b_tab [cbval1]];
-		  R2 = gray_clip [yval2 + Cr_r_tab [crval2]];
-		  G2 = gray_clip [yval2 + Cr_g_tab [crval2]
-				 + Cb_g_tab [cbval2]];
-		  B2 = gray_clip [yval2 + Cb_b_tab [cbval2]];
-
-		  *dst++ = B1 | (G1 << 8) | (R1 << 16) | (B1 << 24);
-		  *dst++ = G1 | (R1 << 8) | (B2 << 16) | (G2 << 24);
-		  *dst++ = R2 | (B2 << 8) | (G2 << 16) | (R2 << 24);
-	       }
-	       memcpy (dst, dst - 3 * (image->width >> 1),
-		       3 * (image->width >> 1) * sizeof (unsigned int));
-	       dst += 3 * (image->width >> 1);
-	    }
-	 }
-	 else
-	 {
-	    unsigned int R1, G1, B1;		/* pixel in RGB color space */
-	    unsigned int R2, G2, B2;		/* pixel in RGB color space */
-	    int		 yval1, crval1, cbval1;	/* pixel1 in YCbCr space */
-	    int		 yval2, crval2, cbval2;	/* pixel2 in YCbCr space */
-	    int		 n;			/* pixel counter */
-	    unsigned int *dst;		        /* dithered pixel pointer */
-	    
-	    dst = (unsigned int *) out;
-	    
-	    for (n = (image->width * image->height) >> 2; n; n--)
-	    {
+
+                  R1 = gray_clip [yval1 + Cr_r_tab [crval1]];
+                  G1 = gray_clip [yval1 + Cr_g_tab [crval1]
+                                 + Cb_g_tab [cbval1]];
+                  B1 = gray_clip [yval1 + Cb_b_tab [cbval1]];
+                  R2 = gray_clip [yval2 + Cr_r_tab [crval2]];
+                  G2 = gray_clip [yval2 + Cr_g_tab [crval2]
+                                 + Cb_g_tab [cbval2]];
+                  B2 = gray_clip [yval2 + Cb_b_tab [cbval2]];
+
+                  *dst++ = B1 | (G1 << 8) | (R1 << 16) | (B1 << 24);
+                  *dst++ = G1 | (R1 << 8) | (B2 << 16) | (G2 << 24);
+                  *dst++ = R2 | (B2 << 8) | (G2 << 16) | (R2 << 24);
+               }
+               memcpy (dst, dst - 3 * (image->width >> 1),
+                       3 * (image->width >> 1) * sizeof (unsigned int));
+               dst += 3 * (image->width >> 1);
+            }
+         }
+         else
+         {
+            unsigned int R1, G1, B1;            /* pixel in RGB color space */
+            unsigned int R2, G2, B2;            /* pixel in RGB color space */
+            int          yval1, crval1, cbval1; /* pixel1 in YCbCr space */
+            int          yval2, crval2, cbval2; /* pixel2 in YCbCr space */
+            int          n;                     /* pixel counter */
+            unsigned int *dst;                  /* dithered pixel pointer */
+
+            dst = (unsigned int *) out;
+
+            for (n = (image->width * image->height) >> 2; n; n--)
+            {
 #ifdef HAVE_SIGNED_SHIFT
-	       yval1  = (*yptr++ >> 4) + 128;
-	       yval2  = (*yptr++ >> 4) + 128;
-	       crval1 = *crptr++ >> 4;
-	       crval2 = *crptr++ >> 4;
-	       cbval1 = *cbptr++ >> 4;
-	       cbval2 = *cbptr++ >> 4;
+               yval1  = (*yptr++ >> 4) + 128;
+               yval2  = (*yptr++ >> 4) + 128;
+               crval1 = *crptr++ >> 4;
+               crval2 = *crptr++ >> 4;
+               cbval1 = *cbptr++ >> 4;
+               cbval2 = *cbptr++ >> 4;
 #else /* not HAVE_SIGNED_SHIFT */
-	       yval1  = *yptr++  / 16 + 128;
-	       yval2  = *yptr++  / 16 + 128;
-	       crval1 = *crptr++ / 16;
-	       crval2 = *crptr++ / 16;
-	       cbval1 = *cbptr++ / 16;
-	       cbval2 = *cbptr++ / 16;
+               yval1  = *yptr++  / 16 + 128;
+               yval2  = *yptr++  / 16 + 128;
+               crval1 = *crptr++ / 16;
+               crval2 = *crptr++ / 16;
+               cbval1 = *cbptr++ / 16;
+               cbval2 = *cbptr++ / 16;
 #endif /* not HAVE_SIGNED_SHIFT */
 
-	       R1 = gray_clip [yval1 + Cr_r_tab [crval1]];
-	       G1 = gray_clip [yval1 + Cr_g_tab [crval1] + Cb_g_tab [cbval1]];
-	       B1 = gray_clip [yval1 + Cb_b_tab [cbval1]];
-	       R2 = gray_clip [yval2 + Cr_r_tab [crval2]];
-	       G2 = gray_clip [yval2 + Cr_g_tab [crval2] + Cb_g_tab [cbval2]];
-	       B2 = gray_clip [yval2 + Cb_b_tab [cbval2]];
+               R1 = gray_clip [yval1 + Cr_r_tab [crval1]];
+               G1 = gray_clip [yval1 + Cr_g_tab [crval1] + Cb_g_tab [cbval1]];
+               B1 = gray_clip [yval1 + Cb_b_tab [cbval1]];
+               R2 = gray_clip [yval2 + Cr_r_tab [crval2]];
+               G2 = gray_clip [yval2 + Cr_g_tab [crval2] + Cb_g_tab [cbval2]];
+               B2 = gray_clip [yval2 + Cb_b_tab [cbval2]];
 
-	       *dst++ = B1 | (G1 << 8) | (R1 << 16) | (B2 << 24);
-	       *dst   = G2 | (R2 << 8);
+               *dst++ = B1 | (G1 << 8) | (R1 << 16) | (B2 << 24);
+               *dst   = G2 | (R2 << 8);
 
 #ifdef HAVE_SIGNED_SHIFT
-	       yval1  = (*yptr++ >> 4) + 128;
-	       yval2  = (*yptr++ >> 4) + 128;
-	       crval1 = *crptr++ >> 4;
-	       crval2 = *crptr++ >> 4;
-	       cbval1 = *cbptr++ >> 4;
-	       cbval2 = *cbptr++ >> 4;
+               yval1  = (*yptr++ >> 4) + 128;
+               yval2  = (*yptr++ >> 4) + 128;
+               crval1 = *crptr++ >> 4;
+               crval2 = *crptr++ >> 4;
+               cbval1 = *cbptr++ >> 4;
+               cbval2 = *cbptr++ >> 4;
 #else /* not HAVE_SIGNED_SHIFT */
-	       yval1  = *yptr++  / 16 + 128;
-	       yval2  = *yptr++  / 16 + 128;
-	       crval1 = *crptr++ / 16;
-	       crval2 = *crptr++ / 16;
-	       cbval1 = *cbptr++ / 16;
-	       cbval2 = *cbptr++ / 16;
+               yval1  = *yptr++  / 16 + 128;
+               yval2  = *yptr++  / 16 + 128;
+               crval1 = *crptr++ / 16;
+               crval2 = *crptr++ / 16;
+               cbval1 = *cbptr++ / 16;
+               cbval2 = *cbptr++ / 16;
 #endif /* not HAVE_SIGNED_SHIFT */
 
-	       R1 = gray_clip [yval1 + Cr_r_tab [crval1]];
-	       G1 = gray_clip [yval1 + Cr_g_tab [crval1] + Cb_g_tab [cbval1]];
-	       B1 = gray_clip [yval1 + Cb_b_tab [cbval1]];
-	       R2 = gray_clip [yval2 + Cr_r_tab [crval2]];
-	       G2 = gray_clip [yval2 + Cr_g_tab [crval2] + Cb_g_tab [cbval2]];
-	       B2 = gray_clip [yval2 + Cb_b_tab [cbval2]];
-
-	       *dst++ |= (B1 << 16) | (G1 << 24);
-	       *dst++ = R1 | (B2 << 8) | (G2 << 16) | (R2 << 24);
-	    }
-	 }
+               R1 = gray_clip [yval1 + Cr_r_tab [crval1]];
+               G1 = gray_clip [yval1 + Cr_g_tab [crval1] + Cb_g_tab [cbval1]];
+               B1 = gray_clip [yval1 + Cb_b_tab [cbval1]];
+               R2 = gray_clip [yval2 + Cr_r_tab [crval2]];
+               G2 = gray_clip [yval2 + Cr_g_tab [crval2] + Cb_g_tab [cbval2]];
+               B2 = gray_clip [yval2 + Cb_b_tab [cbval2]];
+
+               *dst++ |= (B1 << 16) | (G1 << 24);
+               *dst++ = R1 | (B2 << 8) | (G2 << 16) | (R2 << 24);
+            }
+         }
       }
    }
    else
    {
-      unsigned int *dst;		/* pointer to dithered pixels */
-      word_t	   *src;		/* current pixel of frame */
+      unsigned int *dst;                /* pointer to dithered pixels */
+      word_t       *src;                /* current pixel of frame */
 
       dst     = (unsigned int *) out;
       src     = image->pixels [GRAY];
 
       if (private->double_resolution)
       {
-	 int	   x, y;		/* pixel counter */
-	 unsigned *shift_clipping = gray_clip + 128;
-
-	 for (y = image->height; y; y--)
-	 {
-	    for (x = image->width >> 1; x; x--)
-	    {
-	       unsigned int val1, val2;
+         int       x, y;                /* pixel counter */
+         unsigned *shift_clipping = gray_clip + 128;
+
+         for (y = image->height; y; y--)
+         {
+            for (x = image->width >> 1; x; x--)
+            {
+               unsigned int val1, val2;
 #ifdef HAVE_SIGNED_SHIFT
-	       val1 = shift_clipping [*src++ >> 4];
-	       val2 = shift_clipping [*src++ >> 4];
+               val1 = shift_clipping [*src++ >> 4];
+               val2 = shift_clipping [*src++ >> 4];
 #else /* not HAVE_SIGNED_SHIFT */
-	       val1 = shift_clipping [*src++ / 16];
-	       val2 = shift_clipping [*src++ / 16];
+               val1 = shift_clipping [*src++ / 16];
+               val2 = shift_clipping [*src++ / 16];
 #endif /* not HAVE_SIGNED_SHIFT */
 
-	       *dst++ = val1 | (val1 << 8) | (val1 << 16) | (val1 << 24);
-	       *dst++ = val1 | (val1 << 8) | (val2 << 16) | (val2 << 24); 
-	       *dst++ = val2 | (val2 << 8) | (val2 << 16) | (val2 << 24);
-	    }
+               *dst++ = val1 | (val1 << 8) | (val1 << 16) | (val1 << 24);
+               *dst++ = val1 | (val1 << 8) | (val2 << 16) | (val2 << 24);
+               *dst++ = val2 | (val2 << 8) | (val2 << 16) | (val2 << 24);
+            }
 
-	    memcpy (dst, dst - 3 * (image->width >> 1),
-		    3 * (image->width >> 1) * sizeof (unsigned int));
-	    dst += 3 * (image->width >> 1);
-	 }
+            memcpy (dst, dst - 3 * (image->width >> 1),
+                    3 * (image->width >> 1) * sizeof (unsigned int));
+            dst += 3 * (image->width >> 1);
+         }
       }
       else
       {
-	 int	   n;			/* pixel counter */
-	 unsigned *shift_clipping = gray_clip + 128;
+         int       n;                   /* pixel counter */
+         unsigned *shift_clipping = gray_clip + 128;
 
-	 for (n = (image->width * image->height) >> 2; n; n--)
-	 {
-	    unsigned int val1, val2;
+         for (n = (image->width * image->height) >> 2; n; n--)
+         {
+            unsigned int val1, val2;
 
 #ifdef HAVE_SIGNED_SHIFT
-	    val1 = shift_clipping [*src++ >> 4];
-	    val2 = shift_clipping [*src++ >> 4];
+            val1 = shift_clipping [*src++ >> 4];
+            val2 = shift_clipping [*src++ >> 4];
 #else /* not HAVE_SIGNED_SHIFT */
-	    val1 = shift_clipping [*src++ / 16];
-	    val2 = shift_clipping [*src++ / 16];
+            val1 = shift_clipping [*src++ / 16];
+            val2 = shift_clipping [*src++ / 16];
 #endif /* not HAVE_SIGNED_SHIFT */
 
-	    *dst++ = val1 | (val1 << 8)
-		     | (val1 << 16) | (val2 << 24);  /* RGBR */
-	    *dst   = val2 | (val2 << 8);             /* GB-- */
+            *dst++ = val1 | (val1 << 8)
+                     | (val1 << 16) | (val2 << 24);  /* RGBR */
+            *dst   = val2 | (val2 << 8);             /* GB-- */
 
 #ifdef HAVE_SIGNED_SHIFT
-	    val1 = shift_clipping [*src++ >> 4];
-	    val2 = shift_clipping [*src++ >> 4];
+            val1 = shift_clipping [*src++ >> 4];
+            val2 = shift_clipping [*src++ >> 4];
 #else /* not HAVE_SIGNED_SHIFT */
-	    val1 = shift_clipping [*src++ / 16];
-	    val2 = shift_clipping [*src++ / 16];
+            val1 = shift_clipping [*src++ / 16];
+            val2 = shift_clipping [*src++ / 16];
 #endif /* not HAVE_SIGNED_SHIFT */
-	    
-	    *dst++ |= (val1 << 16) | (val1 << 24);   /* --RG */
-	    *dst++  = val1 | (val2 << 8)
-		      | (val2 << 16) | (val2 << 24); /* BRGB */
-	 }
+
+            *dst++ |= (val1 << 16) | (val1 << 24);   /* --RG */
+            *dst++  = val1 | (val2 << 8)
+                      | (val2 << 16) | (val2 << 24); /* BRGB */
+         }
       }
    }
-   
+
    return 1;
 }
 
-static int 
+static int
 display_24_bit_rgb (const struct fiasco_renderer *this, unsigned char *ximage,
-		    const fiasco_image_t *fiasco_image)
+                    const fiasco_image_t *fiasco_image)
 /*
  *  Convert 'image' to 16 bit color bitmap.
  *  If 'double_resolution' is true then double image size in both directions.
@@ -1121,13 +1121,13 @@ display_24_bit_rgb (const struct fiasco_renderer *this, unsigned char *ximage,
  *  No return value.
  *
  *  Side effects:
- *	'out[]'	is filled with dithered image
+ *      'out[]' is filled with dithered image
  */
 {
-   unsigned 	      *gray_clip = init_clipping ();
+   unsigned           *gray_clip = init_clipping ();
    const image_t      *image;
    renderer_private_t *private;
-   byte_t	      *out;
+   byte_t             *out;
 
    if (!gray_clip)
       return 0;
@@ -1147,17 +1147,17 @@ display_24_bit_rgb (const struct fiasco_renderer *this, unsigned char *ximage,
       return 0;
    }
 
-   out 	   = (byte_t *) ximage;
+   out     = (byte_t *) ximage;
    image   = cast_image ((fiasco_image_t *) fiasco_image);
    if (!image)
       return 0;
    private = (renderer_private_t *) this->private;
-   
+
    if (image->color)
    {
-      word_t 	   *cbptr, *crptr;	/* pointer to chroma bands */
-      word_t 	   *yptr;		/* pointers to lumincance band */
-      int 	   *Cr_r_tab, *Cr_g_tab, *Cb_g_tab, *Cb_b_tab;
+      word_t       *cbptr, *crptr;      /* pointer to chroma bands */
+      word_t       *yptr;               /* pointers to lumincance band */
+      int          *Cr_r_tab, *Cr_g_tab, *Cb_g_tab, *Cb_b_tab;
 
       Cr_g_tab = private->Cr_g_tab;
       Cr_r_tab = private->Cr_r_tab;
@@ -1169,396 +1169,396 @@ display_24_bit_rgb (const struct fiasco_renderer *this, unsigned char *ximage,
 
       if (image->format == FORMAT_4_2_0)
       {
-	 if (private->double_resolution)
-	 {
-	    int		  yval1;	/* lumincance pixel */
-	    int 	  crval1, cbval1; /* chroma pixels */
-	    int		  yval2;	/* pixel in YCbCr color space */
-	    unsigned int  R1, G1, B1;	/* pixel in RGB color space */
-	    unsigned int  R2, G2, B2;	/* pixel in RGB color space */
-	    int		  x, y;		/* pixel counter */
-	    unsigned int *dst;		/* pointer to dithered pixels */
-	    unsigned int *dst2;		/* pointers to dithered pixels */
-	    word_t	 *yptr2;	/* pointers to lumincance band */
-	    
-	    dst   = (unsigned int *) out;
-	    dst2  = dst + (image->width >> 1) * 3 * 2;
-	    yptr2 = yptr + image->width;
-	    
-	    for (y = image->height >> 1; y; y--)
-	    {
-	       for (x = image->width >> 1; x; x--)
-	       {
+         if (private->double_resolution)
+         {
+            int           yval1;        /* lumincance pixel */
+            int           crval1, cbval1; /* chroma pixels */
+            int           yval2;        /* pixel in YCbCr color space */
+            unsigned int  R1, G1, B1;   /* pixel in RGB color space */
+            unsigned int  R2, G2, B2;   /* pixel in RGB color space */
+            int           x, y;         /* pixel counter */
+            unsigned int *dst;          /* pointer to dithered pixels */
+            unsigned int *dst2;         /* pointers to dithered pixels */
+            word_t       *yptr2;        /* pointers to lumincance band */
+
+            dst   = (unsigned int *) out;
+            dst2  = dst + (image->width >> 1) * 3 * 2;
+            yptr2 = yptr + image->width;
+
+            for (y = image->height >> 1; y; y--)
+            {
+               for (x = image->width >> 1; x; x--)
+               {
 #ifdef HAVE_SIGNED_SHIFT
-		  yval1  = (*yptr++ >> 4) + 128;
-		  yval2  = (*yptr++ >> 4) + 128;
-		  crval1 = *crptr++ >> 4;
-		  cbval1 = *cbptr++ >> 4;
+                  yval1  = (*yptr++ >> 4) + 128;
+                  yval2  = (*yptr++ >> 4) + 128;
+                  crval1 = *crptr++ >> 4;
+                  cbval1 = *cbptr++ >> 4;
 #else /* not HAVE_SIGNED_SHIFT */
-		  yval1  = *yptr++  / 16 + 128;
-		  yval2  = *yptr++  / 16 + 128;
-		  crval1 = *crptr++ / 16;
-		  cbval1 = *cbptr++ / 16;
+                  yval1  = *yptr++  / 16 + 128;
+                  yval2  = *yptr++  / 16 + 128;
+                  crval1 = *crptr++ / 16;
+                  cbval1 = *cbptr++ / 16;
 #endif /* not HAVE_SIGNED_SHIFT */
 
-		  R1 = gray_clip [yval1 + Cr_r_tab [crval1]];
-		  G1 = gray_clip [yval1 + Cr_g_tab [crval1]
-				  + Cb_g_tab [cbval1]];
-		  B1 = gray_clip [yval1 + Cb_b_tab [cbval1]];
-		  R2 = gray_clip [yval2 + Cr_r_tab [crval1]];
-		  G2 = gray_clip [yval2 + Cr_g_tab [crval1]
-				  + Cb_g_tab [cbval1]];
-		  B2 = gray_clip [yval2 + Cb_b_tab [cbval1]];
+                  R1 = gray_clip [yval1 + Cr_r_tab [crval1]];
+                  G1 = gray_clip [yval1 + Cr_g_tab [crval1]
+                                  + Cb_g_tab [cbval1]];
+                  B1 = gray_clip [yval1 + Cb_b_tab [cbval1]];
+                  R2 = gray_clip [yval2 + Cr_r_tab [crval1]];
+                  G2 = gray_clip [yval2 + Cr_g_tab [crval1]
+                                  + Cb_g_tab [cbval1]];
+                  B2 = gray_clip [yval2 + Cb_b_tab [cbval1]];
 
-		  *dst++ = R1 | (G1 << 8) | (B1 << 16) | (R1 << 24);
-		  *dst++ = G1 | (B1 << 8) | (R2 << 16) | (G2 << 24);
-		  *dst++ = B2 | (R2 << 8) | (G2 << 16) | (B2 << 24);
+                  *dst++ = R1 | (G1 << 8) | (B1 << 16) | (R1 << 24);
+                  *dst++ = G1 | (B1 << 8) | (R2 << 16) | (G2 << 24);
+                  *dst++ = B2 | (R2 << 8) | (G2 << 16) | (B2 << 24);
 
 #ifdef HAVE_SIGNED_SHIFT
-		  yval1  = (*yptr2++ >> 4) + 128;
-		  yval2  = (*yptr2++ >> 4) + 128;
+                  yval1  = (*yptr2++ >> 4) + 128;
+                  yval2  = (*yptr2++ >> 4) + 128;
 #else /* not HAVE_SIGNED_SHIFT */
-		  yval1  = *yptr2++  / 16 + 128;
-		  yval2  = *yptr2++  / 16 + 128;
+                  yval1  = *yptr2++  / 16 + 128;
+                  yval2  = *yptr2++  / 16 + 128;
 #endif /* not HAVE_SIGNED_SHIFT */
 
-		  R1 = gray_clip [yval1 + Cr_r_tab [crval1]];
-		  G1 = gray_clip [yval1 + Cr_g_tab [crval1]
-				  + Cb_g_tab [cbval1]];
-		  B1 = gray_clip [yval1 + Cb_b_tab [cbval1]];
-		  R2 = gray_clip [yval2 + Cr_r_tab [crval1]];
-		  G2 = gray_clip [yval2 + Cr_g_tab [crval1]
-				  + Cb_g_tab [cbval1]];
-		  B2 = gray_clip [yval2 + Cb_b_tab [cbval1]];
-
-		  *dst2++ = R1 | (G1 << 8) | (B1 << 16) | (R1 << 24);
-		  *dst2++ = G1 | (B1 << 8) | (R2 << 16) | (G2 << 24);
-		  *dst2++ = B2 | (R2 << 8) | (G2 << 16) | (B2 << 24);
-	       }
-	       memcpy (dst, dst - (image->width >> 1) * 3,
-		       (image->width >> 1) * 3 * sizeof (unsigned int));
-	       memcpy (dst2, dst2 - (image->width >> 1) * 3, 
-		       (image->width >> 1) * 3 * sizeof (unsigned int));
-	       dst   += (image->width >> 1) * 3 * 3;
-	       dst2  += (image->width >> 1) * 3 * 3;
-	       yptr  += image->width;
-	       yptr2 += image->width;
-	    }
-	 }
-	 else
-	 {
-	    int		  yval1;	/* lumincance pixel */
-	    int 	  crval1, cbval1; /* chroma pixels */
-	    int		  yval2;	/* pixel in YCbCr color space */
-	    unsigned int  R1, G1, B1;	/* pixel in RGB color space */
-	    unsigned int  R2, G2, B2;	/* pixel in RGB color space */
-	    int		  x, y;		/* pixel counter */
-	    unsigned int *dst;		/* pointer to dithered pixels */
-	    unsigned int *dst2;		/* pointers to dithered pixels */
-	    word_t	 *yptr2;	/* pointers to lumincance band */
-	    
-	    dst   = (unsigned int *) out;
-	    dst2  = dst + (image->width >> 2) * 3;
-	    yptr2 = yptr + image->width;
-	    
-	    for (y = image->height >> 1; y; y--)
-	    {
-	       for (x = image->width >> 2; x; x--)
-	       {
+                  R1 = gray_clip [yval1 + Cr_r_tab [crval1]];
+                  G1 = gray_clip [yval1 + Cr_g_tab [crval1]
+                                  + Cb_g_tab [cbval1]];
+                  B1 = gray_clip [yval1 + Cb_b_tab [cbval1]];
+                  R2 = gray_clip [yval2 + Cr_r_tab [crval1]];
+                  G2 = gray_clip [yval2 + Cr_g_tab [crval1]
+                                  + Cb_g_tab [cbval1]];
+                  B2 = gray_clip [yval2 + Cb_b_tab [cbval1]];
+
+                  *dst2++ = R1 | (G1 << 8) | (B1 << 16) | (R1 << 24);
+                  *dst2++ = G1 | (B1 << 8) | (R2 << 16) | (G2 << 24);
+                  *dst2++ = B2 | (R2 << 8) | (G2 << 16) | (B2 << 24);
+               }
+               memcpy (dst, dst - (image->width >> 1) * 3,
+                       (image->width >> 1) * 3 * sizeof (unsigned int));
+               memcpy (dst2, dst2 - (image->width >> 1) * 3,
+                       (image->width >> 1) * 3 * sizeof (unsigned int));
+               dst   += (image->width >> 1) * 3 * 3;
+               dst2  += (image->width >> 1) * 3 * 3;
+               yptr  += image->width;
+               yptr2 += image->width;
+            }
+         }
+         else
+         {
+            int           yval1;        /* lumincance pixel */
+            int           crval1, cbval1; /* chroma pixels */
+            int           yval2;        /* pixel in YCbCr color space */
+            unsigned int  R1, G1, B1;   /* pixel in RGB color space */
+            unsigned int  R2, G2, B2;   /* pixel in RGB color space */
+            int           x, y;         /* pixel counter */
+            unsigned int *dst;          /* pointer to dithered pixels */
+            unsigned int *dst2;         /* pointers to dithered pixels */
+            word_t       *yptr2;        /* pointers to lumincance band */
+
+            dst   = (unsigned int *) out;
+            dst2  = dst + (image->width >> 2) * 3;
+            yptr2 = yptr + image->width;
+
+            for (y = image->height >> 1; y; y--)
+            {
+               for (x = image->width >> 2; x; x--)
+               {
 #ifdef HAVE_SIGNED_SHIFT
-		  yval1  = (*yptr++ >> 4) + 128;
-		  yval2  = (*yptr++ >> 4) + 128;
-		  crval1 = *crptr++ >> 4;
-		  cbval1 = *cbptr++ >> 4;
+                  yval1  = (*yptr++ >> 4) + 128;
+                  yval2  = (*yptr++ >> 4) + 128;
+                  crval1 = *crptr++ >> 4;
+                  cbval1 = *cbptr++ >> 4;
 #else /* not HAVE_SIGNED_SHIFT */
-		  yval1  = *yptr++  / 16 + 128;
-		  yval2  = *yptr++  / 16 + 128;
-		  crval1 = *crptr++ / 16;
-		  cbval1 = *cbptr++ / 16;
+                  yval1  = *yptr++  / 16 + 128;
+                  yval2  = *yptr++  / 16 + 128;
+                  crval1 = *crptr++ / 16;
+                  cbval1 = *cbptr++ / 16;
 #endif /* not HAVE_SIGNED_SHIFT */
 
-		  R1 = gray_clip [yval1 + Cr_r_tab [crval1]];
-		  G1 = gray_clip [yval1 + Cr_g_tab [crval1]
-				  + Cb_g_tab [cbval1]];
-		  B1 = gray_clip [yval1 + Cb_b_tab [cbval1]];
-		  R2 = gray_clip [yval2 + Cr_r_tab [crval1]];
-		  G2 = gray_clip [yval2 + Cr_g_tab [crval1]
-				  + Cb_g_tab [cbval1]];
-		  B2 = gray_clip [yval2 + Cb_b_tab [cbval1]];
+                  R1 = gray_clip [yval1 + Cr_r_tab [crval1]];
+                  G1 = gray_clip [yval1 + Cr_g_tab [crval1]
+                                  + Cb_g_tab [cbval1]];
+                  B1 = gray_clip [yval1 + Cb_b_tab [cbval1]];
+                  R2 = gray_clip [yval2 + Cr_r_tab [crval1]];
+                  G2 = gray_clip [yval2 + Cr_g_tab [crval1]
+                                  + Cb_g_tab [cbval1]];
+                  B2 = gray_clip [yval2 + Cb_b_tab [cbval1]];
 
-		  *dst++ = R1 | (G1 << 8) | (B1 << 16) | (R2 << 24);
-		  *dst   = G2 | (B2 << 8);
+                  *dst++ = R1 | (G1 << 8) | (B1 << 16) | (R2 << 24);
+                  *dst   = G2 | (B2 << 8);
 
 #ifdef HAVE_SIGNED_SHIFT
-		  yval1  = (*yptr2++ >> 4) + 128;
-		  yval2  = (*yptr2++ >> 4) + 128;
+                  yval1  = (*yptr2++ >> 4) + 128;
+                  yval2  = (*yptr2++ >> 4) + 128;
 #else /* not HAVE_SIGNED_SHIFT */
-		  yval1  = *yptr2++  / 16 + 128;
-		  yval2  = *yptr2++  / 16 + 128;
+                  yval1  = *yptr2++  / 16 + 128;
+                  yval2  = *yptr2++  / 16 + 128;
 #endif /* not HAVE_SIGNED_SHIFT */
 
-		  R1 = gray_clip [yval1 + Cr_r_tab [crval1]];
-		  G1 = gray_clip [yval1 + Cr_g_tab [crval1]
-				  + Cb_g_tab [cbval1]];
-		  B1 = gray_clip [yval1 + Cb_b_tab [cbval1]];
-		  R2 = gray_clip [yval2 + Cr_r_tab [crval1]];
-		  G2 = gray_clip [yval2 + Cr_g_tab [crval1]
-				  + Cb_g_tab [cbval1]];
-		  B2 = gray_clip [yval2 + Cb_b_tab [cbval1]];
-
-		  *dst2++ = R1 | (G1 << 8) | (B1 << 16) | (R2 << 24);
-		  *dst2   = G2 | (B2 << 8);
-	       
+                  R1 = gray_clip [yval1 + Cr_r_tab [crval1]];
+                  G1 = gray_clip [yval1 + Cr_g_tab [crval1]
+                                  + Cb_g_tab [cbval1]];
+                  B1 = gray_clip [yval1 + Cb_b_tab [cbval1]];
+                  R2 = gray_clip [yval2 + Cr_r_tab [crval1]];
+                  G2 = gray_clip [yval2 + Cr_g_tab [crval1]
+                                  + Cb_g_tab [cbval1]];
+                  B2 = gray_clip [yval2 + Cb_b_tab [cbval1]];
+
+                  *dst2++ = R1 | (G1 << 8) | (B1 << 16) | (R2 << 24);
+                  *dst2   = G2 | (B2 << 8);
+
 #ifdef HAVE_SIGNED_SHIFT
-		  yval1  = (*yptr++ >> 4) + 128;
-		  yval2  = (*yptr++ >> 4) + 128;
-		  crval1 = *crptr++ >> 4;
-		  cbval1 = *cbptr++ >> 4;
+                  yval1  = (*yptr++ >> 4) + 128;
+                  yval2  = (*yptr++ >> 4) + 128;
+                  crval1 = *crptr++ >> 4;
+                  cbval1 = *cbptr++ >> 4;
 #else /* not HAVE_SIGNED_SHIFT */
-		  yval1  = *yptr++  / 16 + 128;
-		  yval2  = *yptr++  / 16 + 128;
-		  crval1 = *crptr++ / 16;
-		  crval2 = *crptr++ / 16;
-		  cbval1 = *cbptr++ / 16;
-		  cbval2 = *cbptr++ / 16;
+                  yval1  = *yptr++  / 16 + 128;
+                  yval2  = *yptr++  / 16 + 128;
+                  crval1 = *crptr++ / 16;
+                  crval2 = *crptr++ / 16;
+                  cbval1 = *cbptr++ / 16;
+                  cbval2 = *cbptr++ / 16;
 #endif /* not HAVE_SIGNED_SHIFT */
 
-		  R1 = gray_clip [yval1 + Cr_r_tab [crval1]];
-		  G1 = gray_clip [yval1 + Cr_g_tab [crval1]
-				  + Cb_g_tab [cbval1]];
-		  B1 = gray_clip [yval1 + Cb_b_tab [cbval1]];
-		  R2 = gray_clip [yval2 + Cr_r_tab [crval1]];
-		  G2 = gray_clip [yval2 + Cr_g_tab [crval1]
-				  + Cb_g_tab [cbval1]];
-		  B2 = gray_clip [yval2 + Cb_b_tab [cbval1]];
+                  R1 = gray_clip [yval1 + Cr_r_tab [crval1]];
+                  G1 = gray_clip [yval1 + Cr_g_tab [crval1]
+                                  + Cb_g_tab [cbval1]];
+                  B1 = gray_clip [yval1 + Cb_b_tab [cbval1]];
+                  R2 = gray_clip [yval2 + Cr_r_tab [crval1]];
+                  G2 = gray_clip [yval2 + Cr_g_tab [crval1]
+                                  + Cb_g_tab [cbval1]];
+                  B2 = gray_clip [yval2 + Cb_b_tab [cbval1]];
 
-		  *dst++ |= (R1 << 16) | (G1 << 24);
-		  *dst++ = B1 | (R2 << 8) | (G2 << 16) | (B2 << 24);
+                  *dst++ |= (R1 << 16) | (G1 << 24);
+                  *dst++ = B1 | (R2 << 8) | (G2 << 16) | (B2 << 24);
 
 #ifdef HAVE_SIGNED_SHIFT
-		  yval1  = (*yptr2++ >> 4) + 128;
-		  yval2  = (*yptr2++ >> 4) + 128;
+                  yval1  = (*yptr2++ >> 4) + 128;
+                  yval2  = (*yptr2++ >> 4) + 128;
 #else /* not HAVE_SIGNED_SHIFT */
-		  yval1  = *yptr2++  / 16 + 128;
-		  yval2  = *yptr2++  / 16 + 128;
+                  yval1  = *yptr2++  / 16 + 128;
+                  yval2  = *yptr2++  / 16 + 128;
 #endif /* not HAVE_SIGNED_SHIFT */
 
-		  R1 = gray_clip [yval1 + Cr_r_tab [crval1]];
-		  G1 = gray_clip [yval1 + Cr_g_tab [crval1]
-				  + Cb_g_tab [cbval1]];
-		  B1 = gray_clip [yval1 + Cb_b_tab [cbval1]];
-		  R2 = gray_clip [yval2 + Cr_r_tab [crval1]];
-		  G2 = gray_clip [yval2 + Cr_g_tab [crval1]
-				  + Cb_g_tab [cbval1]];
-		  B2 = gray_clip [yval2 + Cb_b_tab [cbval1]];
-
-		  *dst2++ |= (R1 << 16) | (G1 << 24);
-		  *dst2++ = B1 | (R2 << 8) | (G2 << 16) | (B2 << 24);
-	       }
-	       dst   += (image->width >> 2) * 3;
-	       dst2  += (image->width >> 2) * 3;
-	       yptr  += image->width;
-	       yptr2 += image->width;
-	    }
-	 }
+                  R1 = gray_clip [yval1 + Cr_r_tab [crval1]];
+                  G1 = gray_clip [yval1 + Cr_g_tab [crval1]
+                                  + Cb_g_tab [cbval1]];
+                  B1 = gray_clip [yval1 + Cb_b_tab [cbval1]];
+                  R2 = gray_clip [yval2 + Cr_r_tab [crval1]];
+                  G2 = gray_clip [yval2 + Cr_g_tab [crval1]
+                                  + Cb_g_tab [cbval1]];
+                  B2 = gray_clip [yval2 + Cb_b_tab [cbval1]];
+
+                  *dst2++ |= (R1 << 16) | (G1 << 24);
+                  *dst2++ = B1 | (R2 << 8) | (G2 << 16) | (B2 << 24);
+               }
+               dst   += (image->width >> 2) * 3;
+               dst2  += (image->width >> 2) * 3;
+               yptr  += image->width;
+               yptr2 += image->width;
+            }
+         }
       }
-      else				/* 4:4:4 format */
+      else                              /* 4:4:4 format */
       {
-	 if (private->double_resolution)
-	 {
-	    unsigned int R1, G1, B1;		/* pixel1 in RGB color space */
-	    unsigned int R2, G2, B2;		/* pixel2 in RGB color space */
-	    int		 yval1, crval1, cbval1;	/* pixel1 in YCbCr space */
-	    int		 yval2, crval2, cbval2;	/* pixel2 in YCbCr space */
-	    int		 x, y;			/* pixel counter */
-	    unsigned int *dst;		        /* dithered pixel pointer */
-	    
-	    dst = (unsigned int *) out;
-	    
-	    for (y = image->height; y; y--)
-	    {
-	       for (x = image->width >> 1; x; x--)
-	       {
+         if (private->double_resolution)
+         {
+            unsigned int R1, G1, B1;            /* pixel1 in RGB color space */
+            unsigned int R2, G2, B2;            /* pixel2 in RGB color space */
+            int          yval1, crval1, cbval1; /* pixel1 in YCbCr space */
+            int          yval2, crval2, cbval2; /* pixel2 in YCbCr space */
+            int          x, y;                  /* pixel counter */
+            unsigned int *dst;                  /* dithered pixel pointer */
+
+            dst = (unsigned int *) out;
+
+            for (y = image->height; y; y--)
+            {
+               for (x = image->width >> 1; x; x--)
+               {
 #ifdef HAVE_SIGNED_SHIFT
-		  yval1  = (*yptr++ >> 4) + 128;
-		  yval2  = (*yptr++ >> 4) + 128;
-		  crval1 = *crptr++ >> 4;
-		  crval2 = *crptr++ >> 4;
-		  cbval1 = *cbptr++ >> 4;
-		  cbval2 = *cbptr++ >> 4;
+                  yval1  = (*yptr++ >> 4) + 128;
+                  yval2  = (*yptr++ >> 4) + 128;
+                  crval1 = *crptr++ >> 4;
+                  crval2 = *crptr++ >> 4;
+                  cbval1 = *cbptr++ >> 4;
+                  cbval2 = *cbptr++ >> 4;
 #else /* not HAVE_SIGNED_SHIFT */
-		  yval1  = *yptr++  / 16 + 128;
-		  yval2  = *yptr++  / 16 + 128;
-		  crval1 = *crptr++ / 16;
-		  crval2 = *crptr++ / 16;
-		  cbval1 = *cbptr++ / 16;
-		  cbval2 = *cbptr++ / 16;
+                  yval1  = *yptr++  / 16 + 128;
+                  yval2  = *yptr++  / 16 + 128;
+                  crval1 = *crptr++ / 16;
+                  crval2 = *crptr++ / 16;
+                  cbval1 = *cbptr++ / 16;
+                  cbval2 = *cbptr++ / 16;
 #endif /* not HAVE_SIGNED_SHIFT */
-		  
-		  R1 = gray_clip [yval1 + Cr_r_tab [crval1]];
-		  G1 = gray_clip [yval1 + Cr_g_tab [crval1]
-				  + Cb_g_tab [cbval1]];
-		  B1 = gray_clip [yval1 + Cb_b_tab [cbval1]];
-		  R2 = gray_clip [yval2 + Cr_r_tab [crval2]];
-		  G2 = gray_clip [yval2 + Cr_g_tab [crval2]
-				  + Cb_g_tab [cbval2]];
-		  B2 = gray_clip [yval2 + Cb_b_tab [cbval2]];
-
-		  *dst++ = R1 | (G1 << 8) | (B1 << 16) | (R1 << 24);
-		  *dst++ = G1 | (B1 << 8) | (R2 << 16) | (G2 << 24);
-		  *dst++ = B2 | (R2 << 8) | (G2 << 16) | (B2 << 24);
-	       }
-	       memcpy (dst, dst - 3 * (image->width >> 1),
-		       3 * (image->width >> 1) * sizeof (unsigned int));
-	       dst += 3 * (image->width >> 1);
-	    }
-	 }
-	 else
-	 {
-	    unsigned int R1, G1, B1;		/* pixel in RGB color space */
-	    unsigned int R2, G2, B2;		/* pixel in RGB color space */
-	    int		 yval1, crval1, cbval1;	/* pixel1 in YCbCr space */
-	    int		 yval2, crval2, cbval2;	/* pixel2 in YCbCr space */
-	    int		 n;			/* pixel counter */
-	    unsigned int *dst;		        /* dithered pixel pointer */
-	    
-	    dst = (unsigned int *) out;
-	    
-	    for (n = (image->width * image->height) >> 2; n; n--)
-	    {
+
+                  R1 = gray_clip [yval1 + Cr_r_tab [crval1]];
+                  G1 = gray_clip [yval1 + Cr_g_tab [crval1]
+                                  + Cb_g_tab [cbval1]];
+                  B1 = gray_clip [yval1 + Cb_b_tab [cbval1]];
+                  R2 = gray_clip [yval2 + Cr_r_tab [crval2]];
+                  G2 = gray_clip [yval2 + Cr_g_tab [crval2]
+                                  + Cb_g_tab [cbval2]];
+                  B2 = gray_clip [yval2 + Cb_b_tab [cbval2]];
+
+                  *dst++ = R1 | (G1 << 8) | (B1 << 16) | (R1 << 24);
+                  *dst++ = G1 | (B1 << 8) | (R2 << 16) | (G2 << 24);
+                  *dst++ = B2 | (R2 << 8) | (G2 << 16) | (B2 << 24);
+               }
+               memcpy (dst, dst - 3 * (image->width >> 1),
+                       3 * (image->width >> 1) * sizeof (unsigned int));
+               dst += 3 * (image->width >> 1);
+            }
+         }
+         else
+         {
+            unsigned int R1, G1, B1;            /* pixel in RGB color space */
+            unsigned int R2, G2, B2;            /* pixel in RGB color space */
+            int          yval1, crval1, cbval1; /* pixel1 in YCbCr space */
+            int          yval2, crval2, cbval2; /* pixel2 in YCbCr space */
+            int          n;                     /* pixel counter */
+            unsigned int *dst;                  /* dithered pixel pointer */
+
+            dst = (unsigned int *) out;
+
+            for (n = (image->width * image->height) >> 2; n; n--)
+            {
 #ifdef HAVE_SIGNED_SHIFT
-	       yval1  = (*yptr++ >> 4) + 128;
-	       yval2  = (*yptr++ >> 4) + 128;
-	       crval1 = *crptr++ >> 4;
-	       crval2 = *crptr++ >> 4;
-	       cbval1 = *cbptr++ >> 4;
-	       cbval2 = *cbptr++ >> 4;
+               yval1  = (*yptr++ >> 4) + 128;
+               yval2  = (*yptr++ >> 4) + 128;
+               crval1 = *crptr++ >> 4;
+               crval2 = *crptr++ >> 4;
+               cbval1 = *cbptr++ >> 4;
+               cbval2 = *cbptr++ >> 4;
 #else /* not HAVE_SIGNED_SHIFT */
-	       yval1  = *yptr++  / 16 + 128;
-	       yval2  = *yptr++  / 16 + 128;
-	       crval1 = *crptr++ / 16;
-	       crval2 = *crptr++ / 16;
-	       cbval1 = *cbptr++ / 16;
-	       cbval2 = *cbptr++ / 16;
+               yval1  = *yptr++  / 16 + 128;
+               yval2  = *yptr++  / 16 + 128;
+               crval1 = *crptr++ / 16;
+               crval2 = *crptr++ / 16;
+               cbval1 = *cbptr++ / 16;
+               cbval2 = *cbptr++ / 16;
 #endif /* not HAVE_SIGNED_SHIFT */
 
-	       R1 = gray_clip [yval1 + Cr_r_tab [crval1]];
-	       G1 = gray_clip [yval1 + Cr_g_tab [crval1] + Cb_g_tab [cbval1]];
-	       B1 = gray_clip [yval1 + Cb_b_tab [cbval1]];
-	       R2 = gray_clip [yval2 + Cr_r_tab [crval2]];
-	       G2 = gray_clip [yval2 + Cr_g_tab [crval2] + Cb_g_tab [cbval2]];
-	       B2 = gray_clip [yval2 + Cb_b_tab [cbval2]];
+               R1 = gray_clip [yval1 + Cr_r_tab [crval1]];
+               G1 = gray_clip [yval1 + Cr_g_tab [crval1] + Cb_g_tab [cbval1]];
+               B1 = gray_clip [yval1 + Cb_b_tab [cbval1]];
+               R2 = gray_clip [yval2 + Cr_r_tab [crval2]];
+               G2 = gray_clip [yval2 + Cr_g_tab [crval2] + Cb_g_tab [cbval2]];
+               B2 = gray_clip [yval2 + Cb_b_tab [cbval2]];
 
-	       *dst++ = R1 | (G1 << 8) | (B1 << 16) | (R2 << 24);
-	       *dst   = G2 | (B2 << 8);
+               *dst++ = R1 | (G1 << 8) | (B1 << 16) | (R2 << 24);
+               *dst   = G2 | (B2 << 8);
 
 #ifdef HAVE_SIGNED_SHIFT
-	       yval1  = (*yptr++ >> 4) + 128;
-	       yval2  = (*yptr++ >> 4) + 128;
-	       crval1 = *crptr++ >> 4;
-	       crval2 = *crptr++ >> 4;
-	       cbval1 = *cbptr++ >> 4;
-	       cbval2 = *cbptr++ >> 4;
+               yval1  = (*yptr++ >> 4) + 128;
+               yval2  = (*yptr++ >> 4) + 128;
+               crval1 = *crptr++ >> 4;
+               crval2 = *crptr++ >> 4;
+               cbval1 = *cbptr++ >> 4;
+               cbval2 = *cbptr++ >> 4;
 #else /* not HAVE_SIGNED_SHIFT */
-	       yval1  = *yptr++  / 16 + 128;
-	       yval2  = *yptr++  / 16 + 128;
-	       crval1 = *crptr++ / 16;
-	       crval2 = *crptr++ / 16;
-	       cbval1 = *cbptr++ / 16;
-	       cbval2 = *cbptr++ / 16;
+               yval1  = *yptr++  / 16 + 128;
+               yval2  = *yptr++  / 16 + 128;
+               crval1 = *crptr++ / 16;
+               crval2 = *crptr++ / 16;
+               cbval1 = *cbptr++ / 16;
+               cbval2 = *cbptr++ / 16;
 #endif /* not HAVE_SIGNED_SHIFT */
 
-	       R1 = gray_clip [yval1 + Cr_r_tab [crval1]];
-	       G1 = gray_clip [yval1 + Cr_g_tab [crval1] + Cb_g_tab [cbval1]];
-	       B1 = gray_clip [yval1 + Cb_b_tab [cbval1]];
-	       R2 = gray_clip [yval2 + Cr_r_tab [crval2]];
-	       G2 = gray_clip [yval2 + Cr_g_tab [crval2] + Cb_g_tab [cbval2]];
-	       B2 = gray_clip [yval2 + Cb_b_tab [cbval2]];
-
-	       *dst++ |= (R1 << 16) | (G1 << 24);
-	       *dst++ = B1 | (R2 << 8) | (G2 << 16) | (B2 << 24);
-	    }
-	 }
+               R1 = gray_clip [yval1 + Cr_r_tab [crval1]];
+               G1 = gray_clip [yval1 + Cr_g_tab [crval1] + Cb_g_tab [cbval1]];
+               B1 = gray_clip [yval1 + Cb_b_tab [cbval1]];
+               R2 = gray_clip [yval2 + Cr_r_tab [crval2]];
+               G2 = gray_clip [yval2 + Cr_g_tab [crval2] + Cb_g_tab [cbval2]];
+               B2 = gray_clip [yval2 + Cb_b_tab [cbval2]];
+
+               *dst++ |= (R1 << 16) | (G1 << 24);
+               *dst++ = B1 | (R2 << 8) | (G2 << 16) | (B2 << 24);
+            }
+         }
       }
    }
    else
    {
-      unsigned int *dst;		/* pointer to dithered pixels */
-      word_t	   *src;		/* current pixel of frame */
+      unsigned int *dst;                /* pointer to dithered pixels */
+      word_t       *src;                /* current pixel of frame */
 
       dst     = (unsigned int *) out;
       src     = image->pixels [GRAY];
 
       if (private->double_resolution)
       {
-	 int	   x, y;		/* pixel counter */
-	 unsigned *shift_clipping = gray_clip + 128;
-
-	 for (y = image->height; y; y--)
-	 {
-	    for (x = image->width >> 1; x; x--)
-	    {
-	       unsigned int val1, val2;
+         int       x, y;                /* pixel counter */
+         unsigned *shift_clipping = gray_clip + 128;
+
+         for (y = image->height; y; y--)
+         {
+            for (x = image->width >> 1; x; x--)
+            {
+               unsigned int val1, val2;
 #ifdef HAVE_SIGNED_SHIFT
-	       val1 = shift_clipping [*src++ >> 4];
-	       val2 = shift_clipping [*src++ >> 4];
+               val1 = shift_clipping [*src++ >> 4];
+               val2 = shift_clipping [*src++ >> 4];
 #else /* not HAVE_SIGNED_SHIFT */
-	       val1 = shift_clipping [*src++ / 16];
-	       val2 = shift_clipping [*src++ / 16];
+               val1 = shift_clipping [*src++ / 16];
+               val2 = shift_clipping [*src++ / 16];
 #endif /* not HAVE_SIGNED_SHIFT */
 
-	       *dst++ = val1 | (val1 << 8) | (val1 << 16) | (val1 << 24);
-	       *dst++ = val1 | (val1 << 8) | (val2 << 16) | (val2 << 24); 
-	       *dst++ = val2 | (val2 << 8) | (val2 << 16) | (val2 << 24);
-	    }
+               *dst++ = val1 | (val1 << 8) | (val1 << 16) | (val1 << 24);
+               *dst++ = val1 | (val1 << 8) | (val2 << 16) | (val2 << 24);
+               *dst++ = val2 | (val2 << 8) | (val2 << 16) | (val2 << 24);
+            }
 
-	    memcpy (dst, dst - 3 * (image->width >> 1),
-		    3 * (image->width >> 1) * sizeof (unsigned int));
-	    dst += 3 * (image->width >> 1);
-	 }
+            memcpy (dst, dst - 3 * (image->width >> 1),
+                    3 * (image->width >> 1) * sizeof (unsigned int));
+            dst += 3 * (image->width >> 1);
+         }
       }
       else
       {
-	 int	   n;			/* pixel counter */
-	 unsigned *shift_clipping = gray_clip + 128;
+         int       n;                   /* pixel counter */
+         unsigned *shift_clipping = gray_clip + 128;
 
-	 for (n = (image->width * image->height) >> 2; n; n--)
-	 {
-	    unsigned int val1, val2;
+         for (n = (image->width * image->height) >> 2; n; n--)
+         {
+            unsigned int val1, val2;
 
 #ifdef HAVE_SIGNED_SHIFT
-	    val1 = shift_clipping [*src++ >> 4];
-	    val2 = shift_clipping [*src++ >> 4];
+            val1 = shift_clipping [*src++ >> 4];
+            val2 = shift_clipping [*src++ >> 4];
 #else /* not HAVE_SIGNED_SHIFT */
-	    val1 = shift_clipping [*src++ / 16];
-	    val2 = shift_clipping [*src++ / 16];
+            val1 = shift_clipping [*src++ / 16];
+            val2 = shift_clipping [*src++ / 16];
 #endif /* not HAVE_SIGNED_SHIFT */
 
-	    *dst++ = val1 | (val1 << 8)
-		     | (val1 << 16) | (val2 << 24);  /* RGBR */
-	    *dst   = val2 | (val2 << 8);             /* GB-- */
+            *dst++ = val1 | (val1 << 8)
+                     | (val1 << 16) | (val2 << 24);  /* RGBR */
+            *dst   = val2 | (val2 << 8);             /* GB-- */
 
 #ifdef HAVE_SIGNED_SHIFT
-	    val1 = shift_clipping [*src++ >> 4];
-	    val2 = shift_clipping [*src++ >> 4];
+            val1 = shift_clipping [*src++ >> 4];
+            val2 = shift_clipping [*src++ >> 4];
 #else /* not HAVE_SIGNED_SHIFT */
-	    val1 = shift_clipping [*src++ / 16];
-	    val2 = shift_clipping [*src++ / 16];
+            val1 = shift_clipping [*src++ / 16];
+            val2 = shift_clipping [*src++ / 16];
 #endif /* not HAVE_SIGNED_SHIFT */
-	    
-	    *dst++ |= (val1 << 16) | (val1 << 24);   /* --RG */
-	    *dst++  = val1 | (val2 << 8)
-		      | (val2 << 16) | (val2 << 24); /* BRGB */
-	 }
+
+            *dst++ |= (val1 << 16) | (val1 << 24);   /* --RG */
+            *dst++  = val1 | (val2 << 8)
+                      | (val2 << 16) | (val2 << 24); /* BRGB */
+         }
       }
    }
-   
+
    return 1;
 }
 
-static int 
+static int
 display_32_bit (const struct fiasco_renderer *this, unsigned char *ximage,
-		const fiasco_image_t *fiasco_image)
+                const fiasco_image_t *fiasco_image)
 /*
  *  Convert 'image' to 16 bit color bitmap.
  *  If 'double_resolution' is true then double image size in both directions.
@@ -1566,13 +1566,13 @@ display_32_bit (const struct fiasco_renderer *this, unsigned char *ximage,
  *  No return value.
  *
  *  Side effects:
- *	'out[]'	is filled with dithered image
+ *      'out[]' is filled with dithered image
  */
 {
    const image_t      *image;
    renderer_private_t *private;
-   byte_t	      *out;
-   
+   byte_t             *out;
+
    if (!this)
    {
       set_error (_("Parameter `%s' not defined (NULL)."), "this");
@@ -1589,21 +1589,21 @@ display_32_bit (const struct fiasco_renderer *this, unsigned char *ximage,
       return 0;
    }
 
-   out 	   = (byte_t *) ximage;
+   out     = (byte_t *) ximage;
    private = (renderer_private_t *) this->private;
    image   = cast_image ((fiasco_image_t *) fiasco_image);
    if (!image)
       return 0;
-   
+
    if (image->color)
    {
-      word_t 	   *cbptr, *crptr;	/* pointer to chroma bands */
-      word_t 	   *yptr;		/* pointers to lumincance band */
-      int     	    yval, crval, cbval;	/* pixel value in YCbCr color space */
-      int     	    R, G, B;		/* pixel value in RGB color space */
-      int     	    n;			/* pixel counter */
-      int     	    x, y;		/* pixel coordinates */
-      int 	   *Cr_r_tab, *Cr_g_tab, *Cb_g_tab, *Cb_b_tab;
+      word_t       *cbptr, *crptr;      /* pointer to chroma bands */
+      word_t       *yptr;               /* pointers to lumincance band */
+      int           yval, crval, cbval; /* pixel value in YCbCr color space */
+      int           R, G, B;            /* pixel value in RGB color space */
+      int           n;                  /* pixel counter */
+      int           x, y;               /* pixel coordinates */
+      int          *Cr_r_tab, *Cr_g_tab, *Cb_g_tab, *Cb_b_tab;
       unsigned int *r_table, *g_table, *b_table;
 
       Cr_g_tab = private->Cr_g_tab;
@@ -1619,245 +1619,245 @@ display_32_bit (const struct fiasco_renderer *this, unsigned char *ximage,
 
       if (image->format == FORMAT_4_2_0)
       {
-	 unsigned int	*dst, *dst2;	/* pointers to dithered pixels */
-	 word_t		*yptr2;		/* pointers to lumincance band */
-
-	 if (private->double_resolution)
-	 {
-	    yptr2 = yptr + image->width;
-	    dst  = (unsigned int *) out;
-	    dst2 = dst + 4 * image->width;
-	    for (y = image->height / 2; y; y--)
-	    {
-	       for (x = image->width / 2; x; x--)
-	       {
+         unsigned int   *dst, *dst2;    /* pointers to dithered pixels */
+         word_t         *yptr2;         /* pointers to lumincance band */
+
+         if (private->double_resolution)
+         {
+            yptr2 = yptr + image->width;
+            dst  = (unsigned int *) out;
+            dst2 = dst + 4 * image->width;
+            for (y = image->height / 2; y; y--)
+            {
+               for (x = image->width / 2; x; x--)
+               {
 #ifdef HAVE_SIGNED_SHIFT
-		  crval = *crptr++ >> 4;
-		  cbval = *cbptr++ >> 4;
-		  yval  = (*yptr++ >> 4) + 128;
+                  crval = *crptr++ >> 4;
+                  cbval = *cbptr++ >> 4;
+                  yval  = (*yptr++ >> 4) + 128;
 #else /* not HAVE_SIGNED_SHIFT */
-		  crval = *crptr++ / 16;
-		  cbval = *cbptr++ / 16;
-		  yval  = *yptr++  / 16 + 128;
+                  crval = *crptr++ / 16;
+                  cbval = *cbptr++ / 16;
+                  yval  = *yptr++  / 16 + 128;
 #endif /* not HAVE_SIGNED_SHIFT */
-		  R = yval + Cr_r_tab [crval];
-		  G = yval + Cr_g_tab [crval] + Cb_g_tab [cbval];
-		  B = yval + Cb_b_tab [cbval];
-		  *dst++ = r_table [R] | g_table [G] | b_table [B];
-		  *dst++ = r_table [R] | g_table [G] | b_table [B];
-	       
+                  R = yval + Cr_r_tab [crval];
+                  G = yval + Cr_g_tab [crval] + Cb_g_tab [cbval];
+                  B = yval + Cb_b_tab [cbval];
+                  *dst++ = r_table [R] | g_table [G] | b_table [B];
+                  *dst++ = r_table [R] | g_table [G] | b_table [B];
+
 #ifdef HAVE_SIGNED_SHIFT
-		  yval  = (*yptr++ >> 4) + 128;
+                  yval  = (*yptr++ >> 4) + 128;
 #else /* not HAVE_SIGNED_SHIFT */
-		  yval  = *yptr++  / 16 + 128;
+                  yval  = *yptr++  / 16 + 128;
 #endif /* not HAVE_SIGNED_SHIFT */
-		  R = yval + Cr_r_tab [crval];
-		  G = yval + Cr_g_tab [crval] + Cb_g_tab [cbval];
-		  B = yval + Cb_b_tab [cbval];
-		  *dst++ = r_table [R] | g_table [G] | b_table [B];
-		  *dst++ = r_table [R] | g_table [G] | b_table [B];
+                  R = yval + Cr_r_tab [crval];
+                  G = yval + Cr_g_tab [crval] + Cb_g_tab [cbval];
+                  B = yval + Cb_b_tab [cbval];
+                  *dst++ = r_table [R] | g_table [G] | b_table [B];
+                  *dst++ = r_table [R] | g_table [G] | b_table [B];
 
 #ifdef HAVE_SIGNED_SHIFT
-		  yval  = (*yptr2++ >> 4) + 128;
+                  yval  = (*yptr2++ >> 4) + 128;
 #else /* not HAVE_SIGNED_SHIFT */
-		  yval  = *yptr2++  / 16 + 128;
+                  yval  = *yptr2++  / 16 + 128;
 #endif /* not HAVE_SIGNED_SHIFT */
-		  R = yval + Cr_r_tab [crval];
-		  G = yval + Cr_g_tab [crval] + Cb_g_tab [cbval];
-		  B = yval + Cb_b_tab [cbval];
-		  *dst2++ = r_table [R] | g_table [G] | b_table [B];
-		  *dst2++ = r_table [R] | g_table [G] | b_table [B];
+                  R = yval + Cr_r_tab [crval];
+                  G = yval + Cr_g_tab [crval] + Cb_g_tab [cbval];
+                  B = yval + Cb_b_tab [cbval];
+                  *dst2++ = r_table [R] | g_table [G] | b_table [B];
+                  *dst2++ = r_table [R] | g_table [G] | b_table [B];
 
 #ifdef HAVE_SIGNED_SHIFT
-		  yval  = (*yptr2++ >> 4) + 128;
+                  yval  = (*yptr2++ >> 4) + 128;
 #else /* not HAVE_SIGNED_SHIFT */
-		  yval  = *yptr2++  / 16 + 128;
+                  yval  = *yptr2++  / 16 + 128;
 #endif /* not HAVE_SIGNED_SHIFT */
-		  R = yval + Cr_r_tab [crval];
-		  G = yval + Cr_g_tab [crval] + Cb_g_tab [cbval];
-		  B = yval + Cb_b_tab [cbval];
-		  *dst2++ = r_table [R] | g_table [G] | b_table [B];
-		  *dst2++ = r_table [R] | g_table [G] | b_table [B];
-	       }
-	       memcpy (dst, dst - 2 * image->width,
-		       2 * image->width * sizeof (unsigned int));
-	       memcpy (dst2, dst2 - 2 * image->width,
-		       2 * image->width * sizeof (unsigned int));
-	       yptr  += image->width;
-	       yptr2 += image->width;
-	       dst   += 3 * image->width * 2;
-	       dst2  += 3 * image->width * 2;
-	    }
-	 }
-	 else
-	 {
-	    yptr2 = yptr + image->width;
-	    dst   = (unsigned int *) out;
-	    dst2  = dst + image->width;
-	    
-	    for (y = image->height / 2; y; y--)
-	    {
-	       for (x = image->width / 2; x; x--)
-	       {
+                  R = yval + Cr_r_tab [crval];
+                  G = yval + Cr_g_tab [crval] + Cb_g_tab [cbval];
+                  B = yval + Cb_b_tab [cbval];
+                  *dst2++ = r_table [R] | g_table [G] | b_table [B];
+                  *dst2++ = r_table [R] | g_table [G] | b_table [B];
+               }
+               memcpy (dst, dst - 2 * image->width,
+                       2 * image->width * sizeof (unsigned int));
+               memcpy (dst2, dst2 - 2 * image->width,
+                       2 * image->width * sizeof (unsigned int));
+               yptr  += image->width;
+               yptr2 += image->width;
+               dst   += 3 * image->width * 2;
+               dst2  += 3 * image->width * 2;
+            }
+         }
+         else
+         {
+            yptr2 = yptr + image->width;
+            dst   = (unsigned int *) out;
+            dst2  = dst + image->width;
+
+            for (y = image->height / 2; y; y--)
+            {
+               for (x = image->width / 2; x; x--)
+               {
 #ifdef HAVE_SIGNED_SHIFT
-		  crval = *crptr++ >> 4;
-		  cbval = *cbptr++ >> 4;
-		  yval  = (*yptr++ >> 4) + 128;
+                  crval = *crptr++ >> 4;
+                  cbval = *cbptr++ >> 4;
+                  yval  = (*yptr++ >> 4) + 128;
 #else /* not HAVE_SIGNED_SHIFT */
-		  crval = *crptr++ / 16;
-		  cbval = *cbptr++ / 16;
-		  yval  = *yptr++  / 16 + 128;
+                  crval = *crptr++ / 16;
+                  cbval = *cbptr++ / 16;
+                  yval  = *yptr++  / 16 + 128;
 #endif /* not HAVE_SIGNED_SHIFT */
-		  R = yval + Cr_r_tab [crval];
-		  G = yval + Cr_g_tab [crval] + Cb_g_tab [cbval];
-		  B = yval + Cb_b_tab [cbval];
-		  *dst++ = r_table [R] | g_table [G] | b_table [B];
-	       
+                  R = yval + Cr_r_tab [crval];
+                  G = yval + Cr_g_tab [crval] + Cb_g_tab [cbval];
+                  B = yval + Cb_b_tab [cbval];
+                  *dst++ = r_table [R] | g_table [G] | b_table [B];
+
 #ifdef HAVE_SIGNED_SHIFT
-		  yval  = (*yptr++ >> 4) + 128;
+                  yval  = (*yptr++ >> 4) + 128;
 #else /* not HAVE_SIGNED_SHIFT */
-		  yval  = *yptr++  / 16 + 128;
+                  yval  = *yptr++  / 16 + 128;
 #endif /* not HAVE_SIGNED_SHIFT */
-		  R = yval + Cr_r_tab [crval];
-		  G = yval + Cr_g_tab [crval] + Cb_g_tab [cbval];
-		  B = yval + Cb_b_tab [cbval];
-		  *dst++ = r_table [R] | g_table [G] | b_table [B];
+                  R = yval + Cr_r_tab [crval];
+                  G = yval + Cr_g_tab [crval] + Cb_g_tab [cbval];
+                  B = yval + Cb_b_tab [cbval];
+                  *dst++ = r_table [R] | g_table [G] | b_table [B];
 
 #ifdef HAVE_SIGNED_SHIFT
-		  yval  = (*yptr2++ >> 4) + 128;
+                  yval  = (*yptr2++ >> 4) + 128;
 #else /* not HAVE_SIGNED_SHIFT */
-		  yval  = *yptr2++  / 16 + 128;
+                  yval  = *yptr2++  / 16 + 128;
 #endif /* not HAVE_SIGNED_SHIFT */
-		  R = yval + Cr_r_tab [crval];
-		  G = yval + Cr_g_tab [crval] + Cb_g_tab [cbval];
-		  B = yval + Cb_b_tab [cbval];
-		  *dst2++ = r_table [R] | g_table [G] | b_table [B];
+                  R = yval + Cr_r_tab [crval];
+                  G = yval + Cr_g_tab [crval] + Cb_g_tab [cbval];
+                  B = yval + Cb_b_tab [cbval];
+                  *dst2++ = r_table [R] | g_table [G] | b_table [B];
 
 #ifdef HAVE_SIGNED_SHIFT
-		  yval  = (*yptr2++ >> 4) + 128;
+                  yval  = (*yptr2++ >> 4) + 128;
 #else /* not HAVE_SIGNED_SHIFT */
-		  yval  = *yptr2++  / 16 + 128;
+                  yval  = *yptr2++  / 16 + 128;
 #endif /* not HAVE_SIGNED_SHIFT */
-		  R = yval + Cr_r_tab [crval];
-		  G = yval + Cr_g_tab [crval] + Cb_g_tab [cbval];
-		  B = yval + Cb_b_tab [cbval];
-		  *dst2++ = r_table [R] | g_table [G] | b_table [B];
-	       }
-	       yptr  += image->width;
-	       yptr2 += image->width;
-	       dst   += image->width;
-	       dst2  += image->width;
-	    }
-	 }
+                  R = yval + Cr_r_tab [crval];
+                  G = yval + Cr_g_tab [crval] + Cb_g_tab [cbval];
+                  B = yval + Cb_b_tab [cbval];
+                  *dst2++ = r_table [R] | g_table [G] | b_table [B];
+               }
+               yptr  += image->width;
+               yptr2 += image->width;
+               dst   += image->width;
+               dst2  += image->width;
+            }
+         }
       }
-      else				/* 4:4:4 format */
+      else                              /* 4:4:4 format */
       {
-	 if (private->double_resolution)
-	 {
-	    unsigned int *dst;		/* pointer to dithered pixels */
-	    
-	    dst = (unsigned int *) out;
-	    
-	    for (y = image->height; y; y--)
-	    {
-	       for (x = image->width; x; x--)
-	       {
+         if (private->double_resolution)
+         {
+            unsigned int *dst;          /* pointer to dithered pixels */
+
+            dst = (unsigned int *) out;
+
+            for (y = image->height; y; y--)
+            {
+               for (x = image->width; x; x--)
+               {
 #ifdef HAVE_SIGNED_SHIFT
-		  crval = *crptr++ >> 4;
-		  cbval = *cbptr++ >> 4;
-		  yval  = (*yptr++ >> 4) + 128;
+                  crval = *crptr++ >> 4;
+                  cbval = *cbptr++ >> 4;
+                  yval  = (*yptr++ >> 4) + 128;
 #else /* not HAVE_SIGNED_SHIFT */
-		  crval = *crptr++ / 16;
-		  cbval = *cbptr++ / 16;
-		  yval  = *yptr++  / 16 + 128;
+                  crval = *crptr++ / 16;
+                  cbval = *cbptr++ / 16;
+                  yval  = *yptr++  / 16 + 128;
 #endif /* not HAVE_SIGNED_SHIFT */
-		  R = yval + Cr_r_tab [crval];
-		  G = yval + Cr_g_tab [crval] + Cb_g_tab [cbval];
-		  B = yval + Cb_b_tab [cbval];
-		  
-		  *dst++ = r_table [R] | g_table [G] | b_table [B];
-		  *dst++ = r_table [R] | g_table [G] | b_table [B];
-	       }
-	       memcpy (dst, dst - 2 * image->width,
-		       2 * image->width * sizeof (unsigned int));
-	       dst += image->width * 2;
-	    }
-	 }
-	 else
-	 {
-	    unsigned int *dst;		/* pointer to dithered pixels */
-
-	    dst  = (unsigned int *) out;
-	    
-	    for (n = image->width * image->height; n; n--)
-	    {
+                  R = yval + Cr_r_tab [crval];
+                  G = yval + Cr_g_tab [crval] + Cb_g_tab [cbval];
+                  B = yval + Cb_b_tab [cbval];
+
+                  *dst++ = r_table [R] | g_table [G] | b_table [B];
+                  *dst++ = r_table [R] | g_table [G] | b_table [B];
+               }
+               memcpy (dst, dst - 2 * image->width,
+                       2 * image->width * sizeof (unsigned int));
+               dst += image->width * 2;
+            }
+         }
+         else
+         {
+            unsigned int *dst;          /* pointer to dithered pixels */
+
+            dst  = (unsigned int *) out;
+
+            for (n = image->width * image->height; n; n--)
+            {
 #ifdef HAVE_SIGNED_SHIFT
-	       crval = *crptr++ >> 4;
-	       cbval = *cbptr++ >> 4;
-	       yval  = (*yptr++ >> 4) + 128;
+               crval = *crptr++ >> 4;
+               cbval = *cbptr++ >> 4;
+               yval  = (*yptr++ >> 4) + 128;
 #else /* not HAVE_SIGNED_SHIFT */
-	       crval = *crptr++ / 16;
-	       cbval = *cbptr++ / 16;
-	       yval  = *yptr++  / 16 + 128;
+               crval = *crptr++ / 16;
+               cbval = *cbptr++ / 16;
+               yval  = *yptr++  / 16 + 128;
 #endif /* not HAVE_SIGNED_SHIFT */
-	       R = yval + Cr_r_tab [crval];
-	       G = yval + Cr_g_tab [crval] + Cb_g_tab [cbval];
-	       B = yval + Cb_b_tab [cbval];
+               R = yval + Cr_r_tab [crval];
+               G = yval + Cr_g_tab [crval] + Cb_g_tab [cbval];
+               B = yval + Cb_b_tab [cbval];
 
-	       *dst++ = r_table [R] | g_table [G] | b_table [B];
-	    }
-	 }
+               *dst++ = r_table [R] | g_table [G] | b_table [B];
+            }
+         }
       }
    }
    else
    {
-      unsigned int *dst;		/* pointer to dithered pixels */
-      word_t	   *src;		/* current pixel of frame */
+      unsigned int *dst;                /* pointer to dithered pixels */
+      word_t       *src;                /* current pixel of frame */
       unsigned int *y_table;
 
       y_table = private->y_table;
       dst     = (unsigned int *) out;
       src     = image->pixels [GRAY];
-      
+
       if (private->double_resolution)
       {
-	 int x, y;			/* pixel coordinates */
-	 
-	 for (y = image->height; y; y--)
-	 {
-	    for (x = image->width; x; x--)
-	    {
-	       int value;
+         int x, y;                      /* pixel coordinates */
+
+         for (y = image->height; y; y--)
+         {
+            for (x = image->width; x; x--)
+            {
+               int value;
 
 #ifdef HAVE_SIGNED_SHIFT
-	       value = y_table [*src++ >> 4];
+               value = y_table [*src++ >> 4];
 #else /* not HAVE_SIGNED_SHIFT */
-	       value = y_table [*src++ / 16];
+               value = y_table [*src++ / 16];
 #endif /* not HAVE_SIGNED_SHIFT */
-	       *dst++ = value;
-	       *dst++ = value;
-	    }
-
-	    memcpy (dst, dst - 2 * image->width,
-		    2 * image->width * sizeof (unsigned int));
-	    dst += 2 * image->width;
-	 }
+               *dst++ = value;
+               *dst++ = value;
+            }
+
+            memcpy (dst, dst - 2 * image->width,
+                    2 * image->width * sizeof (unsigned int));
+            dst += 2 * image->width;
+         }
       }
       else
       {
-	 int n;				/* pixel counter */
-	 
-	 for (n = image->width * image->height; n; n--)
+         int n;                         /* pixel counter */
+
+         for (n = image->width * image->height; n; n--)
 #ifdef HAVE_SIGNED_SHIFT
-	    *dst++ = y_table [*src++ >> 4];
+            *dst++ = y_table [*src++ >> 4];
 #else /* not HAVE_SIGNED_SHIFT */
-	    *dst++ = y_table [*src++ / 16];
+            *dst++ = y_table [*src++ / 16];
 #endif /* not HAVE_SIGNED_SHIFT */
       }
    }
-   
+
    return 1;
 }
 
 
- 
+
diff --git a/converter/other/fiasco/lib/dither.h b/converter/other/fiasco/lib/dither.h
index 767bca28..e786af1f 100644
--- a/converter/other/fiasco/lib/dither.h
+++ b/converter/other/fiasco/lib/dither.h
@@ -1,8 +1,8 @@
 /*
  *  dither.h
  *
- *  Written by:		Ullrich Hafner
- *		
+ *  Written by:         Ullrich Hafner
+ *              
  *  This file is part of FIASCO (Fractal Image And Sequence COdec)
  *  Copyright (C) 1994-2000 Ullrich Hafner
  */
@@ -19,9 +19,9 @@
 
 typedef struct renderer_private
 {
-   int 	       	*Cr_r_tab, *Cr_g_tab, *Cb_g_tab, *Cb_b_tab;
+   int          *Cr_r_tab, *Cr_g_tab, *Cb_g_tab, *Cb_b_tab;
    unsigned int *r_table, *g_table, *b_table, *y_table;
-   bool_t	double_resolution;
+   bool_t       double_resolution;
 } renderer_private_t;
 
 #endif /* _DITHER_H */
diff --git a/converter/other/fiasco/lib/error.c b/converter/other/fiasco/lib/error.c
index 394f896f..30d0cf97 100644
--- a/converter/other/fiasco/lib/error.c
+++ b/converter/other/fiasco/lib/error.c
@@ -1,11 +1,11 @@
 /*
- *  error.c:		Error handling
+ *  error.c:            Error handling
  *
- *  Written by:		Stefan Frank
- *			Ullrich Hafner
+ *  Written by:         Stefan Frank
+ *                      Ullrich Hafner
  *
- *  Credits:	Modelled after variable argument routines from Jef
- *		Poskanzer's pbmplus package.
+ *  Credits:    Modelled after variable argument routines from Jef
+ *              Poskanzer's pbmplus package.
  *
  *  This file is part of FIASCO (Fractal Image And Sequence COdec)
  *  Copyright (C) 1994-2000 Ullrich Hafner
@@ -24,7 +24,7 @@
 #include <string.h>
 
 #if HAVE_SETJMP_H
-#	include <setjmp.h>
+#       include <setjmp.h>
 #endif /* HAVE_SETJMP_H */
 
 #include "types.h"
@@ -36,12 +36,12 @@
 
 /*****************************************************************************
 
-			     local variables
+                             local variables
 
 *****************************************************************************/
 
 static fiasco_verbosity_e  verboselevel  = FIASCO_SOME_VERBOSITY;
-static char 	      	  *error_message = NULL;
+static char               *error_message = NULL;
 
 #if HAVE_SETJMP_H
 jmp_buf env;
@@ -49,7 +49,7 @@ jmp_buf env;
 
 /*****************************************************************************
 
-			       public code
+                               public code
 
 *****************************************************************************/
 
@@ -195,7 +195,7 @@ warning(const char * const format, ...) {
 /*----------------------------------------------------------------------------
   Issue a warning.
 -----------------------------------------------------------------------------*/
-    va_list	args;
+    va_list     args;
 
     VA_START (args, format);
 
diff --git a/converter/other/fiasco/lib/error.h b/converter/other/fiasco/lib/error.h
index 4159ccd2..dd6a049f 100644
--- a/converter/other/fiasco/lib/error.h
+++ b/converter/other/fiasco/lib/error.h
@@ -1,6 +1,6 @@
 /*
  *  error.h
- *  
+ *
  *  Written by:     Stefan Frank
  *          Ullrich Hafner
  *
@@ -19,11 +19,11 @@ void
 file_error (const char *filename);
 void
 message (const char *format, ...);
-void 
+void
 debug_message (const char *format, ...);
 void
 warning (const char *format, ...);
-void 
+void
 info (const char *format, ...);
 const char *
 get_system_error (void);
diff --git a/converter/other/fiasco/lib/image.h b/converter/other/fiasco/lib/image.h
index c3c5f0df..d6a3c6c0 100644
--- a/converter/other/fiasco/lib/image.h
+++ b/converter/other/fiasco/lib/image.h
@@ -1,8 +1,8 @@
 /*
  *  image.h
  *
- *  Written by:		Ullrich Hafner
- *		
+ *  Written by:         Ullrich Hafner
+ *              
  *  This file is part of FIASCO (Fractal Image And Sequence COdec)
  *  Copyright (C) 1994-2000 Ullrich Hafner
  */
@@ -31,11 +31,11 @@ typedef struct image
 {
    char      id [8];         /* NUL-terminated "IFIASCO" */
    unsigned  reference_count;
-   unsigned  width;			/* Width of the image */
-   unsigned  height;			/* Height of the image */
-   bool_t    color;			/* Color or grayscale image */
-   format_e  format;			/* Pixel format 4:4:4 or 4:2:0 */
-   word_t   *pixels [3];		/* Pixels in short format */
+   unsigned  width;                     /* Width of the image */
+   unsigned  height;                    /* Height of the image */
+   bool_t    color;                     /* Color or grayscale image */
+   format_e  format;                    /* Pixel format 4:4:4 or 4:2:0 */
+   word_t   *pixels [3];                /* Pixels in short format */
 } image_t;
 
 image_t *
@@ -48,7 +48,7 @@ void
 free_image (image_t *image);
 FILE *
 read_pnmheader (const char *image_name, unsigned *width, unsigned *height,
-		bool_t *color);
+                bool_t *color);
 
 image_t *
 read_image_stream(FILE *       const ifP,
diff --git a/converter/other/fiasco/lib/list.c b/converter/other/fiasco/lib/list.c
index b67ff4b8..24ba4985 100644
--- a/converter/other/fiasco/lib/list.c
+++ b/converter/other/fiasco/lib/list.c
@@ -1,8 +1,8 @@
 /*
- *  list.c:		List operations	
+ *  list.c:             List operations
+ *
+ *  Written by:         Ullrich Hafner
  *
- *  Written by:		Ullrich Hafner
- *		
  *  This file is part of FIASCO (Fractal Image And Sequence COdec)
  *  Copyright (C) 1994-2000 Ullrich Hafner
  */
@@ -27,8 +27,8 @@
 
 /*****************************************************************************
 
-				public code
-  
+                                public code
+
 *****************************************************************************/
 
 list_t *
@@ -39,15 +39,15 @@ alloc_list (size_t size_of_element)
  *  Size of list element values is given by 'size_of_element'.
  *
  *  Return value:
- *	pointer to an empty list
+ *      pointer to an empty list
  */
 {
    list_t *new_list = Calloc (1, sizeof (list_t));
 
    assert (size_of_element > 0);
 
-   new_list->head 	     = NULL;
-   new_list->tail 	     = NULL;
+   new_list->head            = NULL;
+   new_list->tail            = NULL;
    new_list->size_of_element = size_of_element;
 
    return new_list;
@@ -62,11 +62,11 @@ free_list (list_t *list)
  *  No return value.
  *
  *  Side effects:
- *	struct 'list' is discarded
+ *      struct 'list' is discarded
  */
 {
    assert (list);
-   
+
    while (list_remove (list, HEAD, NULL))
       ;
    Free (list);
@@ -76,7 +76,7 @@ void
 list_insert (list_t *list, pos_e pos, const void *data)
 /*
  *  Insert a new 'list' element at head ('pos' = HEAD) or
- *  tail ('pos' = TAIL) of 'list'. 
+ *  tail ('pos' = TAIL) of 'list'.
  *  'data' is a pointer to a memory segment of size
  *  'list'->size_of_element containing the value to store.
  *  The value is directly copied - no references are stored.
@@ -84,14 +84,14 @@ list_insert (list_t *list, pos_e pos, const void *data)
  *  No return value.
  *
  *  Side effects:
- *	lists current tail or head is replaced by the new element
+ *      lists current tail or head is replaced by the new element
  */
 {
    node_t *element;
 
    assert (list && data);
 
-   element 	  = Calloc (1, sizeof (node_t));
+   element        = Calloc (1, sizeof (node_t));
    element->value = Calloc (1, list->size_of_element);
    memcpy (element->value, data, list->size_of_element);
 
@@ -100,20 +100,20 @@ list_insert (list_t *list, pos_e pos, const void *data)
       element->next = NULL;
       element->prev = list->tail;
       if (list->tail)
-	 list->tail->next = element;
+         list->tail->next = element;
       list->tail = element;
       if (!list->head)
-	 list->head = element;
+         list->head = element;
    }
-   else					/* pos == HEAD */
+   else                                 /* pos == HEAD */
    {
       element->prev = NULL;
       element->next = list->head;
       if (list->head)
-	 list->head->prev = element;
+         list->head->prev = element;
       list->head = element;
       if (!list->tail)
-	 list->tail = element;
+         list->tail = element;
    }
 }
 
@@ -123,57 +123,57 @@ list_remove (list_t *list, pos_e pos, void *data)
  *  Remove 'list' element from head or tail of 'list'.
  *
  *  Return value:
- *	TRUE on success,
- *	FALSE if list is empty or
- *	      if list value data is NULL
+ *      TRUE on success,
+ *      FALSE if list is empty or
+ *            if list value data is NULL
  *
  *  Side effects:
- *	lists current head or tail is removed
- *	value of the removed list element (if not NULL) is copied to
+ *      lists current head or tail is removed
+ *      value of the removed list element (if not NULL) is copied to
  *      'data' (if 'data' is not NULL)
  */
 {
    node_t *element;
-   void	  *valueptr;
+   void   *valueptr;
 
    assert (list);
-   
+
    if (pos == TAIL)
    {
       element = list->tail;
       if (element)
       {
-	 list->tail = element->prev;
-	 valueptr   = element->value;
-	 Free (element);
+         list->tail = element->prev;
+         valueptr   = element->value;
+         Free (element);
       }
       else
-	 valueptr = NULL;
-      if (!list->tail)			/* 'element' was last node */
-	 list->head = NULL;
+         valueptr = NULL;
+      if (!list->tail)                  /* 'element' was last node */
+         list->head = NULL;
    }
-   else					/* pos == HEAD */
+   else                                 /* pos == HEAD */
    {
       element = list->head;
       if (element)
       {
-	 list->head = element->next;
-	 valueptr   = element->value;
-	 Free (element);
+         list->head = element->next;
+         valueptr   = element->value;
+         Free (element);
       }
       else
-	 valueptr = NULL;
-      if (!list->head)			/* 'element' was last node */
-	 list->tail = NULL;
+         valueptr = NULL;
+      if (!list->head)                  /* 'element' was last node */
+         list->tail = NULL;
    }
 
-   if (valueptr)			/* copy value of node */
+   if (valueptr)                        /* copy value of node */
    {
-      if (data)				
-	 memcpy (data, valueptr, list->size_of_element);
+      if (data)
+         memcpy (data, valueptr, list->size_of_element);
       Free (valueptr);
    }
-   
+
    return valueptr ? TRUE : FALSE;
 }
 
@@ -184,27 +184,27 @@ list_element_n (const list_t *list, pos_e pos, unsigned n, void *data)
  *  (First element is list head if 'pos' == HEAD
  *                 or list tail if 'pos' == TAIL.
  *   Accordingly, traverse the list in ascending or descending order).
- *  
+ *
  *  Return value:
- *	TRUE on success, FALSE if there is no element 'n'
+ *      TRUE on success, FALSE if there is no element 'n'
  *
  *  Side effects:
- *	value of list element 'n' is copied to 'data' 
+ *      value of list element 'n' is copied to 'data'
  */
 {
    node_t *element;
 
    assert (list && data);
-   
+
    if (pos == HEAD)
       for (element = list->head; element != NULL && n;
-	   element = element->next, n--)
-	 ;
+           element = element->next, n--)
+         ;
    else
       for (element = list->tail; element != NULL && n;
-	   element = element->prev, n--)
-	 ;
-      
+           element = element->prev, n--)
+         ;
+
    if (element)
    {
       memcpy (data, element->value, list->size_of_element);
@@ -220,14 +220,14 @@ list_sizeof (const list_t *list)
  *  Count number of 'list' elements.
  *
  *  Return value:
- *	number of 'list' elements.
+ *      number of 'list' elements.
  */
 {
    node_t   *element;
    unsigned  n = 0;
 
    assert (list);
-   
+
    for (element = list->head; element != NULL; element = element->next)
       n++;
 
@@ -247,7 +247,7 @@ list_foreach (const list_t *list, void (*function)(void *, void *), void *data)
    node_t *element;
 
    assert (list && function && data);
-   
+
    for (element = list->head; element; element = element->next)
       function (element->value, data);
 }
diff --git a/converter/other/fiasco/lib/list.h b/converter/other/fiasco/lib/list.h
index 68577dfd..3ba860c0 100644
--- a/converter/other/fiasco/lib/list.h
+++ b/converter/other/fiasco/lib/list.h
@@ -1,8 +1,8 @@
 /*
  *  list.h
  *
- *  Written by:		Ullrich Hafner
- *		
+ *  Written by:         Ullrich Hafner
+ *
  *  This file is part of FIASCO (Fractal Image And Sequence COdec)
  *  Copyright (C) 1994-2000 Ullrich Hafner
  */
@@ -22,16 +22,16 @@
 
 typedef struct node
 {
-   struct node *prev;			/* pointer to prev list element */
-   struct node *next;			/* pointer to next list element */
-   void	       *value;			/* pointer to value of node */
+   struct node *prev;                   /* pointer to prev list element */
+   struct node *next;                   /* pointer to next list element */
+   void        *value;                  /* pointer to value of node */
 } node_t;
 
 typedef struct list
 {
    node_t *head;
    node_t *tail;
-   size_t  size_of_element;		/* number of bytes to store value */
+   size_t  size_of_element;             /* number of bytes to store value */
 } list_t;
 
 typedef enum {TAIL, HEAD} pos_e;
@@ -41,26 +41,26 @@ typedef enum {TAIL, HEAD} pos_e;
  */
 
 typedef list_t lqueue_t ;
-#define alloc_queue		alloc_list
-#define free_queue		free_list		
-#define queue_append(q, d)	(list_insert ((q), TAIL, (d)))
-#define queue_remove(q, d)	(list_remove ((q), HEAD, (d)))
+#define alloc_queue             alloc_list
+#define free_queue              free_list
+#define queue_append(q, d)      (list_insert ((q), TAIL, (d)))
+#define queue_remove(q, d)      (list_remove ((q), HEAD, (d)))
 
 typedef list_t lstack_t ;
-#define alloc_stack		alloc_list
-#define free_stack		free_list
-#define stack_push(q, d)	(list_insert ((q), TAIL, (d)))
-#define stack_pop(q, d)		(list_remove ((q), TAIL, (d)))
+#define alloc_stack             alloc_list
+#define free_stack              free_list
+#define stack_push(q, d)        (list_insert ((q), TAIL, (d)))
+#define stack_pop(q, d)         (list_remove ((q), TAIL, (d)))
 
 list_t *
 alloc_list (size_t size_of_element);
-void 
+void
 free_list (list_t *list);
 bool_t
 list_element_n (const list_t *list, pos_e pos, unsigned n, void *data);
 void
 list_foreach (const list_t *list, void (*function)(void *, void *),
-	      void *data);
+              void *data);
 void
 list_insert (list_t *list, pos_e pos, const void *data);
 bool_t
diff --git a/converter/other/fiasco/lib/macros.h b/converter/other/fiasco/lib/macros.h
index 2f404a74..aafea45b 100644
--- a/converter/other/fiasco/lib/macros.h
+++ b/converter/other/fiasco/lib/macros.h
@@ -1,8 +1,8 @@
 /*
  *  macros.h
  *
- *  Written by:		Ullrich Hafner
- *		
+ *  Written by:         Ullrich Hafner
+ *
  *  This file is part of FIASCO (Fractal Image And Sequence COdec)
  *  Copyright (C) 1994-2000 Ullrich Hafner
  */
@@ -20,34 +20,34 @@
 #include <string.h>
 /*******************************************************************************
 
-			  System configuration section
-  
+                          System configuration section
+
 *******************************************************************************/
 
 #ifndef SEEK_CUR
-#   define SEEK_CUR	1
+#   define SEEK_CUR     1
 #endif /* not SEEK_CUR */
 
 /*****************************************************************************
 
-				Various macros
-  
+                                Various macros
+
 *****************************************************************************/
 
-#define square(x)		((x) * (x))
-#define first_band(color)	((unsigned) ((color) ? Y  : GRAY))
+#define square(x)               ((x) * (x))
+#define first_band(color)       ((unsigned) ((color) ? Y  : GRAY))
 #define last_band(color)        ((unsigned) ((color) ? Cr : GRAY))
-#define width_of_level(l)	((unsigned) (1 << ((l) >> 1)))
-#define height_of_level(l)	((unsigned) (1 << (((l) + 1) >> 1)))
-#define size_of_level(l)	((unsigned) (1 << (l)))
-#define address_of_level(l)	((unsigned) (size_of_level (l) - 1))
-#define size_of_tree(l)		((unsigned) (address_of_level ((l) + 1)))
-#define is_odd(n)		(abs (n) % 2)
-#define _(x) (x) 
+#define width_of_level(l)       ((unsigned) (1 << ((l) >> 1)))
+#define height_of_level(l)      ((unsigned) (1 << (((l) + 1) >> 1)))
+#define size_of_level(l)        ((unsigned) (1 << (l)))
+#define address_of_level(l)     ((unsigned) (size_of_level (l) - 1))
+#define size_of_tree(l)         ((unsigned) (address_of_level ((l) + 1)))
+#define is_odd(n)               (abs (n) % 2)
+#define _(x) (x)
 
 
-#define	MAXSTRLEN 1024
-#define	MAXSTRLEN_SCANF "%1024s"
+#define MAXSTRLEN 1024
+#define MAXSTRLEN_SCANF "%1024s"
 
 typedef enum color {GRAY = 0, Y = 0, Cb = 1, Cr = 2} color_e;
 
diff --git a/converter/other/fiasco/lib/misc.c b/converter/other/fiasco/lib/misc.c
index c5629c5c..d02511de 100644
--- a/converter/other/fiasco/lib/misc.c
+++ b/converter/other/fiasco/lib/misc.c
@@ -1,11 +1,11 @@
 /*
- *  misc.c:		Some useful functions, that don't fit in one of 
- *			the other files and that are needed by at least
- *			two modules. 
+ *  misc.c:             Some useful functions, that don't fit in one of
+ *                      the other files and that are needed by at least
+ *                      two modules.
+ *
+ *  Written by:         Stefan Frank
+ *                      Ullrich Hafner
  *
- *  Written by:		Stefan Frank
- *			Ullrich Hafner
- *		
  *  This file is part of FIASCO (Fractal Image And Sequence COdec)
  *  Copyright (C) 1994-2000 Ullrich Hafner
  */
@@ -23,14 +23,14 @@
 #include <ctype.h>
 
 #ifdef TIME_WITH_SYS_TIME
-#	include <sys/time.h>
-#	include <time.h>
+#       include <sys/time.h>
+#       include <time.h>
 #else  /* not TIME_WITH_SYS_TIME */
-#	if HAVE_SYS_TIME_H
-#		include <sys/time.h>
-#	else /* not HAVE_SYS_TIME_H */
-#		include <time.h>
-#	endif /* not HAVE_SYS_TIME_H */
+#       if HAVE_SYS_TIME_H
+#               include <sys/time.h>
+#       else /* not HAVE_SYS_TIME_H */
+#               include <time.h>
+#       endif /* not HAVE_SYS_TIME_H */
 #endif /* not TIME_WITH_SYS_TIME */
 
 #include <stdlib.h>
@@ -47,8 +47,8 @@
 
 /*****************************************************************************
 
-				prototypes
-  
+                                prototypes
+
 *****************************************************************************/
 
 static void
@@ -56,8 +56,8 @@ remove_comments (FILE *file);
 
 /*****************************************************************************
 
-				public code
-  
+                                public code
+
 *****************************************************************************/
 
 void *
@@ -66,14 +66,14 @@ Calloc (size_t n, size_t size)
  *  Allocate memory like calloc ().
  *
  *  Return value: Pointer to the new block of memory on success,
- *		  otherwise the program is terminated.
+ *                otherwise the program is terminated.
  */
 {
-   void	*ptr;				/* pointer to the new memory block */
+   void *ptr;                           /* pointer to the new memory block */
 
    if (n <= 0 || size <= 0)
       error ("Can't allocate memory for %d items of size %d",
-	     (int) n, (int) size);
+             (int) n, (int) size);
 
    ptr = calloc (n, size);
    if (!ptr)
@@ -100,20 +100,20 @@ unsigned
 prg_timer (clock_t *last_timer, enum action_e action)
 /*
  *  If 'action' == START then store current value of system timer.
- *  If 'action' == STOP	 then compute number of elapsed micro seconds since
- *			 the last time 'prg_timer' was called
- *			 with 'action' == START.
+ *  If 'action' == STOP  then compute number of elapsed micro seconds since
+ *                       the last time 'prg_timer' was called
+ *                       with 'action' == START.
  *
  *  Return value:
- *	Number of elapsed micro seconds if 'action' == STOP
- *	0				if 'action' == START
+ *      Number of elapsed micro seconds if 'action' == STOP
+ *      0                               if 'action' == START
  *
  *  Side effects:
- *	last_timer is set to current timer if action == START
+ *      last_timer is set to current timer if action == START
  */
 {
    assert (last_timer);
-   
+
    if (action == START)
    {
       *last_timer = clock ();
@@ -123,19 +123,19 @@ prg_timer (clock_t *last_timer, enum action_e action)
       return (clock () - *last_timer) / (CLOCKS_PER_SEC / 1000.0);
 }
 
-real_t 
+real_t
 read_real (FILE *infile)
-/* 
+/*
  *  Read one real value from the given input stream 'infile'.
- *  
+ *
  *  Return value:
- *	real value on success
+ *      real value on success
  */
 {
    float input;
 
    assert (infile);
-   
+
    remove_comments (infile);
    if (fscanf(infile, "%f", &input) != 1)
       error("Can't read float value!");
@@ -143,26 +143,26 @@ read_real (FILE *infile)
    return (real_t) input;
 }
 
-int 
+int
 read_int (FILE *infile)
-/* 
+/*
  *  Read one integer value from the given input stream 'infile'.
  *
  *  Return value:
- *	integer value on success
+ *      integer value on success
  */
 {
-   int input;				/* integer */
+   int input;                           /* integer */
 
    assert (infile);
-   
+
    remove_comments (infile);
    if (fscanf(infile, "%d", &input) != 1)
       error("Can't read integer value!");
 
    return input;
 }
-   
+
 static void
 remove_comments (FILE *file)
 /*
@@ -171,27 +171,27 @@ remove_comments (FILE *file)
  *  No return value.
  */
 {
-   int c;				/* current character */
-   
+   int c;                               /* current character */
+
    assert (file);
-   
+
    do
    {
       while (isspace(c = getc (file)))
-	 ;
+         ;
       if (c == EOF)
-	 error ("EOF reached, input seems to be truncated!");
+         error ("EOF reached, input seems to be truncated!");
       if (c == '#')
       {
-	 int dummy;
-	 
-	 while (((dummy = getc (file)) != '\n') && dummy != EOF)
-	    ;
-	 if (dummy == EOF)
-	    error ("EOF reached, input seems to be truncated!");
+         int dummy;
+
+         while (((dummy = getc (file)) != '\n') && dummy != EOF)
+            ;
+         if (dummy == EOF)
+            error ("EOF reached, input seems to be truncated!");
       }
-      else 
-	 ungetc (c, file);
+      else
+         ungetc (c, file);
    } while (c == '#');
 }
 
@@ -203,10 +203,10 @@ write_rice_code (unsigned value, unsigned rice_k, bitfile_t *output)
  *  No return value.
  */
 {
-   unsigned unary;			/* unary part of Rice Code */
+   unsigned unary;                      /* unary part of Rice Code */
 
    assert (output);
-   
+
    for (unary = value >> rice_k; unary; unary--)
       put_bit (output, 1);
    put_bit (output, 0);
@@ -219,13 +219,13 @@ read_rice_code (unsigned rice_k, bitfile_t *input)
  *  Read a Rice encoded integer (base 'rice_k') from the stream 'input'.
  *
  *  Return value:
- *	decoded integer
+ *      decoded integer
  */
 {
-   unsigned unary;			/* unary part of Rice code */
-   
+   unsigned unary;                      /* unary part of Rice code */
+
    assert (input);
-   
+
    for (unary = 0; get_bit (input); unary++) /* unary part */
       ;
 
@@ -243,15 +243,15 @@ write_bin_code (unsigned value, unsigned maxval, bitfile_t *output)
 {
    unsigned k;
    unsigned r;
-   
+
    assert (output && maxval && value <= maxval);
 
    k = log2 (maxval + 1);
    r = (maxval + 1) % (1 << k);
 
-   if (value < maxval + 1 - 2 * r)	/* 0, ... , maxval - 2r */
+   if (value < maxval + 1 - 2 * r)      /* 0, ... , maxval - 2r */
       put_bits (output, value, k);
-   else					/* maxval - 2r + 1, ..., maxval */
+   else                                 /* maxval - 2r + 1, ..., maxval */
       put_bits (output, value + maxval + 1 - 2 * r, k + 1);
 }
 
@@ -261,13 +261,13 @@ read_bin_code (unsigned maxval, bitfile_t *input)
  *  Read a bincode encoded integer from the stream 'input'.
  *
  *  Return value:
- *	decoded integer
+ *      decoded integer
  */
 {
    unsigned k;
    unsigned r;
    unsigned value;
-   
+
    assert (input);
 
    k = log2 (maxval + 1);
@@ -280,7 +280,7 @@ read_bin_code (unsigned maxval, bitfile_t *input)
    {
       value <<= 1;
       if (get_bit (input))
-	 value++;
+         value++;
       return value - maxval - 1 + 2 * r;
    }
 }
@@ -292,12 +292,12 @@ bits_rice_code (unsigned value, unsigned rice_k)
  *  with given Rice code 'rice_k'.
  *
  *  Return value:
- *	number of bits
+ *      number of bits
  */
 {
    unsigned unary;
    unsigned bits = 0;
-   
+
    for (unary = value >> rice_k; unary; unary--)
       bits++;
    bits += rice_k + 1;
@@ -312,7 +312,7 @@ bits_bin_code (unsigned value, unsigned maxval)
  *  with adjusted binary code of given maximum value 'maxval'.
  *
  *  Return value:
- *	number of bits
+ *      number of bits
  */
 {
    unsigned k;
@@ -332,30 +332,30 @@ init_clipping (void)
  *  Initialize the clipping tables
  *
  *  Return value:
- *	pointer to clipping table
+ *      pointer to clipping table
  */
 {
-   static unsigned *gray_clip = NULL;	/* clipping array */
+   static unsigned *gray_clip = NULL;   /* clipping array */
 
-   if (gray_clip == NULL)		/* initialize clipping table */
+   if (gray_clip == NULL)               /* initialize clipping table */
    {
-      int i;				/* counter */
+      int i;                            /* counter */
 
       gray_clip  = calloc (256 * 3, sizeof (unsigned));
       if (!gray_clip)
       {
-	 set_error (_("Out of memory."));
-	 return NULL;
+         set_error (_("Out of memory."));
+         return NULL;
       }
       gray_clip += 256;
 
       for (i = -256; i < 512; i++)
-	 if (i < 0)
-	    gray_clip [i] = 0;
-	 else if (i > 255)
-	    gray_clip [i] = 255;
-	 else
-	    gray_clip [i] = i;
+         if (i < 0)
+            gray_clip [i] = 0;
+         else if (i > 255)
+            gray_clip [i] = 255;
+         else
+            gray_clip [i] = i;
    }
 
    return gray_clip;
@@ -369,29 +369,29 @@ memmove (void *v_dst, const void *v_src, size_t n)
  *  The memory areas may overlap.
  *
  *  Return value:
- *	pointer 'dest'
+ *      pointer 'dest'
  */
 {
-   byte_t	*to, *dst = (byte_t *) v_dst;
-   const byte_t	*from, *src = (byte_t *) v_src;
-   
+   byte_t       *to, *dst = (byte_t *) v_dst;
+   const byte_t *from, *src = (byte_t *) v_src;
+
    assert (v_dst && v_src);
-   
+
    if (dst <= src)
    {
       from = src;
       to   = dst;
       for (; n; n--)
-	 *to++ = *from++;
+         *to++ = *from++;
    }
    else
-   { 
+   {
       from = src + (n - 1);
       to   = dst + (n - 1);
       for (; n; n--)
-	 *to-- = *from--;
+         *to-- = *from--;
    }
-   
+
    return v_dst;
 }
 #endif /* not HAVE_MEMMOVE */
@@ -405,7 +405,7 @@ double
 Log2 (double x)
 /*
  *  Return value:
- *	base-2 logarithm of 'x'
+ *      base-2 logarithm of 'x'
  */
 {
    return log (x) / 0.69314718;
@@ -413,32 +413,32 @@ Log2 (double x)
 
 real_t
 variance (const word_t *pixels, unsigned x0, unsigned y0,
-	  unsigned width, unsigned height, unsigned cols)
+          unsigned width, unsigned height, unsigned cols)
 /*
- *  Compute variance of subimage ('x0', y0', 'width', 'height') of 
+ *  Compute variance of subimage ('x0', y0', 'width', 'height') of
  *  the image data given by 'pixels' ('cols' is the number of pixels
  *  in one row of the image).
  *
  *  Return value:
- *	variance
+ *      variance
  */
 {
-   real_t   average;			/* average of pixel values */
-   real_t   variance;			/* variance of pixel values */
-   unsigned x, y;			/* pixel counter */
-   unsigned n;				/* number of pixels */
+   real_t   average;                    /* average of pixel values */
+   real_t   variance;                   /* variance of pixel values */
+   unsigned x, y;                       /* pixel counter */
+   unsigned n;                          /* number of pixels */
 
    assert (pixels);
-   
+
    for (average = 0, n = 0, y = y0; y < y0 + height; y++)
       for (x = x0; x < MIN(x0 + width, cols); x++, n++)
-	 average += pixels [y * cols + x] / 16;
+         average += pixels [y * cols + x] / 16;
 
    average /= n;
 
    for (variance = 0, y = y0; y < y0 + height; y++)
       for (x = x0; x < MIN(x0 + width, cols); x++)
-	 variance += square ((pixels [y * cols + x] / 16) - average);
+         variance += square ((pixels [y * cols + x] / 16) - average);
 
    return variance;
 }
@@ -482,7 +482,7 @@ sort_asc_pair (const void *value1, const void *value2)
 {
    word_t v1 = ((pair_t *) value1)->key;
    word_t v2 = ((pair_t *) value2)->key;
-   
+
    if (v1 < v2)
       return -1;
    else if (v1 > v2)
diff --git a/converter/other/fiasco/lib/misc.h b/converter/other/fiasco/lib/misc.h
index 6f643b7a..48f8bdaa 100644
--- a/converter/other/fiasco/lib/misc.h
+++ b/converter/other/fiasco/lib/misc.h
@@ -1,9 +1,9 @@
 /*
  *  misc.h
  *
- *  Written by:		Stefan Frank
- *			Ullrich Hafner
- *		
+ *  Written by:         Stefan Frank
+ *                      Ullrich Hafner
+ *
  *  This file is part of FIASCO (Fractal Image And Sequence COdec)
  *  Copyright (C) 1994-2000 Ullrich Hafner
  */
@@ -21,14 +21,14 @@
 #include "config.h"
 
 #if TIME_WITH_SYS_TIME
-#	include <sys/time.h>
-#	include <time.h>
+#       include <sys/time.h>
+#       include <time.h>
 #else  /* not TIME_WITH_SYS_TIME */
-#	if HAVE_SYS_TIME_H
-#		include <sys/time.h>
-#	else /* not HAVE_SYS_TIME_H */
-#		include <time.h>
-#	endif /* not HAVE_SYS_TIME_H */
+#       if HAVE_SYS_TIME_H
+#               include <sys/time.h>
+#       else /* not HAVE_SYS_TIME_H */
+#               include <time.h>
+#       endif /* not HAVE_SYS_TIME_H */
 #endif /* not TIME_WITH_SYS_TIME */
 
 #include <stdio.h>
@@ -43,9 +43,9 @@ void
 Free (void *memory);
 unsigned
 prg_timer (clock_t *ptimer, enum action_e action);
-int 
+int
 read_int(FILE *infile);
-real_t 
+real_t
 read_real(FILE *infile);
 unsigned
 read_rice_code (unsigned rice_k, bitfile_t *input);
@@ -63,7 +63,7 @@ unsigned *
 init_clipping (void);
 real_t
 variance (const word_t *pixels, unsigned x0, unsigned y0,
-	  unsigned width, unsigned height, unsigned cols);
+          unsigned width, unsigned height, unsigned cols);
 
 #ifndef HAVE_MEMMOVE
 void *
diff --git a/converter/other/fiasco/lib/mvcode.c b/converter/other/fiasco/lib/mvcode.c
index d9ce91e2..0e6b6626 100644
--- a/converter/other/fiasco/lib/mvcode.c
+++ b/converter/other/fiasco/lib/mvcode.c
@@ -8,7 +8,7 @@ unsigned mv_code_table [33][2] =
    {0x19, 11}, {0x1b, 11}, {0x1d, 11}, {0x1f, 11}, {0x21, 11}, {0x23, 11},
    {0x13, 10}, {0x15, 10}, {0x17, 10}, {0x7, 8}, {0x9, 8}, {0xb, 8}, {0x7, 7},
    {0x3, 5}, {0x3, 4}, {0x3, 3}, {0x1, 1}, {0x2, 3}, {0x2, 4}, {0x2, 5},
-   {0x6, 7}, {0xa, 8}, {0x8, 8}, {0x6, 8}, {0x16, 10}, {0x14, 10}, {0x12, 10}, 
+   {0x6, 7}, {0xa, 8}, {0x8, 8}, {0x6, 8}, {0x16, 10}, {0x14, 10}, {0x12, 10},
    {0x22, 11}, {0x20, 11}, {0x1e, 11}, {0x1c, 11}, {0x1a, 11}, {0x18, 11}
 };
 
diff --git a/converter/other/fiasco/lib/rpf.c b/converter/other/fiasco/lib/rpf.c
index e6ff6e09..61e2f953 100644
--- a/converter/other/fiasco/lib/rpf.c
+++ b/converter/other/fiasco/lib/rpf.c
@@ -4,7 +4,7 @@
  *  Written by:     Stefan Frank
  *          Richard Krampfl
  *          Ullrich Hafner
- *      
+ *
  *  This file is part of FIASCO («F»ractal «I»mage «A»nd «S»equence «CO»dec)
  *  Copyright (C) 1994-2000 Ullrich Hafner <hafner@bigfoot.de>
  */
@@ -32,7 +32,7 @@ int const RPF_ZERO = -1;
 /*****************************************************************************
 
                    private code
-  
+
 *****************************************************************************/
 
 
@@ -62,25 +62,25 @@ rtob (real_t        const f,
  *  Convert real number 'f' into fixed point format.
  *  The real number in [-'range'; +'range'] is scaled to [-1 ; +1].
  *  Sign and the first 'precision' - 1 bits of the mantissa are
- *  packed into one integer.  
+ *  packed into one integer.
  *
  *  Return value:
  *  real value in reduced precision format
  */
-{  
+{
     /*
      *  Extract mantissa (23 Bits), exponent (8 Bits) and sign (1 Bit)
      */
 
     double const normalized = f / rpfP->range;
-        /* 'f' scaled to [-1,+1] */    
+        /* 'f' scaled to [-1,+1] */
     FracExp const fracExp = fracExpFromDouble(normalized);
     unsigned int const signedMantissa =
         (unsigned int) (fracExp.fraction * (1<<23));
 
     unsigned int mantissa;
     unsigned int sign;  /* 0 for positive; 1 for negative */
-    
+
     if (signedMantissa < 0) {
         mantissa = -signedMantissa;
         sign = 1;
@@ -92,16 +92,16 @@ rtob (real_t        const f,
     /*
      *  Generate reduced precision mantissa.
      */
-    if (fracExp.exponent > 0) 
+    if (fracExp.exponent > 0)
         mantissa <<= fracExp.exponent;
     else
-        mantissa >>= -fracExp.exponent;  
-    
+        mantissa >>= -fracExp.exponent;
+
     mantissa >>= (23 - rpfP->mantissa_bits - 1);
 
     mantissa +=  1;          /* Round last bit. */
     mantissa >>= 1;
-   
+
     if (mantissa == 0)           /* close to zero */
         return RPF_ZERO;
     else if (mantissa >= (1U << rpfP->mantissa_bits)) /* overflow */
@@ -126,7 +126,7 @@ btor (int           const binary,
     unsigned int mantissa;
     float sign;
     float f;
- 
+
     if (binary == RPF_ZERO)
         return 0;
 
@@ -137,16 +137,16 @@ btor (int           const binary,
      *  Restore IEEE float format:
      *  mantissa (23 Bits), exponent (8 Bits) and sign (1 Bit)
      */
-   
+
     sign       = (binary & 0x1) == 0 ? 1.0 : -1.0;
-    mantissa   = (binary & ((0x1 << (rpfP->mantissa_bits + 1)) - 1)) >> 1; 
+    mantissa   = (binary & ((0x1 << (rpfP->mantissa_bits + 1)) - 1)) >> 1;
     mantissa <<= (23 - rpfP->mantissa_bits);
 
-    if (mantissa == 0) 
+    if (mantissa == 0)
         f = sign;
     else
         f =  sign * (float) mantissa / 8388608;
-   
+
     return f * rpfP->range;       /* expand [ -1 ; +1 ] to
                                      [ -range ; +range ] */
 }
@@ -163,7 +163,7 @@ alloc_rpf (unsigned           const mantissa,
  *  Number of mantissa bits is given by `mantissa'.
  *  The range of the real values is in the interval [-`range', +`range'].
  *  In case of invalid parameters, a structure with default values is
- *  returned. 
+ *  returned.
  *
  *  Return value
  *  pointer to the new rpf structure
@@ -172,7 +172,7 @@ alloc_rpf (unsigned           const mantissa,
     rpf_t * rpfP;
 
     MALLOCVAR(rpfP);
-   
+
     if (mantissa < 2) {
         warning (_("Size of RPF mantissa has to be in the interval [2,8]. "
                    "Using minimum value 2.\n"));
diff --git a/converter/other/fiasco/lib/rpf.h b/converter/other/fiasco/lib/rpf.h
index e543f855..19e330fb 100644
--- a/converter/other/fiasco/lib/rpf.h
+++ b/converter/other/fiasco/lib/rpf.h
@@ -1,10 +1,10 @@
 /*
  *  rpf.h
  *
- *  Written by:		Stefan Frank
- *			Richard Krampfl
- *			Ullrich Hafner
- *		
+ *  Written by:         Stefan Frank
+ *                      Richard Krampfl
+ *                      Ullrich Hafner
+ *
  *  This file is part of FIASCO (Fractal Image And Sequence COdec)
  *  Copyright (C) 1994-2000 Ullrich Hafner
  */
@@ -24,14 +24,14 @@
 
 typedef struct rpf
 {
-   unsigned    	      mantissa_bits;	/* number of bits used for mantissa */
-   real_t      	      range;		/* scale value to [-range, +range] */
+   unsigned           mantissa_bits;    /* number of bits used for mantissa */
+   real_t             range;            /* scale value to [-range, +range] */
    fiasco_rpf_range_e range_e;
 } rpf_t;
 
 int
 rtob (real_t real, const rpf_t *rpf);
-real_t 
+real_t
 btor (int b, const rpf_t *rpf);
 rpf_t *
 alloc_rpf (unsigned mantissa, fiasco_rpf_range_e range);
diff --git a/converter/other/fiasco/lib/types.h b/converter/other/fiasco/lib/types.h
index 02e40a90..ce216ce5 100644
--- a/converter/other/fiasco/lib/types.h
+++ b/converter/other/fiasco/lib/types.h
@@ -2,7 +2,7 @@
  *  types.h
  *
  *  Written by:     Ullrich Hafner
- *      
+ *
  *  This file is part of FIASCO (Fractal Image And Sequence COdec)
  *  Copyright (C) 1994-2000 Ullrich Hafner
  */
diff --git a/converter/other/fiasco/output/matrices.c b/converter/other/fiasco/output/matrices.c
index 7dc0e6d9..32289dec 100644
--- a/converter/other/fiasco/output/matrices.c
+++ b/converter/other/fiasco/output/matrices.c
@@ -1,8 +1,8 @@
 /*
- *  matrices.c:		Output of transitions matrices
+ *  matrices.c:         Output of transitions matrices
+ *
+ *  Written by:         Ullrich Hafner
  *
- *  Written by:		Ullrich Hafner
- *		
  *  This file is part of FIASCO (Fractal Image And Sequence COdec)
  *  Copyright (C) 1994-2000 Ullrich Hafner
  */
@@ -38,13 +38,13 @@
 
 /*****************************************************************************
 
-				prototypes
-  
+                                prototypes
+
 *****************************************************************************/
 
 static unsigned
 delta_encoding (bool_t use_normal_domains, bool_t use_delta_domains,
-		const wfa_t *wfa, unsigned last_domain, bitfile_t *output);
+                const wfa_t *wfa, unsigned last_domain, bitfile_t *output);
 static unsigned
 column_0_encoding (const wfa_t *wfa, unsigned last_row, bitfile_t *output);
 static unsigned
@@ -52,75 +52,75 @@ chroma_encoding (const wfa_t *wfa, bitfile_t *output);
 
 /*****************************************************************************
 
-				public code
-  
+                                public code
+
 *****************************************************************************/
 
 unsigned
 write_matrices (bool_t use_normal_domains, bool_t use_delta_domains,
-		const wfa_t *wfa, bitfile_t *output)
+                const wfa_t *wfa, bitfile_t *output)
 /*
  *  Write transition matrices of 'wfa' to stream 'output'.
  *
  *  Return value:
- *	number of transitions encoded
+ *      number of transitions encoded
  */
 {
-   unsigned root_state;			/* root of luminance */
-   unsigned total = 0;			/* number of transitions */
-   
+   unsigned root_state;                 /* root of luminance */
+   unsigned total = 0;                  /* number of transitions */
+
    root_state = wfa->wfainfo->color
-		? wfa->tree [wfa->tree [wfa->root_state][0]][0]
-		: wfa->root_state;
-   
+                ? wfa->tree [wfa->tree [wfa->root_state][0]][0]
+                : wfa->root_state;
+
    total  = column_0_encoding (wfa, root_state, output);
 
    total += delta_encoding (use_normal_domains, use_delta_domains,
-			    wfa, root_state, output);
-   
+                            wfa, root_state, output);
+
    if (wfa->wfainfo->color)
       total += chroma_encoding (wfa, output);
-   
+
    return total;
 }
 
 /*****************************************************************************
 
-				private code
-  
+                                private code
+
 *****************************************************************************/
 
 static unsigned
 delta_encoding (bool_t use_normal_domains, bool_t use_delta_domains,
-		const wfa_t *wfa, unsigned last_domain, bitfile_t *output)
+                const wfa_t *wfa, unsigned last_domain, bitfile_t *output)
 /*
  *  Write transition matrices with delta coding to stream 'input'.
  *  'last_domain' is the maximum state number used as domain image.
  *
  *  Return value:
- *	number of non-zero matrix elements (WFA edges)
+ *      number of non-zero matrix elements (WFA edges)
  */
 {
-   range_sort_t	rs;			/* ranges are sorted as in the coder */
-   unsigned	max_domain;		/* dummy used for recursion */
-   unsigned	total = 0;
-      
+   range_sort_t rs;                     /* ranges are sorted as in the coder */
+   unsigned     max_domain;             /* dummy used for recursion */
+   unsigned     total = 0;
+
    /*
     *  Generate a list of range blocks.
     *  The order is the same as in the coder.
     */
    rs.range_state      = Calloc ((last_domain + 1) * MAXLABELS,
-				 sizeof (u_word_t));
+                                 sizeof (u_word_t));
    rs.range_label      = Calloc ((last_domain + 1) * MAXLABELS,
-				 sizeof (byte_t));
+                                 sizeof (byte_t));
    rs.range_max_domain = Calloc ((last_domain + 1) * MAXLABELS,
-				 sizeof (u_word_t));
+                                 sizeof (u_word_t));
    rs.range_subdivided = Calloc ((last_domain + 1) * MAXLABELS,
-				 sizeof (bool_t));
-   rs.range_no	       = 0;
-   max_domain 	       = wfa->basis_states - 1;
+                                 sizeof (bool_t));
+   rs.range_no         = 0;
+   max_domain          = wfa->basis_states - 1;
    sort_ranges (last_domain, &max_domain, &rs, wfa);
-   
+
    /*
     *  Compute and write distribution of #edges
     */
@@ -132,138 +132,138 @@ delta_encoding (bool_t use_normal_domains, bool_t use_delta_domains,
       unsigned edges = 0;
       unsigned M     = 0;
       unsigned bits  = bits_processed (output);
-      
+
       for (n = 0; n < MAXEDGES + 1; n++)
-	 count [n] = 0;
-      
+         count [n] = 0;
+
       for (state = wfa->basis_states; state <= last_domain; state++)
-	 for (label = 0; label < MAXLABELS; label++)
-	    if (isrange (wfa->tree [state][label]))
-	    {
-	       for (edge = 0; isedge (wfa->into [state][label][edge]); edge++)
-		  ;
-	       count [edge]++;
-	       edges++;
-	       M = MAX(edge, M);
-	    }
+         for (label = 0; label < MAXLABELS; label++)
+            if (isrange (wfa->tree [state][label]))
+            {
+               for (edge = 0; isedge (wfa->into [state][label][edge]); edge++)
+                  ;
+               count [edge]++;
+               edges++;
+               M = MAX(edge, M);
+            }
       write_rice_code (M, 3, output);
       for (n = 0; n <= M; n++)
 /* NETPBM: The following causes a crash when last_domain < 4, because
    it requests writing of a negative number of bits.  And we have seen
-   last_domain = 3.  But we have no clue what last_domain means, or 
+   last_domain = 3.  But we have no clue what last_domain means, or
    even what a rice code is, so we don't know where the error lies.
-   -Bryan 2001.02.09 
+   -Bryan 2001.02.09
 */
-	 write_rice_code (count [n], (int) log2 (last_domain) - 2, output);
+         write_rice_code (count [n], (int) log2 (last_domain) - 2, output);
 
       /*
        * Arithmetic coding of values */
       {
-	 unsigned  range;
-	 model_t  *elements = alloc_model (M + 1, 0, 0, count);
-	 arith_t  *encoder  = alloc_encoder (output);
-	       
-	 for (range = 0; range < rs.range_no; range++)
-	    if (!rs.range_subdivided [range])
-	    {
-	       state = rs.range_state [range];
-	       label = rs.range_label [range];
-	       for (edge = 0; isedge (wfa->into [state][label][edge]); edge++)
-		  ;
-	       
-	       encode_symbol (edge, encoder, elements);
-	    }
-	 free_encoder (encoder);
-	 free_model (elements);
+         unsigned  range;
+         model_t  *elements = alloc_model (M + 1, 0, 0, count);
+         arith_t  *encoder  = alloc_encoder (output);
+
+         for (range = 0; range < rs.range_no; range++)
+            if (!rs.range_subdivided [range])
+            {
+               state = rs.range_state [range];
+               label = rs.range_label [range];
+               for (edge = 0; isedge (wfa->into [state][label][edge]); edge++)
+                  ;
+
+               encode_symbol (edge, encoder, elements);
+            }
+         free_encoder (encoder);
+         free_model (elements);
       }
       debug_message ("delta-#edges: %5d bits. (%5d symbols => %5.2f bps)",
-		     bits_processed (output) - bits, edges,
-		     edges > 0 ? ((bits_processed (output) - bits) /
-				  (double) edges) : 0);
+                     bits_processed (output) - bits, edges,
+                     edges > 0 ? ((bits_processed (output) - bits) /
+                                  (double) edges) : 0);
    }
 
    /*
     *  Write matrix elements
     */
    {
-      unsigned	bits  	 = bits_processed (output);
+      unsigned  bits     = bits_processed (output);
       u_word_t *mapping1 = Calloc (wfa->states, sizeof (u_word_t));
       u_word_t *mapping2 = Calloc (wfa->states, sizeof (u_word_t));
-      unsigned	range;
+      unsigned  range;
 
       put_bit (output, use_normal_domains);
       put_bit (output, use_delta_domains);
-      
+
       /*
        *  Generate array of states which are admitted domains.
        *  When coding intra frames 'mapping1' == 'mapping2' otherwise
-       *  'mapping1' is a list of 'normal' domains which are admitted for 
+       *  'mapping1' is a list of 'normal' domains which are admitted for
        *             coding intra blocks
        *  'mapping2' is a list of 'delta' domains which are admitted for
-       *             coding the motion compensated prediction error 
+       *             coding the motion compensated prediction error
        */
       {
-	 unsigned n1, n2, state;
-	 
-	 for (n1 = n2 = state = 0; state < wfa->states; state++)
-	 {
-	    mapping1 [state] = n1;
-	    if (usedomain (state, wfa)
-		&& (state < wfa->basis_states || use_delta_domains
-		    || !wfa->delta_state [state]))
-	       n1++;
-	    
-	    mapping2 [state] = n2;
-	    if (usedomain (state, wfa)
-		&& (state < wfa->basis_states || use_normal_domains
-		    || wfa->delta_state [state]))
-	       n2++;
-	 }
-	 debug_message ("# normal states = %d, # delta states = %d,"
-			" # WFA states = %d", n1, n2, wfa->states);
+         unsigned n1, n2, state;
+
+         for (n1 = n2 = state = 0; state < wfa->states; state++)
+         {
+            mapping1 [state] = n1;
+            if (usedomain (state, wfa)
+                && (state < wfa->basis_states || use_delta_domains
+                    || !wfa->delta_state [state]))
+               n1++;
+
+            mapping2 [state] = n2;
+            if (usedomain (state, wfa)
+                && (state < wfa->basis_states || use_normal_domains
+                    || wfa->delta_state [state]))
+               n2++;
+         }
+         debug_message ("# normal states = %d, # delta states = %d,"
+                        " # WFA states = %d", n1, n2, wfa->states);
       }
-      
+
       for (range = 0; range < rs.range_no; range++)
-	 if (!rs.range_subdivided [range])
-	 {
-	    unsigned  state = rs.range_state [range];
-	    unsigned  label = rs.range_label [range];
-	    unsigned  last  = 1;
-	    u_word_t *mapping;
-	    unsigned  max_value;
-	    unsigned  edge;
-	    word_t    domain;
-
-	    if (wfa->delta_state [state] ||
-		wfa->mv_tree [state][label].type != NONE)
-	       mapping = mapping2;
-	    else
-	       mapping = mapping1;
-	    
-	    max_value = mapping [rs.range_max_domain [range]];
-	    
-	    for (edge = 0; isedge (domain = wfa->into [state][label][edge]);
-		 edge++)
-	       if (domain > 0)
-	       {
-		  total++;
-		  if (max_value - last)
-		  {
-		     write_bin_code (mapping [domain] - last,
-				     max_value - last, output);
-		     last = mapping [domain] + 1;
-		  }
-	       }
-	 }
+         if (!rs.range_subdivided [range])
+         {
+            unsigned  state = rs.range_state [range];
+            unsigned  label = rs.range_label [range];
+            unsigned  last  = 1;
+            u_word_t *mapping;
+            unsigned  max_value;
+            unsigned  edge;
+            word_t    domain;
+
+            if (wfa->delta_state [state] ||
+                wfa->mv_tree [state][label].type != NONE)
+               mapping = mapping2;
+            else
+               mapping = mapping1;
+
+            max_value = mapping [rs.range_max_domain [range]];
+
+            for (edge = 0; isedge (domain = wfa->into [state][label][edge]);
+                 edge++)
+               if (domain > 0)
+               {
+                  total++;
+                  if (max_value - last)
+                  {
+                     write_bin_code (mapping [domain] - last,
+                                     max_value - last, output);
+                     last = mapping [domain] + 1;
+                  }
+               }
+         }
 
       debug_message ("delta-index:  %5d bits. (%5d symbols => %5.2f bps)",
-		     bits_processed (output) - bits, total,
-		     total > 0 ? ((bits_processed (output) - bits) /
-				  (double) total) : 0);
+                     bits_processed (output) - bits, total,
+                     total > 0 ? ((bits_processed (output) - bits) /
+                                  (double) total) : 0);
       Free (mapping1);
       Free (mapping2);
    }
-   
+
    Free (rs.range_state);
    Free (rs.range_label);
    Free (rs.range_max_domain);
@@ -280,17 +280,17 @@ column_0_encoding (const wfa_t *wfa, unsigned last_row, bitfile_t *output)
  *  All rows from 'wfa->basis_states' up to 'last_row' are decoded.
  *
  *  Return value:
- *	number of non-zero matrix elements (WFA edges)
+ *      number of non-zero matrix elements (WFA edges)
  */
 {
-   u_word_t  high;			/* Start of the current code range */
-   u_word_t  low;			/* End of the current code range */
-   unsigned *prob;			/* probability array */
-   unsigned  row;			/* current matrix row */
-   unsigned  label;			/* current matrix label */
-   unsigned  underflow;			/* Underflow bits */
-   unsigned  index;			/* probability index */
-   unsigned  total = 0;			/* Number of '1' elements */
+   u_word_t  high;                      /* Start of the current code range */
+   u_word_t  low;                       /* End of the current code range */
+   unsigned *prob;                      /* probability array */
+   unsigned  row;                       /* current matrix row */
+   unsigned  label;                     /* current matrix label */
+   unsigned  underflow;                 /* Underflow bits */
+   unsigned  index;                     /* probability index */
+   unsigned  total = 0;                 /* Number of '1' elements */
    unsigned  bits  = bits_processed (output);
 
    /*
@@ -300,18 +300,18 @@ column_0_encoding (const wfa_t *wfa, unsigned last_row, bitfile_t *output)
     */
    {
       unsigned n;
-      unsigned exp;			/* current exponent */
-      
+      unsigned exp;                     /* current exponent */
+
       prob = Calloc (1 << (MAX_PROB + 1), sizeof (unsigned));
-   
+
       for (index = 0, n = MIN_PROB; n <= MAX_PROB; n++)
-	 for (exp = 0; exp < 1U << n; exp++, index++)
-	    prob [index] = n;
+         for (exp = 0; exp < 1U << n; exp++, index++)
+            prob [index] = n;
    }
-   
-   high      = HIGH;			/* 1.0 */
-   low       = LOW;			/* 0.0 */
-   underflow = 0;			/* no underflow bits */
+
+   high      = HIGH;                    /* 1.0 */
+   low       = LOW;                     /* 0.0 */
+   underflow = 0;                       /* no underflow bits */
 
    index = 0;
 
@@ -325,50 +325,50 @@ column_0_encoding (const wfa_t *wfa, unsigned last_row, bitfile_t *output)
     */
    for (row = wfa->basis_states; row <= last_row; row++)
       for (label = 0; label < MAXLABELS; label++)
-	 if (isrange (wfa->tree [row][label]))
-	 {
-	    if (wfa->into [row][label][0] != 0)
-	    {
-	       /*
-		*  encode the MPS '0'
-		*/
-	       high = high - ((high - low) >> prob [index]) - 1;
-	       RESCALE_OUTPUT_INTERVAL;
-	       
-	       if (index < 1020)
-		  index++;
-	    }
-	    else
-	    {
-	       /*
-		*  encode the LPS '1'
-		*/
-	       low = high - ((high - low) >> prob [index]);
-
-	       RESCALE_OUTPUT_INTERVAL;
-	       
-	       total++;
-	       index >>= 1;
-	    }
-	 }
+         if (isrange (wfa->tree [row][label]))
+         {
+            if (wfa->into [row][label][0] != 0)
+            {
+               /*
+                *  encode the MPS '0'
+                */
+               high = high - ((high - low) >> prob [index]) - 1;
+               RESCALE_OUTPUT_INTERVAL;
+
+               if (index < 1020)
+                  index++;
+            }
+            else
+            {
+               /*
+                *  encode the LPS '1'
+                */
+               low = high - ((high - low) >> prob [index]);
+
+               RESCALE_OUTPUT_INTERVAL;
+
+               total++;
+               index >>= 1;
+            }
+         }
    /*
     *  Flush the quasi-arithmetic encoder
     */
    low = high;
 
    RESCALE_OUTPUT_INTERVAL;
-   
+
    OUTPUT_BYTE_ALIGN (output);
 
    Free (prob);
 
    debug_message ("delta-state0: %5d bits. (%5d symbols => %5.2f bps)",
-		  bits_processed (output) - bits, total,
-		  total > 0 ? ((bits_processed (output) - bits) /
-			       (double) total) : 0);
+                  bits_processed (output) - bits, total,
+                  total > 0 ? ((bits_processed (output) - bits) /
+                               (double) total) : 0);
 
    return total;
-}   
+}
 
 static unsigned
 chroma_encoding (const wfa_t *wfa, bitfile_t *output)
@@ -377,24 +377,24 @@ chroma_encoding (const wfa_t *wfa, bitfile_t *output)
  *  chroma channels Cb and Cr to stream 'output'.
  *
  *  Return value:
- *	number of non-zero matrix elements (WFA edges)
+ *      number of non-zero matrix elements (WFA edges)
  */
 {
 
-   unsigned  domain;			/* current domain, counter */
-   unsigned  label;			/* current label */
-   unsigned  total = 0;			/* number of '1' elements */
-   u_word_t  high;			/* Start of the current code range */
-   u_word_t  low;			/* End of the current code range */
-   unsigned  underflow;			/* underflow bits */
-   unsigned *prob;			/* probability array */
-   unsigned  index;			/* probability index, counter */
-   unsigned  next_index;		/* probability of last domain */
-   unsigned  row;			/* current matrix row */
+   unsigned  domain;                    /* current domain, counter */
+   unsigned  label;                     /* current label */
+   unsigned  total = 0;                 /* number of '1' elements */
+   u_word_t  high;                      /* Start of the current code range */
+   u_word_t  low;                       /* End of the current code range */
+   unsigned  underflow;                 /* underflow bits */
+   unsigned *prob;                      /* probability array */
+   unsigned  index;                     /* probability index, counter */
+   unsigned  next_index;                /* probability of last domain */
+   unsigned  row;                       /* current matrix row */
    word_t   *y_domains;
-   unsigned  count = 0;			/* number of transitions for part 1 */
+   unsigned  count = 0;                 /* number of transitions for part 1 */
    unsigned  bits  = bits_processed (output);
-   
+
    /*
     *  Compute the asymmetric probability array
     *  prob[] = { 1/2, 1/2, 1/4, 1/4, 1/4, 1/4,
@@ -402,24 +402,24 @@ chroma_encoding (const wfa_t *wfa, bitfile_t *output)
     */
    {
       unsigned n;
-      unsigned exp;			/* current exponent */
-      
+      unsigned exp;                     /* current exponent */
+
       prob = Calloc (1 << (MAX_PROB + 1), sizeof (unsigned));
-   
+
       for (index = 0, n = MIN_PROB; n <= MAX_PROB; n++)
-	 for (exp = 0; exp < 1U << n; exp++, index++)
-	    prob [index] = n;
+         for (exp = 0; exp < 1U << n; exp++, index++)
+            prob [index] = n;
    }
-   
-   high      = HIGH;			/* 1.0 */
-   low       = LOW;			/* 0.0 */
-   underflow = 0;			/* no underflow bits */
+
+   high      = HIGH;                    /* 1.0 */
+   low       = LOW;                     /* 0.0 */
+   underflow = 0;                       /* no underflow bits */
 
    next_index = index = 0;
 
    y_domains = compute_hits (wfa->basis_states,
-			     wfa->tree [wfa->tree [wfa->root_state][0]][0],
-			     wfa->wfainfo->chroma_max_states, wfa);
+                             wfa->tree [wfa->tree [wfa->root_state][0]][0],
+                             wfa->wfainfo->chroma_max_states, wfa);
 
    /*
     *  First of all, read all matrix columns given in the list 'y_domains'
@@ -428,67 +428,67 @@ chroma_encoding (const wfa_t *wfa, bitfile_t *output)
     */
    for (domain = 0; y_domains [domain] != -1; domain++)
    {
-      bool_t save_index = YES;		/* YES: store current prob. index */
-      
+      bool_t save_index = YES;          /* YES: store current prob. index */
+
       row   = wfa->tree [wfa->tree [wfa->root_state][0]][0] + 1;
       index = next_index;
-	 
+
       for (; row < wfa->states; row++)
       {
-	 for (label = 0; label < MAXLABELS; label++)
-	    if (isrange (wfa->tree [row][label]))
-	    {
-	       unsigned	edge;
-	       int	into;
-	       bool_t    match;		/* approx with current domain found */
-	       
-	       for (match = NO, edge = 0;
-		    isedge (into = wfa->into [row][label][edge])
-			    && (unsigned) into < row;
-		    edge++)
-		  if (into == y_domains [domain]
-		      && into != wfa->y_state [row][label])
-		     match = YES;
-	       if (!match)
-	       {
-		  /*
-		   *  encode the MPS '0'
-		   */
-		  high = high - ((high - low) >> prob [index]) - 1;
-
-		  RESCALE_OUTPUT_INTERVAL;
-		     
-		  if (index < 1020)
-		     index++;
-	       }
-	       else
-	       {
-		  /*
-		   *  encode the LPS '1'
-		   */
-		  low = high - ((high - low) >> prob [index]);
-
-		  RESCALE_OUTPUT_INTERVAL;
-		     
-		  total++;
-		  index >>= 1;
-	       }
-	    }
-	 if (save_index)
-	 {
-	    next_index = index;
-	    save_index = NO;
-	 }
+         for (label = 0; label < MAXLABELS; label++)
+            if (isrange (wfa->tree [row][label]))
+            {
+               unsigned edge;
+               int      into;
+               bool_t    match;         /* approx with current domain found */
+
+               for (match = NO, edge = 0;
+                    isedge (into = wfa->into [row][label][edge])
+                            && (unsigned) into < row;
+                    edge++)
+                  if (into == y_domains [domain]
+                      && into != wfa->y_state [row][label])
+                     match = YES;
+               if (!match)
+               {
+                  /*
+                   *  encode the MPS '0'
+                   */
+                  high = high - ((high - low) >> prob [index]) - 1;
+
+                  RESCALE_OUTPUT_INTERVAL;
+
+                  if (index < 1020)
+                     index++;
+               }
+               else
+               {
+                  /*
+                   *  encode the LPS '1'
+                   */
+                  low = high - ((high - low) >> prob [index]);
+
+                  RESCALE_OUTPUT_INTERVAL;
+
+                  total++;
+                  index >>= 1;
+               }
+            }
+         if (save_index)
+         {
+            next_index = index;
+            save_index = NO;
+         }
       }
    }
 
    debug_message ("CbCr_matrix:  %5d bits. (%5d symbols => %5.2f bps)",
-		  bits_processed (output) - bits, total,
-		  total > 0 ? ((bits_processed (output) - bits) /
-			       (double) total) : 0);
+                  bits_processed (output) - bits, total,
+                  total > 0 ? ((bits_processed (output) - bits) /
+                               (double) total) : 0);
    count = total;
    bits  = bits_processed (output);
-   
+
    /*
     *  Encode the additional column which indicates whether there
     *  are transitions to a state with same spatial coordinates
@@ -500,32 +500,32 @@ chroma_encoding (const wfa_t *wfa, bitfile_t *output)
    next_index = index = 0;
 
    for (row = wfa->tree [wfa->tree [wfa->root_state][0]][0] + 1;
-	row < wfa->states; row++)
+        row < wfa->states; row++)
       for (label = 0; label < MAXLABELS; label++)
-	 if (!wfa->y_column [row][label])
-	 {
-	    /*
-	     *  encode the MPS '0'
-	     */
-	    high = high - ((high - low) >> prob [index]) - 1;
-
-	    RESCALE_OUTPUT_INTERVAL;
-	    
-	    if (index < 1020)
-	       index++;
-	 }
-	 else
-	 {
-	    /*
-	     *  encode the LPS '1'
-	     */
-	    low = high - ((high - low) >> prob [index]);
-
-	    RESCALE_OUTPUT_INTERVAL;
-
-	    index >>= 1;
-	    total++;
-	 }
+         if (!wfa->y_column [row][label])
+         {
+            /*
+             *  encode the MPS '0'
+             */
+            high = high - ((high - low) >> prob [index]) - 1;
+
+            RESCALE_OUTPUT_INTERVAL;
+
+            if (index < 1020)
+               index++;
+         }
+         else
+         {
+            /*
+             *  encode the LPS '1'
+             */
+            low = high - ((high - low) >> prob [index]);
+
+            RESCALE_OUTPUT_INTERVAL;
+
+            index >>= 1;
+            total++;
+         }
 
    /*
     *  Flush the quasi-arithmetic encoder
@@ -536,12 +536,12 @@ chroma_encoding (const wfa_t *wfa, bitfile_t *output)
    OUTPUT_BYTE_ALIGN (output);
 
    debug_message ("Yreferences:  %5d bits. (%5d symbols => %5.2f bps)",
-		  bits_processed (output) - bits, total - count,
-		  total - count > 0 ? ((bits_processed (output) - bits) /
-				       (double) (total - count)) : 0);
+                  bits_processed (output) - bits, total - count,
+                  total - count > 0 ? ((bits_processed (output) - bits) /
+                                       (double) (total - count)) : 0);
 
    Free (prob);
    Free (y_domains);
-   
+
    return total;
 }
diff --git a/converter/other/fiasco/output/matrices.h b/converter/other/fiasco/output/matrices.h
index 44671496..6e6ec8a5 100644
--- a/converter/other/fiasco/output/matrices.h
+++ b/converter/other/fiasco/output/matrices.h
@@ -1,8 +1,8 @@
 /*
  *  matrices.h
  *
- *  Written by:		Ullrich Hafner
- *		
+ *  Written by:         Ullrich Hafner
+ *              
  *  This file is part of FIASCO (Fractal Image And Sequence COdec)
  *  Copyright (C) 1994-2000 Ullrich Hafner
  */
@@ -22,7 +22,7 @@
 
 unsigned
 write_matrices (bool_t use_normal_domains, bool_t use_delta_domains,
-		const wfa_t *wfa, bitfile_t *output);
+                const wfa_t *wfa, bitfile_t *output);
 
 #endif /* _MATRICES_H */
 
diff --git a/converter/other/fiasco/output/mc.c b/converter/other/fiasco/output/mc.c
index 170a2648..06ed0524 100644
--- a/converter/other/fiasco/output/mc.c
+++ b/converter/other/fiasco/output/mc.c
@@ -1,8 +1,8 @@
 /*
- *  mc.c:		Output of motion compensation
+ *  mc.c:               Output of motion compensation
  *
- *  Written by:		Michael Unger
- *			Ullrich Hafner
+ *  Written by:         Michael Unger
+ *                      Ullrich Hafner
  *
  *  This file is part of FIASCO (Fractal Image And Sequence COdec)
  *  Copyright (C) 1994-2000 Ullrich Hafner
@@ -29,7 +29,7 @@
 
 /*****************************************************************************
 
-			     local variables
+                             local variables
 
 *****************************************************************************/
 
@@ -55,19 +55,19 @@ enum vlc_e {CODE = 0, BITS = 1};
 
 /*****************************************************************************
 
-				prototypes
+                                prototypes
 
 *****************************************************************************/
 
 static void
 encode_mc_tree (unsigned max_state, frame_type_e frame_type, const wfa_t *wfa,
-	       bitfile_t *output);
+               bitfile_t *output);
 static void
 encode_mc_coords (unsigned max_state, const wfa_t *wfa, bitfile_t *output);
 
 /*****************************************************************************
 
-				public code
+                                public code
 
 *****************************************************************************/
 
@@ -75,8 +75,8 @@ void
 write_mc (frame_type_e frame_type, const wfa_t *wfa, bitfile_t *output)
 {
    unsigned max_state = wfa->wfainfo->color
-			? wfa->tree[wfa->tree[wfa->root_state][0]][0]
-			: wfa->states;
+                        ? wfa->tree[wfa->tree[wfa->root_state][0]][0]
+                        : wfa->states;
 
    encode_mc_tree (max_state, frame_type, wfa, output);
    encode_mc_coords (max_state, wfa, output);
@@ -84,13 +84,13 @@ write_mc (frame_type_e frame_type, const wfa_t *wfa, bitfile_t *output)
 
 /*****************************************************************************
 
-				private code
+                                private code
 
 *****************************************************************************/
 
 static void
 encode_mc_tree (unsigned max_state, frame_type_e frame_type, const wfa_t *wfa,
-		bitfile_t *output)
+                bitfile_t *output)
 /*
  *  Write tree of motion compensation decisions to the 'output' stream.
  *  Depending on 'frame_type' different decoding methods are used.
@@ -99,20 +99,20 @@ encode_mc_tree (unsigned max_state, frame_type_e frame_type, const wfa_t *wfa,
  *  No return value.
  */
 {
-   unsigned  label;			/* current label */
-   unsigned  state;			/* current state */
-   unsigned  total = 0;			/* number of motion tree decisions */
-   unsigned  queue [MAXSTATES];		/* state numbers in BFO */
-   unsigned  current;			/* current node to process */
-   unsigned  last;			/* last node (update every new node) */
-   mc_type_e type;			/* type of motion compensation */
-   unsigned	     (*mc_tree_codes)[2]; /* pointer to VLC table */
+   unsigned  label;                     /* current label */
+   unsigned  state;                     /* current state */
+   unsigned  total = 0;                 /* number of motion tree decisions */
+   unsigned  queue [MAXSTATES];         /* state numbers in BFO */
+   unsigned  current;                   /* current node to process */
+   unsigned  last;                      /* last node (update every new node) */
+   mc_type_e type;                      /* type of motion compensation */
+   unsigned          (*mc_tree_codes)[2]; /* pointer to VLC table */
    unsigned  bits  = bits_processed (output); /* number of bits used */
 
    if (frame_type == P_FRAME)
-      mc_tree_codes = p_frame_codes;	/* binary code */
+      mc_tree_codes = p_frame_codes;    /* binary code */
    else
-      mc_tree_codes = b_frame_codes;	/* variable length code */
+      mc_tree_codes = b_frame_codes;    /* variable length code */
 
    /*
     *  Traverse tree in breadth first order (starting at
@@ -122,37 +122,37 @@ encode_mc_tree (unsigned max_state, frame_type_e frame_type, const wfa_t *wfa,
 
    for (last = 0, state = wfa->basis_states; state < max_state; state++)
       if (wfa->level_of_state [state] - 1 == (int) wfa->wfainfo->p_max_level)
-	 queue [last++] = state;	/* init level = 'mc_max_level' */
+         queue [last++] = state;        /* init level = 'mc_max_level' */
 
    for (current = 0; current < last; current++)
       for (label = 0; label < MAXLABELS; label++)
       {
-	 state = queue [current];
-	 type  = wfa->mv_tree [state][label].type;
-	 if (wfa->x [state][label]
-	     + width_of_level (wfa->level_of_state [state] - 1)
-	     <= wfa->wfainfo->width
-	     &&
-	     wfa->y [state][label]
-	     + height_of_level (wfa->level_of_state [state] - 1)
-	     <= wfa->wfainfo->height)
-	 {
-	    put_bits (output, mc_tree_codes [type][CODE],
-		      mc_tree_codes [type][BITS]);
-	    total++;
-	 }
-	 if (type == NONE && !isrange (wfa->tree [state][label]) &&
-	     wfa->level_of_state [state] - 1 >=
-	     (int) wfa->wfainfo->p_min_level)
-	    queue [last++] = wfa->tree [state][label]; /* append child */
+         state = queue [current];
+         type  = wfa->mv_tree [state][label].type;
+         if (wfa->x [state][label]
+             + width_of_level (wfa->level_of_state [state] - 1)
+             <= wfa->wfainfo->width
+             &&
+             wfa->y [state][label]
+             + height_of_level (wfa->level_of_state [state] - 1)
+             <= wfa->wfainfo->height)
+         {
+            put_bits (output, mc_tree_codes [type][CODE],
+                      mc_tree_codes [type][BITS]);
+            total++;
+         }
+         if (type == NONE && !isrange (wfa->tree [state][label]) &&
+             wfa->level_of_state [state] - 1 >=
+             (int) wfa->wfainfo->p_min_level)
+            queue [last++] = wfa->tree [state][label]; /* append child */
 
       }
 
    OUTPUT_BYTE_ALIGN (output);
    debug_message ("mc-tree:      %5d bits. (%5d symbols => %5.2f bps)",
-		  bits_processed (output) - bits, total,
-		  total > 0 ? ((bits_processed (output) - bits) /
-			       (double) total) : 0);
+                  bits_processed (output) - bits, total,
+                  total > 0 ? ((bits_processed (output) - bits) /
+                               (double) total) : 0);
 }
 
 static void
@@ -165,85 +165,85 @@ encode_mc_coords (unsigned max_state, const wfa_t *wfa, bitfile_t *output)
  *  No return value.
  */
 {
-   unsigned  state;			/* current state */
-   unsigned  label;			/* current label */
-   unsigned  level_count [MAXLEVEL];	/* number of mv per level */
-   unsigned  level;			/* counter */
-   unsigned  ftotal = 0;		/* #forward motion tree decisions */
-   unsigned  btotal = 0;		/* #backward decisions */
-   unsigned  itotal = 0;		/* #interpolated decisions */
+   unsigned  state;                     /* current state */
+   unsigned  label;                     /* current label */
+   unsigned  level_count [MAXLEVEL];    /* number of mv per level */
+   unsigned  level;                     /* counter */
+   unsigned  ftotal = 0;                /* #forward motion tree decisions */
+   unsigned  btotal = 0;                /* #backward decisions */
+   unsigned  itotal = 0;                /* #interpolated decisions */
    unsigned  bits   = bits_processed (output); /* number of bits used */
    unsigned  sr     = wfa->wfainfo->search_range; /* search range */
 
    for (level = wfa->wfainfo->p_max_level;
-	level >= wfa->wfainfo->p_min_level; level--)
+        level >= wfa->wfainfo->p_min_level; level--)
       level_count [level] = 0;
 
    for (state = wfa->basis_states; state < max_state; state++)
       for (label = 0; label < MAXLABELS; label++)
       {
-	 mv_t *mv = &wfa->mv_tree[state][label]; /* motion vector info */
-
-	 if (mv->type != NONE)
-	 {
-	    level_count [wfa->level_of_state [state] - 1]++;
-	    switch (mv->type)
-	    {
-	       case FORWARD:
-		  put_bits (output,
-			    mv_code_table[(mv->fx + sr)][CODE],
-			    mv_code_table[(mv->fx + sr)][BITS]);
-		  put_bits (output,
-			    mv_code_table[(mv->fy + sr)][CODE],
-			    mv_code_table[(mv->fy + sr)][BITS]);
-		  ftotal++;
-		  break;
-	       case BACKWARD:
-		  put_bits (output,
-			    mv_code_table[(mv->bx + sr)][CODE],
-			    mv_code_table[(mv->bx + sr)][BITS]);
-		  put_bits (output,
-			    mv_code_table[(mv->by + sr)][CODE],
-			    mv_code_table[(mv->by + sr)][BITS]);
-		  btotal++;
-		  break;
-	       case INTERPOLATED:
-		  put_bits (output,
-			    mv_code_table[(mv->fx + sr)][CODE],
-			    mv_code_table[(mv->fx + sr)][BITS]);
-		  put_bits (output,
-			    mv_code_table[(mv->fy + sr)][CODE],
-			    mv_code_table[(mv->fy + sr)][BITS]);
-		  put_bits (output,
-			    mv_code_table[(mv->bx + sr)][CODE],
-			    mv_code_table[(mv->bx + sr)][BITS]);
-		  put_bits (output,
-			    mv_code_table[(mv->by + sr)][CODE],
-			    mv_code_table[(mv->by + sr)][BITS]);
-		  itotal++;
-		  break;
-	       default:
-		  break;
-	    }
-	 }
+         mv_t *mv = &wfa->mv_tree[state][label]; /* motion vector info */
+
+         if (mv->type != NONE)
+         {
+            level_count [wfa->level_of_state [state] - 1]++;
+            switch (mv->type)
+            {
+               case FORWARD:
+                  put_bits (output,
+                            mv_code_table[(mv->fx + sr)][CODE],
+                            mv_code_table[(mv->fx + sr)][BITS]);
+                  put_bits (output,
+                            mv_code_table[(mv->fy + sr)][CODE],
+                            mv_code_table[(mv->fy + sr)][BITS]);
+                  ftotal++;
+                  break;
+               case BACKWARD:
+                  put_bits (output,
+                            mv_code_table[(mv->bx + sr)][CODE],
+                            mv_code_table[(mv->bx + sr)][BITS]);
+                  put_bits (output,
+                            mv_code_table[(mv->by + sr)][CODE],
+                            mv_code_table[(mv->by + sr)][BITS]);
+                  btotal++;
+                  break;
+               case INTERPOLATED:
+                  put_bits (output,
+                            mv_code_table[(mv->fx + sr)][CODE],
+                            mv_code_table[(mv->fx + sr)][BITS]);
+                  put_bits (output,
+                            mv_code_table[(mv->fy + sr)][CODE],
+                            mv_code_table[(mv->fy + sr)][BITS]);
+                  put_bits (output,
+                            mv_code_table[(mv->bx + sr)][CODE],
+                            mv_code_table[(mv->bx + sr)][BITS]);
+                  put_bits (output,
+                            mv_code_table[(mv->by + sr)][CODE],
+                            mv_code_table[(mv->by + sr)][BITS]);
+                  itotal++;
+                  break;
+               default:
+                  break;
+            }
+         }
       }
 
    OUTPUT_BYTE_ALIGN (output);
 
    debug_message ("Motion compensation: %d forward, %d backward, "
-		  "%d interpolated", ftotal, btotal, itotal);
+                  "%d interpolated", ftotal, btotal, itotal);
 
    for (level = wfa->wfainfo->p_max_level;
-	level >= wfa->wfainfo->p_min_level; level--)
+        level >= wfa->wfainfo->p_min_level; level--)
       debug_message ("Level %d: %d motion vectors", level, level_count[level]);
 
    {
       unsigned  total = ftotal * 2 + btotal * 2 + itotal * 4;
 
       debug_message ("mv-coord:     %5d bits. (%5d symbols => %5.2f bps)",
-		     bits_processed (output) - bits, total,
-		     total > 0 ? ((bits_processed (output) - bits) /
-				  (double) total) : 0);
+                     bits_processed (output) - bits, total,
+                     total > 0 ? ((bits_processed (output) - bits) /
+                                  (double) total) : 0);
    }
 
    return;
diff --git a/converter/other/fiasco/output/mc.h b/converter/other/fiasco/output/mc.h
index cacddfe7..9e15ae3d 100644
--- a/converter/other/fiasco/output/mc.h
+++ b/converter/other/fiasco/output/mc.h
@@ -1,9 +1,9 @@
 /*
  *  mc.h
  *
- *  Written by:		Michael Unger
- *			Ullrich Hafner
- *		
+ *  Written by:         Michael Unger
+ *                      Ullrich Hafner
+ *              
  *  This file is part of FIASCO (Fractal Image And Sequence COdec)
  *  Copyright (C) 1994-2000 Ullrich Hafner
  */
diff --git a/converter/other/fiasco/output/nd.c b/converter/other/fiasco/output/nd.c
index b1dd6746..67b8b106 100644
--- a/converter/other/fiasco/output/nd.c
+++ b/converter/other/fiasco/output/nd.c
@@ -1,7 +1,7 @@
 /*
- *  nd.c:		Output of prediction tree
+ *  nd.c:               Output of prediction tree
  *
- *  Written by:		Ullrich Hafner
+ *  Written by:         Ullrich Hafner
  *
  *  This file is part of FIASCO (Fractal Image And Sequence COdec)
  *  Copyright (C) 1994-2000 Ullrich Hafner
@@ -31,7 +31,7 @@
 
 /*****************************************************************************
 
-				prototypes
+                                prototypes
 
 *****************************************************************************/
 
@@ -42,7 +42,7 @@ encode_nd_coefficients (unsigned total, const wfa_t *wfa, bitfile_t *output);
 
 /*****************************************************************************
 
-				public code
+                                public code
 
 *****************************************************************************/
 
@@ -63,7 +63,7 @@ write_nd (const wfa_t *wfa, bitfile_t *output)
 
 /*****************************************************************************
 
-				private code
+                                private code
 
 *****************************************************************************/
 
@@ -75,13 +75,13 @@ encode_nd_tree (const wfa_t *wfa, bitfile_t *output)
  *  No return value.
  */
 {
-   lqueue_t *queue;			/* queue of states */
-   int	     state, next;		/* state and its current child */
-   unsigned  used, not_used;		/* counter ND used/not used */
-   u_word_t  low;			/* Start of the current code range */
-   u_word_t  high;			/* End of the current code range */
-   u_word_t  underflow;			/* Number of underflow bits pending */
-   u_word_t  sum0, sum1;		/* Probability model */
+   lqueue_t *queue;                     /* queue of states */
+   int       state, next;               /* state and its current child */
+   unsigned  used, not_used;            /* counter ND used/not used */
+   u_word_t  low;                       /* Start of the current code range */
+   u_word_t  high;                      /* End of the current code range */
+   u_word_t  underflow;                 /* Number of underflow bits pending */
+   u_word_t  sum0, sum1;                /* Probability model */
    unsigned  bits = bits_processed (output);
 
    used = not_used = 0;
@@ -108,60 +108,60 @@ encode_nd_tree (const wfa_t *wfa, bitfile_t *output)
 
       if (wfa->level_of_state [next] > wfa->wfainfo->p_max_level + 1)
       {
-	 /*
-	  *  Nondetermismn is not allowed at levels larger than
-	  *  'wfa->wfainfo->p_max_level'.
-	  */
-	 for (label = 0; label < MAXLABELS; label++)
-	    if (ischild (state = wfa->tree [next][label]))
-	       queue_append (queue, &state); /* continue with children */
+         /*
+          *  Nondetermismn is not allowed at levels larger than
+          *  'wfa->wfainfo->p_max_level'.
+          */
+         for (label = 0; label < MAXLABELS; label++)
+            if (ischild (state = wfa->tree [next][label]))
+               queue_append (queue, &state); /* continue with children */
       }
       else if (wfa->level_of_state [next] > wfa->wfainfo->p_min_level)
       {
-	 for (label = 0; label < MAXLABELS; label++)
-	    if (ischild (state = wfa->tree [next][label]))
-	    {
-	       unsigned range;		/* Current interval range */
-
-	       if (isedge (wfa->into [next][label][0])) /* prediction used */
-	       {
-		  used++;
-
-		  /*
-		   *  Encode a '1' symbol
-		   */
-		  range =  (high - low) + 1;
-		  low   = low + (u_word_t) ((range * sum0) / sum1);
-		  RESCALE_OUTPUT_INTERVAL;
-	       }
-	       else			/* no predict., continue with children */
-	       {
-		  not_used++;
-		  if (wfa->level_of_state [state] > wfa->wfainfo->p_min_level)
-		     queue_append (queue, &state);
-
-		  /*
-		   *  Encode a '0' symbol
-		   */
-		  range =  (high - low) + 1;
-		  high  = low + (u_word_t) ((range * sum0) / sum1 - 1);
-		  RESCALE_OUTPUT_INTERVAL;
-		  sum0++;
-	       }
-	       /*
-		*  Update the frequency counts
-		*/
-	       sum1++;
-	       if (sum1 > 50)		/* Scale the symbol frequencies */
-	       {
-		  sum0 >>= 1;
-		  sum1 >>= 1;
-		  if (!sum0)
-		     sum0 = 1;
-		  if (sum0 >= sum1)
-		     sum1 = sum0 + 1;
-	       }
-	    }
+         for (label = 0; label < MAXLABELS; label++)
+            if (ischild (state = wfa->tree [next][label]))
+            {
+               unsigned range;          /* Current interval range */
+
+               if (isedge (wfa->into [next][label][0])) /* prediction used */
+               {
+                  used++;
+
+                  /*
+                   *  Encode a '1' symbol
+                   */
+                  range =  (high - low) + 1;
+                  low   = low + (u_word_t) ((range * sum0) / sum1);
+                  RESCALE_OUTPUT_INTERVAL;
+               }
+               else                     /* no predict., continue with children */
+               {
+                  not_used++;
+                  if (wfa->level_of_state [state] > wfa->wfainfo->p_min_level)
+                     queue_append (queue, &state);
+
+                  /*
+                   *  Encode a '0' symbol
+                   */
+                  range =  (high - low) + 1;
+                  high  = low + (u_word_t) ((range * sum0) / sum1 - 1);
+                  RESCALE_OUTPUT_INTERVAL;
+                  sum0++;
+               }
+               /*
+                *  Update the frequency counts
+                */
+               sum1++;
+               if (sum1 > 50)           /* Scale the symbol frequencies */
+               {
+                  sum0 >>= 1;
+                  sum1 >>= 1;
+                  if (!sum0)
+                     sum0 = 1;
+                  if (sum0 >= sum1)
+                     sum1 = sum0 + 1;
+               }
+            }
 
       }
    }
@@ -175,14 +175,14 @@ encode_nd_tree (const wfa_t *wfa, bitfile_t *output)
    OUTPUT_BYTE_ALIGN (output);
 
    debug_message ("%d nd fields: %d used nd, %d used not nd", used + not_used,
-		  used, not_used);
+                  used, not_used);
    {
       unsigned total = used + not_used;
 
       debug_message ("nd-tree:      %5d bits. (%5d symbols => %5.2f bps)",
-		     bits_processed (output) - bits, total,
-		     total > 0 ? ((bits_processed (output) - bits) /
-				  (double) total) : 0);
+                     bits_processed (output) - bits, total,
+                     total > 0 ? ((bits_processed (output) - bits) /
+                                  (double) total) : 0);
    }
 
    return used;
@@ -201,42 +201,42 @@ encode_nd_coefficients (unsigned total, const wfa_t *wfa, bitfile_t *output)
    unsigned bits = bits_processed (output);
 
    {
-      unsigned *coefficients;		/* array of factors to encode */
-      unsigned *ptr;			/* pointer to current factor */
-      unsigned	state, label, edge;
-      word_t	domain;
+      unsigned *coefficients;           /* array of factors to encode */
+      unsigned *ptr;                    /* pointer to current factor */
+      unsigned  state, label, edge;
+      word_t    domain;
 
       ptr = coefficients  = Calloc (total, sizeof (unsigned));
 
       for (state = wfa->basis_states; state < wfa->states; state++)
-	 for (label = 0; label < MAXLABELS; label++)
-	    if (ischild (wfa->tree [state][label])
-		&& isedge (wfa->into [state][label][0]))
-	       for (edge = 0; isedge (domain = wfa->into [state][label][edge]);
-		    edge++)
-	       {
-		  if (ptr - coefficients >= (int) total)
-		     error ("Can't write more than %d coefficients.", total);
-
-		  *ptr++ = rtob (wfa->weight [state][label][edge],
-				 wfa->wfainfo->dc_rpf);
-	       }
+         for (label = 0; label < MAXLABELS; label++)
+            if (ischild (wfa->tree [state][label])
+                && isedge (wfa->into [state][label][0]))
+               for (edge = 0; isedge (domain = wfa->into [state][label][edge]);
+                    edge++)
+               {
+                  if (ptr - coefficients >= (int) total)
+                     error ("Can't write more than %d coefficients.", total);
+
+                  *ptr++ = rtob (wfa->weight [state][label][edge],
+                                 wfa->wfainfo->dc_rpf);
+               }
 
       /*
        *  Encode array of coefficients with arithmetic coding
        */
       {
-	 const int scaling = 50;	/* scaling factor of prob. model */
-	 unsigned  c_symbols = 1 << (wfa->wfainfo->dc_rpf->mantissa_bits + 1);
+         const int scaling = 50;        /* scaling factor of prob. model */
+         unsigned  c_symbols = 1 << (wfa->wfainfo->dc_rpf->mantissa_bits + 1);
 
-	 encode_array (output, coefficients, NULL, &c_symbols, 1,
-		       total, scaling);
+         encode_array (output, coefficients, NULL, &c_symbols, 1,
+                       total, scaling);
       }
 
       debug_message ("nd-factors:   %5d bits. (%5d symbols => %5.2f bps)",
-		     bits_processed (output) - bits, total,
-		     total ? ((bits_processed (output) - bits)
-			      / (double) total) : 0);
+                     bits_processed (output) - bits, total,
+                     total ? ((bits_processed (output) - bits)
+                              / (double) total) : 0);
       Free (coefficients);
    }
 }
diff --git a/converter/other/fiasco/output/nd.h b/converter/other/fiasco/output/nd.h
index 01a37838..7b8ea9fe 100644
--- a/converter/other/fiasco/output/nd.h
+++ b/converter/other/fiasco/output/nd.h
@@ -1,8 +1,8 @@
 /*
  *  nd.h
  *
- *  Written by:		Ullrich Hafner
- *		
+ *  Written by:         Ullrich Hafner
+ *              
  *  This file is part of FIASCO (Fractal Image And Sequence COdec)
  *  Copyright (C) 1994-2000 Ullrich Hafner
  */
diff --git a/converter/other/fiasco/output/tree.c b/converter/other/fiasco/output/tree.c
index 55080a51..02afec50 100644
--- a/converter/other/fiasco/output/tree.c
+++ b/converter/other/fiasco/output/tree.c
@@ -1,7 +1,7 @@
 /*
- *  tree.c:		Output of bintree partitioning
+ *  tree.c:             Output of bintree partitioning
  *
- *  Written by:		Ullrich Hafner
+ *  Written by:         Ullrich Hafner
  *
  *  This file is part of FIASCO (Fractal Image And Sequence COdec)
  *  Copyright (C) 1994-2000 Ullrich Hafner
@@ -29,17 +29,17 @@
 
 /*****************************************************************************
 
-				prototypes
+                                prototypes
 
 *****************************************************************************/
 
 static void
 encode_tree (bitfile_t *output, const byte_t *data, unsigned n_data,
-	     unsigned scaling, u_word_t sum0, u_word_t sum1);
+             unsigned scaling, u_word_t sum0, u_word_t sum1);
 
 /*****************************************************************************
 
-				public code
+                                public code
 
 *****************************************************************************/
 
@@ -53,13 +53,13 @@ write_tree (const wfa_t *wfa, bitfile_t *output)
  *  No return value.
  */
 {
-   unsigned  queue [MAXSTATES];		/* state numbers in BFO */
-   unsigned  current;			/* current node to process */
-   unsigned  last;			/* last node (update every new node) */
-   unsigned  label;			/* current label */
-   int	     into;			/* next child */
-   byte_t   *tree_string;		/* bitstring to encode */
-   unsigned  total = 0;			/* number of ranges */
+   unsigned  queue [MAXSTATES];         /* state numbers in BFO */
+   unsigned  current;                   /* current node to process */
+   unsigned  last;                      /* last node (update every new node) */
+   unsigned  label;                     /* current label */
+   int       into;                      /* next child */
+   byte_t   *tree_string;               /* bitstring to encode */
+   unsigned  total = 0;                 /* number of ranges */
    unsigned  bits  = bits_processed (output); /* number of bits */
 
    /*
@@ -72,17 +72,17 @@ write_tree (const wfa_t *wfa, bitfile_t *output)
    queue [0] = wfa->root_state;
    for (last = 1, current = 0; current < last; current++)
       for (label = 0; label < MAXLABELS; label++)
-	 if (!isrange (into = wfa->tree [queue[current]][label])) /* child ? */
-	 {
-	    queue [last++]        = into;
-	    tree_string [total++] = 1;
-	 }
-	 else				/* or range ? */
-	    tree_string [total++] = 0;
+         if (!isrange (into = wfa->tree [queue[current]][label])) /* child ? */
+         {
+            queue [last++]        = into;
+            tree_string [total++] = 1;
+         }
+         else                           /* or range ? */
+            tree_string [total++] = 0;
 
    if (total != (wfa->states - wfa->basis_states) * MAXLABELS)
       error ("total [%d] != (states - basis_states) * 2 [%d]", total,
-	     (wfa->states - wfa->basis_states) * MAXLABELS);
+             (wfa->states - wfa->basis_states) * MAXLABELS);
 
    {
       unsigned scale = total / 20 ;
@@ -93,20 +93,20 @@ write_tree (const wfa_t *wfa, bitfile_t *output)
    Free (tree_string);
 
    debug_message ("tree:         %5d bits. (%5d symbols => %5.2f bps)",
-		  bits_processed (output) - bits, total,
-		  total > 0 ? ((bits_processed (output) - bits)
-			       / (double) total) : 0);
+                  bits_processed (output) - bits, total,
+                  total > 0 ? ((bits_processed (output) - bits)
+                               / (double) total) : 0);
 }
 
 /*****************************************************************************
 
-				private code
+                                private code
 
 *****************************************************************************/
 
 static void
 encode_tree (bitfile_t *output, const byte_t *data, unsigned n_data,
-	     unsigned scaling, u_word_t sum0, u_word_t sum1)
+             unsigned scaling, u_word_t sum0, u_word_t sum1)
 /*
  *  Encode bintree data with adaptive binary arithmetic coding.
  *  Write 'n_data' output symbols stored in 'data' to stream 'output'.
@@ -116,10 +116,10 @@ encode_tree (bitfile_t *output, const byte_t *data, unsigned n_data,
  *  No return value.
  */
 {
-   u_word_t low;			/* Start of the current code range */
-   u_word_t high;			/* End of the current code range */
-   u_word_t underflow;			/* Number of underflow bits pending */
-   unsigned n;				/* Data counter */
+   u_word_t low;                        /* Start of the current code range */
+   u_word_t high;                       /* End of the current code range */
+   u_word_t underflow;                  /* Number of underflow bits pending */
+   unsigned n;                          /* Data counter */
 
    low       = 0;
    high      = 0xffff;
@@ -127,29 +127,29 @@ encode_tree (bitfile_t *output, const byte_t *data, unsigned n_data,
 
    for (n = n_data; n; n--)
    {
-      unsigned range;			/* Current interval range */
+      unsigned range;                   /* Current interval range */
 
       if (!*data++)
       {
-	 /*
-	  *  encode a '0'
-	  */
-	 range =  (high - low) + 1;
-	 high  = low + (u_word_t) ((range * sum0) / sum1 - 1);
+         /*
+          *  encode a '0'
+          */
+         range =  (high - low) + 1;
+         high  = low + (u_word_t) ((range * sum0) / sum1 - 1);
 
-	 RESCALE_OUTPUT_INTERVAL;
+         RESCALE_OUTPUT_INTERVAL;
 
-	 sum0++;
+         sum0++;
       }
       else
       {
-	 /*
-	  *  encode a '1'
-	  */
-	 range =  (high - low) + 1;
-	 low   = low + (u_word_t) ((range * sum0) / sum1);
+         /*
+          *  encode a '1'
+          */
+         range =  (high - low) + 1;
+         low   = low + (u_word_t) ((range * sum0) / sum1);
 
-	 RESCALE_OUTPUT_INTERVAL;
+         RESCALE_OUTPUT_INTERVAL;
       }
       /*
        *  Update the frequency counts
@@ -157,12 +157,12 @@ encode_tree (bitfile_t *output, const byte_t *data, unsigned n_data,
       sum1++;
       if (sum1 > scaling) /* Scale the symbol frequencies */
       {
-	 sum0 >>= 1;
-	 sum1 >>= 1;
-	 if (!sum0)
-	    sum0 = 1;
-	 if (sum0 >= sum1)
-	    sum1 = sum0 + 1;
+         sum0 >>= 1;
+         sum1 >>= 1;
+         if (!sum0)
+            sum0 = 1;
+         if (sum0 >= sum1)
+            sum1 = sum0 + 1;
       }
    }
    /*
diff --git a/converter/other/fiasco/output/tree.h b/converter/other/fiasco/output/tree.h
index 50fe2279..bcf50ec1 100644
--- a/converter/other/fiasco/output/tree.h
+++ b/converter/other/fiasco/output/tree.h
@@ -1,8 +1,8 @@
 /*
  *  tree.h
  *
- *  Written by:		Ullrich Hafner
- *		
+ *  Written by:         Ullrich Hafner
+ *              
  *  This file is part of FIASCO (Fractal Image And Sequence COdec)
  *  Copyright (C) 1994-2000 Ullrich Hafner
  */
diff --git a/converter/other/fiasco/output/weights.c b/converter/other/fiasco/output/weights.c
index 0203fef0..4eb068ac 100644
--- a/converter/other/fiasco/output/weights.c
+++ b/converter/other/fiasco/output/weights.c
@@ -1,8 +1,8 @@
 /*
- *  weights.c:		Output of weights
+ *  weights.c:          Output of weights
+ *
+ *  Written by:         Ullrich Hafner
  *
- *  Written by:		Ullrich Hafner
- *		
  *  This file is part of FIASCO (Fractal Image And Sequence COdec)
  *  Copyright (C) 1994-2000 Ullrich Hafner
  */
@@ -32,8 +32,8 @@
 
 /*****************************************************************************
 
-				public code
-  
+                                public code
+
 *****************************************************************************/
 
 void
@@ -45,20 +45,20 @@ write_weights (unsigned total, const wfa_t *wfa, bitfile_t *output)
  *  No return value.
  */
 {
-    unsigned  state, label;		/* current label */
-    unsigned  offset1, offset2;		/* model offsets. */
-    unsigned  offset3, offset4;		/* model offsets. */
-    unsigned *weights_array;		/* array of weights to encode */
-    unsigned *wptr;			/* pointer to current weight */
-    unsigned *level_array;		/* array of corresponding levels */
-    unsigned *lptr;			/* pointer to current corr. level */
-    int	     min_level, max_level;	/* min and max range level */
-    int	     d_min_level, d_max_level; 	/* min and max delta range level */
-    bool_t    dc, d_dc;			/* true if dc or delta dc are used */
-    bool_t    delta_approx = NO;		/* true if delta has been used */
-    unsigned  delta_count  = 0;		/* number of delta ranges */
-    unsigned  bits 	  = bits_processed (output);
-   
+    unsigned  state, label;             /* current label */
+    unsigned  offset1, offset2;         /* model offsets. */
+    unsigned  offset3, offset4;         /* model offsets. */
+    unsigned *weights_array;            /* array of weights to encode */
+    unsigned *wptr;                     /* pointer to current weight */
+    unsigned *level_array;              /* array of corresponding levels */
+    unsigned *lptr;                     /* pointer to current corr. level */
+    int      min_level, max_level;      /* min and max range level */
+    int      d_min_level, d_max_level;  /* min and max delta range level */
+    bool_t    dc, d_dc;                 /* true if dc or delta dc are used */
+    bool_t    delta_approx = NO;                /* true if delta has been used */
+    unsigned  delta_count  = 0;         /* number of delta ranges */
+    unsigned  bits        = bits_processed (output);
+
     /*
      *  Check whether delta approximation has been used
      */
@@ -68,14 +68,14 @@ write_weights (unsigned total, const wfa_t *wfa, bitfile_t *output)
             delta_approx = YES;
             break;
         }
-   
+
     /*
      *  Generate array of corresponding levels (context of probability model)
      */
     min_level = d_min_level = MAXLEVEL;
     max_level = d_max_level = 0;
-    dc 	     = d_dc	   = NO;
-   
+    dc       = d_dc        = NO;
+
     for (state = wfa->basis_states; state < wfa->states; state++)
         for (label = 0; label < MAXLABELS; label++)
             if (isrange (wfa->tree [state][label]))
@@ -95,24 +95,24 @@ write_weights (unsigned total, const wfa_t *wfa, bitfile_t *output)
                         dc = YES;
                 }
             }
-    if (min_level > max_level)		/* no lc found */
+    if (min_level > max_level)          /* no lc found */
         max_level = min_level - 1;
     if (d_min_level > d_max_level)
         d_max_level = d_min_level - 1;
 
     /*
      *  Context model:
-     *		0		DC weight
-     *		1		Delta DC weight
-     *		2-k		normal weights per level
-     *		k+1 - m		Delta weights per level
+     *          0               DC weight
+     *          1               Delta DC weight
+     *          2-k             normal weights per level
+     *          k+1 - m         Delta weights per level
      */
 
     offset1 = dc ? 1 : 0;
     offset2 = offset1 + (d_dc ? 1 : 0);
     offset3 = offset2 + (max_level - min_level + 1);
     offset4 = offset3 + (d_max_level - d_min_level + 1);
-   
+
     /*
      *  Weights are encoded as follows:
      *  all weights of state n
@@ -127,15 +127,15 @@ write_weights (unsigned total, const wfa_t *wfa, bitfile_t *output)
         for (label = 0; label < MAXLABELS; label++)
             if (isrange (wfa->tree [state][label]))
             {
-                int	edge;			/* current edge */
-                int	domain;			/* current domain (context of model) */
-	    
+                int     edge;                   /* current edge */
+                int     domain;                 /* current domain (context of model) */
+
                 for (edge = 0; isedge (domain = wfa->into [state][label][edge]);
                      edge++)
                 {
                     if (wptr - weights_array >= (int) total)
                         error ("Can't write more than %d weights.", total);
-                    if (domain)		/* not DC component */
+                    if (domain)         /* not DC component */
                     {
                         if (delta_approx && wfa->delta_state [state]) /* delta */
                         {
@@ -153,7 +153,7 @@ write_weights (unsigned total, const wfa_t *wfa, bitfile_t *output)
                                 + wfa->level_of_state [state] - 1 - min_level;
                         }
                     }
-                    else			/* DC component */
+                    else                        /* DC component */
                     {
                         if (delta_approx && wfa->delta_state [state]) /* delta */
                         {
@@ -172,9 +172,9 @@ write_weights (unsigned total, const wfa_t *wfa, bitfile_t *output)
             }
 
     {
-        unsigned	 i;
-        unsigned	*c_symbols = Calloc (offset4, sizeof (int));
-        const int	 scale 	   = 500;	/* scaling of probability model */
+        unsigned         i;
+        unsigned        *c_symbols = Calloc (offset4, sizeof (int));
+        const int        scale     = 500;       /* scaling of probability model */
 
         c_symbols [0] = 1 << (wfa->wfainfo->dc_rpf->mantissa_bits + 1);
         if (offset1 != offset2)
@@ -184,12 +184,12 @@ write_weights (unsigned total, const wfa_t *wfa, bitfile_t *output)
             c_symbols [i] = 1 << (wfa->wfainfo->rpf->mantissa_bits + 1);
         for (; i < offset4; i++)
             c_symbols [i] = 1 << (wfa->wfainfo->d_rpf->mantissa_bits + 1);
-      
+
         encode_array (output, weights_array, level_array, c_symbols, offset4,
                       total, scale);
         Free (c_symbols);
     }
-   
+
     debug_message ("%d delta weights out of %d.", delta_count, total);
     debug_message ("weights:      %5d bits. (%5d symbols => %5.2f bps)",
                    bits_processed (output) - bits, total,
diff --git a/converter/other/fiasco/output/weights.h b/converter/other/fiasco/output/weights.h
index f22bd9f8..505918ad 100644
--- a/converter/other/fiasco/output/weights.h
+++ b/converter/other/fiasco/output/weights.h
@@ -1,8 +1,8 @@
 /*
  *  weights.h
  *
- *  Written by:		Ullrich Hafner
- *		
+ *  Written by:         Ullrich Hafner
+ *              
  *  This file is part of FIASCO (Fractal Image And Sequence COdec)
  *  Copyright (C) 1994-2000 Ullrich Hafner
  */
diff --git a/converter/other/fiasco/output/write.c b/converter/other/fiasco/output/write.c
index d6faee26..8c825a12 100644
--- a/converter/other/fiasco/output/write.c
+++ b/converter/other/fiasco/output/write.c
@@ -2,7 +2,7 @@
  *  write.c:        Output of WFA files
  *
  *  Written by:     Ullrich Hafner
- *      
+ *
  *  This file is part of FIASCO (Fractal Image And Sequence COdec)
  *  Copyright (C) 1994-2000 Ullrich Hafner
  */
@@ -32,11 +32,11 @@
 #include "mc.h"
 #include "nd.h"
 #include "write.h"
- 
+
 /*****************************************************************************
 
                 prototypes
-  
+
 *****************************************************************************/
 
 static void
@@ -46,7 +46,7 @@ write_tiling (const tiling_t *tiling, bitfile_t *output);
 
                 public code
 
-                
+
 *****************************************************************************/
 
 
@@ -61,26 +61,26 @@ write_next_wfa (const wfa_t *wfa, const coding_t *c, bitfile_t *output)
 {
    unsigned edges = 0;          /* number of transitions */
    unsigned bits;
-   
+
    debug_message ("--------------------------------------"
           "--------------------------------------");
 
    if (c->mt->number == 0)              /* first WFA */
       write_header (wfa->wfainfo, output);
-  
+
    bits = bits_processed (output);
-   
+
    /*
     *  Frame header information
     */
    {
       const int rice_k = 8;     /* parameter of Rice Code */
 
-      write_rice_code (wfa->states, rice_k, output);      
-      write_rice_code (c->mt->frame_type, rice_k, output); 
-      write_rice_code (c->mt->number, rice_k, output);     
+      write_rice_code (wfa->states, rice_k, output);
+      write_rice_code (c->mt->frame_type, rice_k, output);
+      write_rice_code (c->mt->number, rice_k, output);
    }
-   
+
    OUTPUT_BYTE_ALIGN (output);
 
    debug_message ("frame-header: %5d bits.", bits_processed (output) - bits);
@@ -99,7 +99,7 @@ write_next_wfa (const wfa_t *wfa, const coding_t *c, bitfile_t *output)
 
    if (c->options.prediction)       /* write nondeterministic approx. */
    {
-      put_bit (output, 1); 
+      put_bit (output, 1);
       write_nd (wfa, output);
    }
    else
@@ -107,7 +107,7 @@ write_next_wfa (const wfa_t *wfa, const coding_t *c, bitfile_t *output)
 
    if (c->mt->frame_type != I_FRAME)    /* write motion compensation info */
       write_mc (c->mt->frame_type, wfa, output);
-   
+
    edges = write_matrices (c->options.normal_domains,
                c->options.delta_domains, wfa, output);
 
@@ -140,7 +140,7 @@ write_header (const wfa_info_t *wi, bitfile_t *output)
    for (text = wi->basis_name; *text; text++)
       put_bits (output, *text, 8);
    put_bits (output, *text, 8);
-   
+
    write_rice_code (FIASCO_BINFILE_RELEASE, rice_k, output);
 
    write_rice_code (HEADER_TITLE, rice_k, output);
@@ -149,24 +149,24 @@ write_header (const wfa_info_t *wi, bitfile_t *output)
     text++)
       put_bits (output, *text, 8);
    put_bits (output, 0, 8);
-   
+
    write_rice_code (HEADER_COMMENT, rice_k, output);
    for (text = wi->comment;
     text && *text && text - wi->comment < MAXSTRLEN - 2;
     text++)
       put_bits (output, *text, 8);
    put_bits (output, 0, 8);
-   
+
    write_rice_code (HEADER_END, rice_k, output);
-   
-   write_rice_code (wi->max_states, rice_k, output); 
-   put_bit (output, wi->color ? 1 : 0); 
+
+   write_rice_code (wi->max_states, rice_k, output);
+   put_bit (output, wi->color ? 1 : 0);
    write_rice_code (wi->width, rice_k, output);
    write_rice_code (wi->height, rice_k, output);
    if (wi->color)
-      write_rice_code (wi->chroma_max_states, rice_k, output); 
-   write_rice_code (wi->p_min_level, rice_k, output); 
-   write_rice_code (wi->p_max_level, rice_k, output); 
+      write_rice_code (wi->chroma_max_states, rice_k, output);
+   write_rice_code (wi->p_min_level, rice_k, output);
+   write_rice_code (wi->p_max_level, rice_k, output);
    write_rice_code (wi->frames, rice_k, output);
    write_rice_code (wi->smoothing, rice_k, output);
 
@@ -202,9 +202,9 @@ write_header (const wfa_info_t *wi, bitfile_t *output)
 
    if (wi->frames > 1)          /* motion compensation stuff */
    {
-      write_rice_code (wi->fps, rice_k, output); 
-      write_rice_code (wi->search_range, rice_k, output); 
-      put_bit (output, wi->half_pixel ? 1 : 0); 
+      write_rice_code (wi->fps, rice_k, output);
+      write_rice_code (wi->search_range, rice_k, output);
+      put_bit (output, wi->half_pixel ? 1 : 0);
       put_bit (output, wi->B_as_past_ref ? 1 : 0);
    }
 
@@ -215,7 +215,7 @@ write_header (const wfa_info_t *wi, bitfile_t *output)
 /*****************************************************************************
 
                 private code
-  
+
 *****************************************************************************/
 
 static void
@@ -228,21 +228,21 @@ write_tiling (const tiling_t *tiling, bitfile_t *output)
 {
    const unsigned rice_k = 8;       /* parameter of Rice Code */
    unsigned       bits   = bits_processed (output);
-   
+
    write_rice_code (tiling->exponent, rice_k, output);
    if (tiling->method == FIASCO_TILING_VARIANCE_ASC
        || tiling->method == FIASCO_TILING_VARIANCE_DSC)
    {
       unsigned tile;            /* current image tile */
 
-      put_bit (output, 1);      
+      put_bit (output, 1);
       for (tile = 0; tile < 1U << tiling->exponent; tile++)
      if (tiling->vorder [tile] != -1) /* image tile is visible */
         put_bits (output, tiling->vorder [tile], tiling->exponent);
    }
    else
    {
-      put_bit (output, 0);      
+      put_bit (output, 0);
       put_bit (output, tiling->method == FIASCO_TILING_SPIRAL_ASC);
    }
 
diff --git a/converter/other/fiasco/output/write.h b/converter/other/fiasco/output/write.h
index 6bdc2f1b..1fb3393c 100644
--- a/converter/other/fiasco/output/write.h
+++ b/converter/other/fiasco/output/write.h
@@ -1,8 +1,8 @@
 /*
  *  write.h
  *
- *  Written by:		Ullrich Hafner
- *		
+ *  Written by:         Ullrich Hafner
+ *              
  *  This file is part of FIASCO (Fractal Image And Sequence COdec)
  *  Copyright (C) 1994-2000 Ullrich Hafner
  */
diff --git a/converter/other/fiasco/params.c b/converter/other/fiasco/params.c
index 29f52afc..042a14e2 100644
--- a/converter/other/fiasco/params.c
+++ b/converter/other/fiasco/params.c
@@ -1,8 +1,8 @@
 /*
- *  params.c:		Parameter file and command line parsing
+ *  params.c:           Parameter file and command line parsing
  *
- *  Written by:		Stefan Frank
- *			Ullrich Hafner
+ *  Written by:         Stefan Frank
+ *                      Ullrich Hafner
  *
  *  This file is part of FIASCO (Fractal Image And Sequence COdec)
  *  Copyright (C) 1994-2000 Ullrich Hafner
@@ -22,16 +22,18 @@
 
 #include "config.h"
 
+#include <assert.h>
 #include <stdio.h>
 #include <ctype.h>
-#include <math.h>			/* strtod() on SUN sparc */
+#include <math.h>                       /* strtod() on SUN sparc */
 
 #include <stdlib.h>
 #include <string.h>
 
-#include <getopt.h>			/* system or ../lib */
+#include <getopt.h>                     /* system or ../lib */
 
 #include "pm_c_util.h"
+#include "mallocvar.h"
 #include "nstring.h"
 
 #include "types.h"
@@ -40,627 +42,182 @@
 #include "misc.h"
 #include "fiasco.h"
 
-#include "binerror.h"
-
 #include "params.h"
 
-/*****************************************************************************
-
-				prototypes
 
-*****************************************************************************/
-
-static void
-read_parameter_file (param_t *params, FILE *file);
-static int
-get_parameter_index (const param_t *params, const char *search_string);
-static void
-set_parameter (param_t *parameter, const char *value);
 static void
-usage (const param_t *params, const char *progname, const char *synopsis,
-       const char *comment, const char *non_opt_string,
-       bool_t show_all_options, const char *sys_file_name,
-       const char *usr_file_name);
+setParameter(param_t *    const parameter,
+             const char * const value) {
+/*----------------------------------------------------------------------------
+
+  Set value of 'parameter' to 'value'.
+
+  No return value.
+
+  Side effects:
+     'parameter.value' is changed accordingly
+
+-----------------------------------------------------------------------------*/
+    assert (parameter);
+
+    switch (parameter->type) {
+    case PFLAG:
+        if (value != NULL && *value != '\0') {
+            if (strcaseeq (value, "TRUE"))
+                parameter->value.b = YES;
+            else if (strcaseeq (value, "FALSE"))
+                parameter->value.b = NO;
+            else if (strcaseeq (value, "YES"))
+                parameter->value.b = YES;
+            else if (strcaseeq (value, "NO"))
+                parameter->value.b = NO;
+            else {
+                long int data;
+                char     *endptr;
+
+                data = strtol (value, &endptr, 0);
+                if (*endptr != '\0' || endptr == value)
+                    pm_message("Invalid value `%s' converted to %d",
+                               value, (int) data);
+                parameter->value.b = data ? YES : NO;
+            }
+        } else
+            parameter->value.b = !parameter->value.b;
+        break;
+    case PINT: {
+        long int  data;
+        char     *endptr;
+
+        data = strtol (value, &endptr, 0);
+        if (*endptr != '\0' || endptr == value)
+           pm_message("Invalid value `%s' converted to %d",
+                      value, (int) data);
+        parameter->value.i = data;
+    } break;
+    case PFLOAT: {
+        double      data;
+        char        *endptr;
+
+        data = strtod (value, &endptr);
+        if (*endptr != '\0' || endptr == value)
+           pm_message("Invalid value `%s' converted to %f",
+                      value, (double) data);
+        parameter->value.f = data;
+    } break;
+    case PSTR:
+    case POSTR:
+        parameter->value.s = value ? strdup (value) : NULL;
+        break;
+    default:
+         pm_error("Invalid parameter type for %s", parameter->name);
+    }
+}
 
-/*****************************************************************************
 
-				public code
 
-*****************************************************************************/
+static int
+getParameterIndex(const param_t * const params,
+                  const char *    const search_string) {
+/*----------------------------------------------------------------------------
+  Search for parameter with name 'search_string' in parameter struct.
+
+  Return value: index of parameter or -1 if no matching parameter has been
+  found
+-----------------------------------------------------------------------------*/
+    int n;
+    int index = -1;
+
+    assert (params && search_string);
+
+    for (n = 0; params [n].name != NULL; n++) {
+        if (strcaseeq (params [n].name, search_string)) {
+            index = n;
+            break;
+        }
+    }
 
-int
-parseargs (param_t *usr_params,
-           int argc, char **argv,
-           const char *synopsis,
-           const char *comment,
-           const char *non_opt_string,
-           const char *path,
-           const char *sys_file_name,
-           const char *usr_file_name)
-/*
- *  Perform the command line parsing.
- *  List of allowed parameters is given by 'usr_params'.
- *  Command line and number of parameters are given by 'argv' and 'argc'.
- *  'synopsis' contains a brief description of the program and
- *  'comment' may contain some additional advice.
- *  Initialization order of parameters:
- *	1.) Default values given by the param_t struct
- *	2.) System parameter-file ('path'/'sys_file_name')
- *	3.) User parameter-file ($HOME/'usr_file_name')
- *	4.) Command line parameters
- *	5.) Parameter-file forced by option -f (--config-file)
- *
- *  Return value:
- *	index in ARGV of the first ARGV-element that is not an option.
- *
- *  Side effects:
- *	the elements of ARGV are permuted
- *      usr_params [].value is modified
- */
-{
-   extern int optind;			/* index in ARGV of the 1st element
-					   that is not an option */
-   bool_t     detailed_help = NO;	/* NO if all parameters can be modified
-					   with short options too */
-   unsigned   n1;			/* number of user parameters */
-   unsigned   n2;			/* number of system parameters */
-   bool_t     read_config_file = NO;	/* will override command line */
-   param_t    *params;			/* array of user and system params */
-   param_t    *sys_params;		/* array of system parameters */
-   param_t    detailed_sys_params [] =  /* detailed system parameters */
-   {
-      {"version", NULL, 'v', PFLAG, {0}, NULL,
-       "Print program version number, then exit."},
-      {"verbose", "NUM", 'V', PINT, {0}, "1",
-       "Set level of verbosity to `%s'."},
-      {"config", "FILE", 'f', PSTR, {0}, NULL,
-       "Load `%s' to initialize parameters."},
-      {"info", NULL, 'h', PFLAG, {0}, NULL,
-       "Print brief help, then exit."},
-      {"help", NULL, 'H', PFLAG, {0}, NULL,
-       "Print detailed help, then exit."},
-      {NULL, NULL, 0, PSTR, {0}, NULL, NULL }
-   };
-   param_t    short_sys_params [] =	/* short system parameters */
-   {
-      {"version", NULL, 'v', PFLAG, {0}, NULL,
-       "Print program version number, then exit."},
-      {"verbose", "NUM", 'V', PINT, {0}, "1",
-       "Set level of verbosity to `%s'."},
-      {"config", "FILE", 'f', PSTR, {0}, NULL,
-       "Load `%s' to initialize parameters."},
-      {"help", NULL, 'h', PFLAG, {0}, NULL,
-       "Print this help, then exit."},
-      {NULL, NULL, 0, PSTR, {0}, NULL, NULL }
-   };
-   char *sys_path;			/* path to system config file */
-
-   sys_path = calloc (strlen (path) + strlen (sys_file_name) + 2,
-		      sizeof (char));
-   if (!sys_path)
-      error ("Out of memory.");
-   sprintf (sys_path, "%s/%s", path, sys_file_name);
-
-   /*
-    *  Set parameters defaults
-    */
-   {
-       param_t *p;
-
-       for (p = usr_params; p->name != NULL; p++)
-       {
-           set_parameter (p, p->default_value);
-           if (p->optchar == '\0')
-               detailed_help = YES;
-       }
-
-      sys_params = detailed_help ? detailed_sys_params : short_sys_params;
-
-      for (p = sys_params; p->name != NULL; p++)
-          set_parameter (p, p->default_value);
-   }
-   /*
-    *  Append system command line option to user parameters
-    */
-   for (n1 = 0; usr_params [n1].name != NULL; n1++)
-      ;
-   for (n2 = 0; sys_params [n2].name != NULL; n2++)
-      ;
-   params = calloc (n1 + n2 + 1, sizeof (param_t));
-   if (!params)
-      error ("Out of memory.");
-
-   memcpy (params, usr_params, n1 * sizeof (param_t));
-   memcpy (params + n1, sys_params, (n2 + 1) * sizeof (param_t));
-   /*
-    *  Try to open the system resource file 'path'/'sys_file_name'
-    */
-   {
-      FILE *parameter_file = open_file (sys_path, NULL, READ_ACCESS);
-      if (parameter_file == NULL)
-/*
-	 warning ("No system resource file found.");
-*/ {}
-      else
-      {
-	 read_parameter_file (params, parameter_file);
-	 fclose (parameter_file);
-      }
-   }
-   /*
-    *  Try to read user resource file $HOME/'usr_file_name'
-    */
-   {
-      FILE *parameter_file = open_file (usr_file_name, "HOME", READ_ACCESS);
-      if (parameter_file != NULL)
-      {
-	 read_parameter_file (params, parameter_file);
-	 fclose (parameter_file);
-      }
-   }
-   /*
-    *  Parse command line options
-    */
-   {
-      extern char   *optarg;		/* argument of current option */
-      struct option *long_options;	/* array of long options */
-      int	     option_index = 0;
-      char	     optstr [MAXSTRLEN]; /* string containing the legitimate
-					    option characters */
-      int	     optchar;		/* found option character */
-
-      /*
-       *  Build short option string for getopt_long ().
-       */
-      {
-	 param_t *p;			/* counter */
-	 char	 *ptr_optstr;		/* pointer to position in string */
-
-	 ptr_optstr = optstr;
-	 for (p = params; p->name != NULL; p++)
-	    if (p->optchar != '\0')
-	    {
-	       *ptr_optstr++ = p->optchar;
-	       if (p->type == POSTR)
-	       {
-		  *ptr_optstr++ = ':';
-		  *ptr_optstr++ = ':';
-	       }
-	       else if (p->type != PFLAG)
-		  *ptr_optstr++ = ':';
-	    }
-	 *ptr_optstr = '\0';
-      }
-
-      /*
-       *  Build long option string for getopt_long ().
-       */
-      {
-	 int i;
-
-	 long_options = calloc (n1 + n2 + 1, sizeof (struct option));
-	 if (!long_options)
-	    error ("Out of memory.");
-	 for (i = 0; params [i].name != NULL; i++)
-	 {
-	    long_options [i].name    = params [i].name;
-	    switch (params [i].type)
-	    {
-	       case PFLAG:
-		  long_options [i].has_arg = 0;
-		  break;
-	       case POSTR:
-		  long_options [i].has_arg = 2;
-		  break;
-	       case PINT:
-	       case PSTR:
-	       case PFLOAT:
-	       default:
-		  long_options [i].has_arg = 1;
-		  break;
-	    }
-	    long_options [i].has_arg = params [i].type != PFLAG;
-	    long_options [i].flag    = NULL;
-	    long_options [i].val     = 0;
-	 }
-      }
-
-      /*
-       *  Parse command line
-       */
-      while ((optchar = getopt_long (argc, argv, optstr, long_options,
-				     &option_index)) != EOF)
-      {
-	 int param_index = -1;
-
-	 switch (optchar)
-	 {
-	    case 0:
-	       param_index = option_index;
-	       break;
-	    case ':':
-	       if (detailed_help)
-		  fprintf (stderr,
-			   "Try `%s -h' or `%s --help' for "
-			   "more information.\n",
-			   argv [0], argv [0]);
-	       else
-		  fprintf (stderr, "Try `%s --help' for more information.\n",
-			   argv [0]);
-	       exit (2);
-	       break;
-	    case '?':
-	       if (detailed_help)
-		  fprintf (stderr,
-			   "Try `%s -h' or `%s --help' "
-			   "for more information.\n",
-			   argv [0], argv [0]);
-	       else
-		  fprintf (stderr, "Try `%s --help' for more information.\n",
-			   argv [0]);
-	       exit (2);
-	       break;
-	    default:
-	       {
-		  int i;
-
-		  for (i = 0; params [i].name != NULL; i++)
-		     if (params [i].optchar == optchar)
-		     {
-			param_index = i;
-			break;
-		     }
-	       }
-	 }
-	 /*
-	  *  Check for system options
-	  */
-	 if (param_index >= 0)
-	 {
-	    set_parameter (params + param_index, optarg ? optarg : "");
-	    if (streq (params [param_index].name, "help"))
-	       usage (params, argv [0], synopsis, comment, non_opt_string,
-		      YES, sys_path, usr_file_name);
-	    else if (streq (params [param_index].name, "info"))
-	       usage (params, argv [0], synopsis, comment, non_opt_string,
-		      NO, sys_path, usr_file_name);
-	    else if (streq (params [param_index].name, "version"))
-	    {
-           fprintf (stderr, "%s " VERSION "\n", argv [0]);
-           {
-              /* Kludge for standard Netpbm version announcement */
-              char * modified_argv[2];
-              int argc;
-              modified_argv[0] = argv[0];
-              modified_argv[1] = (char *) "--version";
-              argc = 2;
-              pm_proginit(&argc, (const char **) modified_argv);
-           }
-           exit (2);
-	    }
-	    else if (streq (params [param_index].name, "verbose"))
-	       fiasco_set_verbosity (
-               * (fiasco_verbosity_e *) parameter_value (params,
-                                                         "verbose"));
-	    else if (streq (params [param_index].name, "config"))
-	       read_config_file = YES;
-	    param_index = -1;		/* clear index flag */
-	 }
-      }
-
-      free (long_options);
-   }
-
-   /*
-    *  Read config-file if specified by option -f
-    */
-   if (read_config_file)
-   {
-      char *filename;
-
-      if ((filename = (char *) parameter_value (params, "config")) != NULL)
-      {
-	 FILE *parameter_file;		/* input file */
-
-	 warning ("Options set in file `%s' will override"
-		  " command line options.", filename);
-	 parameter_file = open_file (filename, NULL, READ_ACCESS);
-	 if (parameter_file != NULL)
-	 {
-	    read_parameter_file (params, parameter_file);
-	    fclose (parameter_file);
-	 }
-	 else
-	    file_error (filename);
-      }
-      else
-	 error ("Invalid config filename.");
-   }
-
-   memcpy (usr_params, params, n1 * sizeof (param_t)); /* fill user struct */
-   free (sys_path);
-
-   return optind;
+    return index;
 }
 
-void *
-parameter_value (const param_t *params, const char *name)
-/*
- *  Extract value of parameter 'name.' of the given parameters 'params'.
- *
- *  Return value:
- *	value of given parameter
- */
-{
-   int pind = get_parameter_index (params, name);
 
-   if (pind < 0)
-      error ("Invalid parameter `%s'.", name);
 
-   if (params [pind].type == PSTR || params [pind].type == POSTR)
-      return (void *) params [pind].value.s;
+static void
+readParameterFile(param_t * const params,
+                  FILE *    const file) {
+/*----------------------------------------------------------------------------
 
-   return (void *) &(params [pind].value);
-}
+  Read parameter settings from 'file'.
 
-void
-ask_and_set (param_t *params, const char *name, const char *msg)
-/*
- *  Ask user (print given message 'msg') for missing mandatory
- *  parameter 'name' of the given parameters 'params'.
- *
- *  No return value.
- *
- *  Side effects:
- *	'params ['name'].value' is changed
- */
-{
-   char answer [MAXSTRLEN];
-   int  index = get_parameter_index (params, name);
-
-   if (index < 0)
-      error ("Invalid parameter %s.", name);
-
-   if (msg)
-      fprintf (stderr, "%s\n", msg);
-
-   switch (params [index].type)
-   {
-      case PFLAG:			/* Unusual, at least. */
-	 warning ("Flags should be initialized and set on demand, "
-		  "not request");
-      case PINT:
-      case PSTR:
-      case POSTR:
-      case PFLOAT:
-	 scanf (MAXSTRLEN_SCANF, answer);
-	 set_parameter (&params [index], answer);
-	 break;
-      default:
-	 error ("Invalid parameter type for %s", name);
-   }
-}
+  No return value.
 
-void
-write_parameters (const param_t *params, FILE *output)
-/*
- *  Write all parameter settings to 'output'.
- *
- *  No return value.
- */
-{
-   int pind;
-
-   if (!params || !output)
-      error ("Parameters must be not NULL.");
-
-   for (pind = 0; params [pind].name != NULL; pind++)
-   {
-      fprintf (output, "# %s = ", params [pind].name);
-      switch (params [pind].type)
-      {
-	 case PFLAG:
-	    fprintf (output, "%s\n", params [pind].value.b ? "TRUE" : "FALSE");
-	    break;
-	 case PINT:
-	    fprintf (output, "%d\n", params [pind].value.i);
-	    break;
-	 case PFLOAT:
-	    fprintf (output, "%.4f\n", (double) params [pind].value.f);
-	    break;
-	 case PSTR:
-	 case POSTR:
-	    fprintf (output, "%s\n", params [pind].value.s);
-	    break;
-	 default:
-	    error ("Invalid type %d for parameter %s",
-		   params [pind].type, params [pind].name);
-      }
-   }
-   fputc ('\n', output);
-}
+  Side effects:
+      'params [].value' are changed if specified in 'file'
+-----------------------------------------------------------------------------*/
+    char buffer [MAXSTRLEN];
+    int  n = 0;
 
-/*****************************************************************************
+    assert (params && file);
 
-				private code
+    while (fgets (buffer, MAXSTRLEN, file) != NULL) {
+        char *b;                          /* temporary variable */
+        char *name;                       /* parameter name */
+        char *value;                      /* parameter value */
+        int   pind;                       /* current argument number */
 
-*****************************************************************************/
+        b = strchr (buffer, '#');
+        if (b != NULL)                    /* Strip comments. */
+            *b = '\0';
 
-static void
-set_parameter (param_t *parameter, const char *value)
-/*
- *  Set value of 'parameter' to 'value'.
- *
- *  No return value.
- *
- *  Side effects:
- *	'parameter.value' is changed accordingly
- */
-{
-   assert (parameter);
-
-   switch (parameter->type)
-   {
-      case PFLAG:
-	 if (value != NULL && *value != '\0')
-	 {
-	    if (strcaseeq (value, "TRUE"))
-	       parameter->value.b = YES;
-	    else if (strcaseeq (value, "FALSE"))
-	       parameter->value.b = NO;
-	    else if (strcaseeq (value, "YES"))
-	       parameter->value.b = YES;
-	    else if (strcaseeq (value, "NO"))
-	       parameter->value.b = NO;
-	    else
-	    {
-	       long int	data;
-	       char	*endptr;
-
-	       data = strtol (value, &endptr, 0);
-	       if (*endptr != '\0' || endptr == value)
-		  warning ("Invalid value `%s' converted to %d",
-			   value, (int) data);
-	       parameter->value.b = data ? YES : NO;
-	    }
-	 }
-	 else
-	    parameter->value.b = !parameter->value.b;
-	 break;
-      case PINT:
-	 {
-	    long int  data;
-	    char     *endptr;
-
-	    data = strtol (value, &endptr, 0);
-	    if (*endptr != '\0' || endptr == value)
-	       warning ("Invalid value `%s' converted to %d",
-			value, (int) data);
-	    parameter->value.i = data;
-	 }
-	 break;
-      case PFLOAT:
-	 {
-	    double	data;
-	    char	*endptr;
-
-	    data = strtod (value, &endptr);
-	    if (*endptr != '\0' || endptr == value)
-	       warning ("Invalid value `%s' converted to %f",
-			value, (double) data);
-	    parameter->value.f = data;
-	 }
-	 break;
-      case PSTR:
-      case POSTR:
-	 parameter->value.s = value ? strdup (value) : NULL;
-	 break;
-      default:
-	 error ("Invalid parameter type for %s", parameter->name);
-   }
-}
+        b = strchr (buffer, '=');
+        if (b == NULL)                    /* Strip lines that contain no '=' */
+            continue;
+        *b = '\0';                       /* Replace '=' by string terminator */
 
-static int
-get_parameter_index (const param_t *params, const char *search_string)
-/*
- *  Search for parameter with name 'search_string' in parameter struct.
- *
- *  Return value:
- *	index of parameter or -1 if no matching parameter has been found
- */
-{
-   int n;
-   int index = -1;
+        /* Extract value of parameter */
+        for (value = b + 1; ISSPACE (*value); value++)
+            ;                              /* Delete leading spaces */
 
-   assert (params && search_string);
+        for (b = value + strlen (value) - 1; b >= value && ISSPACE (*b); b--)
+            *b = '\0';                     /* Delete trailing spaces. */
 
-   for (n = 0; params [n].name != NULL; n++)
-      if (strcaseeq (params [n].name, search_string))
-      {
-	 index = n;
-	 break;
-      }
+        /* Extract parameter name */
+        for (name = buffer; ISSPACE (*name); name++)
+            ;                              /* Delete leading spaces */
 
-   return index;
-}
+        for (b = name + strlen (name) - 1; b >= name && ISSPACE (*b); b--)
+            *b = '\0';                     /* Delete trailing spaces. */
 
-static void
-read_parameter_file (param_t *params, FILE *file)
-/*
- *  Read parameter settings from 'file'.
- *
- *  No return value.
- *
- *  Side effects:
- *	'params [].value' are changed if specified in 'file'
- */
-{
-   char buffer [MAXSTRLEN];
-   int  n = 0;
-
-   assert (params && file);
-
-   while (fgets (buffer, MAXSTRLEN, file) != NULL)
-   {
-      char *b;				/* temporary variable */
-      char *name;			/* parameter name */
-      char *value;			/* parameter value */
-      int   pind;			/* current argument number */
-
-      b = strchr (buffer, '#');
-      if (b != NULL)			/* Strip comments. */
-	 *b = '\0';
-
-      b = strchr (buffer, '=');
-      if (b == NULL)			/* Strip lines that contain no '=' */
-	 continue;
-      *b = '\0';			/* Replace '=' by string terminator */
-
-      /*
-       *  Extract value of parameter
-       */
-      for (value = b + 1; ISSPACE (*value); value++)
-	 ;				/* Delete leading spaces */
-
-      for (b = value + strlen (value) - 1; b >= value && ISSPACE (*b); b--)
-	 *b = '\0';			/* Delete trailing spaces. */
-
-      /*
-       *  Extract parameter name
-       */
-      for (name = buffer; ISSPACE (*name); name++)
-	 ;				/* Delete leading spaces */
-
-      for (b = name + strlen (name) - 1; b >= name && ISSPACE (*b); b--)
-	 *b = '\0';			/* Delete trailing spaces. */
-
-      pind = get_parameter_index (params, name);
-      if (pind >= 0)
-	 set_parameter (&params [pind], value);
-
-      n++;
-   }
+        pind = getParameterIndex(params, name);
+        if (pind >= 0)
+            setParameter(&params[pind], value);
+
+        ++n;
+    }
 }
 
 
 
 static void
-usage (const param_t *params, const char *progname, const char *synopsis,
-       const char *comment, const char *non_opt_string,
-       bool_t show_all_options, const char *sys_file_name,
-       const char *usr_file_name)
-/*
- *  Generates and prints command line description from param_t struct 'params'.
- *  'progname' is the name of the executable, 'synopsis' a short program
- *  description, and 'comment' some more advice.
- *  If flag 'show_all_options' is set then print also options that are not
- *  associated with a short option character.
- *  'sys_file_name' and 'usr_file_name' are filenames to parameter files.
- *
- *  No return value.
- */
-{
-    int	  i;
+usage(const param_t *  const params,
+      const char *     const progname,
+      const char *     const synopsis,
+      const char *     const comment,
+      const char *     const non_opt_string,
+      bool_t           const show_all_options,
+      const char *     const sys_file_name,
+      const char *     const usr_file_name) {
+/*----------------------------------------------------------------------------
+
+  Generates and prints command line description from param_t struct 'params'.
+  'progname' is the name of the executable, 'synopsis' a short program
+  description, and 'comment' some more advice.
+  If flag 'show_all_options' is set then print also options that are not
+  associated with a short option character.
+  'sys_file_name' and 'usr_file_name' are filenames to parameter files.
+
+  No return value.
+-----------------------------------------------------------------------------*/
+    int   i;
     size_t width = 0;
 
     fprintf (stderr, "Usage: %s [OPTION]...%s\n", progname,
@@ -671,9 +228,8 @@ usage (const param_t *params, const char *progname, const char *synopsis,
     fprintf (stderr, "Mandatory or optional arguments to long options "
              "are mandatory or optional\nfor short options too. "
              "Default values are surrounded by {}.\n");
-    for (i = 0; params [i].name != NULL; i++)
-        if (params [i].optchar != '\0' || show_all_options)
-        {
+    for (i = 0; params [i].name != NULL; i++) {
+        if (params [i].optchar != '\0' || show_all_options) {
             if (params [i].type == POSTR)
                 width = MAX(width, (strlen (params [i].name)
                                      + strlen (params [i].argument_name) + 2));
@@ -683,10 +239,9 @@ usage (const param_t *params, const char *progname, const char *synopsis,
             else
                 width = MAX(width, (strlen (params [i].name)) - 1);
         }
-
-    for (i = 0; params [i].name != NULL; i++)
-        if (params [i].optchar != '\0' || show_all_options)
-        {
+    }
+    for (i = 0; params [i].name != NULL; i++) {
+        if (params [i].optchar != '\0' || show_all_options) {
             if (params [i].optchar != '\0')
                 fprintf (stderr, "  -%c, --", params [i].optchar);
             else
@@ -708,8 +263,7 @@ usage (const param_t *params, const char *progname, const char *synopsis,
 
             fprintf (stderr, params [i].use, params [i].argument_name);
 
-            switch (params [i].type)
-            {
+            switch (params [i].type) {
             case PFLAG:
                 break;
             case PINT:
@@ -724,20 +278,407 @@ usage (const param_t *params, const char *progname, const char *synopsis,
                     fprintf (stderr, "{%s}", params [i].value.s);
                 break;
             default:
-                error ("type %d for %s invalid",
-                       params [i].type, params [i].name);
+               pm_error("type %d for %s invalid",
+                        params [i].type, params [i].name);
             }
             fprintf (stderr, "\n");
         }
+    }
     fprintf (stderr, "\n");
+
     fprintf (stderr, "Parameter initialization order:\n");
     fprintf (stderr,
              "1.) %s\n2.) $HOME/%s\t 3.) command line\t 4.) --config=file",
              sys_file_name, usr_file_name);
     fprintf (stderr, "\n\n");
+
     if (comment != NULL)
         fprintf (stderr, "%s\n", comment);
 
     exit (1);
 }
 
+
+
+const void *
+parameter_value(const param_t * const params,
+                const char *    const name) {
+/*----------------------------------------------------------------------------
+  Extract value of parameter 'name.' of the given parameters 'params'.
+
+  Return value: value of given parameter
+
+-----------------------------------------------------------------------------*/
+    int pind = getParameterIndex(params, name);
+
+    if (pind < 0)
+        pm_error("Invalid parameter '%s'.", name);
+
+    if (params[pind].type == PSTR || params[pind].type == POSTR)
+        return params[pind].value.s;
+
+    return &(params[pind].value);
+}
+
+
+
+int
+parseargs(param_t *     const usr_params,
+          int argc,
+          const char ** const argv,
+          const char *  const synopsis,
+          const char *  const comment,
+          const char *  const non_opt_string,
+          const char *  const path,
+          const char *  const sys_file_name,
+          const char *  const usr_file_name) {
+/*----------------------------------------------------------------------------
+  Perform the command line parsing.
+  List of allowed parameters is given by 'usr_params'.
+  Command line and number of parameters are given by 'argv' and 'argc'.
+  'synopsis' contains a brief description of the program and
+  'comment' may contain some additional advice.
+  Initialization order of parameters:
+     1.) Default values given by the param_t struct
+     2.) System parameter-file ('path'/'sys_file_name')
+     3.) User parameter-file ($HOME/'usr_file_name')
+     4.) Command line parameters
+     5.) Parameter-file forced by option -f (--config-file)
+
+  Return value:
+      index in ARGV of the first ARGV-element that is not an option.
+
+  Side effects:
+      the elements of ARGV are permuted
+      usr_params [].value is modified
+-----------------------------------------------------------------------------*/
+    extern int optind;                   /* index in ARGV of the 1st element
+                                            that is not an option */
+    bool_t     detailed_help = NO;      /* NO if all parameters can be modified
+                                            with short options too */
+    unsigned   n1;                       /* number of user parameters */
+    unsigned   n2;                       /* number of system parameters */
+    bool_t     read_config_file = NO;    /* will override command line */
+    param_t    *params;                  /* array of user and system params */
+    param_t    *sys_params;              /* array of system parameters */
+    param_t    detailed_sys_params [] =  /* detailed system parameters */
+        {
+            {"version", NULL, 'v', PFLAG, {0}, NULL,
+             "Print program version number, then exit."},
+            {"verbose", "NUM", 'V', PINT, {0}, "1",
+             "Set level of verbosity to `%s'."},
+            {"config", "FILE", 'f', PSTR, {0}, NULL,
+             "Load `%s' to initialize parameters."},
+            {"info", NULL, 'h', PFLAG, {0}, NULL,
+             "Print brief help, then exit."},
+            {"help", NULL, 'H', PFLAG, {0}, NULL,
+             "Print detailed help, then exit."},
+            {NULL, NULL, 0, PSTR, {0}, NULL, NULL }
+        };
+    param_t    short_sys_params [] =     /* short system parameters */
+        {
+            {"version", NULL, 'v', PFLAG, {0}, NULL,
+             "Print program version number, then exit."},
+            {"verbose", "NUM", 'V', PINT, {0}, "1",
+             "Set level of verbosity to `%s'."},
+            {"config", "FILE", 'f', PSTR, {0}, NULL,
+             "Load `%s' to initialize parameters."},
+            {"help", NULL, 'h', PFLAG, {0}, NULL,
+             "Print this help, then exit."},
+            {NULL, NULL, 0, PSTR, {0}, NULL, NULL }
+        };
+    const char * sys_path;                     /* path to system config file */
+
+    pm_asprintf(&sys_path, "%s/%s", path, sys_file_name);
+
+    /* Set parameters defaults */
+    {
+        param_t *p;
+
+        for (p = usr_params; p->name != NULL; p++)
+        {
+            setParameter(p, p->default_value);
+            if (p->optchar == '\0')
+                detailed_help = YES;
+        }
+
+        sys_params = detailed_help ? detailed_sys_params : short_sys_params;
+
+        for (p = sys_params; p->name != NULL; p++)
+            setParameter(p, p->default_value);
+    }
+    /* Append system command line option to user parameters */
+    for (n1 = 0; usr_params [n1].name != NULL; n1++)
+        ;
+    for (n2 = 0; sys_params [n2].name != NULL; n2++)
+        ;
+    MALLOCARRAY_NOFAIL(params, n1 + n2 + 1);
+
+    memcpy(params, usr_params, n1 * sizeof(param_t));
+    memcpy(params + n1, sys_params, (n2 + 1) * sizeof(param_t));
+
+    {
+        /* Try to open the system resource file 'path'/'sys_file_name' */
+
+        FILE *parameter_file = open_file(sys_path, NULL, READ_ACCESS);
+
+        if (parameter_file) {
+            readParameterFile(params, parameter_file);
+            fclose(parameter_file);
+        }
+    }
+    {
+        /* Try to read user resource file $HOME/'usr_file_name' */
+
+        FILE *parameter_file = open_file(usr_file_name, "HOME", READ_ACCESS);
+
+        if (parameter_file) {
+            readParameterFile(params, parameter_file);
+            fclose(parameter_file);
+        }
+    }
+    {
+        /* Parse command line options */
+
+        extern char   *optarg;            /* argument of current option */
+        struct option *long_options;      /* array of long options */
+        int            option_index = 0;
+        char           optstr [MAXSTRLEN]; /* string containing the legitimate
+                                              option characters */
+        int            optchar;           /* found option character */
+
+        {
+            /* Build short option string for getopt_long (). */
+            param_t *p;                    /* counter */
+            char    *ptr_optstr;           /* pointer to position in string */
+
+            ptr_optstr = optstr;
+            for (p = params; p->name != NULL; p++)
+                if (p->optchar != '\0')
+                {
+                    *ptr_optstr++ = p->optchar;
+                    if (p->type == POSTR)
+                    {
+                        *ptr_optstr++ = ':';
+                        *ptr_optstr++ = ':';
+                    }
+                    else if (p->type != PFLAG)
+                        *ptr_optstr++ = ':';
+                }
+            *ptr_optstr = '\0';
+        }
+
+        {
+            /* Build long option string for getopt_long (). */
+
+            int i;
+
+            MALLOCARRAY_NOFAIL(long_options, n1 + n2 + 1);
+
+            for (i = 0; params [i].name != NULL; i++) {
+                long_options [i].name    = params [i].name;
+                switch (params [i].type)
+                {
+                case PFLAG:
+                    long_options [i].has_arg = 0;
+                    break;
+                case POSTR:
+                    long_options [i].has_arg = 2;
+                    break;
+                case PINT:
+                case PSTR:
+                case PFLOAT:
+                default:
+                    long_options [i].has_arg = 1;
+                    break;
+                }
+                long_options [i].has_arg = params [i].type != PFLAG;
+                long_options [i].flag    = NULL;
+                long_options [i].val     = 0;
+            }
+        }
+
+        /* Parse command line */
+
+        while ((optchar = getopt_long(argc, (char **)argv, optstr,
+                                      long_options,
+                                      &option_index)) != EOF) {
+            int param_index = -1;
+
+            switch (optchar) {
+            case 0:
+                param_index = option_index;
+                break;
+            case ':':
+                if (detailed_help)
+                    fprintf (stderr,
+                             "Try `%s -h' or `%s --help' for "
+                             "more information.\n",
+                             argv [0], argv [0]);
+                else
+                    fprintf (stderr, "Try `%s --help' for more information.\n",
+                             argv [0]);
+                exit (2);
+                break;
+            case '?':
+                if (detailed_help)
+                    fprintf (stderr,
+                             "Try `%s -h' or `%s --help' "
+                             "for more information.\n",
+                             argv [0], argv [0]);
+                else
+                    fprintf (stderr, "Try `%s --help' for more information.\n",
+                             argv [0]);
+                exit (2);
+                break;
+            default: {
+                int i;
+
+                for (i = 0; params [i].name != NULL; i++) {
+                    if (params [i].optchar == optchar) {
+                        param_index = i;
+                        break;
+                    }
+                }
+            }
+            }
+            /* Check for system options  */
+
+            if (param_index >= 0) {
+                setParameter(params + param_index, optarg ? optarg : "");
+                if (streq(params[param_index].name, "help"))
+                    usage(params, argv [0], synopsis, comment, non_opt_string,
+                          YES, sys_path, usr_file_name);
+                else if (streq(params[param_index].name, "info"))
+                    usage(params, argv [0], synopsis, comment, non_opt_string,
+                           NO, sys_path, usr_file_name);
+                else if (streq(params[param_index].name, "version")) {
+                    fprintf(stderr, "%s " VERSION "\n", argv [0]);
+                    {
+                        /* Kludge for standard Netpbm version announcement */
+                        const char * modifiedArgv[2];
+                        int argc;
+                        modifiedArgv[0] = argv[0];
+                        modifiedArgv[1] = (char *) "--version";
+                        argc = 2;
+                        pm_proginit(&argc, modifiedArgv);
+                    }
+                    exit (2);
+                } else if (streq(params[param_index].name, "verbose"))
+                    fiasco_set_verbosity(
+                        * (fiasco_verbosity_e *) parameter_value(params,
+                                                                 "verbose"));
+                else if (streq(params[param_index].name, "config"))
+                    read_config_file = YES;
+                param_index = -1;           /* clear index flag */
+            }
+        }
+        free(long_options);
+    }
+
+    /* Read config-file if specified by option -f */
+    if (read_config_file) {
+        char * filename;
+
+        if ((filename = (char *) parameter_value(params, "config")) != NULL) {
+            FILE * parameter_file;          /* input file */
+
+            pm_message("Options set in file `%s' will override"
+                       " command line options.", filename);
+            parameter_file = open_file(filename, NULL, READ_ACCESS);
+            if (parameter_file != NULL) {
+                readParameterFile(params, parameter_file);
+                fclose(parameter_file);
+            } else
+                pm_error("Failed to open config file '%s'", filename);
+        } else
+            pm_error("Invalid config filename.");
+    }
+
+    memcpy(usr_params, params, n1 * sizeof (param_t)); /* fill user struct */
+    pm_strfree(sys_path);
+
+    return optind;
+}
+
+
+
+void
+ask_and_set(param_t *    const params,
+            const char * const name,
+            const char * const msg) {
+/*----------------------------------------------------------------------------
+  Ask user (print given message 'msg') for missing mandatory
+  parameter 'name' of the given parameters 'params'.
+
+  No return value.
+
+  Side effects:
+     'params ['name'].value' is changed
+-----------------------------------------------------------------------------*/
+    char answer[MAXSTRLEN];
+    int  index = getParameterIndex(params, name);
+
+    if (index < 0)
+        pm_error("Invalid parameter '%s'.", name);
+
+    if (msg)
+        pm_message("%s", msg);
+
+    switch (params[index].type) {
+    case PFLAG:                       /* Unusual, at least. */
+        pm_message("Flags should be initialized and set on demand, "
+                   "not request");
+    case PINT:
+    case PSTR:
+    case POSTR:
+    case PFLOAT:
+        scanf(MAXSTRLEN_SCANF, answer);
+        setParameter(&params [index], answer);
+        break;
+    default:
+        pm_error("Invalid parameter type for %s", name);
+    }
+}
+
+
+
+void
+write_parameters(const param_t * const params,
+                 FILE *          const output) {
+/*----------------------------------------------------------------------------
+  Write all parameter settings to 'output'.
+
+  No return value.
+-----------------------------------------------------------------------------*/
+    unsigned int pind;
+
+    if (!params || !output)
+        pm_error("Parameters must be not NULL.");
+
+    for (pind = 0; params[pind].name != NULL; pind++) {
+        fprintf(output, "# %s = ", params[pind].name);
+        switch(params[pind].type) {
+        case PFLAG:
+            fprintf(output, "%s\n", params[pind].value.b ? "TRUE" : "FALSE");
+            break;
+        case PINT:
+            fprintf(output, "%d\n", params[pind].value.i);
+            break;
+        case PFLOAT:
+            fprintf(output, "%.4f\n", (double) params[pind].value.f);
+            break;
+        case PSTR:
+        case POSTR:
+            fprintf(output, "%s\n", params[pind].value.s);
+            break;
+        default:
+            pm_error("Invalid type %d for parameter %s",
+                     params[pind].type, params[pind].name);
+        }
+    }
+    fputc ('\n', output);
+}
+
+
+
diff --git a/converter/other/fiasco/params.h b/converter/other/fiasco/params.h
index a1164cf7..85b0b648 100644
--- a/converter/other/fiasco/params.h
+++ b/converter/other/fiasco/params.h
@@ -3,7 +3,7 @@
  *
  *  Written by:     Stefan Frank
  *          Ullrich Hafner
- *      
+ *
  *  This file is part of FIASCO (Fractal Image And Sequence COdec)
  *  Copyright (C) 1994-2000 Ullrich Hafner
  */
@@ -43,19 +43,21 @@ typedef struct param_t
 } param_t;
 
 int
-parseargs (param_t *usr_params, 
-           int argc, char **argv, 
+parseargs (param_t *usr_params,
+           int argc, const char **argv,
            const char *synopsis,
-           const char *comment, 
-           const char *non_opt_string, 
+           const char *comment,
+           const char *non_opt_string,
            const char *path,
-           const char *sys_file_name, 
+           const char *sys_file_name,
            const char *usr_file_name);
 void
 write_parameters (const param_t *params, FILE *output);
+
 void
 ask_and_set (param_t *params, const char *name, const char *msg);
-void *
+
+const void *
 parameter_value (const param_t *params, const char *name);
 
 #endif /* not PARAMS_H */
diff --git a/converter/other/fiasco/pnmtofiasco.c b/converter/other/fiasco/pnmtofiasco.c
index 9f63e7a1..311a21c3 100644
--- a/converter/other/fiasco/pnmtofiasco.c
+++ b/converter/other/fiasco/pnmtofiasco.c
@@ -1,5 +1,5 @@
 /*
- *  cwfa.c:     FIASCO coder
+ *  FIASCO coder
  *
  *  Written by:     Ullrich Hafner
  *
@@ -15,32 +15,25 @@
  */
 
 #include "config.h"
-#include "pm_c_util.h"
-#include "pnm.h"
-
 #include <stdlib.h>
 #include <string.h>
 #include <string.h>
 
+#include "pm_c_util.h"
+#include "mallocvar.h"
+#include "pnm.h"
+
 #include "types.h"
 #include "macros.h"
 
-#include "binerror.h"
 #include "misc.h"
 #include "params.h"
 #include "fiasco.h"
 
-/*****************************************************************************
 
-                 local variables
 
-*****************************************************************************/
-
-static param_t params [] =
-{
-  /*
-   *  Options for standard user
-   */
+static param_t params[] = {
+  /* Options for standard user */
   {"image-name", "FILE", 'i', PSTR, {0}, NULL,
    "Compress raw PPM/PGM image(s) `%s'."},
   {"output-name", "FILE", 'o', PSTR, {0}, "-",
@@ -136,244 +129,202 @@ static param_t params [] =
   {NULL, NULL, 0, PSTR, {0}, NULL, NULL }
 };
 
-/*****************************************************************************
-
-                prototypes
-
-*****************************************************************************/
-
-static void
-checkargs (int argc, char **argv, char const ***image_template,
-       char **wfa_name, float *quality, fiasco_c_options_t **options);
-
-/*****************************************************************************
-
-                public code
-
-*****************************************************************************/
-
-int
-main (int argc, char **argv)
-{
-   char const         **image_template; /* template for input image files */
-   char                *wfa_name;   /* filename of output WFA */
-   float            quality;    /* approximation quality */
-   fiasco_c_options_t  *options;    /* additional coder options */
-
-   pnm_init(&argc, argv);
-
-   init_error_handling (argv [0]);
-
-   checkargs (argc, argv, &image_template, &wfa_name, &quality, &options);
-
-   if (fiasco_coder (image_template, wfa_name, quality, options))
-      return 0;
-   else
-   {
-       fprintf (stderr, "%s", fiasco_get_error_message ());
-      fprintf (stderr, "\n");
-      return 1;
-   }
-}
-
-/*****************************************************************************
-
-                private code
 
-*****************************************************************************/
 
 static void
-checkargs (int argc, char **argv, char const ***image_template,
-           char **wfa_name, float *quality, fiasco_c_options_t **options)
-/*
- *  Check validness of command line parameters and of the parameter files.
- *
- *  Return value:
- *  1 on success
- *  0 otherwise
- *
- *
- *  Side effects:
- *  'image_template', 'wfa_name', 'quality' and 'options' are set.
- */
-{
-    int   optind;            /* last processed commandline param */
-    char *image_name;            /* filename given by option '--input_name' */
-    int   i;             /* counter */
-
-    optind = parseargs (params, argc, argv,
-                        "Compress raw PPM/PGM image FILEs to a FIASCO file.",
-                        "With no image FILE, or if FILE is -, "
-                        "read standard input.\n"
-                        "FILE must be either a filename"
-                        " or an image template of the form:\n"
-                        "`prefix[start-end{+,-}step]suffix'\n"
-                        "e.g., img0[12-01-1].pgm is substituted by"
-                        " img012.pgm ... img001.pgm\n\n"
-                        "Environment:\n"
-                        "FIASCO_DATA   Search and save path for FIASCO files. "
-                        "Default: ./\n"
-                        "FIASCO_IMAGES Search path for image files. "
-                        "Default: ./", " [FILE]...",
-                        FIASCO_SHARE, "system.fiascorc", ".fiascorc");
-
-    /*
-     *  Default options ...
-     */
-    image_name = (char *) parameter_value (params, "image-name");
-    *wfa_name  = (char *) parameter_value (params, "output-name");
-    for (;;)
-    {
-        *quality = * (float *) parameter_value (params, "quality");
+checkargs(int                         argc,
+          const char **               argv,
+          const char ***        const imageTemplateListP,
+          char **               const wfa_name,
+          float *               const quality,
+          fiasco_c_options_t ** const options) {
+/*----------------------------------------------------------------------------
+  Check validness of command line parameters and of the parameter files.
+
+  Return value:
+    1 on success
+    0 otherwise
+-----------------------------------------------------------------------------*/
+    int    optind;            /* last processed commandline param */
+    char * image_name;            /* filename given by option '--input_name' */
+    const char ** imageTemplateList;
+
+    optind = parseargs(params, argc, argv,
+                       "Compress raw PPM/PGM image FILEs to a FIASCO file.",
+                       "With no image FILE, or if FILE is -, "
+                       "read standard input.\n"
+                       "FILE must be either a filename"
+                       " or an image template of the form:\n"
+                       "`prefix[start-end{+,-}step]suffix'\n"
+                       "e.g., img0[12-01-1].pgm is substituted by"
+                       " img012.pgm ... img001.pgm\n\n"
+                       "Environment:\n"
+                       "FIASCO_DATA   Search and save path for FIASCO files. "
+                       "Default: ./\n"
+                       "FIASCO_IMAGES Search path for image files. "
+                       "Default: ./", " [FILE]...",
+                       FIASCO_SHARE, "system.fiascorc", ".fiascorc");
+
+    /* Default options  */
+    image_name = (char *) parameter_value(params, "image-name");
+    *wfa_name  = (char *) parameter_value(params, "output-name");
+    for (;;) {
+        *quality = * (float *) parameter_value(params, "quality");
         if (*quality > 100)
-            fprintf (stderr, "Typical range of quality: (0,100].\n"
-                     "Expect some trouble on slow machines.\n");
+            pm_message("Typical range of quality: (0,100].  "
+                       "Expect some trouble on slow machines.");
         if (*quality > 0)
             break;
-        ask_and_set (params, "quality",
-                     "Please enter coding quality 'q' ('q' > 0): ");
+        ask_and_set(params, "quality",
+                    "Please enter coding quality 'q' ('q' > 0): ");
     }
 
-    if (optind < argc)           /* Additional command line param */
-    {
+    /* Non-option command line params */
+    if (optind < argc) {
+        unsigned int i;
         if (image_name)
-            error ("Multiple image_template arguments."
-                   "\nOption --input-name %s already specified!", image_name);
-
-        *image_template = calloc (argc - optind + 1, sizeof (char *));
-        if (!*image_template)
-            error ("Out of memory.");
-        for (i = 0; optind < argc; i++, optind++)
-            (*image_template) [i] = argv [optind];
-        (*image_template) [i] = NULL;
-    }
-    else                 /* option -i image_name */
-    {
-        *image_template = calloc (2, sizeof (char *));
-        if (!*image_template)
-            error ("Out of memory.");
-        (*image_template) [0] = image_name;
-        (*image_template) [1] = NULL;
+            pm_error("Multiple image name template arguments.  "
+                     "Option --image-name already specified with '%s'",
+                     image_name);
+
+        MALLOCARRAY_NOFAIL(imageTemplateList, argc - optind + 1);
+
+        for (i = 0; optind < argc; ++i, ++optind)
+            imageTemplateList[i] = argv[optind];
+        imageTemplateList[i] = NULL;
+    } else {
+        /* option -i image_name */
+
+        MALLOCARRAY_NOFAIL(imageTemplateList, 2);
+
+        imageTemplateList[0] = image_name;
+        imageTemplateList[1] = NULL;
     }
-    /*
-     *  Additional options ... (have to be set with the fiasco_set_... methods)
+    /* Additional options ... (have to be set with the fiasco_set_... methods)
      */
     {
-        *options = fiasco_c_options_new ();
+        *options = fiasco_c_options_new();
 
         {
-            char *pattern = (char *) parameter_value (params, "pattern");
+            const char * const pattern = parameter_value(params, "pattern");
 
             if (!fiasco_c_options_set_frame_pattern (*options, pattern))
-                error (fiasco_get_error_message ());
+                pm_error("%s", fiasco_get_error_message ());
         }
 
         {
-            char *basis = (char *) parameter_value (params, "basis-name");
+            const char *const basis = parameter_value(params, "basis-name");
 
             if (!fiasco_c_options_set_basisfile (*options, basis))
-                error (fiasco_get_error_message ());
+                pm_error("%s", fiasco_get_error_message ());
         }
 
         {
-            int   n = * (int *) parameter_value (params, "chroma-dictionary");
-            float q = * (float *) parameter_value (params, "chroma-qfactor");
+            int   const n =
+                *(int *)parameter_value(params, "chroma-dictionary");
+            float const q =
+                *(float *)parameter_value(params, "chroma-qfactor");
 
-            if (!fiasco_c_options_set_chroma_quality (*options, q, MAX(0, n)))
-                error (fiasco_get_error_message ());
+            if (!fiasco_c_options_set_chroma_quality(*options, q, MAX(0, n)))
+                pm_error("%s", fiasco_get_error_message ());
         }
 
         {
-            int n = *((int *) parameter_value (params, "smooth"));
+            int const n = *((int *)parameter_value(params, "smooth"));
 
-            if (!fiasco_c_options_set_smoothing (*options, MAX(0, n)))
-                error (fiasco_get_error_message ());
+            if (!fiasco_c_options_set_smoothing(*options, MAX(0, n)))
+                pm_error("%s", fiasco_get_error_message ());
         }
 
         {
-            int n = * (int *) parameter_value (params, "progress-meter");
+            int const n = *(int *)parameter_value(params, "progress-meter");
             fiasco_progress_e type = (n < 0) ?
                 FIASCO_PROGRESS_NONE : (fiasco_progress_e) n;
 
-            if (!fiasco_c_options_set_progress_meter (*options, type))
-                error (fiasco_get_error_message ());
+            if (!fiasco_c_options_set_progress_meter(*options, type))
+                pm_error("%s", fiasco_get_error_message ());
         }
 
         {
-            char *t = (char *) parameter_value (params, "title");
+            const char * const t = parameter_value(params, "title");
 
-            if (strlen (t) > 0 && !fiasco_c_options_set_title (*options, t))
-                error (fiasco_get_error_message ());
+            if (strlen(t) > 0 && !fiasco_c_options_set_title(*options, t))
+                pm_error("%s", fiasco_get_error_message ());
         }
 
         {
-            char *c = (char *) parameter_value (params, "comment");
+            const char * const c = parameter_value(params, "comment");
 
             if (strlen (c) > 0 && !fiasco_c_options_set_comment (*options, c))
-                error (fiasco_get_error_message ());
+                pm_error("%s", fiasco_get_error_message ());
         }
 
         {
             fiasco_tiling_e method = FIASCO_TILING_VARIANCE_DSC;
-            int   e  = * (int *) parameter_value (params, "tiling-exponent");
-            char *m  = (char *) parameter_value (params, "tiling-method");
+            int    const e =
+                *(int *)parameter_value(params, "tiling-exponent");
+            const char * const m = parameter_value (params, "tiling-method");
 
-            if (strcaseeq (m, "desc-variance"))
+            if (strcaseeq(m, "desc-variance"))
                 method = FIASCO_TILING_VARIANCE_DSC;
-            else if (strcaseeq (m, "asc-variance"))
+            else if (strcaseeq(m, "asc-variance"))
                 method = FIASCO_TILING_VARIANCE_ASC;
-            else if (strcaseeq (m, "asc-spiral"))
+            else if (strcaseeq(m, "asc-spiral"))
                 method = FIASCO_TILING_SPIRAL_ASC;
-            else if (strcaseeq (m, "dsc-spiral"))
+            else if (strcaseeq(m, "dsc-spiral"))
                 method = FIASCO_TILING_SPIRAL_DSC;
             else
-                error (_("Invalid tiling method `%s' specified."), m);
+                pm_error("Invalid tiling method `%s' specified.", m);
 
-            if (!fiasco_c_options_set_tiling (*options, method, MAX(0, e)))
-                error (fiasco_get_error_message ());
+            if (!fiasco_c_options_set_tiling(*options, method, MAX(0, e)))
+                pm_error("%s", fiasco_get_error_message ());
         }
 
         {
-            int M/*  = * (int *) parameter_value (params, "max-level") */;
-            int m/*  = * (int *) parameter_value (params, "min-level") */;
-            int N/*  = * (int *) parameter_value (params, "max-elements") */;
-            int D = * (int *) parameter_value (params, "dictionary-size");
-            int o = * (int *) parameter_value (params, "optimize");
-
-            if (o <= 0)
-            {
+            int M /*  = * (int *) parameter_value (params, "max-level") */;
+            int m /*  = * (int *) parameter_value (params, "min-level") */;
+            int N /*  = * (int *) parameter_value (params, "max-elements") */;
+            int o;
+            int D = * (int *) parameter_value(params, "dictionary-size");
+            int const optimizeOpt =
+                *(int *)parameter_value(params, "optimize");
+
+            if (optimizeOpt <= 0) {
                 o = 0;
                 M = 10;
                 m = 6;
                 N = 3;
-            }
-            else
-            {
+            } else {
                 o -= 1;
                 M = 12;
                 m = 4;
                 N = 5;
             }
 
-            if (!fiasco_c_options_set_optimizations (*options, m, M, N,
-                                                     MAX(0, D), o))
-                error (fiasco_get_error_message ());
+            if (!fiasco_c_options_set_optimizations(*options, m, M, N,
+                                                    MAX(0, D), o))
+                pm_error("%s", fiasco_get_error_message ());
         }
         {
-            int M = * (int *) parameter_value (params, "max-level");
-            int m = * (int *) parameter_value (params, "min-level");
-            int p = * (int *) parameter_value (params, "prediction");
+            int const M = *(int *)parameter_value(params, "max-level");
+            int const m = *(int *)parameter_value(params, "min-level");
+            int const p = *(int *)parameter_value(params, "prediction");
 
             if (!fiasco_c_options_set_prediction (*options,
                                                   p, MAX(0, m), MAX(0, M)))
-                error (fiasco_get_error_message ());
+                pm_error("%s", fiasco_get_error_message ());
         }
         {
-            float r    = * (float *)parameter_value(params, "rpf-range");
-            float dc_r = * (float *)parameter_value(params, "dc-rpf-range");
-            int   m    = * (int *)  parameter_value(params, "rpf-mantissa");
-            int   dc_m = * (int *)  parameter_value(params, "dc-rpf-mantissa");
-            fiasco_rpf_range_e range, dc_range;
+            float const r    =
+                *(float *)parameter_value(params, "rpf-range");
+            float const dcR =
+                *(float *)parameter_value(params, "dc-rpf-range");
+            int   const m    =
+                *(int *)parameter_value(params, "rpf-mantissa");
+            int   const dcM =
+                *(int *)parameter_value(params, "dc-rpf-mantissa");
+
+            fiasco_rpf_range_e range, dcRange;
 
             if (r < 1)
                 range = FIASCO_RPF_RANGE_0_75;
@@ -384,24 +335,49 @@ checkargs (int argc, char **argv, char const ***image_template,
             else
                 range = FIASCO_RPF_RANGE_2_00;
 
-            if (dc_r < 1)
-                dc_range = FIASCO_RPF_RANGE_0_75;
-            else if (dc_r < 1.5)
-                dc_range = FIASCO_RPF_RANGE_1_00;
-            else if (dc_r < 2.0)
-                dc_range = FIASCO_RPF_RANGE_1_50;
+            if (dcR < 1)
+                dcRange = FIASCO_RPF_RANGE_0_75;
+            else if (dcR < 1.5)
+                dcRange = FIASCO_RPF_RANGE_1_00;
+            else if (dcR < 2.0)
+                dcRange = FIASCO_RPF_RANGE_1_50;
             else
-                dc_range = FIASCO_RPF_RANGE_2_00;
+                dcRange = FIASCO_RPF_RANGE_2_00;
 
-            if (!fiasco_c_options_set_quantization (*options,
-                                                    MAX(0, m), range,
-                                                    MAX(0, dc_m), dc_range))
-                error (fiasco_get_error_message ());
+            if (!fiasco_c_options_set_quantization(*options,
+                                                   MAX(0, m), range,
+                                                   MAX(0, dcM), dcRange))
+                pm_error("%s", fiasco_get_error_message ());
         }
 
-        if (fiasco_get_verbosity () == FIASCO_ULTIMATE_VERBOSITY)
-            write_parameters (params, stderr);
+        if (fiasco_get_verbosity() == FIASCO_ULTIMATE_VERBOSITY)
+            write_parameters(params, stderr);
+    }
+    *imageTemplateListP = imageTemplateList;
+}
+
+
+
+int
+main(int argc, const char **argv) {
+
+    char const **        image_template; /* template for input image files */
+    char *               wfa_name;   /* filename of output WFA */
+    float                quality;    /* approximation quality */
+    fiasco_c_options_t * options;    /* additional coder options */
+    int                  retval;
+
+    pm_proginit(&argc, argv);
+
+    checkargs(argc, argv, &image_template, &wfa_name, &quality, &options);
+
+    if (fiasco_coder(image_template, wfa_name, quality, options))
+        retval = 0;
+    else {
+        pm_message("Encoding failed.  %s", fiasco_get_error_message());
+        retval = 1;
     }
+    return retval;
 }
 
 
diff --git a/converter/other/fitstopnm.c b/converter/other/fitstopnm.c
index bdf5c78a..90bd16f1 100644
--- a/converter/other/fitstopnm.c
+++ b/converter/other/fitstopnm.c
@@ -44,6 +44,7 @@
 #include <string.h>
 #include <float.h>
 #include <assert.h>
+#include <stdbool.h>
 
 #include "pm_config.h"
 #include "pm_c_util.h"
@@ -74,12 +75,12 @@ struct CmdlineInfo {
 
 
 
-static void 
-parseCommandLine(int argc, const char ** argv, 
+static void
+parseCommandLine(int argc, const char ** argv,
                  struct CmdlineInfo * const cmdlineP) {
 /* --------------------------------------------------------------------------
    Parse program command line described in Unix standard form by argc
-   and argv.  Return the information in the options as *cmdlineP.  
+   and argv.  Return the information in the options as *cmdlineP.
 
    If command line is internally inconsistent (invalid options, etc.),
    issue error message to stderr and abort program.
@@ -87,8 +88,7 @@ parseCommandLine(int argc, const char ** argv,
    Note that the strings we return are stored in the storage that
    was passed to us as the argv array.  We also trash *argv.
 --------------------------------------------------------------------------*/
-    optEntry * option_def;
-        /* Instructions to pm_optParseOptions3 on how to parse our options. */
+    optEntry * option_def;   /* Used by OPTENT3 */
     optStruct3 opt;
 
     unsigned int imageSpec;
@@ -120,7 +120,7 @@ parseCommandLine(int argc, const char ** argv,
 
     /* Set some defaults the lazy way (using multiple setting of variables) */
 
-    pm_optParseOptions3(&argc, (char**)argv, opt, sizeof(opt), 0);
+    pm_optParseOptions4(&argc, argv, opt, sizeof(opt), 0);
         /* Uses and sets argc, argv, and some of *cmdlineP and others. */
 
     if (imageSpec) {
@@ -140,7 +140,7 @@ parseCommandLine(int argc, const char ** argv,
         cmdlineP->inputFileName = "-";
     else {
         cmdlineP->inputFileName = argv[1];
-        
+
         if (argc-1 > 1)
             pm_error("Too many arguments (%u).  The only non-option argument "
                      "is the input file name.", argc-1);
@@ -150,29 +150,25 @@ parseCommandLine(int argc, const char ** argv,
 
 
 
-struct FITS_Header {
-  int simple;       /* basic format or not */
-  int bitpix;
-      /* number of bits per pixel, positive for integer, negative 
-         for floating point
-      */
-  int naxis;        /* number of axes */
-  int naxis1;       /* number of points on axis 1 */
-  int naxis2;       /* number of points on axis 2 */
-  int naxis3;       /* number of points on axis 3 */
-  double datamin;   /* min # (Physical value!) */
-  double datamax;   /* max #     "       "     */
-  double bzer;      /* Physical value = Array value*bscale + bzero */
-  double bscale;
-};
-
-
 typedef enum {
     VF_CHAR, VF_SHORT, VF_LONG, VF_FLOAT, VF_DOUBLE
-} valFmt;
+} ValFmt;
+
+struct FITS_Header {
+    bool simple;      /* basic format */
+    ValFmt valFmt;    /* format of values -- bits per pixel, integer/float */
+    unsigned int naxis;  /* number of axes */
+    unsigned int naxis1;       /* number of points on axis 1 */
+    unsigned int naxis2;       /* number of points on axis 2 */
+    unsigned int naxis3;       /* number of points on axis 3 */
+    double datamin;   /* min # (Physical value!) */
+    double datamax;   /* max #     "       "     */
+    double bzer;      /* Physical value = Array value*bscale + bzero */
+    double bscale;
+};
 
-struct fitsRasterInfo {
-    valFmt valFmt;
+struct FitsRasterInfo {
+    ValFmt valFmt;
     double bzer;
     double bscale;
 };
@@ -296,7 +292,7 @@ readFitsDouble(FILE *   const ifP,
 
 
 
-static valFmt
+static ValFmt
 valFmtFromBitpix(int const bitpix) {
 /*----------------------------------------------------------------------------
    Return the format of a "value" in the FITS file, given the value
@@ -323,7 +319,7 @@ valFmtFromBitpix(int const bitpix) {
 
 static void
 readVal(FILE *   const ifP,
-        valFmt   const fmt,
+        ValFmt   const fmt,
         double * const vP) {
 
     switch (fmt) {
@@ -334,15 +330,15 @@ readVal(FILE *   const ifP,
     case VF_SHORT:
         readFitsShort(ifP, vP);
         break;
-      
+
     case VF_LONG:
         readFitsLong(ifP, vP);
         break;
-      
+
     case VF_FLOAT:
         readFitsFloat(ifP, vP);
         break;
-      
+
     case VF_DOUBLE:
         readFitsDouble(ifP, vP);
         break;
@@ -358,49 +354,134 @@ readCard(FILE * const ifP,
     size_t bytesRead;
 
     bytesRead = fread(buf, 1, 80, ifP);
-    if (bytesRead == 0)
+    if (bytesRead < 80)
         pm_error("error reading header");
 }
 
 
 
 static void
+processNaxisN(unsigned int   const n,
+              int            const value,
+              bool           const gotNaxis,
+              unsigned int   const naxis,
+              bool *         const gotNaxisNP,
+              unsigned int * const naxisNP) {
+
+    if (*gotNaxisNP)
+        pm_error("Invalid FITS header: two NAXIS%u keywords", n);
+    else {
+        *gotNaxisNP = true;
+
+        if (!gotNaxis)
+            pm_error("Invalid FITS header: NAXIS must precede NAXIS%u", n);
+        else if (naxis < n)
+            pm_error("Invalid FITS header: NAXIS%u for image with "
+                     "only %u axes", n, naxis);
+        else if (value < 0)
+            pm_error("Invalid NAXIS%u value %d in FITS header:  "
+                     "Must not be negative", n, value);
+        else
+            *naxisNP = value;
+    }
+}
+
+
+
+static void
 readFitsHeader(FILE *               const ifP,
                struct FITS_Header * const hP) {
 
-    int seenEnd;
-  
-    seenEnd = 0;
+
+    bool gotEmpty, gotSimple, gotNaxis, gotN1, gotN2, gotN3, gotBitpix, gotEnd;
+
+    gotEmpty  = false;  /* initial value */
+    gotSimple = false;  /* initial value */
+    gotNaxis  = false;  /* initial value */
+    gotN1     = false;  /* initial value */
+    gotN2     = false;  /* initial value */
+    gotN3     = false;  /* initial value */
+    gotBitpix = false;  /* initial value */
+    gotEnd    = false;  /* initial value */
+
     /* Set defaults */
-    hP->simple  = 0;
     hP->bzer    = 0.0;
     hP->bscale  = 1.0;
     hP->datamin = - DBL_MAX;
     hP->datamax = DBL_MAX;
-  
-    while (!seenEnd) {
+
+    while (!gotEnd) {
         unsigned int i;
+
         for (i = 0; i < 36; ++i) {
-            char buf[80];
+            char buf[81];
             char c;
+            int n;
+
+            readCard(ifP, buf); /* Reads into first 80 elements of buf[] */
+
+            buf[80] = '\0'; /* Make ASCIIZ string */
 
-            readCard(ifP, buf);
-    
-            if (sscanf(buf, "SIMPLE = %c", &c) == 1) {
+            if (sscanf(buf, " %c", &c) < 1) {
+                gotEmpty = true;
+            } else if (sscanf(buf, "SIMPLE = %c", &c) == 1) {
+                if (gotSimple)
+                    pm_error("FITS header has two SIMPLE keywords");
+                gotSimple = true;
                 if (c == 'T' || c == 't')
-                    hP->simple = 1;
-            } else if (sscanf(buf, "BITPIX = %d", &(hP->bitpix)) == 1);
-            else if (sscanf(buf, "NAXIS = %d", &(hP->naxis)) == 1);
-            else if (sscanf(buf, "NAXIS1 = %d", &(hP->naxis1)) == 1);
-            else if (sscanf(buf, "NAXIS2 = %d", &(hP->naxis2)) == 1);
-            else if (sscanf(buf, "NAXIS3 = %d", &(hP->naxis3)) == 1);
-            else if (sscanf(buf, "DATAMIN = %lf", &(hP->datamin)) == 1);
-            else if (sscanf(buf, "DATAMAX = %lf", &(hP->datamax)) == 1);
-            else if (sscanf(buf, "BZERO = %lf", &(hP->bzer)) == 1);
-            else if (sscanf(buf, "BSCALE = %lf", &(hP->bscale)) == 1);
-            else if (strncmp(buf, "END ", 4 ) == 0) seenEnd = 1;
+                    hP->simple = true;
+                else if (c == 'F' || c == 'f')
+                    hP->simple = false;
+                else
+                    pm_error("Invalid SIMPLE value '%c'.  Only 'T' and 'F' "
+                             "are recognized", c);
+            } else if (sscanf(buf, "BITPIX = %d", &n) == 1) {
+                if (gotBitpix)
+                    pm_error("FITS header has two NAXIS keywords");
+                gotBitpix = true;
+                hP->valFmt = valFmtFromBitpix(n);
+            } else if (sscanf(buf, "NAXIS = %d", &n) == 1) {
+                gotNaxis = true;
+                if (n < 0)
+                    pm_error("Invalid value %d for NAXIS in FITS header.  "
+                             "Value must not be negative", n);
+                else
+                    hP->naxis = n;
+            } else if (sscanf(buf, "NAXIS1 = %d", &n) == 1) {
+                processNaxisN(1, n, gotNaxis, hP->naxis, &gotN1, &hP->naxis1);
+            } else if (sscanf(buf, "NAXIS2 = %d", &n) == 1) {
+                processNaxisN(2, n, gotNaxis, hP->naxis, &gotN2, &hP->naxis2);
+            } else if (sscanf(buf, "NAXIS3 = %d", &n) == 1) {
+                processNaxisN(3, n, gotNaxis, hP->naxis, &gotN3, &hP->naxis3);
+            } else if (sscanf(buf, "DATAMIN = %lf", &(hP->datamin)) == 1) {
+            } else if (sscanf(buf, "DATAMAX = %lf", &(hP->datamax)) == 1) {
+            } else if (sscanf(buf, "BZERO = %lf", &(hP->bzer)) == 1) {
+            } else if (sscanf(buf, "BSCALE = %lf", &(hP->bscale)) == 1) {
+            } else if (strncmp(buf, "END ", 4 ) == 0) {
+                gotEnd = true;
+                if (gotEmpty == true)
+                    pm_message("Blank card(s) were encountered before "
+                               "END in header");
+            }
         }
     }
+    if (!gotSimple)
+        pm_error("FITS header missing the SIMPLE keyword");
+    if (!gotBitpix)
+        pm_error("FITS header missing the BITPIX keyword");
+    if (!gotNaxis)
+        pm_error("FITS header missing the NAXIS keyword");
+
+    if (hP->naxis > 3)
+        pm_error("FITS file has %u axes; this program can handle "
+                 "no more than 3", hP->naxis);
+
+    if (hP->naxis > 0 && !gotN1)
+        pm_error("FITS header missing NAXIS1 keyword");
+    if (hP->naxis > 1 && !gotN2)
+        pm_error("FITS header missing NAXIS1 keyword");
+    if (hP->naxis > 2 && !gotN3)
+        pm_error("FITS header missing NAXIS3 keyword");
 }
 
 
@@ -421,7 +502,7 @@ interpretPlanes(struct FITS_Header const fitsHeader,
         if (imageRequest) {
             if (imageRequest > fitsHeader.naxis3)
                 pm_error("Only %u plane%s in this file.  "
-                         "You requested image %u", 
+                         "You requested image %u",
                          fitsHeader.naxis3, fitsHeader.naxis3 > 1 ? "s" : "",
                          imageRequest);
             else {
@@ -446,7 +527,7 @@ interpretPlanes(struct FITS_Header const fitsHeader,
         }
     }
     if (verbose) {
-        
+
         pm_message("FITS stream is %smultiplane", *multiplaneP ? "" : "not ");
         pm_message("We will take image %u (1 is first) of %u "
                    "in the FITS stream",
@@ -461,7 +542,7 @@ scanImageForMinMax(FILE *       const ifP,
                    unsigned int const images,
                    int          const cols,
                    int          const rows,
-                   valFmt       const valFmt,
+                   ValFmt       const valFmt,
                    double       const bscale,
                    double       const bzer,
                    unsigned int const imagenum,
@@ -476,7 +557,7 @@ scanImageForMinMax(FILE *       const ifP,
     unsigned int image;
     pm_filepos rasterPos;
     double fmaxval;
-    
+
     pm_tell2(ifP, &rasterPos, sizeof(rasterPos));
 
     pm_message("Scanning file for scaling parameters");
@@ -554,7 +635,7 @@ computeMinMax(FILE *             const ifP,
     if (datamin == -DBL_MAX || datamax == DBL_MAX) {
         double scannedDatamin, scannedDatamax;
         scanImageForMinMax(ifP, images, cols, rows,
-                           valFmtFromBitpix(h.bitpix), h.bscale, h.bzer,
+                           h.valFmt, h.bscale, h.bzer,
                            imagenum, multiplane,
                            &scannedDatamin, &scannedDatamax);
 
@@ -571,12 +652,12 @@ computeMinMax(FILE *             const ifP,
 
 static xelval
 determineMaxval(struct CmdlineInfo const cmdline,
-                valFmt             const valFmt,
+                ValFmt             const valFmt,
                 double             const datamax,
                 double             const datamin) {
 
     xelval retval;
-                
+
     if (cmdline.omaxvalSpec)
         retval = cmdline.omaxval;
     else {
@@ -612,11 +693,11 @@ convertPgmRaster(FILE *                const ifP,
                  xelval                const maxval,
                  unsigned int          const desiredImage,
                  unsigned int          const imageCount,
-                 struct fitsRasterInfo const rasterInfo,
+                 struct FitsRasterInfo const rasterInfo,
                  double                const scale,
                  double                const datamin,
                  xel **                const xels) {
-        
+
     /* Note: the FITS specification does not give the association between
        file position and image position (i.e. is the first pixel in the
        file the top left, bottom left, etc.).  We use the common sense,
@@ -648,7 +729,7 @@ convertPgmRaster(FILE *                const ifP,
                 }
             }
         }
-    } 
+    }
 }
 
 
@@ -658,7 +739,7 @@ convertPpmRaster(FILE *                const ifP,
                  unsigned int          const cols,
                  unsigned int          const rows,
                  xelval                const maxval,
-                 struct fitsRasterInfo const rasterInfo,
+                 struct FitsRasterInfo const rasterInfo,
                  double                const scale,
                  double                const datamin,
                  xel **                const xels) {
@@ -708,7 +789,7 @@ convertRaster(FILE *                const ifP,
               bool                  const multiplane,
               unsigned int          const desiredImage,
               unsigned int          const imageCount,
-              struct fitsRasterInfo const rasterInfo,
+              struct FitsRasterInfo const rasterInfo,
               double                const scale,
               double                const datamin) {
 
@@ -743,7 +824,7 @@ main(int argc, const char * argv[]) {
     double scale;
     double datamin, datamax;
     struct FITS_Header fitsHeader;
-    struct fitsRasterInfo rasterInfo;
+    struct FitsRasterInfo rasterInfo;
 
     unsigned int imageCount;
     unsigned int desiredImage;
@@ -754,15 +835,15 @@ main(int argc, const char * argv[]) {
         /* This is a one-image multiplane stream; 'desiredImage'
            is undefined
         */
-  
+
     pm_proginit(&argc, argv);
-  
+
     parseCommandLine(argc, argv, &cmdline);
 
     ifP = pm_openr(cmdline.inputFileName);
 
     readFitsHeader(ifP, &fitsHeader);
-  
+
     if (!fitsHeader.simple)
         pm_error("FITS file is not in simple format, can't read");
 
@@ -774,7 +855,7 @@ main(int argc, const char * argv[]) {
 
     rasterInfo.bscale = fitsHeader.bscale;
     rasterInfo.bzer   = fitsHeader.bzer;
-    rasterInfo.valFmt = valFmtFromBitpix(fitsHeader.bitpix);
+    rasterInfo.valFmt = fitsHeader.valFmt;
 
     interpretPlanes(fitsHeader, cmdline.image, cmdline.verbose,
                     &imageCount, &multiplane, &desiredImage);
diff --git a/converter/other/gemtopnm.c b/converter/other/gemtopnm.c
index 6bbfcc05..70debc2e 100644
--- a/converter/other/gemtopnm.c
+++ b/converter/other/gemtopnm.c
@@ -40,6 +40,8 @@
  */
 
 #include <assert.h>
+
+#include "mallocvar.h"
 #include "pnm.h"
 
 #define MAXVAL 3
@@ -47,35 +49,80 @@
 #define DARK   1
 #define BLACK  0
 
-char pattern[8];
 
-static void getinit ARGS ((FILE *file, int *colsP, int *rowsP, int *padrightP,
-               int *patlenP, int *planesP));
+
+static void
+getinit(FILE * const ifP,
+        int *  const colsP,
+        int *  const rowsP,
+        int *  const padrightP,
+        int *  const patlenP,
+        int *  const planesP) {
+
+    short s;
+    short headlen;
+
+    if (pm_readbigshort(ifP, &s) == -1) /* Image file version */
+        pm_error("EOF / read error");
+    if (s != 1)
+        pm_error("unknown version number (%d)", s);
+    if (pm_readbigshort(ifP, &headlen) == -1) /* Header length in words */
+        pm_error("EOF / read error");
+    if (headlen < 8)
+        pm_error("short header (%d)", headlen);
+    if (pm_readbigshort(ifP, &s) == -1) /* Number of planes */
+        pm_error("EOF / read error");
+    if (s != 4 && s != 1)
+        pm_error("This program can interpret IMGs with only 1 or 4 planes");
+    *planesP = s;
+    if (pm_readbigshort(ifP, &s) == -1) /* Pattern definition length (bytes) */
+        pm_error("EOF / read error");
+    if (s < 1 || s > 8)
+        pm_error("illegal pattern length (%d)", s);
+    *patlenP = s;
+    if (pm_readbigshort(ifP, &s) == -1 /* Pixel height (microns) */
+        || pm_readbigshort(ifP, &s) == -1 /* Pixel height (microns) */
+        || pm_readbigshort(ifP, &s) == -1) /* Scan line width */
+        pm_error("EOF / read error");
+    *colsP = s;
+    if (pm_readbigshort(ifP, &s) == -1) /* Number of scan line items */
+        pm_error("EOF / read error");
+    *rowsP = s;
+    *padrightP = 7 - ((*colsP + 7) & 0x7);
+
+    headlen -= 8;
+    while (headlen-- > 0) {
+        getc(ifP);
+        getc(ifP);
+    }
+}
+
+
 
 int
-main(argc, argv)
-    int             argc;
-    char           *argv[];
-{
+main(int argc, const char ** argv) {
+
     int     debug = 0;
-    FILE    *f;
+    FILE    *ifP;
     int     row;
     int     rows, cols, padright, patlen, planes;
       /* attributes of input image */
     int type;  /* The format type (PBM/PPM) of the output image */
-    bit *bitrow[4];
+    bit * bitrow[4];
       /* One row of input, one or four planes.  (If one, only [0] is defined)*/
     xel * xelrow;  /* One row of output */
+    char pattern[8];
     const char * const usage = "[-debug] [gem IMG file]";
     int argn;
 
-/* Process multiple planes by maintaining a separate row of bits for each
- * plane. In a single-plane image, all we have to do is write out the
- * first plane; in a multiple-plane image, we combine them just before writing
- * out the row.
- */
-    pnm_init( &argc, argv );
+    /* Process multiple planes by maintaining a separate row of bits for each
+       plane. In a single-plane image, all we have to do is write out the
+       first plane; in a multiple-plane image, we combine them just before
+       writing out the row.
+    */
+    pm_proginit(&argc, argv);
 
+    debug = 0; /* initial value */
     argn = 1;
 
     while (argn < argc && argv[argn][0] == '-' && argv[argn][1] != '\0')
@@ -88,220 +135,175 @@ main(argc, argv)
       }
 
     if (argc == argn)
-        f = stdin;
+        ifP = stdin;
     else {
-        f = pm_openr (argv[argn]);
+        ifP = pm_openr (argv[argn]);
         ++argn;
     }
 
     if (argn != argc)
       pm_usage (usage);
 
-    getinit (f, &cols, &rows, &padright, &patlen, &planes);
+    getinit(ifP, &cols, &rows, &padright, &patlen, &planes);
 
     if (planes == 1)
         type = PBM_TYPE;
     else
         type = PPM_TYPE;
 
-    pnm_writepnminit( stdout, cols, rows, MAXVAL, type, 0 );
+    pnm_writepnminit(stdout, cols, rows, MAXVAL, type, 0);
 
     {
         /* allocate input row data structure */
-        int plane;
-        for (plane = 0; plane < planes; plane++)
-            bitrow[plane] = malloc (cols + padright);
+        unsigned int plane;
+        for (plane = 0; plane < planes; ++plane) {
+            MALLOCARRAY(bitrow[plane], cols + padright);
+            if (!bitrow[plane])
+                pm_error("Unable to allocate memory for %u columns", cols);
+        }
     }
-    xelrow = pnm_allocrow(cols+padright);   /* Output row */
+    xelrow = pnm_allocrow(cols + padright);   /* Output row */
 
     for (row = 0; row < rows; ) {
-      int linerep;
-      int plane;
-
-      linerep = 1;
-      for (plane = 0; plane < planes; plane++) {
-        int col;
-        col = 0;
-        while (col < cols) {
-            int c;
-            switch (c = getc(f)) {
-            case 0x80:  /* Bit String */
-            {
-                int j;
-                c = getc(f);    /* Byte count */
-                if (debug)
-                  pm_message("bit string of %d bytes", c);
-
-                if (col + c * 8 > cols + padright)
-                  pm_error ("bad byte count");
-                for (j = 0; j < c; ++j) {
-                    int cc, k;
-                    cc = getc(f);
-                    for (k = 0x80; k; k >>= 1) {
-                        bitrow[plane][col] = (k & cc) ? 0 : 1;
-                        ++col;
-                    }
-                }
-            }
-            break;
-            case 0:     /* Pattern run */
-            {
-                int j, l;
-                c = getc(f);    /* Repeat count */
-                if (debug)
-                    pm_message("pattern run of %d repetitions", c);
-                /* line repeat */
-                if (c == 0) {
-                    c = getc(f);
-                    if (c != 0x00ff)
-                        pm_error( "badly formed line repeat" );
-                    linerep = getc(f);
-                    break;
-                }
-                fread (pattern, 1, patlen, f);
-                if (col + c * patlen * 8 > cols + padright)
-                  pm_error ("bad pattern repeat count");
-                for (j = 0; j < c; ++j)
-                    for (l = 0; l < patlen; ++l) {
-                        int k;
-                        for (k = 0x80; k; k >>= 1) {
-                            bitrow[plane][col] = (k & pattern[l]) ? 0 : 1;
+        int linerep;
+        unsigned int plane;
+
+        linerep = 1;
+
+        for (plane = 0; plane < planes; ++plane) {
+            unsigned int col;
+            col = 0;
+            while (col < cols) {
+                int c;
+                switch (c = getc(ifP)) {
+                case 0x80: { /* Bit String */
+                    unsigned int j;
+                    c = getc(ifP);    /* Byte count */
+                    if (debug)
+                        pm_message("bit string of %d bytes", c);
+
+                    if (col + c * 8 > cols + padright)
+                        pm_error("bad byte count");
+                    for (j = 0; j < c; ++j) {
+                        unsigned char cc;
+                        unsigned char k;
+                        cc = getc(ifP);
+                        for (k = 0x80; k != 0x00; k >>= 1) {
+                            bitrow[plane][col] = (k & cc) ? 0 : 1;
                             ++col;
                         }
                     }
-            }
-            break;
-
-            default:    /* Solid run */
-            {
-                int l, j;
-                if (debug)
-                    pm_message("solid run of %d bytes %s", c & 0x7f,
-                               c & 0x80 ? "on" : "off" );
-                /* each byte had eight bits DSB */
-                l = (c & 0x80) ? 0: 1;
-                c = (c & 0x7f) * 8;
-                if (col + c > cols + padright)
-                    pm_error ("bad solid run repeat count");
-                for (j = 0; j < c; ++j) {
-                    bitrow[plane][col] = l;
-                    ++col;
+                } break;
+                case 0: {    /* Pattern run */
+                    unsigned int j;
+                    c = getc(ifP);    /* Repeat count */
+                    if (debug)
+                        pm_message("pattern run of %d repetitions", c);
+                    /* line repeat */
+                    if (c == 0) {
+                        c = getc(ifP);
+                        if (c != 0x00ff)
+                            pm_error("badly formed line repeat");
+                        linerep = getc(ifP);
+                    } else {
+                        fread(pattern, 1, patlen, ifP);
+                        if (col + c * patlen * 8 > cols + padright)
+                            pm_error("bad pattern repeat count");
+                        for (j = 0; j < c; ++j) {
+                            unsigned int l;
+                            for (l = 0; l < patlen; ++l) {
+                                unsigned int k;
+                                for (k = 0x80; k; k >>= 1) {
+                                    bitrow[plane][col] =
+                                        (k & pattern[l]) ? 0 : 1;
+                                    ++col;
+                                }
+                            }
+                        }
+                    }
+                } break;
+
+                default: {   /* Solid run */
+                    unsigned int const l = (c & 0x80) ? 0: 1;
+
+                    unsigned int j;
+
+                    if (debug)
+                        pm_message("solid run of %d bytes %s", c & 0x7f,
+                                   c & 0x80 ? "on" : "off" );
+                    /* each byte had eight bits DSB */
+                    c = (c & 0x7f) * 8;
+                    if (col + c > cols + padright)
+                        pm_error("bad solid run repeat count");
+                    for (j = 0; j < c; ++j) {
+                        bitrow[plane][col] = l;
+                        ++col;
+                    }
                 }
-            }
                 break;
 
-            case EOF:   /* End of file */
-                pm_error( "end of file reached" );
-
+                case EOF:   /* End of file */
+                    pm_error("end of file reached");
+                }
             }
+            if (debug)
+                pm_message("EOL plane %d row %d", plane, row);
+            if (col != cols + padright)
+                pm_error("EOL beyond edge");
         }
-                if ( debug )
-                        pm_message( "EOL plane %d row %d", plane, row );
-                if (col != cols + padright)
-                        pm_error( "EOL beyond edge" );
-      }
 
-      if (planes == 4) {
-          /* Construct a pixel from the 4 planes of bits for this row */
-          int col;
-          for (col = 0; col < cols; col++) {
-            int r, g, b, i;
-
-            const int r_bit = !bitrow[0][col];
-            const int g_bit = !bitrow[1][col];
-            const int b_bit = !bitrow[2][col];
-            i = bitrow[3][col];
-
-            /* Deal with weird GEM palette - white/black/gray are
-               encoded oddly
-            */
-            if (r_bit == g_bit && g_bit == b_bit) {
-                /* It's black, white, or gray */
-                if (r_bit && i) r = LIGHT;
-                else if (r_bit) r = BLACK;
-                else if (i) r = MAXVAL;
-                else r = DARK;
-                g = b = r;
-            } else {
-                /* It's one of the twelve colored colors */
-                if (!i) {
-                    /* Low intensity */
-                    r = r_bit * LIGHT;
-                    g = g_bit * LIGHT;
-                    b = b_bit * LIGHT;
+        if (planes == 4) {
+            /* Construct a pixel from the 4 planes of bits for this row */
+            unsigned int col;
+            for (col = 0; col < cols; ++col) {
+                unsigned int const r_bit = !bitrow[0][col];
+                unsigned int const g_bit = !bitrow[1][col];
+                unsigned int const b_bit = !bitrow[2][col];
+                unsigned int const i     =  bitrow[3][col];
+
+                unsigned int r, g, b;
+
+                /* Deal with weird GEM palette - white/black/gray are
+                   encoded oddly
+                */
+                if (r_bit == g_bit && g_bit == b_bit) {
+                    /* It's black, white, or gray */
+                    if (r_bit && i) r = LIGHT;
+                    else if (r_bit) r = BLACK;
+                    else if (i) r = MAXVAL;
+                    else r = DARK;
+                    g = b = r;
                 } else {
-                    /* Normal intensity */
-                    r = r_bit * MAXVAL;
-                    g = g_bit * MAXVAL;
-                    b = b_bit * MAXVAL;
+                    /* It's one of the twelve colored colors */
+                    if (!i) {
+                        /* Low intensity */
+                        r = r_bit * LIGHT;
+                        g = g_bit * LIGHT;
+                        b = b_bit * LIGHT;
+                    } else {
+                        /* Normal intensity */
+                        r = r_bit * MAXVAL;
+                        g = g_bit * MAXVAL;
+                        b = b_bit * MAXVAL;
+                    }
                 }
+                PPM_ASSIGN(xelrow[col], r, g, b);
             }
-            PPM_ASSIGN(xelrow[col], r, g, b);
+        } else {
+            unsigned int col;
+            for (col = 0; col < cols; ++col)
+                PNM_ASSIGN1(xelrow[col], bitrow[0][col]);
+        }
+        while (linerep--) {
+            pnm_writepnmrow(stdout, xelrow, cols, MAXVAL, type, 0);
+            ++row;
         }
-      } else {
-          int col;
-          for (col = 0; col < cols; col++)
-              PNM_ASSIGN1(xelrow[col], bitrow[0][col]);
-      }
-      while (linerep--) {
-        pnm_writepnmrow( stdout, xelrow, cols, MAXVAL, type, 0 );
-        ++row;
-      }
     }
     pnm_freerow(xelrow);
-    pm_close( f );
-    pm_close( stdout );
+    pm_close(ifP);
+    pm_close(stdout);
     exit(0);
 }
 
 
-static void
-getinit (file, colsP, rowsP, padrightP, patlenP, planesP)
-     FILE *file;
-     int *colsP;
-     int *rowsP;
-     int *padrightP;
-     int *patlenP;
-     int *planesP;
-{
-  short s;
-  short headlen;
-
-  if (pm_readbigshort (file, &s) == -1) /* Image file version */
-    pm_error ("EOF / read error");
-  if (s != 1)
-    pm_error ("unknown version number (%d)", (int) s);
-  if (pm_readbigshort (file, &headlen) == -1) /* Header length in words */
-    pm_error ("EOF / read error");
-  if (headlen < 8)
-    pm_error ("short header (%d)", (int) headlen);
-  if (pm_readbigshort (file, &s) == -1) /* Number of planes */
-    pm_error ("EOF / read error");
-  if (s != 4 && s != 1)
-    pm_error ("This program can interpret IMGs with only 1 or 4 planes");
-  *planesP = s;
-  if (pm_readbigshort (file, &s) == -1) /* Pattern definition length (bytes) */
-    pm_error ("EOF / read error");
-  if (s < 1 || s > 8)
-    pm_error ("illegal pattern length (%d)", (int) s);
-  *patlenP = (int) s;
-  if (pm_readbigshort (file, &s) == -1 /* Pixel height (microns) */
-      || pm_readbigshort (file, &s) == -1 /* Pixel height (microns) */
-      || pm_readbigshort (file, &s) == -1) /* Scan line width */
-    pm_error ("EOF / read error");
-  *colsP = (int) s;
-  if (pm_readbigshort (file, &s) == -1) /* Number of scan line items */
-    pm_error ("EOF / read error");
-  *rowsP = (int) s;
-  *padrightP = 7 - ((*colsP + 7) & 7);
-
-  headlen -= 8;
-  while (headlen-- > 0)
-    {
-      (void) getc (file);
-      (void) getc (file);
-    }
-}
-
-
 
diff --git a/converter/other/giftopnm.c b/converter/other/giftopnm.c
index 470c85b7..55d7ccc6 100644
--- a/converter/other/giftopnm.c
+++ b/converter/other/giftopnm.c
@@ -113,10 +113,7 @@ parseCommandLine(int argc, const char ** argv,
    Note that the file spec array we return is stored in the storage that
    was passed to us as the argv array.
 -----------------------------------------------------------------------------*/
-    optEntry * option_def;
-        /* Instructions to pm_optParseOptions3 on how to parse our options.
-         */
-
+    optEntry * option_def;   /* Used by OPTENT3 */
     optStruct3 opt;
 
     unsigned int alphaSpec, imageSpec;
@@ -144,7 +141,7 @@ parseCommandLine(int argc, const char ** argv,
     opt.short_allowed = false;  /* We have no short (old-fashioned) options */
     opt.allowNegNum = false;  /* We have no parms that are negative numbers */
 
-    pm_optParseOptions3(&argc, (char **)argv, opt, sizeof(opt), 0);
+    pm_optParseOptions4(&argc, argv, opt, sizeof(opt), 0);
         /* Uses and sets argc, argv, and some of *cmdlineP and others. */
 
     free(option_def);
@@ -291,6 +288,7 @@ initGif89(struct Gif89 * const gif89P) {
 }
 
 
+
 static bool verbose;
 static bool showComment;
 
@@ -1237,7 +1235,6 @@ lzwReadByteFresh(struct GetCodeState * const getCodeStateP,
 
 
 
-
 static void
 lzwReadByte(Decompressor *  const decompP,
             unsigned char * const dataReadP,
@@ -1357,6 +1354,7 @@ bumpRowInterlace(unsigned int   const rows,
 }
 
 
+
 static void
 renderRow(unsigned char *    const cmapIndexRow,
           unsigned int       const cols,
@@ -1448,20 +1446,14 @@ pnmFormat(bool const hasGray,
   by 'hasGray' and 'hasColor'.
 -----------------------------------------------------------------------------*/
     int format;
-    const char * formatName;
 
     if (hasColor) {
         format = PPM_FORMAT;
-        formatName = "PPM";
     } else if (hasGray) {
         format = PGM_FORMAT;
-        formatName = "PGM";
     } else {
         format = PBM_FORMAT;
-        formatName = "PBM";
     }
-    if (verbose)
-        pm_message("writing a %s file", formatName);
 
     return format;
 }
@@ -1554,6 +1546,9 @@ convertRaster(Decompressor * const decompP,
 
     MALLOCARRAY2(cmapIndexArray, interlace ? rows : 1 , cols);
 
+    if (verbose)
+        pm_message("writing a %s file", pnm_formattypenm(format));
+
     if (imageOutFileP)
         pnm_writepnminit(imageOutFileP, cols, rows, GIFMAXVAL, format, false);
     if (alphaFileP)
@@ -2198,3 +2193,4 @@ main(int argc, const char **argv) {
 }
 
 
+
diff --git a/converter/other/hdifftopam.c b/converter/other/hdifftopam.c
index c9363040..1b058a78 100644
--- a/converter/other/hdifftopam.c
+++ b/converter/other/hdifftopam.c
@@ -1,7 +1,7 @@
 /******************************************************************************
                                 hdifftopam
 *******************************************************************************
-  This program recovers a PAM image from a horizontal difference images 
+  This program recovers a PAM image from a horizontal difference images
   such as created by Pamtohdiff.
 
   By Bryan Henderson, San Jose, CA 2002.04.15.
@@ -10,15 +10,16 @@
 #include <stdio.h>
 
 #include "pm_c_util.h"
-#include "pam.h"
-#include "shhopt.h"
+#include "mallocvar.h"
 #include "nstring.h"
+#include "shhopt.h"
+#include "pam.h"
 
-struct cmdlineInfo {
+struct CmdlineInfo {
     /* All the information the user supplied in the command line,
        in a form easy for the program to use.
     */
-    const char *inputFilespec;  /* Filespecs of input files */
+    const char * inputFileNm;  /* Names of input files */
     unsigned int pnm;
     unsigned int verbose;
 };
@@ -26,19 +27,19 @@ struct cmdlineInfo {
 
 
 static void
-parseCommandLine(int argc, char ** argv,
-                 struct cmdlineInfo * const cmdlineP) {
+parseCommandLine(int argc, const char ** const argv,
+                 struct CmdlineInfo * const cmdlineP) {
 /*----------------------------------------------------------------------------
    Note that the file spec array we return is stored in the storage that
    was passed to us as the argv array.
 -----------------------------------------------------------------------------*/
-    optEntry *option_def = malloc( 100*sizeof( optEntry ) );
-        /* Instructions to pm_optParseOptions3 on how to parse our options.
-         */
+    optEntry * option_def;   /* Used by OPTENT3 */
     optStruct3 opt;
 
     unsigned int option_def_index;
 
+    MALLOCARRAY_NOFAIL(option_def, 100);
+
     option_def_index = 0;   /* incremented by OPTENTRY */
     OPTENT3(0, "pnm",       OPT_FLAG,    NULL, &cmdlineP->pnm,      0);
     OPTENT3(0, "verbose",   OPT_FLAG,    NULL, &cmdlineP->verbose,  0);
@@ -47,13 +48,13 @@ parseCommandLine(int argc, char ** argv,
     opt.short_allowed = FALSE;  /* We have no short (old-fashioned) options */
     opt.allowNegNum = FALSE;  /* We have no parms that are negative numbers */
 
-    pm_optParseOptions3(&argc, argv, opt, sizeof(opt), 0);
+    pm_optParseOptions4(&argc, argv, opt, sizeof(opt), 0);
         /* Uses and sets argc, argv, and some of *cmdlineP and others. */
 
     if (argc-1 < 1)
-        cmdlineP->inputFilespec = "-";
+        cmdlineP->inputFileNm = "-";
     else if (argc-1 == 1)
-        cmdlineP->inputFilespec = argv[1];
+        cmdlineP->inputFileNm = argv[1];
     else
         pm_error("Too many arguments.");
 }
@@ -64,7 +65,7 @@ static void
 makePnm(struct pam * const pamP) {
 
     switch (pamP->depth) {
-    case 1: 
+    case 1:
         pamP->format = PGM_FORMAT;
         break;
     case 3:
@@ -87,27 +88,28 @@ static void
 
 
 
-int 
-main(int argc, char *argv[]) {
-    FILE *ifP;
-    struct cmdlineInfo cmdline;
+int
+main(int argc, const char ** argv) {
+
+    FILE * ifP;
+    struct CmdlineInfo cmdline;
     struct pam diffpam, outpam;
     unsigned int row;
     tuple * diffrow;
     tuple * outrow;
     tuple * prevrow;
 
-    pnm_init(&argc, argv);
+    pm_proginit(&argc, argv);
 
     parseCommandLine(argc, argv, &cmdline);
 
-    ifP = pm_openr(cmdline.inputFilespec);
+    ifP = pm_openr(cmdline.inputFileNm);
 
     pnm_readpaminit(ifP, &diffpam, PAM_STRUCT_SIZE(tuple_type));
 
-    if (diffpam.format != PAM_FORMAT) 
+    if (diffpam.format != PAM_FORMAT)
         pm_error("Input must be a PAM file, not PNM");
-    else if (!streq(diffpam.tuple_type, "hdiff")) 
+    else if (!streq(diffpam.tuple_type, "hdiff"))
         pm_error("Input tuple type is '%s'.  Must be 'hdiff'",
                  diffpam.tuple_type);
 
@@ -130,7 +132,7 @@ main(int argc, char *argv[]) {
 
     {
         unsigned int const bias = diffpam.maxval/2;
-        
+
         for (row = 0; row < diffpam.height; ++row) {
             unsigned int col;
             pnm_readpamrow(&diffpam, diffrow);
@@ -139,8 +141,8 @@ main(int argc, char *argv[]) {
                 for (plane = 0; plane < diffpam.depth; ++plane) {
                     sample const prevSample = prevrow[col][plane];
                     sample const diffSample = diffrow[col][plane];
-                    
-                    outrow[col][plane] = 
+
+                    outrow[col][plane] =
                         (-bias + prevSample + diffSample) % (outpam.maxval+1);
                     prevrow[col][plane] = outrow[col][plane];
                 }
@@ -155,3 +157,5 @@ main(int argc, char *argv[]) {
     exit(0);
 }
 
+
+
diff --git a/converter/other/infotopam.c b/converter/other/infotopam.c
index 24c4d776..e9ce4d04 100644
--- a/converter/other/infotopam.c
+++ b/converter/other/infotopam.c
@@ -29,10 +29,10 @@
  *
  * The icon data has the following format:
  *
- *   BIT-PLANE planes, each with HEIGHT rows of (WIDTH +15) / 16 * 2 bytes
- *   length.
+ *   BIT-PLANE planes, each with HEIGHT rows WIDTH bits long, rounded up to
+ *   a multiple of 2 bytes.
  *
- * So if you have a 9x3x2 icon, the icon data will look like this:
+ * So if you have a 9x3x2 icon, the icon data looks like this:
  *
  *   aaaa aaaa a000 0000
  *   aaaa aaaa a000 0000
@@ -45,9 +45,128 @@
  * bit-plane, and '0' is padding.  Thanks again to Ben Hutchings for his
  * very helpful post!
  *
- * This program uses code from "sidplay" and an older "infotoxpm" program I
- * wrote, both of which are released under GPL.
+ *-----------------------------------------------------------------------------
+ * The following specification for the DiskObject header is from
+ * http://amigadev.elowar.com/read/ADCD_2.1/Libraries_Manual_guide/node0241.html
+ * on 2024.03.14.
  *
+ * The DiskObject C structure is defined in the include file
+ * <workbench/workbench.h>.  For a complete listing, see the Amiga ROM Kernel
+ * Reference Manual: Includes and Autodocs.  The DiskObject structure contains
+ * the following elements:
+ *
+ *     struct DiskObject {
+ *         UWORD              do_Magic;    magic number at start of file
+ *         UWORD              do_Version;  so we can change structure
+ *         struct Gadget      do_Gadget;   a copy of in core gadget
+ *         UBYTE              do_Type;
+ *         char              *do_DefaultTool;
+ *         char             **do_ToolTypes;
+ *         LONG               do_CurrentX;
+ *         LONG               do_CurrentY;
+ *         struct DrawerData *do_DrawerData;
+ *         char              *do_ToolWindow;  applies only to tools
+ *         LONG               do_StackSize;   applies only to tools
+ *     };
+ *
+ * do_Magic
+ *
+ *     A magic number that the icon library looks for to make sure that the
+ *     file it is reading really contains an icon.  It should be the manifest
+ *     constant WB_DISKMAGIC.  PutDiskObject() will put this value in the
+ *     structure, and GetDiskObject() will not believe that a file is really
+ *     an icon unless this value is correct.
+ *
+ * do_Version
+ *
+ *     This provides a way to enhance the .info file in an upwardly-compatible
+ *     way.  It should be WB_DISKVERSION.  The icon library will set this value
+ *     for you and will not believe weird values.
+ *
+ * do_Gadget
+ *
+ *     This contains all the imagery for the icon. See the "Gadget Structure"
+ *     section below for more details.
+ *
+ * do_Type
+ *
+ *     The type of the icon; can be set to any of the following values.
+ *
+ *         WBDISK     The root of a disk
+ *         WBDRAWER   A directory on the disk
+ *         WBTOOL     An executable program
+ *         WBPROJECT  A data file
+ *         WBGARBAGE  The Trashcan directory
+ *         WBKICK     A Kickstart disk
+ *         WBAPPICON  Any object not directly associated with a filing system
+ *                    object, such as a print spooler (new in Release 2).
+ *
+ * do_DefaultTool
+ *
+ *     Default tools are used for project and disk icons.  For projects (data
+ *     files), the default tool is the program Workbench runs when the project
+ *     is activated.  Any valid AmigaDOS path may be entered in this field
+ *     such as "SYS:myprogram", "df0:mypaint", "myeditor" or ":work/mytool".
+ *
+ *     For disk icons, the default tool is the diskcopy program
+ *     ("SYS:System/DiskCopy") that will be used when this disk is the source
+ *     of a copy.
+ *
+ * do_ToolTypes
+ *
+ *     This is an array of free-format strings.  Workbench does not enforce
+ *     any rules on these strings, but they are useful for passing
+ *     environment information.  See the section on "The Tool Types Array"
+ *     below for more information.
+ *
+ * do_CurrentX, do_CurrentY
+ *
+ *     Drawers have a virtual coordinate system.  The user can scroll around
+ *     in this system using the scroll gadgets on the window that opens when
+ *     the drawer is activated.  Each icon in the drawer has a position in
+ *     the coordinate system.  CurrentX and CurrentY contain the icon's
+ *     current position in the drawer.  Picking a position for a newly
+ *     created icon can be tricky.  NO_ICON_POSITION is a system constant
+ *     for do_CurrentX and do_CurrentY that instructs Workbench to pick a
+ *     reasonable place for the icon.  Workbench will place the icon in an
+ *     unused region of the drawer.  If there is no space in the drawers
+ *     window, the icon will be placed just to the right of the visible
+ *     region.
+ *
+ * do_DrawerData
+ *
+ *     If the icon is associated with a directory (WBDISK, WBDRAWER,
+ *     WBGARBAGE), it needs a DrawerData structure to go with it.  This
+ *     structure contains an Intuition NewWindow structure (see the
+ *     "Intuition Windows" chapter for more information):
+ *
+ *         struct DrawerData {
+ *              struct NewWindow dd_NewWindow; structure to open window
+ *              LONG             dd_CurrentX;  current x coordinate of origin
+ *              LONG             dd_CurrentY;  current y coordinate of origin
+ *         };
+ *
+ *     Workbench uses this to hold the current window position and size of
+ *     the window so it will reopen in the same place.
+ *
+ * do_ToolWindow
+ *
+ *     This field is reserved for future use.
+ *
+ * do_StackSize
+ *
+ *     This is the size of the stack (in bytes) used for running the tool.
+ *     If this is NULL, then Workbench will use a reasonable default stack
+ *     size (currently 4K bytes).
+ *
+ *     When a tool is run via the default tool mechanism (i.e., a project
+ *     was activated, not the tool itself), Workbench uses the stack size
+ *     specified in the project's .info file and the tool's .info file is
+ *     ignored.
+ *
+ *-------------------------------------------------------------------------
+ * This program uses code from "sidplay" and an older "infotoxpm" program
+ * Richard Griswold wrote, both of which are offered under GPL.
  *-------------------------------------------------------------------------
  *
  * This program is free software; you can redistribute it and/or
@@ -65,42 +184,51 @@
  * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
  */
 
-#include "pm_c_util.h"
-#include "pam.h"
-#include "shhopt.h"
-#include "mallocvar.h"
-
-#include <errno.h>
-#include <stdio.h>
+#include <stdbool.h>
 #include <stdlib.h>
 #include <string.h>
+#include <errno.h>
+#include <stdio.h>
 
+#include "pm_c_util.h"
+#include "mallocvar.h"
+#include "nstring.h"
+#include "shhopt.h"
+#include "pam.h"
 
-/* Struct to hold miscellaneous icon information */
-typedef struct IconInfo_ {
-    const char  *name;        /* Icon file name */
-    FILE        *fp;          /* Input file pointer */
 
-    bool         forceColor;  /* Convert 1 bitplane icon to color icon */
-    unsigned int numColors;   /* Number of colors to override */
-    bool         selected;    /* Converting selected (second) icon */
+typedef struct CmdlineInfo_ {
+    const char  * inputFileNm;
+    unsigned int  forcecolor;
+    pixel         colors[4];   /* Colors to use for converted icons */
+    unsigned int  selected;
+    unsigned int  verbose;
+} CmdlineInfo;
 
-    bool         drawerData;  /* Icon has drawer data */
-    unsigned int version;     /* Icon version */
-    unsigned int width;       /* Width in pixels */
-    unsigned int height;      /* Height in pixels */
-    unsigned int depth;       /* Bits of color per pixel */
-    pixel        colors[4];   /* Colors to use for converted icons */
-    unsigned char *icon;      /* Completed icon */
+typedef struct IconInfo_ {
+    /* Miscellaneous icon information */
+    FILE *          ifP;            /* Input file */
+    bool            hasDrawerData;  /* Icon has drawer data */
+    unsigned int    version;        /* Icon version */
+    unsigned int    width;          /* Width in pixels */
+    unsigned int    height;         /* Height in pixels */
+    unsigned int    depth;          /* Bits of color per pixel */
+    unsigned int    bpwidth;
+        /* Bitplane width; Width of each row in icon, including padding */
+    unsigned char * icon;           /* Completed icon */
 
 } IconInfo;
 
-/* Header for each icon image */
 typedef struct IconHeader_ { /* 20 bytes */
-    unsigned char pad0[4];        /* Padding (always seems to be zero) */
+    /* Text of header for one icon image */
+    unsigned char type[4];
+        /* Reverse engineered.  This always seems to be 0x00000000 in
+           icon headers, but we've seen 0x00000010 in some 51-byte object
+           we don't understand.
+        */
     unsigned char iconWidth[2];   /* Width (usually equal to Gadget width) */
     unsigned char iconHeight[2];
-    /* Height (usually equal to Gadget height -1) */
+        /* Height (usually equal to Gadget height -1) */
     unsigned char bpp[2];         /* Bits per pixel */
     unsigned char pad1[10];       /* ??? */
 } IconHeader;
@@ -110,6 +238,7 @@ typedef struct IconHeader_ { /* 20 bytes */
  * http://www.geocities.com/SiliconValley/Lakes/5147/sidplay/linux.html
  */
 typedef struct DiskObject_ { /* 78 bytes (including Gadget struct) */
+    /* Text of Info Disk Object header */
     unsigned char magic[2];         /* Magic number at the start of the file */
     unsigned char version[2];       /* Object version number */
     unsigned char gadget[44];       /* Copy of in memory gadget (44 by */
@@ -127,139 +256,140 @@ typedef struct DiskObject_ { /* 78 bytes (including Gadget struct) */
 
 
 static void
-parseCommandLine( int              argc,
-                  char *           argv[],
-                  IconInfo * const infoP ) {
-
-    unsigned int numColorArgs,  /* Number of arguments for overriding colors */
-        colorIdx,      /* Color index */
-        i;             /* Argument index */
-    const char  * const colors[4] = {
-        /* Pixel colors based on original Amiga colors */
-        "#0055AA",    /*   Blue      0,  85, 170 */
-        "#FFFFFF",    /*   White   255, 255, 255 */
-        "#000020",    /*   Black     0,   0,  32 */
-        "#FF8A00"     /*   Orange  255, 138,   0 */
-    };
-
-    /* Option entry variables */
-    optEntry     *option_def;
-    optStruct3    opt;
-    unsigned int  option_def_index;
-    unsigned int numColorsSpec, forceColorSpec, selectedSpec;
+parseCommandLine(int                 argc,
+                 const char **       argv,
+                 CmdlineInfo * const cmdlineP) {
+
+    unsigned int   argIdx;
+    optEntry     * option_def;
+    optStruct3     opt;
+    unsigned int   option_def_index;
+    unsigned int   numcolorsSpec;
+    unsigned int   numcolors;
 
     MALLOCARRAY_NOFAIL(option_def, 100);
 
     /* Set command line options */
     option_def_index = 0;   /* Incremented by OPTENT3 */
-    OPTENT3(0, "forcecolor", OPT_FLAG, NULL, &forceColorSpec, 0);
-    OPTENT3(0, "numcolors",  OPT_UINT, &infoP->numColors, &numColorsSpec, 0);
-    OPTENT3(0, "selected",   OPT_FLAG, NULL, &selectedSpec,   0);
-
-    /* Initialize the iconInfo struct */
-    infoP->name = NULL;
-    infoP->fp = NULL;
-    infoP->drawerData = FALSE;
-    infoP->version = 0;
-    infoP->width = 0;
-    infoP->height = 0;
-    infoP->depth = 0;
-    infoP->icon = NULL;
-    for ( colorIdx = 0; colorIdx < 4; colorIdx++ )
-        infoP->colors[colorIdx] =
-            ppm_parsecolor( (char*) colors[colorIdx], 0xFF );
-
-    /* Initialize option structure */
+    OPTENT3(0, "forcecolor", OPT_FLAG, NULL,       &cmdlineP->forcecolor,
+            0);
+    OPTENT3(0, "numcolors",  OPT_UINT, &numcolors, &numcolorsSpec,
+            0);
+    OPTENT3(0, "selected",   OPT_FLAG, NULL,       &cmdlineP->selected,
+            0);
+    OPTENT3(0, "verbose",    OPT_FLAG, NULL,       &cmdlineP->verbose,
+            0);
+
     opt.opt_table     = option_def;
-    opt.short_allowed = FALSE;  /* No short (old-fashioned) options */
-    opt.allowNegNum   = FALSE;  /* No negative number parameters */
-
-    /* Parse the command line */
-    pm_optParseOptions3( &argc, argv, opt, sizeof( opt ), 0 );
-
-    infoP->forceColor = forceColorSpec;
-    infoP->selected = selectedSpec;
-    if (!numColorsSpec)
-        infoP->numColors = 0;
-
-    /* Get colors and file name */
-    numColorArgs = infoP->numColors * 2;
-    if ( ( argc - 1 != numColorArgs ) && ( argc - 1 != numColorArgs + 1 ) ) {
-        pm_error( "Wrong number of arguments for number of colors.  "
-                  "For %u colors, you need %u color arguments, "
-                  "with possibly one more argument for the input file name.",
-                  infoP->numColors, numColorArgs );
-    }
+    opt.short_allowed = false;  /* No short (old-fashioned) options */
+    opt.allowNegNum   = false;  /* No negative number parameters */
+
+    pm_optParseOptions4(&argc, argv, opt, sizeof(opt), 0);
+
+    {
+        const char * const colors[4] = {
+            /* Pixel colors based on original Amiga colors */
+            "#0055AA",    /*   Blue      0,  85, 170 */
+            "#FFFFFF",    /*   White   255, 255, 255 */
+            "#000020",    /*   Black     0,   0,  32 */
+            "#FF8A00"     /*   Orange  255, 138,   0 */
+        };
+
+        unsigned int colorArgCt;
+            /* Number of arguments for overriding colors */
 
-    /* Convert color arguments */
-    for ( i = 1; i < numColorArgs; i += 2 ) {
-        char *       endptr;        /* End pointer for strtol() */
         unsigned int colorIdx;
 
-        /* Get color index from argument */
-        colorIdx = strtoul( argv[i], &endptr, 0 );
+        if (numcolorsSpec) {
+            colorArgCt = numcolors * 2;
+            if (argc-1 < colorArgCt) {
+                pm_error("Insufficient arguments for %u color "
+                         "specifications.  Need at least %u arguments",
+                         numcolors, colorArgCt);
+            }
+        } else
+            colorArgCt = 0;
 
-        if ( *endptr != '\0' ) {
-            pm_error( "'%s' is not a valid color index", argv[i] );
-        }
+        /* Initialize palette to defaults */
+        for (colorIdx = 0; colorIdx < 4; ++colorIdx)
+            cmdlineP->colors[colorIdx] =
+                ppm_parsecolor(colors[colorIdx], 0xFF);
 
-        /* Check color index range (current 0 to 3) */
-        if ( ( colorIdx < 0 ) || ( colorIdx > 3 ) ) {
-            pm_error( "%u is not a valid color index (minimum 0, maximum 3)",
-                      colorIdx );
-        }
+        /* Convert color arguments */
+        for (argIdx = 1; argIdx < colorArgCt; argIdx += 2) {
+            char *       endptr;        /* End pointer for strtol() */
+            unsigned int colorIdx;
+
+            /* Get color index from argument */
+            colorIdx = strtoul(argv[argIdx], &endptr, 0);
+
+            if (*endptr != '\0') {
+                pm_error("'%s' is not a valid color index", argv[argIdx]);
+            }
+
+            if ((colorIdx < 0) || (colorIdx > 3)) {
+                pm_error(
+                    "%u is not a valid color index (minimum 0, maximum 3)",
+                    colorIdx);
+            }
 
-        /* Convert the color for this color index */
-        infoP->colors[colorIdx] = ppm_parsecolor( argv[i+1], 0xFF );
+            cmdlineP->colors[colorIdx] = ppm_parsecolor(argv[argIdx+1], 0xFF);
+        }
     }
 
-    /* Set file name */
-    if ( i > argc-1 )
-        infoP->name = "-";  /* Read from standard input */
+    if (argIdx > argc-1)
+        cmdlineP->inputFileNm = "-";  /* Read from standard input */
     else
-        infoP->name = argv[i];
+        cmdlineP->inputFileNm = argv[argIdx];
 }
 
 
 
 static void
-getDiskObject( IconInfo * const infoP ) {
-/*-------------------------------------------------------------------------
- * Get fields from disk object portion of info file
- *-------------------------------------------------------------------------*/
+readDiskObjectHeader(FILE *         const ifP,
+                     unsigned int * const versionP,
+                     bool *         const hasDrawerDataP) {
+/*---------------------------------------------------------------------------
+  Read disk object header from file *ifP; validate it and return its contents.
+----------------------------------------------------------------------------*/
     DiskObject  dobj;      /* Disk object structure */
-    size_t      bytesRead;
+    size_t      bytesReadCt;
 
     /* Read the disk object header */
-    bytesRead = fread( &dobj, 1, sizeof(dobj), infoP->fp );
-    if (ferror(infoP->fp))
-        pm_error("Cannot read disk object header for file '%s'.  "
+    bytesReadCt = fread(&dobj, 1, sizeof(dobj), ifP);
+    if (ferror(ifP))
+        pm_error("Cannot read disk object header.  "
                  "fread() errno = %d (%s)",
-                 infoP->name, errno, strerror(errno));
-    else if (bytesRead != sizeof(dobj))
-        pm_error("Cannot read entire disk object header for file '%s'.  "
+                 errno, strerror(errno));
+    else if (bytesReadCt != sizeof(dobj))
+        pm_error("Cannot read entire disk object header.  "
                  "Only read 0x%X of 0x%X bytes",
-                 infoP->name, (unsigned)bytesRead, (unsigned)sizeof(dobj));
+                 (unsigned)bytesReadCt, (unsigned)sizeof(dobj));
 
-    /* Check magic number */
+    /* Validate magic number */
     if ((dobj.magic[0] != 0xE3) && (dobj.magic[1] != 0x10))
-        pm_error("Wrong magic number for file '%s'.  "
+        pm_error("Wrong magic number in icon file.  "
                  "Expected 0xE310, but got 0x%X%X",
-                 infoP->name, dobj.magic[0], dobj.magic[1]);
+                 dobj.magic[0], dobj.magic[1]);
+
+    *versionP = (dobj.version[0] <<  8) + (dobj.version[1]);
 
-    /* Set version info and have drawer data flag */
-    infoP->version     = (dobj.version[0]     <<  8) +
-        (dobj.version[1]           );
-    infoP->drawerData  = (dobj.pDrawerData[0] << 24) +
+    *hasDrawerDataP =
+        (dobj.pDrawerData[0] << 24) +
         (dobj.pDrawerData[1] << 16) +
         (dobj.pDrawerData[2] <<  8) +
-        (dobj.pDrawerData[3]      ) ? TRUE : FALSE;
+        (dobj.pDrawerData[3]      )
+        > 0;
 }
 
 
 
 static void
-getIconHeader(IconInfo * const infoP) {
+readIconHeader(FILE *         const ifP,
+               unsigned int * const widthP,
+               unsigned int * const heightP,
+               unsigned int * const depthP,
+               unsigned int * const bpwidthP) {
 /*-------------------------------------------------------------------------
  * Get fields from icon header portion of info file
  *-------------------------------------------------------------------------*/
@@ -267,25 +397,37 @@ getIconHeader(IconInfo * const infoP) {
     size_t      bytesRead;
 
     /* Read icon header */
-    bytesRead = fread(&ihead, 1, sizeof(ihead), infoP->fp);
-    if (ferror(infoP->fp))
-        pm_error("Cannot read icon header for file '%s'.  "
-                 "fread() errno = %d (%s)",
-                 infoP->name, errno, strerror(errno));
+    bytesRead = fread(&ihead, 1, sizeof(ihead), ifP);
+    if (ferror(ifP))
+        pm_error("Failed to read icon header.  fread() errno = %d (%s)",
+                 errno, strerror(errno));
     else if (bytesRead != sizeof(ihead))
-        pm_error("Cannot read the entire icon header for file '%s'.  "
-                 "Only read 0x%X of 0x%X bytes",
-                 infoP->name, (unsigned)bytesRead, (unsigned)sizeof(ihead));
+        pm_error("Failed to read the entire icon header.  "
+                 "Read only %u of %u bytes",
+                 (unsigned)bytesRead, (unsigned)sizeof(ihead));
+
+    if (!memeq(ihead.type, "\0\0\0\0", 4)) {
+        pm_message("Unrecognized object where icon header expected.  "
+                   "First 4 bytes are 0x%02x%02x%02x%02x.  We expect "
+                   "0x00000000",
+                   ihead.type[0], ihead.type[1], ihead.type[2], ihead.type[3]);
+    }
 
-    /* Get icon width, height, and bitplanes */
-    infoP->width  = (ihead.iconWidth[0]  << 8) + ihead.iconWidth[1];
-    infoP->height = (ihead.iconHeight[0] << 8) + ihead.iconHeight[1];
-    infoP->depth  = (ihead.bpp[0]        << 8) + ihead.bpp[1];
+    *widthP  = (ihead.iconWidth[0]  << 8) + ihead.iconWidth[1];
+    *heightP = (ihead.iconHeight[0] << 8) + ihead.iconHeight[1];
+    *depthP  = (ihead.bpp[0]        << 8) + ihead.bpp[1];
 
-    /* Check number of bit planes */
-    if ((infoP->depth > 2) || (infoP->depth < 1))
-        pm_error("We don't know how to interpret %u bitplanes file '%s'.  ",
-                 infoP->depth, infoP->name);
+    if (*widthP < 1)
+        pm_error("Invalid width value in icon header: %u", *widthP);
+
+    if (*heightP < 1)
+        pm_error("Invalid height value in icon header: %u", *heightP);
+
+    if (*depthP > 2 || *depthP < 1)
+        pm_error("We don't know how to interpret file with %u bitplanes.  ",
+                 *depthP);
+
+    *bpwidthP = ROUNDUP(*widthP, 16);
 }
 
 
@@ -298,17 +440,16 @@ addBitplane(unsigned char * const icon,
    Add bitplane to existing icon image
 -----------------------------------------------------------------------------*/
     unsigned int i;
-    unsigned int j;
-
-    for (i = j = 0; i < bpsize; ++i, j += 8) {
-        icon[j+0] = (icon[j+0] << 1) | ((buff[i] >> 0) & 0x01);
-        icon[j+1] = (icon[j+1] << 1) | ((buff[i] >> 1) & 0x01);
-        icon[j+2] = (icon[j+2] << 1) | ((buff[i] >> 2) & 0x01);
-        icon[j+3] = (icon[j+3] << 1) | ((buff[i] >> 3) & 0x01);
-        icon[j+4] = (icon[j+4] << 1) | ((buff[i] >> 4) & 0x01);
-        icon[j+5] = (icon[j+5] << 1) | ((buff[i] >> 5) & 0x01);
-        icon[j+6] = (icon[j+6] << 1) | ((buff[i] >> 6) & 0x01);
-        icon[j+7] = (icon[j+7] << 1) | ((buff[i] >> 7) & 0x01);
+
+    for (i = 0; i < bpsize; ++i) {
+        icon[(i*8)+0] = (icon[(i*8)+0] << 1) | ((buff[i] >> 7) & 0x01);
+        icon[(i*8)+1] = (icon[(i*8)+1] << 1) | ((buff[i] >> 6) & 0x01);
+        icon[(i*8)+2] = (icon[(i*8)+2] << 1) | ((buff[i] >> 5) & 0x01);
+        icon[(i*8)+3] = (icon[(i*8)+3] << 1) | ((buff[i] >> 4) & 0x01);
+        icon[(i*8)+4] = (icon[(i*8)+4] << 1) | ((buff[i] >> 3) & 0x01);
+        icon[(i*8)+5] = (icon[(i*8)+5] << 1) | ((buff[i] >> 2) & 0x01);
+        icon[(i*8)+6] = (icon[(i*8)+6] << 1) | ((buff[i] >> 1) & 0x01);
+        icon[(i*8)+7] = (icon[(i*8)+7] << 1) | ((buff[i] >> 0) & 0x01);
     }
 }
 
@@ -392,156 +533,134 @@ readIconData(FILE *           const fileP,
 
 
 static void
-writeIconData( IconInfo *   const infoP,
-               struct pam * const pamP ) {
+writeRaster(IconInfo *    const infoP,
+            struct pam *  const pamP,
+            bool          const wantColor,
+            const pixel * const colors) {
 /*-------------------------------------------------------------------------
- * Write icon data to file
- *-------------------------------------------------------------------------*/
-    unsigned int const bpwidth = ( ( infoP->width + 15 ) / 16 ) * 16;
-        /* Bitplane width; Width of each row in icon, including padding */
+  Write out raster of PAM image described by *pamP.
 
-    tuple * row;      /* Output row */
+  'wantColor' means the user wants the PAM to be tuple type RGB, regardless
+  of the input image type.
 
-    /* Allocate row */
-    row = pnm_allocpamrow( pamP );
+  'colors' is the palette.  It has 4 entries, one for each of the possible
+  color indices in the input icon raster.
+--------------------------------------------------------------------------*/
+    unsigned int row;
+    tuple * tuplerow;      /* Output row */
 
-    /* Write icon image to output file */
-    /* Put if check outside for loop to reduce number of times check is made */
-    if ( infoP->depth == 1 ) {
-        if ( infoP->forceColor ) {
-            /* Convert 1 bitplane icon into color PAM */
-            unsigned int i;
-            for ( i = 0; i < infoP->height; ++i ) {
-                unsigned int j;
-                for ( j = 0; j < infoP->width; ++j ) {
+    tuplerow = pnm_allocpamrow(pamP);
+
+    for (row = 0; row < infoP->height; ++row) {
+        unsigned int col;
+
+        for (col = 0; col < infoP->width; ++col) {
+            if (infoP->depth == 1) {
+                if (wantColor) {
                     /* 1 is black and 0 is white */
                     unsigned int colorIdx =
-                        infoP->icon[ i * bpwidth + j ] ? 2 : 1;
-                    row[j][PAM_RED_PLANE] =
-                        PPM_GETR( infoP->colors[colorIdx] );
-                    row[j][PAM_GRN_PLANE] =
-                        PPM_GETG( infoP->colors[colorIdx] );
-                    row[j][PAM_BLU_PLANE] =
-                        PPM_GETB( infoP->colors[colorIdx] );
-                }
-                pnm_writepamrow( pamP, row );
-            }
-        } else {
-            /* Convert 1 bitplane icon into bitmap PAM */
-            unsigned int i;
-            for ( i = 0; i < infoP->height; ++i ) {
-                unsigned int j;
-                for ( j = 0; j < infoP->width; j++ ) {
+                        infoP->icon[row * infoP->bpwidth + col] ? 2 : 1;
+
+                    tuplerow[col][PAM_RED_PLANE] = PPM_GETR(colors[colorIdx]);
+                    tuplerow[col][PAM_GRN_PLANE] = PPM_GETG(colors[colorIdx]);
+                    tuplerow[col][PAM_BLU_PLANE] = PPM_GETB(colors[colorIdx]);
+                } else {
                     /* 1 is black and 0 is white */
-                    row[j][0] = infoP->icon[ i * bpwidth + j ] ? 0 : 1;
+                    tuplerow[col][0] =
+                        infoP->icon[row * infoP->bpwidth + col] ? 0 : 1;
                 }
-                pnm_writepamrow( pamP, row );
+            } else {
+                unsigned int const colorIdx =
+                    infoP->icon[row * infoP->bpwidth + col];
+                tuplerow[col][PAM_RED_PLANE] = PPM_GETR(colors[colorIdx]);
+                tuplerow[col][PAM_GRN_PLANE] = PPM_GETG(colors[colorIdx]);
+                tuplerow[col][PAM_BLU_PLANE] = PPM_GETB(colors[colorIdx]);
             }
         }
-    } else {
-        /* Convert color icon into color PAM */
-        unsigned int i;
-        for ( i = 0; i < infoP->height; ++i ) {
-            unsigned int j;
-            for ( j = 0; j < infoP->width; ++j ) {
-                unsigned int const colorIdx = infoP->icon[ i * bpwidth + j ];
-                row[j][PAM_RED_PLANE] = PPM_GETR( infoP->colors[colorIdx] );
-                row[j][PAM_GRN_PLANE] = PPM_GETG( infoP->colors[colorIdx] );
-                row[j][PAM_BLU_PLANE] = PPM_GETB( infoP->colors[colorIdx] );
-            }
-            pnm_writepamrow( pamP, row );
-        }
+        pnm_writepamrow(pamP, tuplerow);
     }
 
-    /* Clean up allocated memory */
-    pnm_freepamrow( row );
+    pnm_freepamrow(tuplerow);
 }
 
 
 
 int
-main( int argc,
-      char *argv[] ) {
+main(int argc, const char **argv) {
 
-    IconInfo    info;    /* Miscellaneous icon information */
-    struct pam  pam;     /* PAM header */
-    int         skip;    /* Bytes to skip to read next icon header */
+    CmdlineInfo  cmdline;
+    IconInfo     info;      /* Miscellaneous icon information */
+    struct pam   pam;       /* PAM header */
 
-    /* Init PNM library */
-    pnm_init( &argc, argv );
+    pm_proginit(&argc, argv);
 
-    /* Parse command line arguments */
-    parseCommandLine( argc, argv, &info );
+    parseCommandLine(argc, argv, &cmdline);
 
-    /* Open input file */
-    info.fp = pm_openr( info.name );
+    info.ifP = pm_openr(cmdline.inputFileNm);
 
-    /* Read disk object header */
-    getDiskObject( &info );
+    readDiskObjectHeader(info.ifP, &info.version, &info.hasDrawerData);
 
     /* Skip drawer data, if any */
-    if ( info.drawerData ) {
-        skip = 56;   /* Draw data size */
-        if ( fseek( info.fp, skip, SEEK_CUR ) < 0 )
-            pm_error( "Cannot skip header information in file '%s'.  "
-                      "fseek() errno = %d (%s)",
-                      info.name, errno, strerror( errno ) );
-    }
+    if (info.hasDrawerData) {
+        unsigned int const skipCt = 56;   /* Draw data size */
 
-    /* Get dimensions for first icon */
-    getIconHeader( &info );
+        int rc;
 
-    /* Skip ahead to next header if converting second icon */
-    if ( info.selected ) {
-        skip = info.height * ( ( ( info.width + 15 ) / 16 ) * 2 ) * info.depth;
+        rc = fseek(info.ifP, skipCt, SEEK_CUR);
+        if (rc < 0) {
+            pm_error("Failed to skip header information in input file.  "
+                     "fseek() errno = %d (%s)",
+                     errno, strerror(errno));
+        }
+    }
 
-        if ( fseek( info.fp, skip, SEEK_CUR ) < 0 )
-            pm_error( "Cannot skip to next icon in file '%s'.  "
-                      "fseek() errno = %d (%s)",
-                      info.name, errno, strerror( errno ) );
+    /* Read header of first icon */
+    readIconHeader(info.ifP, &info.width, &info.height, &info.depth,
+                   &info.bpwidth);
 
-        /* Get dimensions for second icon */
-        getIconHeader( &info );
-    }
+    readIconData(info.ifP, info.width, info.height, info.depth, &info.icon);
 
-    /* Read icon data */
-    readIconData( info.fp, info.width, info.height, info.depth, &info.icon );
+    if (cmdline.selected) {
+        /* He wants the second icon, so update info.width, etc.  to be for the
+           second icon.
+        */
+        readIconHeader(info.ifP, &info.width, &info.height, &info.depth,
+                       &info.bpwidth);
 
-    /* Print icon info */
-    pm_message( "converting %s, version %d, %s icon: %d X %d X %d",
-                info.name, info.version, info.selected ? "second" : "first",
-                info.width, info.height, info.depth );
+        readIconData(info.ifP, info.width, info.height, info.depth,
+                     &info.icon);
+    }
 
-    /* Write PAM header */
-    pam.size   = sizeof( pam );
-    pam.len    = PAM_STRUCT_SIZE( tuple_type );
+    if (cmdline.verbose) {
+        pm_message("Version %u .info file, %s icon: %uW x %uH x %u deep",
+                   info.version, cmdline.selected ? "second" : "first",
+                   info.width, info.height, info.depth);
+    }
+    pam.size   = sizeof(pam);
+    pam.len    = PAM_STRUCT_SIZE(tuple_type);
     pam.file   = stdout;
     pam.height = info.height;
     pam.width  = info.width;
     pam.format = PAM_FORMAT;
 
-    if ( ( info.depth == 1 ) && ( info.forceColor == FALSE ) ) {
+    if ((info.depth == 1) && !cmdline.forcecolor) {
         pam.depth  = 1;
         pam.maxval = 1;
-        strcpy( pam.tuple_type, "BLACKANDWHITE" );
+        strcpy(pam.tuple_type, "BLACKANDWHITE");
     } else {
         pam.depth  = 3;
         pam.maxval = 0xFF;
-        strcpy( pam.tuple_type, "RGB" );
+        strcpy(pam.tuple_type, "RGB");
     }
-    pnm_writepaminit( &pam );
+    pnm_writepaminit(&pam);
 
-    /* Write icon data */
-    writeIconData( &info, &pam );
+    writeRaster(&info, &pam, cmdline.forcecolor, cmdline.colors);
 
-    free( info.icon );
-
-    /* Close input file and return */
-    pm_close( pam.file );
-    pm_close( info.fp );
+    free(info.icon);
+    pm_close(pam.file);
+    pm_close(info.ifP);
 
     return 0;
 }
 
 
-
diff --git a/converter/other/ipdb.c b/converter/other/ipdb.c
index 5e4dc82e..d524c7e9 100644
--- a/converter/other/ipdb.c
+++ b/converter/other/ipdb.c
@@ -23,15 +23,12 @@
 #define _XOPEN_SOURCE 500  /* Make sure strdup() is in string.h */
 #define _BSD_SOURCE   /* Ensure strdup() is in <string.h> */
 #include <assert.h>
-#include <time.h>
 #include <string.h>
 
 #include "mallocvar.h"
 #include "nstring.h"
-#include "ipdb.h"
-
-typedef uint32_t pilot_time_t;
 
+#include "ipdb.h"
 
 
 
@@ -49,7 +46,7 @@ imgPpb(IMAGE * const imgP) {
 
 
 unsigned int
-ipdb_img_ppb(IMAGE * const imgP) {
+ipdb_imgPpb(IMAGE * const imgP) {
 /*----------------------------------------------------------------------------
    Pixels per byte
 -----------------------------------------------------------------------------*/
@@ -59,7 +56,7 @@ ipdb_img_ppb(IMAGE * const imgP) {
 
 
 size_t
-ipdb_img_size(IMAGE * const imgP) {
+ipdb_imgSize(IMAGE * const imgP) {
 /*----------------------------------------------------------------------------
   Size (in bytes) of an image's data.
 -----------------------------------------------------------------------------*/
@@ -71,115 +68,97 @@ ipdb_img_size(IMAGE * const imgP) {
 /*
  * Return the start of row `r'.
  */
- uint8_t *
- ipdb_img_row(IMAGE *      const imgP,
-              unsigned int const row) {
-
-     return &imgP->data[(row) * imgP->width / imgPpb(imgP)];
- }
-
-
+uint8_t *
+ipdb_imgRow(IMAGE *      const imgP,
+            unsigned int const row) {
 
- #define img_row(i, r)   
-
- static pilot_time_t const unixepoch = (66*365+17)*24*3600;
-     /* The unix epoch in Mac time (the Mac epoch is 00:00 UTC 1904.01.01).
-        The 17 is the number of leap years.
-     */
-
- static const char * const errorDesc[] = {
-     /* E_BADCOLORS      */
-     "Invalid palette, only {0x00, 0x55, 0xAA, 0xFF} allowed.",
+    return &imgP->data[(row) * imgP->width / imgPpb(imgP)];
+}
 
-     /* E_NOTIMAGE       */
-     "Not an image file.",
 
-     /* E_IMAGETHERE     */
-     "Image record already present, logic error.",
 
-     /* E_IMAGENOTTHERE  */
-     "Image record required before text record, logic error.",
+static const char * const errorDesc[] = {
+    /* E_BADCOLORS      */
+    "Invalid palette, only {0x00, 0x55, 0xAA, 0xFF} allowed.",
 
-     /* E_TEXTTHERE      */
-     "Text record already present, logic error.",
+    /* E_NOTIMAGE       */
+    "Not an image file.",
 
-     /* E_NOTRECHDR      */
-     "Invalid record header encountered.",
+    /* E_IMAGETHERE     */
+    "Image record already present, logic error.",
 
-     /* E_UNKNOWNRECHDR  */
-     "Unknown record header.",
+    /* E_IMAGENOTTHERE  */
+    "Image record required before text record, logic error.",
 
-     /* E_TOOBIGG        */
-     "Image too big, maximum size approx. 640*400 gray pixels.",
+    /* E_TEXTTHERE      */
+    "Text record already present, logic error.",
 
-     /* E_TOOBIGM        */
-     "Image too big, maximum size approx. 640*800 monochrome pixels.",
- };
+    /* E_NOTRECHDR      */
+    "Invalid record header encountered.",
 
+    /* E_UNKNOWNRECHDR  */
+    "Unknown record header.",
 
+    /* E_TOOBIGG        */
+    "Image too big, maximum size approx. 640*400 gray pixels.",
 
- const char *
- ipdb_err(int const e) {
+    /* E_TOOBIGM        */
+    "Image too big, maximum size approx. 640*800 monochrome pixels.",
+};
 
-     if (e < 0)
-         return e >= E_LAST ? errorDesc[-e - 1] : "unknown error";
-     else
-         return strerror(e);
- }
 
 
+const char *
+ipdb_err(int const e) {
 
- static void
- rechdr_free(RECHDR * const recP) {
+    if (e < 0)
+        return e >= E_LAST ? errorDesc[-e - 1] : "unknown error";
+    else
+        return strerror(e);
+}
 
-     if (recP) {
-         free(recP->extra);
-         free(recP);
-     }
- }
 
 
+static void
+rechdr_free(RECHDR * const recP) {
 
- void
- ipdb_image_free(IMAGE * const imgP) {
+    if (recP) {
+        free(recP->extra);
+        free(recP);
+    }
+}
 
-     if (imgP) {
-         rechdr_free(imgP->r);
-         free(imgP->data);
-         free(imgP);
-     }
- }
 
 
+void
+ipdb_imageFree(IMAGE * const imgP) {
 
- void
- ipdb_text_free(TEXT * const textP) {
+    if (imgP) {
+        rechdr_free(imgP->r);
+        free(imgP->data);
+        free(imgP);
+    }
+}
 
-     if (textP) {
-         rechdr_free(textP->r);
-         free(textP->data);
-         free(textP);
-     }
- }
 
 
+void
+ipdb_textFree(TEXT * const textP) {
 
- void
- ipdb_pdbhead_free(PDBHEAD * const headP) {
+    if (textP) {
+        rechdr_free(textP->r);
+        if (textP->data)
+            free(textP->data);
+        free(textP);
+    }
+}
 
-     free(headP);
- }
 
 
+void
+ipdb_pdbheadFree(PDBHEAD * const headP) {
 
- void
- ipdb_clear(IPDB * const pdbP) {
-     
-     if (pdbP) {
-         ipdb_image_free(pdbP->i);
-         ipdb_text_free(pdbP->t);
-         ipdb_pdbhead_free(pdbP->p);
-    }
+    free(headP);
 }
 
 
@@ -187,14 +166,22 @@ ipdb_img_size(IMAGE * const imgP) {
 void
 ipdb_free(IPDB * const pdbP) {
 
-    ipdb_clear(pdbP);
+    if (pdbP->i)
+        ipdb_imageFree(pdbP->i);
+
+    if (pdbP->t)
+        ipdb_textFree(pdbP->t);
+
+    if (pdbP->p)
+        ipdb_pdbheadFree(pdbP->p);
+
     free(pdbP);
 }
 
 
 
 PDBHEAD *
-ipdb_pdbhead_alloc(const char * const name) {
+ipdb_pdbheadAlloc() {
 
     PDBHEAD * pdbHeadP;
 
@@ -202,20 +189,6 @@ ipdb_pdbhead_alloc(const char * const name) {
 
     if (pdbHeadP) {
         MEMSZERO(pdbHeadP);
-
-        STRSCPY(pdbHeadP->name, name == NULL ? "unnamed" : name);
-
-        /*
-         * All of the Image Viewer pdb files that I've come across have
-         * 3510939142U (1997.08.16 14:38:22 UTC) here.  I don't know where
-         * this bizarre date comes from but the real date works fine so
-         * I'm using it.
-         */
-        pdbHeadP->ctime =
-            pdbHeadP->mtime = (pilot_time_t)time(NULL) + unixepoch;
-        
-        MEMSCPY(&pdbHeadP->type, IPDB_vIMG);
-        MEMSCPY(&pdbHeadP->id,   IPDB_View);
     }
     return pdbHeadP;
 }
@@ -223,7 +196,7 @@ ipdb_pdbhead_alloc(const char * const name) {
 
 
 static RECHDR *
-rechdr_alloc(int      const type,
+rechdrCreate(int      const type,
              uint32_t const offset) {
 
     /*
@@ -234,7 +207,7 @@ rechdr_alloc(int      const type,
     RECHDR  * recHdrP;
 
     MALLOCVAR(recHdrP);
-    
+
     if (recHdrP) {
         MEMSSET(recHdrP, 0);
 
@@ -255,10 +228,10 @@ rechdr_alloc(int      const type,
 
 
 IMAGE *
-ipdb_image_alloc(const char * const name,
-            int          const type,
-            int          const w,
-            int          const h) {
+ipdb_imageCreate(const char * const name,
+                 int          const type,
+                 int          const w,
+                 int          const h) {
 
     bool failed;
     IMAGE * imgP;
@@ -277,7 +250,7 @@ ipdb_image_alloc(const char * const name,
         imgP->width    = w;
         imgP->height   = h;
 
-        imgP->r = rechdr_alloc(IMG_REC, IMGOFFSET);
+        imgP->r = rechdrCreate(IMG_REC, IMGOFFSET);
 
         if (imgP->r) {
             if (w != 0 && h != 0) {
@@ -292,10 +265,10 @@ ipdb_image_alloc(const char * const name,
                 rechdr_free(imgP->r);
         } else
             failed = true;
-        
+
         if (failed)
-            ipdb_image_free(imgP);
-    } else 
+            ipdb_imageFree(imgP);
+    } else
         failed = true;
 
     return failed ? NULL : imgP;
@@ -304,7 +277,7 @@ ipdb_image_alloc(const char * const name,
 
 
 TEXT *
-ipdb_text_alloc(const char * const content) {
+ipdb_textAlloc(void) {
 
     TEXT * textP;
     bool failed;
@@ -320,22 +293,13 @@ ipdb_text_alloc(const char * const content) {
     if (textP) {
         MEMSZERO(textP);
 
-        textP->r = rechdr_alloc(TEXT_REC, 0);
+        textP->r = rechdrCreate(TEXT_REC, 0);
 
-        if (textP->r) {
-            if (content) {
-                textP->data = strdup(content);
-
-                if (!textP->data)
-                    failed = true;
-            }
-            if (failed)
-                rechdr_free(textP->r);
-        } else
+        if (textP->r == NULL)
             failed = true;
 
         if (failed)
-            ipdb_text_free(textP);
+            free(textP);
     } else
         failed = true;
 
@@ -345,7 +309,7 @@ ipdb_text_alloc(const char * const content) {
 
 
 IPDB *
-ipdb_alloc(const char * const name) {
+ipdb_alloc(void) {
 
     IPDB * pdbP;
     bool failed;
@@ -357,12 +321,11 @@ ipdb_alloc(const char * const name) {
     if (pdbP) {
         MEMSZERO(pdbP);
 
-        if (name) {
-            pdbP->p = ipdb_pdbhead_alloc(name);
+        pdbP->p = ipdb_pdbheadAlloc();
+
+        if (!pdbP->p)
+            failed = true;
 
-            if (!pdbP->p)
-                failed = true;
-        }
         if (failed)
             ipdb_free(pdbP);
     } else
@@ -383,3 +346,6 @@ ipdb_typeName(uint8_t const type) {
     default: return "???";
     }
 }
+
+
+
diff --git a/converter/other/ipdb.h b/converter/other/ipdb.h
index 6af5fc44..59e5d266 100644
--- a/converter/other/ipdb.h
+++ b/converter/other/ipdb.h
@@ -201,43 +201,40 @@ const char *
 ipdb_err(int error);
 
 size_t
-ipdb_img_size(IMAGE * const imgP);
+ipdb_imgSize(IMAGE * const imgP);
 
 unsigned int
-ipdb_img_ppb(IMAGE * const imgP);
+ipdb_imgPpb(IMAGE * const imgP);
 
 uint8_t *
-ipdb_img_row(IMAGE *      const imgP,
+ipdb_imgRow(IMAGE *      const imgP,
              unsigned int const row);
 
 void
 ipdb_free(IPDB *);
 
 IPDB *
-ipdb_alloc(const char *);
-
-void
-ipdb_clear(IPDB * const pdbP);
+ipdb_alloc(void);
 
 PDBHEAD *
-ipdb_pdbhead_alloc(const char * const name);
+ipdb_pdbheadAlloc(void);
 
 void
-ipdb_pdbhead_free(PDBHEAD * const headP);
+ipdb_pdbheadFree(PDBHEAD * const headP);
 
 IMAGE *
-ipdb_image_alloc(const char * const name,
+ipdb_imageCreate(const char * const name,
                  int          const type,
                  int          const w,
                  int          const h);
 
 void
-ipdb_image_free(IMAGE * const imgP);
+ipdb_imageFree(IMAGE * const imgP);
 
 void
-ipdb_text_free(TEXT * const textP);
+ipdb_textFree(TEXT * const textP);
 
 TEXT *
-ipdb_text_alloc(const char * const content);
+ipdb_textAlloc(void);
 
 #endif
diff --git a/converter/other/jbig/jbigtopnm.c b/converter/other/jbig/jbigtopnm.c
index 0d55ccc1..69767e11 100644
--- a/converter/other/jbig/jbigtopnm.c
+++ b/converter/other/jbig/jbigtopnm.c
@@ -198,6 +198,7 @@ diagnose_bie(FILE *f)
 }
 
 
+
 int main (int argc, const char **argv)
 {
     CmdlineInfo cmdline;
diff --git a/converter/other/jbig/libjbig/include/jbig.h b/converter/other/jbig/libjbig/include/jbig.h
index 67994107..3c991b08 100644
--- a/converter/other/jbig/libjbig/include/jbig.h
+++ b/converter/other/jbig/libjbig/include/jbig.h
@@ -39,7 +39,7 @@ struct jbg_buf {
   int len;                             /* length of the data in this block */
   struct jbg_buf *next;                           /* pointer to next block */
   struct jbg_buf *previous;                   /* pointer to previous block *
-					       * (unused in freelist)      */
+                                               * (unused in freelist)      */
   struct jbg_buf *last;     /* only used in list head: final block of list */
   struct jbg_buf **free_list;   /* pointer to pointer to head of free list */
 };
@@ -70,12 +70,12 @@ struct jbg_buf {
 /* encoding options that will not be indicated in the header */
 
 #define JBG_DELAY_AT   0x100  /* Delay ATMOVE until the first line of the next
-			       * stripe. Option available for compatibility
-			       * with conformance test example in clause 7.2. */
+                               * stripe. Option available for compatibility
+                               * with conformance test example in clause 7.2. */
 
 #define JBG_SDRST      0x200  /* Use SDRST instead of SDNORM. This option is
-			       * there for anyone who needs to generate
-			       * test data that covers the SDRST cases. */
+                               * there for anyone who needs to generate
+                               * test data that covers the SDRST cases. */
 
 /*
  * Possible error code return values
@@ -115,7 +115,7 @@ struct jbg_enc_state {
   char *dppriv;         /* optional private deterministic prediction table */
   char *res_tab;           /* table for the resolution reduction algorithm */
   struct jbg_buf ****sde;      /* array [stripe][layer][plane] pointers to *
-				* buffers for stored SDEs                  */
+                                * buffers for stored SDEs                  */
   struct jbg_arenc_state *s;  /* array [planes] for arithm. encoder status */
   struct jbg_buf *free_list; /* list of currently unused SDE block buffers */
   void (*data_out)(unsigned char *start, size_t len, void *file);
@@ -140,7 +140,7 @@ struct jbg_dec_state {
   unsigned long xd, yd;     /* size of the full image (resolution layer d) */
   int planes;                         /* number of different bitmap planes */
   unsigned long l0;                /* number of lines per stripe at lowest *
-				    * resolution layer 0                   */
+                                    * resolution layer 0                   */
   unsigned long stripes;    /* number of stripes required  (determ. by l0) */
   int order;                                    /* SDE ordering parameters */
   int options;                                      /* encoding parameters */
@@ -152,34 +152,34 @@ struct jbg_dec_state {
 
   /*
    * Pointers to array [planes] of lower/higher resolution images.
-   * lhp[d & 1] contains image of layer d. 
+   * lhp[d & 1] contains image of layer d.
    */
   unsigned char **lhp[2];
 
   /* status information */
   int **tx, **ty;   /* array [plane][layer-dl] with x,y-offset of AT pixel */
   struct jbg_ardec_state **s;    /* array [plane][layer-dl] for arithmetic *
-				  * decoder status */
+                                  * decoder status */
   int **reset;     /* array [plane][layer-dl] remembers if previous stripe *
-		    * in that plane/resolution ended with SDRST.           */
+                    * in that plane/resolution ended with SDRST.           */
   unsigned long bie_len;                    /* number of bytes read so far */
   unsigned char buffer[20]; /* used to store BIH or marker segments fragm. */
   int buf_len;                                /* number of bytes in buffer */
   unsigned long comment_skip;      /* remaining bytes of a COMMENT segment */
   unsigned long x;              /* x position of next pixel in current SDE */
-  unsigned long i; /* line in current SDE (first line of each stripe is 0) */ 
+  unsigned long i; /* line in current SDE (first line of each stripe is 0) */
   int at_moves;                /* number of AT moves in the current stripe */
   unsigned long at_line[JBG_ATMOVES_MAX];           /* lines at which an   *
-					             * AT move will happen */
+                                                     * AT move will happen */
   int at_tx[JBG_ATMOVES_MAX], at_ty[JBG_ATMOVES_MAX]; /* ATMOVE offsets in *
-						       * current stripe    */
+                                                       * current stripe    */
   unsigned long line_h1, line_h2, line_h3;     /* variables of decode_pscd */
   unsigned long line_l1, line_l2, line_l3;
   int pseudo;         /* flag for TPBON/TPDON:  next pixel is pseudo pixel */
   int **lntp;        /* flag [plane][layer-dl] for TP: line is not typical */
 
   unsigned long xmax, ymax;         /* if possible abort before image gets *
-				     * larger than this size */
+                                     * larger than this size */
   int dmax;                                      /* abort after this layer */
 };
 
@@ -192,31 +192,31 @@ struct jbg_dec_state {
 /* function prototypes */
 
 void jbg_enc_init(struct jbg_enc_state *s, unsigned long x, unsigned long y,
-		  int planes, unsigned char **p,
-		  void (*data_out)(unsigned char *start, size_t len,
-				   void *file),
-		  void *file);
+                  int planes, unsigned char **p,
+                  void (*data_out)(unsigned char *start, size_t len,
+                                   void *file),
+                  void *file);
 int jbg_enc_lrlmax(struct jbg_enc_state *s, unsigned long mwidth,
-		   unsigned long mheight);
+                   unsigned long mheight);
 void jbg_enc_layers(struct jbg_enc_state *s, int d);
 int  jbg_enc_lrange(struct jbg_enc_state *s, int dl, int dh);
 void jbg_enc_options(struct jbg_enc_state *s, int order, int options,
-		     unsigned long l0, int mx, int my);
+                     unsigned long l0, int mx, int my);
 void jbg_enc_out(struct jbg_enc_state *s);
 void jbg_enc_free(struct jbg_enc_state *s);
 
 void jbg_dec_init(struct jbg_dec_state *s);
 void jbg_dec_maxsize(struct jbg_dec_state *s, unsigned long xmax,
-		     unsigned long ymax);
+                     unsigned long ymax);
 int  jbg_dec_in(struct jbg_dec_state *s, unsigned char *data, size_t len,
-		size_t *cnt);
+                size_t *cnt);
 unsigned long jbg_dec_getwidth(const struct jbg_dec_state *s);
 unsigned long jbg_dec_getheight(const struct jbg_dec_state *s);
 unsigned char *jbg_dec_getimage(const struct jbg_dec_state *s, int plane);
 unsigned long jbg_dec_getsize(const struct jbg_dec_state *s);
 void jbg_dec_merge_planes(const struct jbg_dec_state *s, int use_graycode,
-			  void (*data_out)(unsigned char *start, size_t len,
-					   void *file), void *file);
+                          void (*data_out)(unsigned char *start, size_t len,
+                                           void *file), void *file);
 unsigned long jbg_dec_getsize_merged(const struct jbg_dec_state *s);
 void jbg_dec_free(struct jbg_dec_state *s);
 
@@ -225,9 +225,9 @@ void jbg_int2dppriv(unsigned char *dptable, const char *internal);
 void jbg_dppriv2int(char *internal, const unsigned char *dptable);
 unsigned long jbg_ceil_half(unsigned long x, int n);
 void jbg_split_planes(unsigned long x, unsigned long y, int has_planes,
-		      int encode_planes,
-		      const unsigned char *src, unsigned char **dest,
-		      int use_graycode);
+                      int encode_planes,
+                      const unsigned char *src, unsigned char **dest,
+                      int use_graycode);
 int jbg_newlen(unsigned char *bie, size_t len);
 
 #endif /* JBG_H */
diff --git a/converter/other/jbig/libjbig/include/jbig_ar.h b/converter/other/jbig/libjbig/include/jbig_ar.h
index ed5f2f86..e3366aed 100644
--- a/converter/other/jbig/libjbig/include/jbig_ar.h
+++ b/converter/other/jbig/libjbig/include/jbig_ar.h
@@ -39,9 +39,9 @@ struct jbg_ardec_state {
               * special value -1 signals that zero-padding has started     */
   int startup;          /* boolean flag that controls initial fill of s->c */
   int nopadding;        /* boolean flag that triggers return -2 between
-			 * reaching PSCD end and decoding the first symbol
-			 * that might never have been encoded in the first
-			 * place */
+                         * reaching PSCD end and decoding the first symbol
+                         * that might never have been encoded in the first
+                         * place */
 };
 
 void arith_encode_init(struct jbg_arenc_state *s, int reuse_st);
diff --git a/converter/other/jbig/libjbig/jbig.c b/converter/other/jbig/libjbig/jbig.c
index cf24a93b..fcb39f5c 100644
--- a/converter/other/jbig/libjbig/jbig.c
+++ b/converter/other/jbig/libjbig/jbig.c
@@ -143,13 +143,14 @@ static void *checked_malloc(size_t nmemb, size_t size)
 
 #if 0
   fprintf(stderr, "%p = malloc(%lu * %lu)\n", p,
-	  (unsigned long) nmemb, (unsigned long) size);
+          (unsigned long) nmemb, (unsigned long) size);
 #endif
 
   return p;
 }
 
 
+
 static void *checked_realloc(void *ptr, size_t nmemb, size_t size)
 {
   void *p;
@@ -169,13 +170,14 @@ static void *checked_realloc(void *ptr, size_t nmemb, size_t size)
 
 #if 0
   fprintf(stderr, "%p = realloc(%p, %lu * %lu)\n", p, ptr,
-	  (unsigned long) nmemb, (unsigned long) size);
+          (unsigned long) nmemb, (unsigned long) size);
 #endif
 
   return p;
 }
 
 
+
 static void checked_free(void *ptr)
 {
   free(ptr);
@@ -188,7 +190,6 @@ static void checked_free(void *ptr)
 
 
 
-
 /*
  * Memory management for buffers which are used for temporarily
  * storing SDEs by the encoder.
@@ -229,6 +230,7 @@ static struct jbg_buf *jbg_buf_init(struct jbg_buf **free_list)
 }
 
 
+
 /*
  * Return an entire free_list to the memory management of stdlib.
  * This is only done by jbg_enc_free().
@@ -247,6 +249,7 @@ static void jbg_buf_free(struct jbg_buf **free_list)
 }
 
 
+
 /*
  * Append a single byte to a single list that starts with the block
  * *(struct jbg_buf *) head. The type of *head is void here in order to
@@ -272,6 +275,7 @@ static void jbg_buf_write(int b, void *head)
 }
 
 
+
 /*
  * Remove any trailing zero bytes from the end of a linked jbg_buf list,
  * however make sure that no zero byte is removed which directly
@@ -311,6 +315,7 @@ static void jbg_buf_remove_zeros(struct jbg_buf *head)
 }
 
 
+
 /*
  * The jbg_buf list which starts with block *new_prefix is concatenated
  * with the list which starts with block **start and *start will then point
@@ -327,6 +332,7 @@ static void jbg_buf_prefix(struct jbg_buf *new_prefix, struct jbg_buf **start)
 }
 
 
+
 /*
  * Send the contents of a jbg_buf list that starts with block **head to
  * the call back function data_out and return the blocks of the jbg_buf
@@ -334,9 +340,9 @@ static void jbg_buf_prefix(struct jbg_buf *new_prefix, struct jbg_buf **start)
  * After the call, *head == NULL.
  */
 static void jbg_buf_output(struct jbg_buf **head,
-			void (*data_out)(unsigned char *start,
-					 size_t len, void *file),
-			void *file)
+                        void (*data_out)(unsigned char *start,
+                                         size_t len, void *file),
+                        void *file)
 {
   struct jbg_buf *tmp;
 
@@ -352,6 +358,7 @@ static void jbg_buf_output(struct jbg_buf **head,
 }
 
 
+
 /*
  * Calculate y = ceil(x/2) applied n times, which is equivalent to
  * y = ceil(x/(2^n)). This function is used to
@@ -369,6 +376,7 @@ unsigned long jbg_ceil_half(unsigned long x, int n)
 }
 
 
+
 /*
  * Set L0 (the number of lines in a stripe at lowest resolution)
  * to a default value, such that there are about 35 stripes, as
@@ -384,11 +392,12 @@ static void jbg_set_default_l0(struct jbg_enc_state *s)
 }
 
 
+
 /*
  * Calculate the number of stripes, as defined in clause 6.2.3 of T.82.
  */
 static unsigned long jbg_stripes(unsigned long l0, unsigned long yd,
-			  unsigned long d)
+                          unsigned long d)
 {
   unsigned long y0 = jbg_ceil_half(yd, d);
 
@@ -396,6 +405,7 @@ static unsigned long jbg_stripes(unsigned long l0, unsigned long yd,
 }
 
 
+
 /*
  * Resolution reduction table given by ITU-T T.82 Table 17
  */
@@ -767,8 +777,8 @@ static char jbg_dptable[256 + 512 + 2048 + 4096] = {
 void jbg_enc_init(struct jbg_enc_state *s, unsigned long x, unsigned long y,
                   int planes, unsigned char **p,
                   void (*data_out)(unsigned char *start, size_t len,
-				   void *file),
-		  void *file)
+                                   void *file),
+                  void *file)
 {
   unsigned long l, lx;
   int i;
@@ -818,6 +828,7 @@ void jbg_enc_init(struct jbg_enc_state *s, unsigned long x, unsigned long y,
 }
 
 
+
 /*
  * This function selects the number of differential layers based on
  * the maximum size requested for the lowest resolution layer. If
@@ -831,7 +842,7 @@ void jbg_enc_init(struct jbg_enc_state *s, unsigned long x, unsigned long y,
  * is returned.
  */
 int jbg_enc_lrlmax(struct jbg_enc_state *s, unsigned long x,
-		   unsigned long y)
+                   unsigned long y)
 {
   for (s->d = 0; s->d < 6; s->d++)
     if (jbg_ceil_half(s->xd, s->d) <= x && jbg_ceil_half(s->yd, s->d) <= y)
@@ -843,6 +854,7 @@ int jbg_enc_lrlmax(struct jbg_enc_state *s, unsigned long x,
 }
 
 
+
 /*
  * As an alternative to jbg_enc_lrlmax(), the following function allows the
  * user to specify the number of layers directly. The stripe height and layer
@@ -860,6 +872,7 @@ void jbg_enc_layers(struct jbg_enc_state *s, int d)
 }
 
 
+
 /*
  * Specify the highest and lowest resolution layers which will be
  * written to the output file. Call this function not before
@@ -876,13 +889,14 @@ int jbg_enc_lrange(struct jbg_enc_state *s, int dl, int dh)
 }
 
 
+
 /*
  * The following function allows the user to specify the bits describing the
  * options of the format as well as the maximum AT movement window and the
  * number of layer 0 lines per stripes.
  */
 void jbg_enc_options(struct jbg_enc_state *s, int order, int options,
-		     unsigned long l0, int mx, int my)
+                     unsigned long l0, int mx, int my)
 {
   if (order >= 0 && order <= 0x0f) s->order = order;
   if (options >= 0) s->options = options;
@@ -894,13 +908,14 @@ void jbg_enc_options(struct jbg_enc_state *s, int order, int options,
 }
 
 
+
 /*
  * This function actually does all the tricky work involved in producing
  * a SDE, which is stored in the appropriate s->sde[][][] element
  * for later output in the correct order.
  */
 static void encode_sde(struct jbg_enc_state *s,
-		       long stripe, int layer, int plane)
+                       long stripe, int layer, int plane)
 {
   unsigned char *hp, *lp1, *lp2, *p0, *p1, *q1, *q2;
   unsigned long hl, ll, hx, hy, lx, ly, hbpl, lbpl;
@@ -933,7 +948,7 @@ static void encode_sde(struct jbg_enc_state *s,
   if (stripe == 0)
     tp_lines = tp_exceptions = tp_pixels = dp_pixels = encoded_pixels = 0;
   fprintf(stderr, "encode_sde: s/d/p = %2ld/%2d/%2d\n",
-	  stripe, layer, plane);
+          stripe, layer, plane);
 #endif
 
   /* number of lines per stripe in highres image */
@@ -1001,59 +1016,59 @@ static void encode_sde(struct jbg_enc_state *s,
 
       /* check whether it is worth to perform an ATMOVE */
       if (!at_determined && c_all > 2048) {
-	cmin = clmin = 0xffffffffL;
-	cmax = clmax = 0;
-	tmax = 0;
-	for (t = (s->options & JBG_LRLTWO) ? 5 : 3; t <= s->mx; t++) {
-	  if (c[t] > cmax) cmax = c[t];
-	  if (c[t] < cmin) cmin = c[t];
-	  if (c[t] > c[tmax]) tmax = t;
-	}
-	clmin = (c[0] < cmin) ? c[0] : cmin;
-	clmax = (c[0] > cmax) ? c[0] : cmax;
-	if (c_all - cmax < (c_all >> 3) &&
-	    cmax - c[s->tx[plane]] > c_all - cmax &&
-	    cmax - c[s->tx[plane]] > (c_all >> 4) &&
-	    /*                     ^ T.82 said < here, fixed in Cor.1/25 */
-	    cmax - (c_all - c[s->tx[plane]]) > c_all - cmax &&
-	    cmax - (c_all - c[s->tx[plane]]) > (c_all >> 4) &&
-	    cmax - cmin > (c_all >> 2) &&
-	    (s->tx[plane] || clmax - clmin > (c_all >> 3))) {
-	  /* we have decided to perform an ATMOVE */
-	  new_tx = tmax;
-	  if (!(s->options & JBG_DELAY_AT)) {
-	    new_tx_line = i;
-	    s->tx[plane] = new_tx;
-	  }
+        cmin = clmin = 0xffffffffL;
+        cmax = clmax = 0;
+        tmax = 0;
+        for (t = (s->options & JBG_LRLTWO) ? 5 : 3; t <= s->mx; t++) {
+          if (c[t] > cmax) cmax = c[t];
+          if (c[t] < cmin) cmin = c[t];
+          if (c[t] > c[tmax]) tmax = t;
+        }
+        clmin = (c[0] < cmin) ? c[0] : cmin;
+        clmax = (c[0] > cmax) ? c[0] : cmax;
+        if (c_all - cmax < (c_all >> 3) &&
+            cmax - c[s->tx[plane]] > c_all - cmax &&
+            cmax - c[s->tx[plane]] > (c_all >> 4) &&
+            /*                     ^ T.82 said < here, fixed in Cor.1/25 */
+            cmax - (c_all - c[s->tx[plane]]) > c_all - cmax &&
+            cmax - (c_all - c[s->tx[plane]]) > (c_all >> 4) &&
+            cmax - cmin > (c_all >> 2) &&
+            (s->tx[plane] || clmax - clmin > (c_all >> 3))) {
+          /* we have decided to perform an ATMOVE */
+          new_tx = tmax;
+          if (!(s->options & JBG_DELAY_AT)) {
+            new_tx_line = i;
+            s->tx[plane] = new_tx;
+          }
 #ifdef DEBUG
-	  fprintf(stderr, "ATMOVE: line=%ld, tx=%d, c_all=%ld\n",
-		  i, new_tx, c_all);
+          fprintf(stderr, "ATMOVE: line=%ld, tx=%d, c_all=%ld\n",
+                  i, new_tx, c_all);
 #endif
-	}
-	at_determined = 1;
+        }
+        at_determined = 1;
       }
       assert(s->tx[plane] >= 0); /* i.e., tx can safely be cast to unsigned */
 
       /* typical prediction */
       if (s->options & JBG_TPBON) {
-	ltp = 1;
-	p1 = hp;
-	if (i > 0 || !reset) {
-	  q1 = hp - hbpl;
-	  while (q1 < hp && (ltp = (*p1++ == *q1++)) != 0) ;
-	} else
-	  while (p1 < hp + hbpl && (ltp = (*p1++ == 0)) != 0) ;
-	arith_encode(se, (s->options & JBG_LRLTWO) ? TPB2CX : TPB3CX,
-		     ltp == ltp_old);
+        ltp = 1;
+        p1 = hp;
+        if (i > 0 || !reset) {
+          q1 = hp - hbpl;
+          while (q1 < hp && (ltp = (*p1++ == *q1++)) != 0) ;
+        } else
+          while (p1 < hp + hbpl && (ltp = (*p1++ == 0)) != 0) ;
+        arith_encode(se, (s->options & JBG_LRLTWO) ? TPB2CX : TPB3CX,
+                     ltp == ltp_old);
 #ifdef DEBUG
-	tp_lines += ltp;
+        tp_lines += ltp;
 #endif
-	ltp_old = ltp;
-	if (ltp) {
-	  /* skip next line */
-	  hp += hbpl;
-	  continue;
-	}
+        ltp_old = ltp;
+        if (ltp) {
+          /* skip next line */
+          hp += hbpl;
+          continue;
+        }
       }
 
       /*
@@ -1071,102 +1086,102 @@ static void encode_sde(struct jbg_enc_state *s,
 
       /* encode line */
       for (j = 0; j < hx; hp++) {
-	line_h1 |= *hp;
-	if (j < hbpl * 8 - 8 && (i > 0 || !reset)) {
-	  line_h2 |= *(hp - hbpl + 1);
-	  if (i > 1 || !reset)
-	    line_h3 |= *(hp - hbpl - hbpl + 1);
-	}
-	if (s->options & JBG_LRLTWO) {
-	  /* two line template */
-	  do {
-	    line_h1 <<= 1;  line_h2 <<= 1;  line_h3 <<= 1;
-	    if (s->tx[plane]) {
-	      if ((unsigned) s->tx[plane] > j)
-		a = 0;
-	      else {
-		o = (j - s->tx[plane]) - (j & ~7L);
-		a = (hp[o >> 3] >> (7 - (o & 7))) & 1;
-		a <<= 4;
-	      }
-	      assert(s->tx[plane] > 23 ||
-		     a == ((line_h1 >> (4 + s->tx[plane])) & 0x010));
-	      arith_encode(se, (((line_h2 >> 10) & 0x3e0) | a |
-				((line_h1 >>  9) & 0x00f)),
-			   (line_h1 >> 8) & 1);
-	    }
-	    else
-	      arith_encode(se, (((line_h2 >> 10) & 0x3f0) |
-				((line_h1 >>  9) & 0x00f)),
-			   (line_h1 >> 8) & 1);
+        line_h1 |= *hp;
+        if (j < hbpl * 8 - 8 && (i > 0 || !reset)) {
+          line_h2 |= *(hp - hbpl + 1);
+          if (i > 1 || !reset)
+            line_h3 |= *(hp - hbpl - hbpl + 1);
+        }
+        if (s->options & JBG_LRLTWO) {
+          /* two line template */
+          do {
+            line_h1 <<= 1;  line_h2 <<= 1;  line_h3 <<= 1;
+            if (s->tx[plane]) {
+              if ((unsigned) s->tx[plane] > j)
+                a = 0;
+              else {
+                o = (j - s->tx[plane]) - (j & ~7L);
+                a = (hp[o >> 3] >> (7 - (o & 7))) & 1;
+                a <<= 4;
+              }
+              assert(s->tx[plane] > 23 ||
+                     a == ((line_h1 >> (4 + s->tx[plane])) & 0x010));
+              arith_encode(se, (((line_h2 >> 10) & 0x3e0) | a |
+                                ((line_h1 >>  9) & 0x00f)),
+                           (line_h1 >> 8) & 1);
+            }
+            else
+              arith_encode(se, (((line_h2 >> 10) & 0x3f0) |
+                                ((line_h1 >>  9) & 0x00f)),
+                           (line_h1 >> 8) & 1);
 #ifdef DEBUG
-	    encoded_pixels++;
+            encoded_pixels++;
 #endif
-	    /* statistics for adaptive template changes */
-	    if (!at_determined && j >= s->mx && j < hx-2) {
-	      p = (line_h1 & 0x100) != 0; /* current pixel value */
-	      c[0] += ((line_h2 & 0x4000) != 0) == p; /* default position */
-	      assert((!(((line_h2 >> 6) ^ line_h1) & 0x100)) ==
-		     (((line_h2 & 0x4000) != 0) == p));
-	      for (t = 5; t <= s->mx && t <= j; t++) {
-		o = (j - t) - (j & ~7L);
-		a = (hp[o >> 3] >> (7 - (o & 7))) & 1;
-		assert(t > 23 ||
-		       (a == p) == !(((line_h1 >> t) ^ line_h1) & 0x100));
-		c[t] += a == p;
-	      }
-	      for (; t <= s->mx; t++) {
-		c[t] += 0 == p;
-	      }
-	      ++c_all;
-	    }
-	  } while (++j & 7 && j < hx);
-	} else {
-	  /* three line template */
-	  do {
-	    line_h1 <<= 1;  line_h2 <<= 1;  line_h3 <<= 1;
-	    if (s->tx[plane]) {
-	      if ((unsigned) s->tx[plane] > j)
-		a = 0;
-	      else {
-		o = (j - s->tx[plane]) - (j & ~7L);
-		a = (hp[o >> 3] >> (7 - (o & 7))) & 1;
-		a <<= 2;
-	      }
-	      assert(s->tx[plane] > 23 ||
-		     a == ((line_h1 >> (6 + s->tx[plane])) & 0x004));
-	      arith_encode(se, (((line_h3 >>  8) & 0x380) |
-				((line_h2 >> 12) & 0x078) | a |
-				((line_h1 >>  9) & 0x003)),
-			   (line_h1 >> 8) & 1);
-	    } else
-	      arith_encode(se, (((line_h3 >>  8) & 0x380) |
-				((line_h2 >> 12) & 0x07c) |
-				((line_h1 >>  9) & 0x003)),
-			   (line_h1 >> 8) & 1);
+            /* statistics for adaptive template changes */
+            if (!at_determined && j >= s->mx && j < hx-2) {
+              p = (line_h1 & 0x100) != 0; /* current pixel value */
+              c[0] += ((line_h2 & 0x4000) != 0) == p; /* default position */
+              assert((!(((line_h2 >> 6) ^ line_h1) & 0x100)) ==
+                     (((line_h2 & 0x4000) != 0) == p));
+              for (t = 5; t <= s->mx && t <= j; t++) {
+                o = (j - t) - (j & ~7L);
+                a = (hp[o >> 3] >> (7 - (o & 7))) & 1;
+                assert(t > 23 ||
+                       (a == p) == !(((line_h1 >> t) ^ line_h1) & 0x100));
+                c[t] += a == p;
+              }
+              for (; t <= s->mx; t++) {
+                c[t] += 0 == p;
+              }
+              ++c_all;
+            }
+          } while (++j & 7 && j < hx);
+        } else {
+          /* three line template */
+          do {
+            line_h1 <<= 1;  line_h2 <<= 1;  line_h3 <<= 1;
+            if (s->tx[plane]) {
+              if ((unsigned) s->tx[plane] > j)
+                a = 0;
+              else {
+                o = (j - s->tx[plane]) - (j & ~7L);
+                a = (hp[o >> 3] >> (7 - (o & 7))) & 1;
+                a <<= 2;
+              }
+              assert(s->tx[plane] > 23 ||
+                     a == ((line_h1 >> (6 + s->tx[plane])) & 0x004));
+              arith_encode(se, (((line_h3 >>  8) & 0x380) |
+                                ((line_h2 >> 12) & 0x078) | a |
+                                ((line_h1 >>  9) & 0x003)),
+                           (line_h1 >> 8) & 1);
+            } else
+              arith_encode(se, (((line_h3 >>  8) & 0x380) |
+                                ((line_h2 >> 12) & 0x07c) |
+                                ((line_h1 >>  9) & 0x003)),
+                           (line_h1 >> 8) & 1);
 #ifdef DEBUG
-	    encoded_pixels++;
+            encoded_pixels++;
 #endif
-	    /* statistics for adaptive template changes */
-	    if (!at_determined && j >= s->mx && j < hx-2) {
-	      p = (line_h1 & 0x100) != 0; /* current pixel value */
-	      c[0] += ((line_h2 & 0x4000) != 0) == p; /* default position */
-	      assert((!(((line_h2 >> 6) ^ line_h1) & 0x100)) ==
-		     (((line_h2 & 0x4000) != 0) == p));
-	      for (t = 3; t <= s->mx && t <= j; t++) {
-		o = (j - t) - (j & ~7L);
-		a = (hp[o >> 3] >> (7 - (o & 7))) & 1;
-		assert(t > 23 ||
-		       (a == p) == !(((line_h1 >> t) ^ line_h1) & 0x100));
-		c[t] += a == p;
-	      }
-	      for (; t <= s->mx; t++) {
-		c[t] += 0 == p;
-	      }
-	      ++c_all;
-	    }
-	  } while (++j & 7 && j < hx);
-	} /* if (s->options & JBG_LRLTWO) */
+            /* statistics for adaptive template changes */
+            if (!at_determined && j >= s->mx && j < hx-2) {
+              p = (line_h1 & 0x100) != 0; /* current pixel value */
+              c[0] += ((line_h2 & 0x4000) != 0) == p; /* default position */
+              assert((!(((line_h2 >> 6) ^ line_h1) & 0x100)) ==
+                     (((line_h2 & 0x4000) != 0) == p));
+              for (t = 3; t <= s->mx && t <= j; t++) {
+                o = (j - t) - (j & ~7L);
+                a = (hp[o >> 3] >> (7 - (o & 7))) & 1;
+                assert(t > 23 ||
+                       (a == p) == !(((line_h1 >> t) ^ line_h1) & 0x100));
+                c[t] += a == p;
+              }
+              for (; t <= s->mx; t++) {
+                c[t] += 0 == p;
+              }
+              ++c_all;
+            }
+          } while (++j & 7 && j < hx);
+        } /* if (s->options & JBG_LRLTWO) */
       } /* for (j = ...) */
     } /* for (i = ...) */
 
@@ -1180,101 +1195,101 @@ static void encode_sde(struct jbg_enc_state *s,
 
       /* check whether it is worth to perform an ATMOVE */
       if (!at_determined && c_all > 2048) {
-	cmin = clmin = 0xffffffffL;
-	cmax = clmax = 0;
-	tmax = 0;
-	for (t = 3; t <= s->mx; t++) {
-	  if (c[t] > cmax) cmax = c[t];
-	  if (c[t] < cmin) cmin = c[t];
-	  if (c[t] > c[tmax]) tmax = t;
-	}
-	clmin = (c[0] < cmin) ? c[0] : cmin;
-	clmax = (c[0] > cmax) ? c[0] : cmax;
-	if (c_all - cmax < (c_all >> 3) &&
-	    cmax - c[s->tx[plane]] > c_all - cmax &&
-	    cmax - c[s->tx[plane]] > (c_all >> 4) &&
-	    /*                     ^ T.82 said < here, fixed in Cor.1/25 */
-	    cmax - (c_all - c[s->tx[plane]]) > c_all - cmax &&
-	    cmax - (c_all - c[s->tx[plane]]) > (c_all >> 4) &&
-	    cmax - cmin > (c_all >> 2) &&
-	    (s->tx[plane] || clmax - clmin > (c_all >> 3))) {
-	  /* we have decided to perform an ATMOVE */
-	  new_tx = tmax;
-	  if (!(s->options & JBG_DELAY_AT)) {
-	    new_tx_line = i;
-	    s->tx[plane] = new_tx;
-	  }
+        cmin = clmin = 0xffffffffL;
+        cmax = clmax = 0;
+        tmax = 0;
+        for (t = 3; t <= s->mx; t++) {
+          if (c[t] > cmax) cmax = c[t];
+          if (c[t] < cmin) cmin = c[t];
+          if (c[t] > c[tmax]) tmax = t;
+        }
+        clmin = (c[0] < cmin) ? c[0] : cmin;
+        clmax = (c[0] > cmax) ? c[0] : cmax;
+        if (c_all - cmax < (c_all >> 3) &&
+            cmax - c[s->tx[plane]] > c_all - cmax &&
+            cmax - c[s->tx[plane]] > (c_all >> 4) &&
+            /*                     ^ T.82 said < here, fixed in Cor.1/25 */
+            cmax - (c_all - c[s->tx[plane]]) > c_all - cmax &&
+            cmax - (c_all - c[s->tx[plane]]) > (c_all >> 4) &&
+            cmax - cmin > (c_all >> 2) &&
+            (s->tx[plane] || clmax - clmin > (c_all >> 3))) {
+          /* we have decided to perform an ATMOVE */
+          new_tx = tmax;
+          if (!(s->options & JBG_DELAY_AT)) {
+            new_tx_line = i;
+            s->tx[plane] = new_tx;
+          }
 #ifdef DEBUG
-	  fprintf(stderr, "ATMOVE: line=%ld, tx=%d, c_all=%ld\n",
-		  i, new_tx, c_all);
+          fprintf(stderr, "ATMOVE: line=%ld, tx=%d, c_all=%ld\n",
+                  i, new_tx, c_all);
 #endif
-	}
-	at_determined = 1;
+        }
+        at_determined = 1;
       }
 
       if ((i >> 1) >= ll - 1 || (y >> 1) >= ly - 1)
-	lp1 = lp2;
+        lp1 = lp2;
 
       /* typical prediction */
       if (s->options & JBG_TPDON && (i & 1) == 0) {
-	q1 = lp1; q2 = lp2;
-	p0 = p1 = hp;
-	if (i < hl - 1 && y < hy - 1)
-	  p0 = hp + hbpl;
-	if (i > 1 || !reset)
-	  line_l3 = (long)*(q2 - lbpl) << 8;
-	else
-	  line_l3 = 0;
-	line_l2 = (long)*q2 << 8;
-	line_l1 = (long)*q1 << 8;
-	ltp = 1;
-	for (j = 0; j < lx && ltp; q1++, q2++) {
-	  if (j < lbpl * 8 - 8) {
-	    if (i > 1 || !reset)
-	      line_l3 |= *(q2 - lbpl + 1);
-	    line_l2 |= *(q2 + 1);
-	    line_l1 |= *(q1 + 1);
-	  }
-	  do {
-	    if ((j >> 2) < hbpl) {
-	      line_h1 = *(p1++);
-	      line_h0 = *(p0++);
-	    }
-	    do {
-	      line_l3 <<= 1;
-	      line_l2 <<= 1;
-	      line_l1 <<= 1;
-	      line_h1 <<= 2;
-	      line_h0 <<= 2;
-	      cx = (((line_l3 >> 15) & 0x007) |
-		    ((line_l2 >> 12) & 0x038) |
-		    ((line_l1 >> 9)  & 0x1c0));
-	      if (cx == 0x000)
-		if ((line_h1 & 0x300) == 0 && (line_h0 & 0x300) == 0)
-		  s->tp[j] = 0;
-		else {
-		  ltp = 0;
+        q1 = lp1; q2 = lp2;
+        p0 = p1 = hp;
+        if (i < hl - 1 && y < hy - 1)
+          p0 = hp + hbpl;
+        if (i > 1 || !reset)
+          line_l3 = (long)*(q2 - lbpl) << 8;
+        else
+          line_l3 = 0;
+        line_l2 = (long)*q2 << 8;
+        line_l1 = (long)*q1 << 8;
+        ltp = 1;
+        for (j = 0; j < lx && ltp; q1++, q2++) {
+          if (j < lbpl * 8 - 8) {
+            if (i > 1 || !reset)
+              line_l3 |= *(q2 - lbpl + 1);
+            line_l2 |= *(q2 + 1);
+            line_l1 |= *(q1 + 1);
+          }
+          do {
+            if ((j >> 2) < hbpl) {
+              line_h1 = *(p1++);
+              line_h0 = *(p0++);
+            }
+            do {
+              line_l3 <<= 1;
+              line_l2 <<= 1;
+              line_l1 <<= 1;
+              line_h1 <<= 2;
+              line_h0 <<= 2;
+              cx = (((line_l3 >> 15) & 0x007) |
+                    ((line_l2 >> 12) & 0x038) |
+                    ((line_l1 >> 9)  & 0x1c0));
+              if (cx == 0x000)
+                if ((line_h1 & 0x300) == 0 && (line_h0 & 0x300) == 0)
+                  s->tp[j] = 0;
+                else {
+                  ltp = 0;
 #ifdef DEBUG
-		  tp_exceptions++;
+                  tp_exceptions++;
 #endif
-		}
-	      else if (cx == 0x1ff)
-		if ((line_h1 & 0x300) == 0x300 && (line_h0 & 0x300) == 0x300)
-		  s->tp[j] = 1;
-		else {
-		  ltp = 0;
+                }
+              else if (cx == 0x1ff)
+                if ((line_h1 & 0x300) == 0x300 && (line_h0 & 0x300) == 0x300)
+                  s->tp[j] = 1;
+                else {
+                  ltp = 0;
 #ifdef DEBUG
-		  tp_exceptions++;
+                  tp_exceptions++;
 #endif
-		}
-	      else
-		s->tp[j] = 2;
-	    } while (++j & 3 && j < lx);
-	  } while (j & 7 && j < lx);
-	} /* for (j = ...) */
-	arith_encode(se, TPDCX, !ltp);
+                }
+              else
+                s->tp[j] = 2;
+            } while (++j & 3 && j < lx);
+          } while (j & 7 && j < lx);
+        } /* for (j = ...) */
+        arith_encode(se, TPDCX, !ltp);
 #ifdef DEBUG
-	tp_lines += ltp;
+        tp_lines += ltp;
 #endif
       }
 
@@ -1302,158 +1317,158 @@ static void encode_sde(struct jbg_enc_state *s,
       line_h1 = line_h2 = line_h3 = line_l1 = line_l2 = line_l3 = 0;
       if (i > 0 || !reset) line_h2 = (long)*(hp - hbpl) << 8;
       if (i > 1 || !reset) {
-	line_h3 = (long)*(hp - hbpl - hbpl) << 8;
-	line_l3 = (long)*(lp2 - lbpl) << 8;
+        line_h3 = (long)*(hp - hbpl - hbpl) << 8;
+        line_l3 = (long)*(lp2 - lbpl) << 8;
       }
       line_l2 = (long)*lp2 << 8;
       line_l1 = (long)*lp1 << 8;
 
       /* encode line */
       for (j = 0; j < hx; lp1++, lp2++) {
-	if ((j >> 1) < lbpl * 8 - 8) {
-	  if (i > 1 || !reset)
-	    line_l3 |= *(lp2 - lbpl + 1);
-	  line_l2 |= *(lp2 + 1);
-	  line_l1 |= *(lp1 + 1);
-	}
-	do { /* ... while (j & 15 && j < hx) */
-
-	  assert(hp - (s->lhp[s->highres[plane]][plane] +
-		       (stripe * hl + i) * hbpl)
-		 == (ptrdiff_t) j >> 3);
-
-	  assert(lp2 - (s->lhp[1-s->highres[plane]][plane] +
-			(stripe * ll + (i>>1)) * lbpl)
-		 == (ptrdiff_t) j >> 4);
-
-	  line_h1 |= *hp;
-	  if (j < hbpl * 8 - 8) {
-	    if (i > 0 || !reset) {
-	      line_h2 |= *(hp - hbpl + 1);
-	      if (i > 1 || !reset)
-		line_h3 |= *(hp - hbpl - hbpl + 1);
-	    }
-	  }
-	  do { /* ... while (j & 7 && j < hx) */
-	    line_l1 <<= 1;  line_l2 <<= 1;  line_l3 <<= 1;
-	    if (ltp && s->tp[j >> 1] < 2) {
-	      /* pixel are typical and have not to be encoded */
-	      line_h1 <<= 2;  line_h2 <<= 2;  line_h3 <<= 2;
+        if ((j >> 1) < lbpl * 8 - 8) {
+          if (i > 1 || !reset)
+            line_l3 |= *(lp2 - lbpl + 1);
+          line_l2 |= *(lp2 + 1);
+          line_l1 |= *(lp1 + 1);
+        }
+        do { /* ... while (j & 15 && j < hx) */
+
+          assert(hp - (s->lhp[s->highres[plane]][plane] +
+                       (stripe * hl + i) * hbpl)
+                 == (ptrdiff_t) j >> 3);
+
+          assert(lp2 - (s->lhp[1-s->highres[plane]][plane] +
+                        (stripe * ll + (i>>1)) * lbpl)
+                 == (ptrdiff_t) j >> 4);
+
+          line_h1 |= *hp;
+          if (j < hbpl * 8 - 8) {
+            if (i > 0 || !reset) {
+              line_h2 |= *(hp - hbpl + 1);
+              if (i > 1 || !reset)
+                line_h3 |= *(hp - hbpl - hbpl + 1);
+            }
+          }
+          do { /* ... while (j & 7 && j < hx) */
+            line_l1 <<= 1;  line_l2 <<= 1;  line_l3 <<= 1;
+            if (ltp && s->tp[j >> 1] < 2) {
+              /* pixel are typical and have not to be encoded */
+              line_h1 <<= 2;  line_h2 <<= 2;  line_h3 <<= 2;
 #ifdef DEBUG
-	      do {
-		++tp_pixels;
-	      } while (++j & 1 && j < hx);
+              do {
+                ++tp_pixels;
+              } while (++j & 1 && j < hx);
 #else
-	      j += 2;
+              j += 2;
 #endif
-	    } else
-	      do { /* ... while (++j & 1 && j < hx) */
-		line_h1 <<= 1;  line_h2 <<= 1;  line_h3 <<= 1;
-
-		/* deterministic prediction */
-		if (s->options & JBG_DPON) {
-		  if ((y & 1) == 0) {
-		    if ((j & 1) == 0) {
-		      /* phase 0 */
-		      if (s->dppriv[((line_l3 >> 16) & 0x003) |
-				    ((line_l2 >> 14) & 0x00c) |
-				    ((line_h1 >> 5)  & 0x010) |
-				    ((line_h2 >> 10) & 0x0e0)] < 2) {
+            } else
+              do { /* ... while (++j & 1 && j < hx) */
+                line_h1 <<= 1;  line_h2 <<= 1;  line_h3 <<= 1;
+
+                /* deterministic prediction */
+                if (s->options & JBG_DPON) {
+                  if ((y & 1) == 0) {
+                    if ((j & 1) == 0) {
+                      /* phase 0 */
+                      if (s->dppriv[((line_l3 >> 16) & 0x003) |
+                                    ((line_l2 >> 14) & 0x00c) |
+                                    ((line_h1 >> 5)  & 0x010) |
+                                    ((line_h2 >> 10) & 0x0e0)] < 2) {
 #ifdef DEBUG
-			++dp_pixels;
+                        ++dp_pixels;
 #endif
-			continue;
-		      }
-		    } else {
-		      /* phase 1 */
-		      if (s->dppriv[(((line_l3 >> 16) & 0x003) |
-				     ((line_l2 >> 14) & 0x00c) |
-				     ((line_h1 >> 5)  & 0x030) |
-				     ((line_h2 >> 10) & 0x1c0)) + 256] < 2) {
+                        continue;
+                      }
+                    } else {
+                      /* phase 1 */
+                      if (s->dppriv[(((line_l3 >> 16) & 0x003) |
+                                     ((line_l2 >> 14) & 0x00c) |
+                                     ((line_h1 >> 5)  & 0x030) |
+                                     ((line_h2 >> 10) & 0x1c0)) + 256] < 2) {
 #ifdef DEBUG
-			++dp_pixels;
+                        ++dp_pixels;
 #endif
-			continue;
-		      }
-		    }
-		  } else {
-		    if ((j & 1) == 0) {
-		      /* phase 2 */
-		      if (s->dppriv[(((line_l3 >> 16) & 0x003) |
-				     ((line_l2 >> 14) & 0x00c) |
-				     ((line_h1 >> 5)  & 0x010) |
-				     ((line_h2 >> 10) & 0x0e0) |
-				     ((line_h3 >> 7) & 0x700)) + 768] < 2) {
+                        continue;
+                      }
+                    }
+                  } else {
+                    if ((j & 1) == 0) {
+                      /* phase 2 */
+                      if (s->dppriv[(((line_l3 >> 16) & 0x003) |
+                                     ((line_l2 >> 14) & 0x00c) |
+                                     ((line_h1 >> 5)  & 0x010) |
+                                     ((line_h2 >> 10) & 0x0e0) |
+                                     ((line_h3 >> 7) & 0x700)) + 768] < 2) {
 #ifdef DEBUG
-			++dp_pixels;
+                        ++dp_pixels;
 #endif
-			continue;
-		      }
-		    } else {
-		      /* phase 3 */
-		      if (s->dppriv[(((line_l3 >> 16) & 0x003) |
-				     ((line_l2 >> 14) & 0x00c) |
-				     ((line_h1 >> 5)  & 0x030) |
-				     ((line_h2 >> 10) & 0x1c0) |
-				     ((line_h3 >> 7)  & 0xe00)) + 2816] < 2) {
+                        continue;
+                      }
+                    } else {
+                      /* phase 3 */
+                      if (s->dppriv[(((line_l3 >> 16) & 0x003) |
+                                     ((line_l2 >> 14) & 0x00c) |
+                                     ((line_h1 >> 5)  & 0x030) |
+                                     ((line_h2 >> 10) & 0x1c0) |
+                                     ((line_h3 >> 7)  & 0xe00)) + 2816] < 2) {
 #ifdef DEBUG
-			++dp_pixels;
+                        ++dp_pixels;
 #endif
-			continue;
-		      }
-		    }
-		  }
-		}
-
-		/* determine context */
-		if (s->tx[plane]) {
-		  if ((unsigned) s->tx[plane] > j)
-		    a = 0;
-		  else {
-		    o = (j - s->tx[plane]) - (j & ~7L);
-		    a = (hp[o >> 3] >> (7 - (o & 7))) & 1;
-		    a <<= 4;
-		  }
-		  assert(s->tx[plane] > 23 ||
-			 a == ((line_h1 >> (4 + s->tx[plane])) & 0x010));
-		  cx = (((line_h1 >> 9)  & 0x003) | a |
-			((line_h2 >> 13) & 0x00c) |
-			((line_h3 >> 11) & 0x020));
-		} else
-		  cx = (((line_h1 >> 9)  & 0x003) |
-			((line_h2 >> 13) & 0x01c) |
-			((line_h3 >> 11) & 0x020));
-		if (j & 1)
-		  cx |= (((line_l2 >> 9)  & 0x0c0) |
-			 ((line_l1 >> 7)  & 0x300)) | (1UL << 10);
-		else
-		  cx |= (((line_l2 >> 10) & 0x0c0) |
-			 ((line_l1 >> 8)  & 0x300));
-		cx |= (y & 1) << 11;
-
-		arith_encode(se, cx, (line_h1 >> 8) & 1);
+                        continue;
+                      }
+                    }
+                  }
+                }
+
+                /* determine context */
+                if (s->tx[plane]) {
+                  if ((unsigned) s->tx[plane] > j)
+                    a = 0;
+                  else {
+                    o = (j - s->tx[plane]) - (j & ~7L);
+                    a = (hp[o >> 3] >> (7 - (o & 7))) & 1;
+                    a <<= 4;
+                  }
+                  assert(s->tx[plane] > 23 ||
+                         a == ((line_h1 >> (4 + s->tx[plane])) & 0x010));
+                  cx = (((line_h1 >> 9)  & 0x003) | a |
+                        ((line_h2 >> 13) & 0x00c) |
+                        ((line_h3 >> 11) & 0x020));
+                } else
+                  cx = (((line_h1 >> 9)  & 0x003) |
+                        ((line_h2 >> 13) & 0x01c) |
+                        ((line_h3 >> 11) & 0x020));
+                if (j & 1)
+                  cx |= (((line_l2 >> 9)  & 0x0c0) |
+                         ((line_l1 >> 7)  & 0x300)) | (1UL << 10);
+                else
+                  cx |= (((line_l2 >> 10) & 0x0c0) |
+                         ((line_l1 >> 8)  & 0x300));
+                cx |= (y & 1) << 11;
+
+                arith_encode(se, cx, (line_h1 >> 8) & 1);
 #ifdef DEBUG
-		encoded_pixels++;
+                encoded_pixels++;
 #endif
 
-		/* statistics for adaptive template changes */
-		if (!at_determined && j >= s->mx) {
-		  c[0] += !(((line_h2 >> 6) ^ line_h1) & 0x100);
-		  for (t = 3; t <= s->mx; t++)
-		    c[t] += !(((line_h1 >> t) ^ line_h1) & 0x100);
-		  ++c_all;
-		}
-
-	      } while (++j & 1 && j < hx);
-	  } while (j & 7 && j < hx);
-	  hp++;
-	} while (j & 15 && j < hx);
+                /* statistics for adaptive template changes */
+                if (!at_determined && j >= s->mx) {
+                  c[0] += !(((line_h2 >> 6) ^ line_h1) & 0x100);
+                  for (t = 3; t <= s->mx; t++)
+                    c[t] += !(((line_h1 >> t) ^ line_h1) & 0x100);
+                  ++c_all;
+                }
+
+              } while (++j & 1 && j < hx);
+          } while (j & 7 && j < hx);
+          hp++;
+        } while (j & 15 && j < hx);
       } /* for (j = ...) */
 
       /* low resolution pixels are used twice */
       if ((i & 1) == 0) {
-	lp1 -= lbpl;
-	lp2 -= lbpl;
+        lp1 -= lbpl;
+        lp2 -= lbpl;
       }
 
     } /* for (i = ...) */
@@ -1463,7 +1478,7 @@ static void encode_sde(struct jbg_enc_state *s,
   jbg_buf_remove_zeros(s->sde[stripe][layer][plane]);
   jbg_buf_write(MARKER_ESC, s->sde[stripe][layer][plane]);
   jbg_buf_write((s->options & JBG_SDRST) ? MARKER_SDRST : MARKER_SDNORM,
-		s->sde[stripe][layer][plane]);
+                s->sde[stripe][layer][plane]);
   if (s->options & JBG_SDRST)
     s->tx[plane] = 0;
 
@@ -1499,19 +1514,20 @@ static void encode_sde(struct jbg_enc_state *s,
 #if 0
   if (stripe == s->stripes - 1)
     fprintf(stderr, "tp_lines = %ld, tp_exceptions = %ld, tp_pixels = %ld, "
-	    "dp_pixels = %ld, encoded_pixels = %ld\n",
-	    tp_lines, tp_exceptions, tp_pixels, dp_pixels, encoded_pixels);
+            "dp_pixels = %ld, encoded_pixels = %ld\n",
+            tp_lines, tp_exceptions, tp_pixels, dp_pixels, encoded_pixels);
 #endif
 
   return;
 }
 
 
+
 /*
  * Create the next lower resolution version of an image
  */
 static void resolution_reduction(struct jbg_enc_state *s, int plane,
-				 int higher_layer)
+                                 int higher_layer)
 {
   unsigned long hl, ll, hx, hy, lx, ly, hbpl, lbpl;
   unsigned char *hp1, *hp2, *hp3, *lp;
@@ -1542,7 +1558,7 @@ static void resolution_reduction(struct jbg_enc_state *s, int plane,
 
 #ifdef DEBUG
   fprintf(stderr, "resolution_reduction: plane = %d, higher_layer = %d\n",
-	  plane, higher_layer);
+          plane, higher_layer);
 #endif
 
   /*
@@ -1566,34 +1582,34 @@ static void resolution_reduction(struct jbg_enc_state *s, int plane,
   for (y = 0; y < ly;) {
     for (i = 0; i < ll && y < ly; i++, y++) {
       if (2*y + 1 >= hy)
-	hp1 = hp2;
+        hp1 = hp2;
       pix = 0;
       line_h1 = line_h2 = line_h3 = line_l2 = 0;
       for (j = 0; j < lbpl * 8; j += 8) {
-	*lp = 0;
-	if (i > 0 || (y > 0 && !(s->options & JBG_SDRST)))
-	  line_l2 |= *(lp-lbpl);
-	for (k = 0; k < 8 && j + k < lx; k += 4) {
-	  if (((j + k) >> 2) < hbpl) {
-	    if (i > 0 || (y > 0 && !(s->options & JBG_SDRST)))
-	      line_h3 |= *hp3;
-	    ++hp3;
-	    line_h2 |= *(hp2++);
-	    line_h1 |= *(hp1++);
-	  }
-	  for (l = 0; l < 4 && j + k + l < lx; l++) {
-	    line_h3 <<= 2;
-	    line_h2 <<= 2;
-	    line_h1 <<= 2;
-	    line_l2 <<= 1;
-	    pix = s->res_tab[((line_h1 >> 8) & 0x007) |
-			     ((line_h2 >> 5) & 0x038) |
-			     ((line_h3 >> 2) & 0x1c0) |
-			     (pix << 9) | ((line_l2 << 2) & 0xc00)];
-	    *lp = (*lp << 1) | pix;
-	  }
-	}
-	++lp;
+        *lp = 0;
+        if (i > 0 || (y > 0 && !(s->options & JBG_SDRST)))
+          line_l2 |= *(lp-lbpl);
+        for (k = 0; k < 8 && j + k < lx; k += 4) {
+          if (((j + k) >> 2) < hbpl) {
+            if (i > 0 || (y > 0 && !(s->options & JBG_SDRST)))
+              line_h3 |= *hp3;
+            ++hp3;
+            line_h2 |= *(hp2++);
+            line_h1 |= *(hp1++);
+          }
+          for (l = 0; l < 4 && j + k + l < lx; l++) {
+            line_h3 <<= 2;
+            line_h2 <<= 2;
+            line_h1 <<= 2;
+            line_l2 <<= 1;
+            pix = s->res_tab[((line_h1 >> 8) & 0x007) |
+                             ((line_h2 >> 5) & 0x038) |
+                             ((line_h3 >> 2) & 0x1c0) |
+                             (pix << 9) | ((line_l2 << 2) & 0xc00)];
+            *lp = (*lp << 1) | pix;
+          }
+        }
+        ++lp;
       }
       *(lp - 1) <<= lbpl * 8 - lx;
       hp1 += hbpl;
@@ -1619,6 +1635,7 @@ static void resolution_reduction(struct jbg_enc_state *s, int plane,
 }
 
 
+
 /*
  * This function is called inside the three loops of jbg_enc_out() in
  * order to write the next SDE. It has first to generate the required
@@ -1635,7 +1652,7 @@ static void resolution_reduction(struct jbg_enc_state *s, int plane,
  * of doing it, but it minimizes the amount of temporary memory used.
  */
 static void output_sde(struct jbg_enc_state *s,
-		       unsigned long stripe, int layer, int plane)
+                       unsigned long stripe, int layer, int plane)
 {
   int lfcl;     /* lowest fully coded layer */
   long i;
@@ -1646,7 +1663,7 @@ static void output_sde(struct jbg_enc_state *s,
   if (s->sde[stripe][layer][plane] != SDE_TODO) {
 #ifdef DEBUG
     fprintf(stderr, "writing SDE: s/d/p = %2lu/%2d/%2d\n",
-	    stripe, layer, plane);
+            stripe, layer, plane);
 #endif
     jbg_buf_output(&s->sde[stripe][layer][plane], s->data_out, s->file);
     s->sde[stripe][layer][plane] = SDE_DONE;
@@ -1697,6 +1714,7 @@ static void output_sde(struct jbg_enc_state *s,
 }
 
 
+
 /*
  * Convert the table which controls the deterministic prediction
  * process from the internal format into the representation required
@@ -1748,6 +1766,7 @@ void jbg_int2dppriv(unsigned char *dptable, const char *internal)
 }
 
 
+
 /*
  * Convert the table which controls the deterministic prediction
  * process from the 1728 byte long DPTABLE format into the 6912 byte long
@@ -1779,6 +1798,7 @@ void jbg_dppriv2int(char *internal, const unsigned char *dptable)
 }
 
 
+
 /*
  * Encode one full BIE and pass the generated data to the specified
  * call-back function
@@ -1822,7 +1842,7 @@ void jbg_enc_out(struct jbg_enc_state *s)
     bpl = jbg_ceil_half(s->xd, 3);     /* bytes per line */
     for (plane = 0; plane < s->planes; plane++)
       for (y = 0; y < s->yd; y++)
-	s->lhp[0][plane][y * bpl + bpl - 1] &= ~((1 << (8 - (s->xd & 7))) - 1);
+        s->lhp[0][plane][y * bpl + bpl - 1] &= ~((1 << (8 - (s->xd & 7))) - 1);
   }
 
   /* prepare BIH */
@@ -1864,12 +1884,12 @@ void jbg_enc_out(struct jbg_enc_state *s)
       checked_malloc(s->stripes, sizeof(struct jbg_buf ***));
     for (stripe = 0; stripe < s->stripes; stripe++) {
       s->sde[stripe] = (struct jbg_buf ***)
-	checked_malloc(s->d + 1, sizeof(struct jbg_buf **));
+        checked_malloc(s->d + 1, sizeof(struct jbg_buf **));
       for (layer = 0; layer < s->d + 1; layer++) {
-	s->sde[stripe][layer] = (struct jbg_buf **)
-	  checked_malloc(s->planes, sizeof(struct jbg_buf *));
-	for (plane = 0; plane < s->planes; plane++)
-	  s->sde[stripe][layer][plane] = SDE_TODO;
+        s->sde[stripe][layer] = (struct jbg_buf **)
+          checked_malloc(s->planes, sizeof(struct jbg_buf *));
+        for (plane = 0; plane < s->planes; plane++)
+          s->sde[stripe][layer][plane] = SDE_TODO;
       }
     }
   }
@@ -1892,9 +1912,9 @@ void jbg_enc_out(struct jbg_enc_state *s)
   for (layer = s->dh; layer >= s->dl; layer--) {
     for (plane = 0; plane < s->planes; plane++) {
       if (layer > 0)
-	resolution_reduction(s, plane, layer);
+        resolution_reduction(s, plane, layer);
       for (stripe = 0; stripe < s->stripes; stripe++)
-	encode_sde(s, stripe, layer, plane);
+        encode_sde(s, stripe, layer, plane);
       s->highres[plane] ^= 1;
     }
   }
@@ -1917,55 +1937,55 @@ void jbg_enc_out(struct jbg_enc_state *s)
     for (ii[1] = is[1]; ii[1] <= ie[1]; ii[1]++)
       for (ii[2] = is[2]; ii[2] <= ie[2]; ii[2]++) {
 
-	stripe = ii[iindex[order][STRIPE]];
-	if (s->order & JBG_HITOLO)
-	  layer = s->dh - (ii[iindex[order][LAYER]] - s->dl);
-	else
-	  layer = ii[iindex[order][LAYER]];
-	plane = ii[iindex[order][PLANE]];
-
-	/* output comment marker segment if there is any pending */
-	if (s->comment) {
-	  buf[0] = MARKER_ESC;
-	  buf[1] = MARKER_COMMENT;
-	  buf[2] = s->comment_len >> 24;
-	  buf[3] = (s->comment_len >> 16) & 0xff;
-	  buf[4] = (s->comment_len >> 8) & 0xff;
-	  buf[5] = s->comment_len & 0xff;
-	  s->data_out(buf, 6, s->file);
-	  s->data_out(s->comment, s->comment_len, s->file);
-	  s->comment = NULL;
-	}
-
-	output_sde(s, stripe, layer, plane);
-
-	/*
-	 * When we generate a NEWLEN test case (s->yd1 > s->yd), output
-	 * NEWLEN after last stripe if we have only a single
-	 * resolution layer or plane (see ITU-T T.85 profile), otherwise
-	 * output NEWLEN before last stripe.
-	 */
-	if (s->yd1 > s->yd &&
-	    (stripe == s->stripes - 1 ||
-	     (stripe == s->stripes - 2 &&
-	      (s->dl != s->dh || s->planes > 1)))) {
-	  s->yd1 = s->yd;
-	  yd = jbg_ceil_half(s->yd, s->d - s->dh);
-	  buf[0] = MARKER_ESC;
-	  buf[1] = MARKER_NEWLEN;
-	  buf[2] = yd >> 24;
-	  buf[3] = (yd >> 16) & 0xff;
-	  buf[4] = (yd >> 8) & 0xff;
-	  buf[5] = yd & 0xff;
-	  s->data_out(buf, 6, s->file);
+        stripe = ii[iindex[order][STRIPE]];
+        if (s->order & JBG_HITOLO)
+          layer = s->dh - (ii[iindex[order][LAYER]] - s->dl);
+        else
+          layer = ii[iindex[order][LAYER]];
+        plane = ii[iindex[order][PLANE]];
+
+        /* output comment marker segment if there is any pending */
+        if (s->comment) {
+          buf[0] = MARKER_ESC;
+          buf[1] = MARKER_COMMENT;
+          buf[2] = s->comment_len >> 24;
+          buf[3] = (s->comment_len >> 16) & 0xff;
+          buf[4] = (s->comment_len >> 8) & 0xff;
+          buf[5] = s->comment_len & 0xff;
+          s->data_out(buf, 6, s->file);
+          s->data_out(s->comment, s->comment_len, s->file);
+          s->comment = NULL;
+        }
+
+        output_sde(s, stripe, layer, plane);
+
+        /*
+         * When we generate a NEWLEN test case (s->yd1 > s->yd), output
+         * NEWLEN after last stripe if we have only a single
+         * resolution layer or plane (see ITU-T T.85 profile), otherwise
+         * output NEWLEN before last stripe.
+         */
+        if (s->yd1 > s->yd &&
+            (stripe == s->stripes - 1 ||
+             (stripe == s->stripes - 2 &&
+              (s->dl != s->dh || s->planes > 1)))) {
+          s->yd1 = s->yd;
+          yd = jbg_ceil_half(s->yd, s->d - s->dh);
+          buf[0] = MARKER_ESC;
+          buf[1] = MARKER_NEWLEN;
+          buf[2] = yd >> 24;
+          buf[3] = (yd >> 16) & 0xff;
+          buf[4] = (yd >> 8) & 0xff;
+          buf[5] = yd & 0xff;
+          s->data_out(buf, 6, s->file);
 #ifdef DEBUG
-	  fprintf(stderr, "NEWLEN: yd=%lu\n", yd);
+          fprintf(stderr, "NEWLEN: yd=%lu\n", yd);
 #endif
-	  if (stripe == s->stripes - 1) {
-	    buf[1] = MARKER_SDNORM;
-	    s->data_out(buf, 2, s->file);
-	  }
-	}
+          if (stripe == s->stripes - 1) {
+            buf[1] = MARKER_SDNORM;
+            s->data_out(buf, 2, s->file);
+          }
+        }
 
       }
 
@@ -1973,6 +1993,7 @@ void jbg_enc_out(struct jbg_enc_state *s)
 }
 
 
+
 void jbg_enc_free(struct jbg_enc_state *s)
 {
   unsigned long stripe;
@@ -1986,11 +2007,11 @@ void jbg_enc_free(struct jbg_enc_state *s)
   if (s->sde) {
     for (stripe = 0; stripe < s->stripes; stripe++) {
       for (layer = 0; layer < s->d + 1; layer++) {
-	for (plane = 0; plane < s->planes; plane++)
-	  if (s->sde[stripe][layer][plane] != SDE_DONE &&
-	      s->sde[stripe][layer][plane] != SDE_TODO)
-	    jbg_buf_free(&s->sde[stripe][layer][plane]);
-	checked_free(s->sde[stripe][layer]);
+        for (plane = 0; plane < s->planes; plane++)
+          if (s->sde[stripe][layer][plane] != SDE_DONE &&
+              s->sde[stripe][layer][plane] != SDE_TODO)
+            jbg_buf_free(&s->sde[stripe][layer][plane]);
+        checked_free(s->sde[stripe][layer]);
       }
       checked_free(s->sde[stripe]);
     }
@@ -2023,6 +2044,7 @@ void jbg_enc_free(struct jbg_enc_state *s)
 }
 
 
+
 /*
  * Convert the error codes used by jbg_dec_in() into an English ASCII string
  */
@@ -2036,6 +2058,7 @@ const char *jbg_strerror(int errnum)
 }
 
 
+
 /*
  * The constructor for a decoder
  */
@@ -2055,6 +2078,7 @@ void jbg_dec_init(struct jbg_dec_state *s)
 }
 
 
+
 /*
  * Specify a maximum image size for the decoder. If the JBIG file has
  * the order bit ILEAVE, but not the bit SEQ set, then the decoder
@@ -2063,7 +2087,7 @@ void jbg_dec_init(struct jbg_dec_state *s)
  * ymax.
  */
 void jbg_dec_maxsize(struct jbg_dec_state *s, unsigned long xmax,
-		     unsigned long ymax)
+                     unsigned long ymax)
 {
   if (xmax > 0) s->xmax = xmax;
   if (ymax > 0) s->ymax = ymax;
@@ -2072,6 +2096,7 @@ void jbg_dec_maxsize(struct jbg_dec_state *s, unsigned long xmax,
 }
 
 
+
 /*
  * Decode the new len PSDC bytes to which data points and add them to
  * the current stripe. Return the number of bytes which have actually
@@ -2080,7 +2105,7 @@ void jbg_dec_maxsize(struct jbg_dec_state *s, unsigned long xmax,
  * this code cannot determine whether we have a marker segment).
  */
 static size_t decode_pscd(struct jbg_dec_state *s, unsigned char *data,
-			  size_t len)
+                          size_t len)
 {
   unsigned long stripe;
   unsigned int layer, plane;
@@ -2139,7 +2164,7 @@ static size_t decode_pscd(struct jbg_dec_state *s, unsigned char *data,
 #ifdef DEBUG
   if (s->x == 0 && s->i == 0 && s->pseudo)
     fprintf(stderr, "decode_pscd(%p, %p, %ld): s/d/p = %2lu/%2u/%2u\n",
-	    (void *) s, (void *) data, (long) len, stripe, layer, plane);
+            (void *) s, (void *) data, (long) len, stripe, layer, plane);
 #endif
 
   if (s->x == 0 && s->i == 0 &&
@@ -2158,38 +2183,38 @@ static size_t decode_pscd(struct jbg_dec_state *s, unsigned char *data,
 
       /* adaptive template changes */
       if (x == 0 && s->pseudo)
-	for (n = 0; n < s->at_moves; n++)
-	  if (s->at_line[n] == s->i) {
-	    s->tx[plane][layer - s->dl] = s->at_tx[n];
-	    s->ty[plane][layer - s->dl] = s->at_ty[n];
+        for (n = 0; n < s->at_moves; n++)
+          if (s->at_line[n] == s->i) {
+            s->tx[plane][layer - s->dl] = s->at_tx[n];
+            s->ty[plane][layer - s->dl] = s->at_ty[n];
 #ifdef DEBUG
-	    fprintf(stderr, "ATMOVE: line=%lu, tx=%d, ty=%d.\n", s->i,
-		    s->tx[plane][layer - s->dl], s->ty[plane][layer - s->dl]);
+            fprintf(stderr, "ATMOVE: line=%lu, tx=%d, ty=%d.\n", s->i,
+                    s->tx[plane][layer - s->dl], s->ty[plane][layer - s->dl]);
 #endif
-	  }
+          }
       tx = s->tx[plane][layer - s->dl];
       assert(tx >= 0); /* i.e., tx can safely be cast to unsigned */
 
       /* typical prediction */
       if (s->options & JBG_TPBON && s->pseudo) {
-	slntp = arith_decode(se, (s->options & JBG_LRLTWO) ? TPB2CX : TPB3CX);
-	if (slntp < 0)
-	  goto leave;
-	s->lntp[plane][layer - s->dl] =
-	  !(slntp ^ s->lntp[plane][layer - s->dl]);
-	if (!s->lntp[plane][layer - s->dl]) {
-	  /* this line is 'typical' (i.e. identical to the previous one) */
-	  p1 = hp;
-	  if (s->i == 0 && (stripe == 0 || s->reset[plane][layer - s->dl]))
-	    while (p1 < hp + hbpl) *p1++ = 0;
-	  else {
-	    q1 = hp - hbpl;
-	    while (q1 < hp) *p1++ = *q1++;
-	  }
-	  hp += hbpl;
-	  continue;
-	}
-	/* this line is 'not typical' and has to be coded completely */
+        slntp = arith_decode(se, (s->options & JBG_LRLTWO) ? TPB2CX : TPB3CX);
+        if (slntp < 0)
+          goto leave;
+        s->lntp[plane][layer - s->dl] =
+          !(slntp ^ s->lntp[plane][layer - s->dl]);
+        if (!s->lntp[plane][layer - s->dl]) {
+          /* this line is 'typical' (i.e. identical to the previous one) */
+          p1 = hp;
+          if (s->i == 0 && (stripe == 0 || s->reset[plane][layer - s->dl]))
+            while (p1 < hp + hbpl) *p1++ = 0;
+          else {
+            q1 = hp - hbpl;
+            while (q1 < hp) *p1++ = *q1++;
+          }
+          hp += hbpl;
+          continue;
+        }
+        /* this line is 'not typical' and has to be coded completely */
       }
       s->pseudo = 0;
 
@@ -2203,11 +2228,11 @@ static size_t decode_pscd(struct jbg_dec_state *s, unsigned char *data,
        */
 
       if (x == 0) {
-	line_h1 = line_h2 = line_h3 = 0;
-	if (s->i > 0 || (y > 0 && !s->reset[plane][layer - s->dl]))
-	  line_h2 = (long)*(hp - hbpl) << 8;
-	if (s->i > 1 || (y > 1 && !s->reset[plane][layer - s->dl]))
-	  line_h3 = (long)*(hp - hbpl - hbpl) << 8;
+        line_h1 = line_h2 = line_h3 = 0;
+        if (s->i > 0 || (y > 0 && !s->reset[plane][layer - s->dl]))
+          line_h2 = (long)*(hp - hbpl) << 8;
+        if (s->i > 1 || (y > 1 && !s->reset[plane][layer - s->dl]))
+          line_h3 = (long)*(hp - hbpl - hbpl) << 8;
       }
 
       /*
@@ -2256,70 +2281,70 @@ static size_t decode_pscd(struct jbg_dec_state *s, unsigned char *data,
 
       /* decode line */
       while (x < hx) {
-	if ((x & 7) == 0) {
-	  if (x < hbpl * 8 - 8 &&
-	      (s->i > 0 || (y > 0 && !s->reset[plane][layer - s->dl]))) {
-	    line_h2 |= *(hp - hbpl + 1);
-	    if (s->i > 1 || (y > 1 && !s->reset[plane][layer - s->dl]))
-	      line_h3 |= *(hp - hbpl - hbpl + 1);
-	  }
-	}
-	if (s->options & JBG_LRLTWO) {
-	  /* two line template */
-	  do {
-	    if (tx) {
-	      if ((unsigned) tx > x)
-		a = 0;
-	      else if (tx < 8)
-		a = ((line_h1 >> (tx - 5)) & 0x010);
-	      else {
-		o = (x - tx) - (x & ~7L);
-		a = (hp[o >> 3] >> (7 - (o & 7))) & 1;
-		a <<= 4;
-	      }
-	      assert(tx > 31 ||
-		     a == ((line_h1 >> (tx - 5)) & 0x010));
-	      pix = arith_decode(se, (((line_h2 >> 9) & 0x3e0) | a |
-				      (line_h1 & 0x00f)));
-	    } else
-	      pix = arith_decode(se, (((line_h2 >> 9) & 0x3f0) |
-				      (line_h1 & 0x00f)));
-	    if (pix < 0)
-	      goto leave;
-	    line_h1 = (line_h1 << 1) | pix;
-	    line_h2 <<= 1;
-	  } while ((++x & 7) && x < hx);
-	} else {
-	  /* three line template */
-	  do {
-	    if (tx) {
-	      if ((unsigned) tx > x)
-		a = 0;
-	      else if (tx < 8)
-		a = ((line_h1 >> (tx - 3)) & 0x004);
-	      else {
-		o = (x - tx) - (x & ~7L);
-		a = (hp[o >> 3] >> (7 - (o & 7))) & 1;
-		a <<= 2;
-	      }
-	      assert(tx > 31 ||
-		     a == ((line_h1 >> (tx - 3)) & 0x004));
-	      pix = arith_decode(se, (((line_h3 >>  7) & 0x380) |
-				      ((line_h2 >> 11) & 0x078) | a |
-				      (line_h1 & 0x003)));
-	    } else
-	      pix = arith_decode(se, (((line_h3 >>  7) & 0x380) |
-				      ((line_h2 >> 11) & 0x07c) |
-				      (line_h1 & 0x003)));
-	    if (pix < 0)
-	      goto leave;
-
-	    line_h1 = (line_h1 << 1) | pix;
-	    line_h2 <<= 1;
-	    line_h3 <<= 1;
-	  } while ((++x & 7) && x < hx);
-	} /* if (s->options & JBG_LRLTWO) */
-	*hp++ = line_h1;
+        if ((x & 7) == 0) {
+          if (x < hbpl * 8 - 8 &&
+              (s->i > 0 || (y > 0 && !s->reset[plane][layer - s->dl]))) {
+            line_h2 |= *(hp - hbpl + 1);
+            if (s->i > 1 || (y > 1 && !s->reset[plane][layer - s->dl]))
+              line_h3 |= *(hp - hbpl - hbpl + 1);
+          }
+        }
+        if (s->options & JBG_LRLTWO) {
+          /* two line template */
+          do {
+            if (tx) {
+              if ((unsigned) tx > x)
+                a = 0;
+              else if (tx < 8)
+                a = ((line_h1 >> (tx - 5)) & 0x010);
+              else {
+                o = (x - tx) - (x & ~7L);
+                a = (hp[o >> 3] >> (7 - (o & 7))) & 1;
+                a <<= 4;
+              }
+              assert(tx > 31 ||
+                     a == ((line_h1 >> (tx - 5)) & 0x010));
+              pix = arith_decode(se, (((line_h2 >> 9) & 0x3e0) | a |
+                                      (line_h1 & 0x00f)));
+            } else
+              pix = arith_decode(se, (((line_h2 >> 9) & 0x3f0) |
+                                      (line_h1 & 0x00f)));
+            if (pix < 0)
+              goto leave;
+            line_h1 = (line_h1 << 1) | pix;
+            line_h2 <<= 1;
+          } while ((++x & 7) && x < hx);
+        } else {
+          /* three line template */
+          do {
+            if (tx) {
+              if ((unsigned) tx > x)
+                a = 0;
+              else if (tx < 8)
+                a = ((line_h1 >> (tx - 3)) & 0x004);
+              else {
+                o = (x - tx) - (x & ~7L);
+                a = (hp[o >> 3] >> (7 - (o & 7))) & 1;
+                a <<= 2;
+              }
+              assert(tx > 31 ||
+                     a == ((line_h1 >> (tx - 3)) & 0x004));
+              pix = arith_decode(se, (((line_h3 >>  7) & 0x380) |
+                                      ((line_h2 >> 11) & 0x078) | a |
+                                      (line_h1 & 0x003)));
+            } else
+              pix = arith_decode(se, (((line_h3 >>  7) & 0x380) |
+                                      ((line_h2 >> 11) & 0x07c) |
+                                      (line_h1 & 0x003)));
+            if (pix < 0)
+              goto leave;
+
+            line_h1 = (line_h1 << 1) | pix;
+            line_h2 <<= 1;
+            line_h3 <<= 1;
+          } while ((++x & 7) && x < hx);
+        } /* if (s->options & JBG_LRLTWO) */
+        *hp++ = line_h1;
       } /* while */
       *(hp - 1) <<= hbpl * 8 - hx;
       x = 0;
@@ -2336,25 +2361,25 @@ static size_t decode_pscd(struct jbg_dec_state *s, unsigned char *data,
 
       /* adaptive template changes */
       if (x == 0)
-	for (n = 0; n < s->at_moves; n++)
-	  if (s->at_line[n] == s->i) {
-	    s->tx[plane][layer - s->dl] = s->at_tx[n];
-	    s->ty[plane][layer - s->dl] = s->at_ty[n];
+        for (n = 0; n < s->at_moves; n++)
+          if (s->at_line[n] == s->i) {
+            s->tx[plane][layer - s->dl] = s->at_tx[n];
+            s->ty[plane][layer - s->dl] = s->at_ty[n];
 #ifdef DEBUG
-	    fprintf(stderr, "ATMOVE: line=%lu, tx=%d, ty=%d.\n", s->i,
-		    s->tx[plane][layer - s->dl], s->ty[plane][layer - s->dl]);
+            fprintf(stderr, "ATMOVE: line=%lu, tx=%d, ty=%d.\n", s->i,
+                    s->tx[plane][layer - s->dl], s->ty[plane][layer - s->dl]);
 #endif
-	  }
+          }
       tx = s->tx[plane][layer - s->dl];
 
       /* handle lower border of low-resolution image */
       if ((s->i >> 1) >= ll - 1 || (y >> 1) >= ly - 1)
-	lp1 = lp2;
+        lp1 = lp2;
 
       /* typical prediction */
       if ((s->options & JBG_TPDON) && s->pseudo) {
-	if ((s->lntp[plane][layer - s->dl] = arith_decode(se, TPDCX)) < 0)
-	  goto leave;
+        if ((s->lntp[plane][layer - s->dl] = arith_decode(se, TPDCX)) < 0)
+          goto leave;
       }
       s->pseudo = 0;
 
@@ -2379,135 +2404,135 @@ static size_t decode_pscd(struct jbg_dec_state *s, unsigned char *data,
 
 
       if (x == 0) {
-	line_h1 = line_h2 = line_h3 = line_l1 = line_l2 = line_l3 = 0;
-	if (s->i > 0 || (y > 0 && !s->reset[plane][layer - s->dl])) {
-	  line_h2 = (long)*(hp - hbpl) << 8;
-	  if (s->i > 1 || (y > 1 && !s->reset[plane][layer - s->dl]))
-	    line_h3 = (long)*(hp - hbpl - hbpl) << 8;
-	}
-	if (s->i > 1 || (y > 1 && !s->reset[plane][layer-s->dl]))
-	  line_l3 = (long)*(lp2 - lbpl) << 8;
-	line_l2 = (long)*lp2 << 8;
-	line_l1 = (long)*lp1 << 8;
+        line_h1 = line_h2 = line_h3 = line_l1 = line_l2 = line_l3 = 0;
+        if (s->i > 0 || (y > 0 && !s->reset[plane][layer - s->dl])) {
+          line_h2 = (long)*(hp - hbpl) << 8;
+          if (s->i > 1 || (y > 1 && !s->reset[plane][layer - s->dl]))
+            line_h3 = (long)*(hp - hbpl - hbpl) << 8;
+        }
+        if (s->i > 1 || (y > 1 && !s->reset[plane][layer-s->dl]))
+          line_l3 = (long)*(lp2 - lbpl) << 8;
+        line_l2 = (long)*lp2 << 8;
+        line_l1 = (long)*lp1 << 8;
       }
 
       /* decode line */
       while (x < hx) {
-	if ((x & 15) == 0)
-	  if ((x >> 1) < lbpl * 8 - 8) {
-	    line_l1 |= *(lp1 + 1);
-	    line_l2 |= *(lp2 + 1);
-	    if (s->i > 1 ||
-		(y > 1 && !s->reset[plane][layer - s->dl]))
-	      line_l3 |= *(lp2 - lbpl + 1);
-	  }
-	do {
-
-	  assert(hp  - (s->lhp[ layer     &1][plane] + (stripe * hl + s->i)
-			* hbpl) == (ptrdiff_t) x >> 3);
-	  assert(lp2 - (s->lhp[(layer-1) &1][plane] + (stripe * ll + (s->i>>1))
-			* lbpl) == (ptrdiff_t) x >> 4);
-
-	  if ((x & 7) == 0)
-	    if (x < hbpl * 8 - 8) {
-	      if (s->i > 0 || (y > 0 && !s->reset[plane][layer - s->dl])) {
-		line_h2 |= *(hp + 1 - hbpl);
-		if (s->i > 1 || (y > 1 && !s->reset[plane][layer - s->dl]))
-		  line_h3 |= *(hp + 1 - hbpl - hbpl);
-	      }
-	    }
-	  do {
-	    if (!s->lntp[plane][layer - s->dl])
+        if ((x & 15) == 0)
+          if ((x >> 1) < lbpl * 8 - 8) {
+            line_l1 |= *(lp1 + 1);
+            line_l2 |= *(lp2 + 1);
+            if (s->i > 1 ||
+                (y > 1 && !s->reset[plane][layer - s->dl]))
+              line_l3 |= *(lp2 - lbpl + 1);
+          }
+        do {
+
+          assert(hp  - (s->lhp[ layer     &1][plane] + (stripe * hl + s->i)
+                        * hbpl) == (ptrdiff_t) x >> 3);
+          assert(lp2 - (s->lhp[(layer-1) &1][plane] + (stripe * ll + (s->i>>1))
+                        * lbpl) == (ptrdiff_t) x >> 4);
+
+          if ((x & 7) == 0)
+            if (x < hbpl * 8 - 8) {
+              if (s->i > 0 || (y > 0 && !s->reset[plane][layer - s->dl])) {
+                line_h2 |= *(hp + 1 - hbpl);
+                if (s->i > 1 || (y > 1 && !s->reset[plane][layer - s->dl]))
+                  line_h3 |= *(hp + 1 - hbpl - hbpl);
+              }
+            }
+          do {
+            if (!s->lntp[plane][layer - s->dl])
               cx = (((line_l3 >> 14) & 0x007) |
                     ((line_l2 >> 11) & 0x038) |
                     ((line_l1 >> 8)  & 0x1c0));
-	    if (!s->lntp[plane][layer - s->dl] &&
-		(cx == 0x000 || cx == 0x1ff)) {
-	      /* pixels are typical and have not to be decoded */
-	      do {
-		line_h1 = (line_h1 << 1) | (cx & 1);
-	      } while ((++x & 1) && x < hx);
-	      line_h2 <<= 2;  line_h3 <<= 2;
-	    } else
-	      do {
-
-		/* deterministic prediction */
-		if (s->options & JBG_DPON)
-		  if ((y & 1) == 0)
-		    if ((x & 1) == 0)
-		      /* phase 0 */
-		      pix = s->dppriv[((line_l3 >> 15) & 0x003) |
-				      ((line_l2 >> 13) & 0x00c) |
-				      ((line_h1 <<  4) & 0x010) |
-				      ((line_h2 >>  9) & 0x0e0)];
-		    else
-		      /* phase 1 */
-		      pix = s->dppriv[(((line_l3 >> 15) & 0x003) |
-				       ((line_l2 >> 13) & 0x00c) |
-				       ((line_h1 <<  4) & 0x030) |
-				       ((line_h2 >>  9) & 0x1c0)) + 256];
-		  else
-		    if ((x & 1) == 0)
-		      /* phase 2 */
-		      pix = s->dppriv[(((line_l3 >> 15) & 0x003) |
-				       ((line_l2 >> 13) & 0x00c) |
-				       ((line_h1 <<  4) & 0x010) |
-				       ((line_h2 >>  9) & 0x0e0) |
-				       ((line_h3 >>  6) & 0x700)) + 768];
-		    else
-		      /* phase 3 */
-		      pix = s->dppriv[(((line_l3 >> 15) & 0x003) |
-				       ((line_l2 >> 13) & 0x00c) |
-				       ((line_h1 <<  4) & 0x030) |
-				       ((line_h2 >>  9) & 0x1c0) |
-				       ((line_h3 >>  6) & 0xe00)) + 2816];
-		else
-		  pix = 2;
-
-		if (pix & 2) {
-		  if (tx)
-		    cx = ((line_h1         & 0x003) |
-			  (((line_h1 << 2) >> (tx - 3)) & 0x010) |
-			  ((line_h2 >> 12) & 0x00c) |
-			  ((line_h3 >> 10) & 0x020));
-		  else
-		    cx = ((line_h1         & 0x003) |
-			  ((line_h2 >> 12) & 0x01c) |
-			  ((line_h3 >> 10) & 0x020));
-		  if (x & 1)
-		    cx |= (((line_l2 >> 8) & 0x0c0) |
-			   ((line_l1 >> 6) & 0x300)) | (1UL << 10);
-		  else
-		    cx |= (((line_l2 >> 9) & 0x0c0) |
-			   ((line_l1 >> 7) & 0x300));
-		  cx |= (y & 1) << 11;
-
-		  pix = arith_decode(se, cx);
-		  if (pix < 0)
-		    goto leave;
-		}
-
-		line_h1 = (line_h1 << 1) | pix;
-		line_h2 <<= 1;
-		line_h3 <<= 1;
-
-	      } while ((++x & 1) && x < hx);
-	    line_l1 <<= 1; line_l2 <<= 1;  line_l3 <<= 1;
-	  } while ((x & 7) && x < hx);
-	  *hp++ = line_h1;
-	} while ((x & 15) && x < hx);
-	++lp1;
-	++lp2;
+            if (!s->lntp[plane][layer - s->dl] &&
+                (cx == 0x000 || cx == 0x1ff)) {
+              /* pixels are typical and have not to be decoded */
+              do {
+                line_h1 = (line_h1 << 1) | (cx & 1);
+              } while ((++x & 1) && x < hx);
+              line_h2 <<= 2;  line_h3 <<= 2;
+            } else
+              do {
+
+                /* deterministic prediction */
+                if (s->options & JBG_DPON)
+                  if ((y & 1) == 0)
+                    if ((x & 1) == 0)
+                      /* phase 0 */
+                      pix = s->dppriv[((line_l3 >> 15) & 0x003) |
+                                      ((line_l2 >> 13) & 0x00c) |
+                                      ((line_h1 <<  4) & 0x010) |
+                                      ((line_h2 >>  9) & 0x0e0)];
+                    else
+                      /* phase 1 */
+                      pix = s->dppriv[(((line_l3 >> 15) & 0x003) |
+                                       ((line_l2 >> 13) & 0x00c) |
+                                       ((line_h1 <<  4) & 0x030) |
+                                       ((line_h2 >>  9) & 0x1c0)) + 256];
+                  else
+                    if ((x & 1) == 0)
+                      /* phase 2 */
+                      pix = s->dppriv[(((line_l3 >> 15) & 0x003) |
+                                       ((line_l2 >> 13) & 0x00c) |
+                                       ((line_h1 <<  4) & 0x010) |
+                                       ((line_h2 >>  9) & 0x0e0) |
+                                       ((line_h3 >>  6) & 0x700)) + 768];
+                    else
+                      /* phase 3 */
+                      pix = s->dppriv[(((line_l3 >> 15) & 0x003) |
+                                       ((line_l2 >> 13) & 0x00c) |
+                                       ((line_h1 <<  4) & 0x030) |
+                                       ((line_h2 >>  9) & 0x1c0) |
+                                       ((line_h3 >>  6) & 0xe00)) + 2816];
+                else
+                  pix = 2;
+
+                if (pix & 2) {
+                  if (tx)
+                    cx = ((line_h1         & 0x003) |
+                          (((line_h1 << 2) >> (tx - 3)) & 0x010) |
+                          ((line_h2 >> 12) & 0x00c) |
+                          ((line_h3 >> 10) & 0x020));
+                  else
+                    cx = ((line_h1         & 0x003) |
+                          ((line_h2 >> 12) & 0x01c) |
+                          ((line_h3 >> 10) & 0x020));
+                  if (x & 1)
+                    cx |= (((line_l2 >> 8) & 0x0c0) |
+                           ((line_l1 >> 6) & 0x300)) | (1UL << 10);
+                  else
+                    cx |= (((line_l2 >> 9) & 0x0c0) |
+                           ((line_l1 >> 7) & 0x300));
+                  cx |= (y & 1) << 11;
+
+                  pix = arith_decode(se, cx);
+                  if (pix < 0)
+                    goto leave;
+                }
+
+                line_h1 = (line_h1 << 1) | pix;
+                line_h2 <<= 1;
+                line_h3 <<= 1;
+
+              } while ((++x & 1) && x < hx);
+            line_l1 <<= 1; line_l2 <<= 1;  line_l3 <<= 1;
+          } while ((x & 7) && x < hx);
+          *hp++ = line_h1;
+        } while ((x & 15) && x < hx);
+        ++lp1;
+        ++lp2;
       } /* while */
       x = 0;
 
       *(hp - 1) <<= hbpl * 8 - hx;
       if ((s->i & 1) == 0) {
-	/* low resolution pixels are used twice */
-	lp1 -= lbpl;
-	lp2 -= lbpl;
+        /* low resolution pixels are used twice */
+        lp1 -= lbpl;
+        lp2 -= lbpl;
       } else
-	s->pseudo = 1;
+        s->pseudo = 1;
 
     } /* for (i = ...) */
 
@@ -2528,6 +2553,7 @@ static size_t decode_pscd(struct jbg_dec_state *s, unsigned char *data,
 }
 
 
+
 /*
  * Provide to the decoder a new BIE fragment of len bytes starting at data.
  *
@@ -2563,7 +2589,7 @@ static size_t decode_pscd(struct jbg_dec_state *s, unsigned char *data,
  * information by identifying which test exactly has failed.)
  */
 int jbg_dec_in(struct jbg_dec_state *s, unsigned char *data, size_t len,
-	       size_t *cnt)
+               size_t *cnt)
 {
   int i, j, required_length;
   unsigned long x, y;
@@ -2595,18 +2621,18 @@ int jbg_dec_in(struct jbg_dec_state *s, unsigned char *data, size_t len,
       s->planes = s->buffer[2];
     else
       if (s->planes != s->buffer[2])
-	return JBG_ENOCONT | 2;
+        return JBG_ENOCONT | 2;
     x = (((long) s->buffer[ 4] << 24) | ((long) s->buffer[ 5] << 16) |
-	 ((long) s->buffer[ 6] <<  8) | (long) s->buffer[ 7]);
+         ((long) s->buffer[ 6] <<  8) | (long) s->buffer[ 7]);
     y = (((long) s->buffer[ 8] << 24) | ((long) s->buffer[ 9] << 16) |
-	 ((long) s->buffer[10] <<  8) | (long) s->buffer[11]);
+         ((long) s->buffer[10] <<  8) | (long) s->buffer[11]);
     if (s->dl != 0 && ((s->xd << (s->d - s->dl + 1)) != x &&
-		       (s->yd << (s->d - s->dl + 1)) != y))
+                       (s->yd << (s->d - s->dl + 1)) != y))
       return JBG_ENOCONT | 3;
     s->xd = x;
     s->yd = y;
     s->l0 = (((long) s->buffer[12] << 24) | ((long) s->buffer[13] << 16) |
-	     ((long) s->buffer[14] <<  8) | (long) s->buffer[15]);
+             ((long) s->buffer[14] <<  8) | (long) s->buffer[15]);
     /* ITU-T T.85 trick not directly implemented by decoder; for full
      * T.85 compatibility with respect to all NEWLEN marker scenarios,
      * preprocess BIE with jbg_newlen() before passing it to the decoder,
@@ -2647,51 +2673,51 @@ int jbg_dec_in(struct jbg_dec_state *s, unsigned char *data, size_t len,
     s->ii[iindex[s->order & 7][PLANE]] = 0;
     if (s->dl == 0) {
       s->s      = (struct jbg_ardec_state **)
-	checked_malloc(s->planes, sizeof(struct jbg_ardec_state *));
+        checked_malloc(s->planes, sizeof(struct jbg_ardec_state *));
       s->tx     = (int **) checked_malloc(s->planes, sizeof(int *));
       s->ty     = (int **) checked_malloc(s->planes, sizeof(int *));
       s->reset  = (int **) checked_malloc(s->planes, sizeof(int *));
       s->lntp   = (int **) checked_malloc(s->planes, sizeof(int *));
       s->lhp[0] = (unsigned char **)
-	checked_malloc(s->planes, sizeof(unsigned char *));
+        checked_malloc(s->planes, sizeof(unsigned char *));
       s->lhp[1] = (unsigned char **)
-	checked_malloc(s->planes, sizeof(unsigned char *));
+        checked_malloc(s->planes, sizeof(unsigned char *));
       for (i = 0; i < s->planes; i++) {
-	s->s[i]     = (struct jbg_ardec_state *)
-	  checked_malloc(s->d - s->dl + 1, sizeof(struct jbg_ardec_state));
-	s->tx[i]    = (int *) checked_malloc(s->d - s->dl + 1, sizeof(int));
-	s->ty[i]    = (int *) checked_malloc(s->d - s->dl + 1, sizeof(int));
-	s->reset[i] = (int *) checked_malloc(s->d - s->dl + 1, sizeof(int));
-	s->lntp[i]  = (int *) checked_malloc(s->d - s->dl + 1, sizeof(int));
-	s->lhp[ s->d    & 1][i] = (unsigned char *)
-	  checked_malloc(s->yd, jbg_ceil_half(s->xd, 3));
-	s->lhp[(s->d-1) & 1][i] = (unsigned char *)
-	  checked_malloc(jbg_ceil_half(s->yd, 1), jbg_ceil_half(s->xd, 1+3));
+        s->s[i]     = (struct jbg_ardec_state *)
+          checked_malloc(s->d - s->dl + 1, sizeof(struct jbg_ardec_state));
+        s->tx[i]    = (int *) checked_malloc(s->d - s->dl + 1, sizeof(int));
+        s->ty[i]    = (int *) checked_malloc(s->d - s->dl + 1, sizeof(int));
+        s->reset[i] = (int *) checked_malloc(s->d - s->dl + 1, sizeof(int));
+        s->lntp[i]  = (int *) checked_malloc(s->d - s->dl + 1, sizeof(int));
+        s->lhp[ s->d    & 1][i] = (unsigned char *)
+          checked_malloc(s->yd, jbg_ceil_half(s->xd, 3));
+        s->lhp[(s->d-1) & 1][i] = (unsigned char *)
+          checked_malloc(jbg_ceil_half(s->yd, 1), jbg_ceil_half(s->xd, 1+3));
       }
     } else {
       for (i = 0; i < s->planes; i++) {
-	s->s[i]     = (struct jbg_ardec_state *)
-	  checked_realloc(s->s[i], s->d - s->dl + 1,
-			  sizeof(struct jbg_ardec_state));
-	s->tx[i]    = (int *) checked_realloc(s->tx[i],
-					      s->d - s->dl + 1, sizeof(int));
-	s->ty[i]    = (int *) checked_realloc(s->ty[i],
-					      s->d - s->dl + 1, sizeof(int));
-	s->reset[i] = (int *) checked_realloc(s->reset[i],
-					      s->d - s->dl + 1, sizeof(int));
-	s->lntp[i]  = (int *) checked_realloc(s->lntp[i],
-					      s->d - s->dl + 1, sizeof(int));
-	s->lhp[ s->d    & 1][i] = (unsigned char *)
-	  checked_realloc(s->lhp[ s->d    & 1][i],
-			  s->yd, jbg_ceil_half(s->xd, 3));
-	s->lhp[(s->d-1) & 1][i] = (unsigned char *)
-	  checked_realloc(s->lhp[(s->d-1) & 1][i],
-			  jbg_ceil_half(s->yd, 1), jbg_ceil_half(s->xd, 1+3));
+        s->s[i]     = (struct jbg_ardec_state *)
+          checked_realloc(s->s[i], s->d - s->dl + 1,
+                          sizeof(struct jbg_ardec_state));
+        s->tx[i]    = (int *) checked_realloc(s->tx[i],
+                                              s->d - s->dl + 1, sizeof(int));
+        s->ty[i]    = (int *) checked_realloc(s->ty[i],
+                                              s->d - s->dl + 1, sizeof(int));
+        s->reset[i] = (int *) checked_realloc(s->reset[i],
+                                              s->d - s->dl + 1, sizeof(int));
+        s->lntp[i]  = (int *) checked_realloc(s->lntp[i],
+                                              s->d - s->dl + 1, sizeof(int));
+        s->lhp[ s->d    & 1][i] = (unsigned char *)
+          checked_realloc(s->lhp[ s->d    & 1][i],
+                          s->yd, jbg_ceil_half(s->xd, 3));
+        s->lhp[(s->d-1) & 1][i] = (unsigned char *)
+          checked_realloc(s->lhp[(s->d-1) & 1][i],
+                          jbg_ceil_half(s->yd, 1), jbg_ceil_half(s->xd, 1+3));
       }
     }
     for (i = 0; i < s->planes; i++)
       for (j = 0; j <= s->d - s->dl; j++)
-	arith_decode_init(s->s[i] + j, 0);
+        arith_decode_init(s->s[i] + j, 0);
     if (s->dl == 0 || (s->options & JBG_DPON && !(s->options & JBG_DPPRIV)))
       s->dppriv = jbg_dptable;
     s->comment_skip = 0;
@@ -2730,11 +2756,11 @@ int jbg_dec_in(struct jbg_dec_state *s, unsigned char *data, size_t len,
     /* skip COMMENT contents */
     if (s->comment_skip) {
       if (s->comment_skip <= len - *cnt) {
-	*cnt += s->comment_skip;
-	s->comment_skip = 0;
+        *cnt += s->comment_skip;
+        s->comment_skip = 0;
       } else {
-	s->comment_skip -= len - *cnt;
-	*cnt = len;
+        s->comment_skip -= len - *cnt;
+        *cnt = len;
       }
       continue;
     }
@@ -2743,7 +2769,7 @@ int jbg_dec_in(struct jbg_dec_state *s, unsigned char *data, size_t len,
     if (s->buf_len > 0) {
       assert(s->buffer[0] == MARKER_ESC);
       while (s->buf_len < 2 && *cnt < len)
-	s->buffer[s->buf_len++] = data[(*cnt)++];
+        s->buffer[s->buf_len++] = data[(*cnt)++];
       if (s->buf_len < 2) continue;
       switch (s->buffer[1]) {
       case MARKER_COMMENT: required_length = 6; break;
@@ -2753,120 +2779,120 @@ int jbg_dec_in(struct jbg_dec_state *s, unsigned char *data, size_t len,
       case MARKER_SDNORM:
       case MARKER_SDRST:   required_length = 2; break;
       case MARKER_STUFF:
-	/* forward stuffed 0xff to arithmetic decoder */
-	s->buf_len = 0;
-	decode_pscd(s, s->buffer, 2);
-	continue;
+        /* forward stuffed 0xff to arithmetic decoder */
+        s->buf_len = 0;
+        decode_pscd(s, s->buffer, 2);
+        continue;
       default:
-	return JBG_EMARKER;
+        return JBG_EMARKER;
       }
       while (s->buf_len < required_length && *cnt < len)
-	s->buffer[s->buf_len++] = data[(*cnt)++];
+        s->buffer[s->buf_len++] = data[(*cnt)++];
       if (s->buf_len < required_length) continue;
       /* now the buffer is filled with exactly one marker segment */
       switch (s->buffer[1]) {
       case MARKER_COMMENT:
-	s->comment_skip =
-	  (((long) s->buffer[2] << 24) | ((long) s->buffer[3] << 16) |
-	   ((long) s->buffer[4] <<  8) | (long) s->buffer[5]);
-	break;
+        s->comment_skip =
+          (((long) s->buffer[2] << 24) | ((long) s->buffer[3] << 16) |
+           ((long) s->buffer[4] <<  8) | (long) s->buffer[5]);
+        break;
       case MARKER_ATMOVE:
-	if (s->at_moves < JBG_ATMOVES_MAX) {
-	  s->at_line[s->at_moves] =
-	    (((long) s->buffer[2] << 24) | ((long) s->buffer[3] << 16) |
-	     ((long) s->buffer[4] <<  8) | (long) s->buffer[5]);
-	  s->at_tx[s->at_moves] = (signed char) s->buffer[6];
-	  s->at_ty[s->at_moves] = s->buffer[7];
-	  if (s->at_tx[s->at_moves] < - (int) s->mx ||
-	      s->at_tx[s->at_moves] >   (int) s->mx ||
-	      s->at_ty[s->at_moves] >   (int) s->my ||
-	      (s->at_ty[s->at_moves] == 0 && s->at_tx[s->at_moves] < 0))
-	    return JBG_EINVAL | 11;
-	  if (s->at_ty[s->at_moves] != 0)
-	    return JBG_EIMPL | 6;
-	  s->at_moves++;
-	} else
-	  return JBG_EIMPL | 7; /* more than JBG_ATMOVES_MAX ATMOVES */
-	break;
+        if (s->at_moves < JBG_ATMOVES_MAX) {
+          s->at_line[s->at_moves] =
+            (((long) s->buffer[2] << 24) | ((long) s->buffer[3] << 16) |
+             ((long) s->buffer[4] <<  8) | (long) s->buffer[5]);
+          s->at_tx[s->at_moves] = (signed char) s->buffer[6];
+          s->at_ty[s->at_moves] = s->buffer[7];
+          if (s->at_tx[s->at_moves] < - (int) s->mx ||
+              s->at_tx[s->at_moves] >   (int) s->mx ||
+              s->at_ty[s->at_moves] >   (int) s->my ||
+              (s->at_ty[s->at_moves] == 0 && s->at_tx[s->at_moves] < 0))
+            return JBG_EINVAL | 11;
+          if (s->at_ty[s->at_moves] != 0)
+            return JBG_EIMPL | 6;
+          s->at_moves++;
+        } else
+          return JBG_EIMPL | 7; /* more than JBG_ATMOVES_MAX ATMOVES */
+        break;
       case MARKER_NEWLEN:
-	y = (((long) s->buffer[2] << 24) | ((long) s->buffer[3] << 16) |
-	     ((long) s->buffer[4] <<  8) | (long) s->buffer[5]);
-	if (y > s->yd)                   return JBG_EINVAL | 12;
-	if (!(s->options & JBG_VLENGTH)) return JBG_EINVAL | 13;
-	s->yd = y;
-	/* calculate again number of stripes that will be required */
-	s->stripes = jbg_stripes(s->l0, s->yd, s->d);
-	break;
+        y = (((long) s->buffer[2] << 24) | ((long) s->buffer[3] << 16) |
+             ((long) s->buffer[4] <<  8) | (long) s->buffer[5]);
+        if (y > s->yd)                   return JBG_EINVAL | 12;
+        if (!(s->options & JBG_VLENGTH)) return JBG_EINVAL | 13;
+        s->yd = y;
+        /* calculate again number of stripes that will be required */
+        s->stripes = jbg_stripes(s->l0, s->yd, s->d);
+        break;
       case MARKER_ABORT:
-	return JBG_EABORT;
+        return JBG_EABORT;
 
       case MARKER_SDNORM:
       case MARKER_SDRST:
-	/* decode final pixels based on trailing zero bytes */
-	decode_pscd(s, s->buffer, 2);
-
-	arith_decode_init(s->s[s->ii[iindex[s->order & 7][PLANE]]] +
-			  s->ii[iindex[s->order & 7][LAYER]] - s->dl,
-			  s->ii[iindex[s->order & 7][STRIPE]] != s->stripes - 1
-			  && s->buffer[1] != MARKER_SDRST);
-
-	s->reset[s->ii[iindex[s->order & 7][PLANE]]]
-	  [s->ii[iindex[s->order & 7][LAYER]] - s->dl] =
-	    (s->buffer[1] == MARKER_SDRST);
-
-	/* prepare for next SDE */
-	s->x = 0;
-	s->i = 0;
-	s->pseudo = 1;
-	s->at_moves = 0;
-
-	/* increment layer/stripe/plane loop variables */
-	/* start and end value for each loop: */
-	is[iindex[s->order & 7][STRIPE]] = 0;
-	ie[iindex[s->order & 7][STRIPE]] = s->stripes - 1;
-	is[iindex[s->order & 7][LAYER]] = s->dl;
-	ie[iindex[s->order & 7][LAYER]] = s->d;
-	is[iindex[s->order & 7][PLANE]] = 0;
-	ie[iindex[s->order & 7][PLANE]] = s->planes - 1;
-	i = 2;  /* index to innermost loop */
-	do {
-	  j = 0;  /* carry flag */
-	  if (++s->ii[i] > ie[i]) {
-	    /* handling overflow of loop variable */
-	    j = 1;
-	    if (i > 0)
-	      s->ii[i] = is[i];
-	  }
-	} while (--i >= 0 && j);
-
-	s->buf_len = 0;
-
-	/* check whether this have been all SDEs */
-	if (j) {
+        /* decode final pixels based on trailing zero bytes */
+        decode_pscd(s, s->buffer, 2);
+
+        arith_decode_init(s->s[s->ii[iindex[s->order & 7][PLANE]]] +
+                          s->ii[iindex[s->order & 7][LAYER]] - s->dl,
+                          s->ii[iindex[s->order & 7][STRIPE]] != s->stripes - 1
+                          && s->buffer[1] != MARKER_SDRST);
+
+        s->reset[s->ii[iindex[s->order & 7][PLANE]]]
+          [s->ii[iindex[s->order & 7][LAYER]] - s->dl] =
+            (s->buffer[1] == MARKER_SDRST);
+
+        /* prepare for next SDE */
+        s->x = 0;
+        s->i = 0;
+        s->pseudo = 1;
+        s->at_moves = 0;
+
+        /* increment layer/stripe/plane loop variables */
+        /* start and end value for each loop: */
+        is[iindex[s->order & 7][STRIPE]] = 0;
+        ie[iindex[s->order & 7][STRIPE]] = s->stripes - 1;
+        is[iindex[s->order & 7][LAYER]] = s->dl;
+        ie[iindex[s->order & 7][LAYER]] = s->d;
+        is[iindex[s->order & 7][PLANE]] = 0;
+        ie[iindex[s->order & 7][PLANE]] = s->planes - 1;
+        i = 2;  /* index to innermost loop */
+        do {
+          j = 0;  /* carry flag */
+          if (++s->ii[i] > ie[i]) {
+            /* handling overflow of loop variable */
+            j = 1;
+            if (i > 0)
+              s->ii[i] = is[i];
+          }
+        } while (--i >= 0 && j);
+
+        s->buf_len = 0;
+
+        /* check whether this have been all SDEs */
+        if (j) {
 #ifdef DEBUG
-	  fprintf(stderr, "This was the final SDE in this BIE, "
-		  "%ld bytes left.\n", (long) (len - *cnt));
+          fprintf(stderr, "This was the final SDE in this BIE, "
+                  "%ld bytes left.\n", (long) (len - *cnt));
 #endif
-	  s->bie_len = 0;
-	  return JBG_EOK;
-	}
-
-	/* check whether we have to abort because of xmax/ymax */
-	if (iindex[s->order & 7][LAYER] == 0 && i < 0) {
-	  /* LAYER is the outermost loop and we have just gone to next layer */
-	  if (jbg_ceil_half(s->xd, s->d - s->ii[0]) > s->xmax ||
-	      jbg_ceil_half(s->yd, s->d - s->ii[0]) > s->ymax) {
-	    s->xmax = 4294967295UL;
-	    s->ymax = 4294967295UL;
-	    return JBG_EOK_INTR;
-	  }
-	  if (s->ii[0] > (unsigned long) s->dmax) {
-	    s->dmax = 256;
-	    return JBG_EOK_INTR;
-	  }
-	}
-
-	break;
+          s->bie_len = 0;
+          return JBG_EOK;
+        }
+
+        /* check whether we have to abort because of xmax/ymax */
+        if (iindex[s->order & 7][LAYER] == 0 && i < 0) {
+          /* LAYER is the outermost loop and we have just gone to next layer */
+          if (jbg_ceil_half(s->xd, s->d - s->ii[0]) > s->xmax ||
+              jbg_ceil_half(s->yd, s->d - s->ii[0]) > s->ymax) {
+            s->xmax = 4294967295UL;
+            s->ymax = 4294967295UL;
+            return JBG_EOK_INTR;
+          }
+          if (s->ii[0] > (unsigned long) s->dmax) {
+            s->dmax = 256;
+            return JBG_EOK_INTR;
+          }
+        }
+
+        break;
       }
       s->buf_len = 0;
 
@@ -2879,11 +2905,11 @@ int jbg_dec_in(struct jbg_dec_state *s, unsigned char *data, size_t len,
       *cnt += decode_pscd(s, data + *cnt, len - *cnt);
       if (*cnt < len && data[*cnt] != 0xff) {
 #ifdef DEBUG
-	fprintf(stderr, "PSCD was longer than expected, unread bytes "
-		"%02x %02x %02x %02x ...\n", data[*cnt], data[*cnt+1],
-		data[*cnt+2], data[*cnt+3]);
+        fprintf(stderr, "PSCD was longer than expected, unread bytes "
+                "%02x %02x %02x %02x ...\n", data[*cnt], data[*cnt+1],
+                data[*cnt+2], data[*cnt+3]);
 #endif
-	return JBG_EINVAL | 14;
+        return JBG_EINVAL | 14;
       }
 
     }
@@ -2893,6 +2919,7 @@ int jbg_dec_in(struct jbg_dec_state *s, unsigned char *data, size_t len,
 }
 
 
+
 /*
  * After jbg_dec_in() returned JBG_EOK or JBG_EOK_INTR, you can call this
  * function in order to find out the width of the image. Returns 0 if
@@ -2913,6 +2940,7 @@ unsigned long jbg_dec_getwidth(const struct jbg_dec_state *s)
 }
 
 
+
 /*
  * After jbg_dec_in() returned JBG_EOK or JBG_EOK_INTR, you can call this
  * function in order to find out the height of the image. Returns 0 if
@@ -2933,6 +2961,7 @@ unsigned long jbg_dec_getheight(const struct jbg_dec_state *s)
 }
 
 
+
 /*
  * After jbg_dec_in() returned JBG_EOK or JBG_EOK_INTR, you can call this
  * function in order to get a pointer to the image. Returns NULL if
@@ -2953,6 +2982,7 @@ unsigned char *jbg_dec_getimage(const struct jbg_dec_state *s, int plane)
 }
 
 
+
 /*
  * After jbg_dec_in() returned JBG_EOK or JBG_EOK_INTR, you can call
  * this function in order to find out the size in bytes of one
@@ -2967,14 +2997,15 @@ unsigned long jbg_dec_getsize(const struct jbg_dec_state *s)
       return 0;
     else
       return
-	jbg_ceil_half(s->xd, s->d - (s->ii[0] - 1) + 3) * /* overflow risk? */
-	jbg_ceil_half(s->yd, s->d - (s->ii[0] - 1));
+        jbg_ceil_half(s->xd, s->d - (s->ii[0] - 1) + 3) * /* overflow risk? */
+        jbg_ceil_half(s->yd, s->d - (s->ii[0] - 1));
   }
 
   return jbg_ceil_half(s->xd, 3) * s->yd;
 }
 
 
+
 /*
  * After jbg_dec_in() returned JBG_EOK or JBG_EOK_INTR, you can call
  * this function in order to find out the size of the image that you
@@ -2989,15 +3020,16 @@ unsigned long jbg_dec_getsize_merged(const struct jbg_dec_state *s)
       return 0;
     else
       return
-	jbg_ceil_half(s->xd, s->d - (s->ii[0] - 1)) * /* overflow risk? */
-	jbg_ceil_half(s->yd, s->d - (s->ii[0] - 1)) *
-	((s->planes + 7) / 8);
+        jbg_ceil_half(s->xd, s->d - (s->ii[0] - 1)) * /* overflow risk? */
+        jbg_ceil_half(s->yd, s->d - (s->ii[0] - 1)) *
+        ((s->planes + 7) / 8);
   }
 
   return s->xd * s->yd * ((s->planes + 7) / 8);
 }
 
 
+
 /*
  * The destructor function which releases any resources obtained by the
  * other decoder functions.
@@ -3036,6 +3068,7 @@ void jbg_dec_free(struct jbg_dec_state *s)
 }
 
 
+
 /*
  * Split bigendian integer pixel field into separate bit planes. In the
  * src array, every pixel is represented by a ((has_planes + 7) / 8) byte
@@ -3045,9 +3078,9 @@ void jbg_dec_free(struct jbg_dec_state *s)
  * actually transfer to dest.
  */
 void jbg_split_planes(unsigned long x, unsigned long y, int has_planes,
-		      int encode_planes,
-		      const unsigned char *src, unsigned char **dest,
-		      int use_graycode)
+                      int encode_planes,
+                      const unsigned char *src, unsigned char **dest,
+                      int use_graycode)
 {
   unsigned long bpl = jbg_ceil_half(x, 3);  /* bytes per line in dest plane */
   unsigned long line, i;
@@ -3068,29 +3101,29 @@ void jbg_split_planes(unsigned long x, unsigned long y, int has_planes,
   for (line = 0; line < y; line++) {                 /* lines loop */
     for (i = 0; i * 8 < x; i++) {                    /* dest bytes loop */
       for (k = 0; k < 8 && i * 8 + k < x; k++) {     /* pixel loop */
-	prev = 0;
-	for (p = 0; p < encode_planes; p++) {        /* bit planes loop */
-	  /* calculate which bit in *src do we want */
-	  bitno = (msb - p) & 7;
-	  /* put this bit with its left neighbor right adjusted into bits */
-	  bits = (prev | *src) >> bitno;
-	  /* go to next *src byte, but keep old */
-	  if (bitno == 0)
-	    prev = *src++ << 8;
-	  /* make space for inserting new bit */
-	  dest[p][bpl * line + i] <<= 1;
-	  /* insert bit, if requested apply Gray encoding */
-	  dest[p][bpl * line + i] |= (bits ^ (use_graycode & (bits>>1))) & 1;
-	  /*
-	   * Theorem: Let b(n),...,b(1),b(0) be the digits of a
-	   * binary word and let g(n),...,g(1),g(0) be the digits of the
-	   * corresponding Gray code word, then g(i) = b(i) xor b(i+1).
-	   */
-	}
-	/* skip unused *src bytes */
-	for (;p < has_planes; p++)
-	  if (((msb - p) & 7) == 0)
-	    src++;
+        prev = 0;
+        for (p = 0; p < encode_planes; p++) {        /* bit planes loop */
+          /* calculate which bit in *src do we want */
+          bitno = (msb - p) & 7;
+          /* put this bit with its left neighbor right adjusted into bits */
+          bits = (prev | *src) >> bitno;
+          /* go to next *src byte, but keep old */
+          if (bitno == 0)
+            prev = *src++ << 8;
+          /* make space for inserting new bit */
+          dest[p][bpl * line + i] <<= 1;
+          /* insert bit, if requested apply Gray encoding */
+          dest[p][bpl * line + i] |= (bits ^ (use_graycode & (bits>>1))) & 1;
+          /*
+           * Theorem: Let b(n),...,b(1),b(0) be the digits of a
+           * binary word and let g(n),...,g(1),g(0) be the digits of the
+           * corresponding Gray code word, then g(i) = b(i) xor b(i+1).
+           */
+        }
+        /* skip unused *src bytes */
+        for (;p < has_planes; p++)
+          if (((msb - p) & 7) == 0)
+            src++;
       }
     }
     for (p = 0; p < encode_planes; p++)              /* right padding loop */
@@ -3100,14 +3133,16 @@ void jbg_split_planes(unsigned long x, unsigned long y, int has_planes,
   return;
 }
 
+
+
 /*
  * Merge the separate bit planes decoded by the JBIG decoder into an
  * integer pixel field. This is essentially the counterpart to
  * jbg_split_planes().
  */
 void jbg_dec_merge_planes(const struct jbg_dec_state *s, int use_graycode,
-			  void (*data_out)(unsigned char *start, size_t len,
-					   void *file), void *file)
+                          void (*data_out)(unsigned char *start, size_t len,
+                                           void *file), void *file)
 {
 #define BUFLEN 4096
   unsigned long bpl, line, i;
@@ -3139,19 +3174,19 @@ void jbg_dec_merge_planes(const struct jbg_dec_state *s, int use_graycode,
   for (line = 0; line < y; line++) {                    /* lines loop */
     for (i = 0; i * 8 < x; i++) {                       /* src bytes loop */
       for (k = 0; k < 8 && i * 8 + k < x; k++) {        /* pixel loop */
-	v = 0;
-	for (p = 0; p < s->planes;) {                   /* dest bytes loop */
-	  do {
-	    v = (v << 1) |
-	      (((src[p][bpl * line + i] >> (7 - k)) & 1) ^
-	       (use_graycode & v));
-	  } while ((s->planes - ++p) & 7);
-	  *bp++ = v;
-	  if (bp - buf == BUFLEN) {
-	    data_out(buf, BUFLEN, file);
-	    bp = buf;
-	  }
-	}
+        v = 0;
+        for (p = 0; p < s->planes;) {                   /* dest bytes loop */
+          do {
+            v = (v << 1) |
+              (((src[p][bpl * line + i] >> (7 - k)) & 1) ^
+               (use_graycode & v));
+          } while ((s->planes - ++p) & 7);
+          *bp++ = v;
+          if (bp - buf == BUFLEN) {
+            data_out(buf, BUFLEN, file);
+            bp = buf;
+          }
+        }
       }
     }
   }
@@ -3163,6 +3198,7 @@ void jbg_dec_merge_planes(const struct jbg_dec_state *s, int use_graycode,
 }
 
 
+
 /*
  * Given a pointer p to the first byte of either a marker segment or a
  * PSCD, as well as the length len of the remaining data, return
@@ -3186,15 +3222,15 @@ static unsigned char *jbg_next_pscdms(unsigned char *p, size_t len)
   if (p[0] != MARKER_ESC || p[1] == MARKER_STUFF) {
     do {
       while (p[0] == MARKER_ESC && p[1] == MARKER_STUFF) {
-	p += 2;
-	len -= 2;
-	if (len < 2)
-	  return NULL; /* not enough bytes left for complete marker segment */
+        p += 2;
+        len -= 2;
+        if (len < 2)
+          return NULL; /* not enough bytes left for complete marker segment */
       }
       assert(len >= 2);
       pp = (unsigned char *) memchr(p, MARKER_ESC, len - 1);
       if (!pp)
-	return NULL; /* no marker segment terminates the PSCD */
+        return NULL; /* no marker segment terminates the PSCD */
       l = pp - p;
       assert(l < len);
       p += l;
@@ -3208,19 +3244,19 @@ static unsigned char *jbg_next_pscdms(unsigned char *p, size_t len)
       return p + 2;
     case MARKER_NEWLEN:
       if (len < 6)
-	return NULL; /* not enough bytes left for complete marker segment */
+        return NULL; /* not enough bytes left for complete marker segment */
       return p + 6;
     case MARKER_ATMOVE:
       if (len < 8)
-	return NULL; /* not enough bytes left for complete marker segment */
+        return NULL; /* not enough bytes left for complete marker segment */
       return p + 8;
     case MARKER_COMMENT:
       if (len < 6)
-	return NULL; /* not enough bytes left for complete marker segment */
+        return NULL; /* not enough bytes left for complete marker segment */
       l = (((long) p[2] << 24) | ((long) p[3] << 16) |
-	   ((long) p[4] <<  8) |  (long) p[5]);
+           ((long) p[4] <<  8) |  (long) p[5]);
       if (len - 6 < l)
-	return NULL; /* not enough bytes left for complete marker segment */
+        return NULL; /* not enough bytes left for complete marker segment */
       return p + 6 + l;
     default:
       /* unknown marker sequence encountered */
@@ -3232,6 +3268,7 @@ static unsigned char *jbg_next_pscdms(unsigned char *p, size_t len)
 }
 
 
+
 /*
  * Scan a complete BIE for a NEWLEN marker segment, then read the new
  * YD value found in it and use it to overwrite the one in the BIE
@@ -3265,19 +3302,22 @@ int jbg_newlen(unsigned char *bie, size_t len)
     else if (p[0] == MARKER_ESC)
       switch (p[1]) {
       case MARKER_NEWLEN:
-	y = (((long) bie[ 8] << 24) | ((long) bie[ 9] << 16) |
-	     ((long) bie[10] <<  8) |  (long) bie[11]);
-	yn = (((long) p[2] << 24) | ((long) p[3] << 16) |
-	      ((long) p[4] <<  8) |  (long) p[5]);
-	if (yn > y) return JBG_EINVAL | 12;
-	/* overwrite YD in BIH with YD from NEWLEN */
-	for (i = 0; i < 4; i++) {
-	  bie[8+i] = p[2+i];
-	}
-	return JBG_EOK;
+        y = (((long) bie[ 8] << 24) | ((long) bie[ 9] << 16) |
+             ((long) bie[10] <<  8) |  (long) bie[11]);
+        yn = (((long) p[2] << 24) | ((long) p[3] << 16) |
+              ((long) p[4] <<  8) |  (long) p[5]);
+        if (yn > y) return JBG_EINVAL | 12;
+        /* overwrite YD in BIH with YD from NEWLEN */
+        for (i = 0; i < 4; i++) {
+          bie[8+i] = p[2+i];
+        }
+        return JBG_EOK;
       case MARKER_ABORT:
-	return JBG_EABORT;
+        return JBG_EABORT;
       }
   }
   return JBG_EINVAL | 0;
 }
+
+
+
diff --git a/converter/other/jbig/libjbig/jbig_ar.c b/converter/other/jbig/libjbig/jbig_ar.c
index d23a317d..aad293f2 100644
--- a/converter/other/jbig/libjbig/jbig_ar.c
+++ b/converter/other/jbig/libjbig/jbig_ar.c
@@ -22,7 +22,7 @@
  *  You should have received a copy of the GNU General Public License
  *  along with this program; if not, write to the Free Software
  *  Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
- * 
+ *
  *  If you want to use this program under different license conditions,
  *  then contact the author for an arrangement.
  */
@@ -106,7 +106,7 @@ static unsigned char nlpstab[113] = {
 void arith_encode_init(struct jbg_arenc_state *s, int reuse_st)
 {
   int i;
-  
+
   if (!reuse_st)
     for (i = 0; i < 4096; s->st[i++] = 0) ;
   s->c = 0;
@@ -114,11 +114,12 @@ void arith_encode_init(struct jbg_arenc_state *s, int reuse_st)
   s->sc = 0;
   s->ct = 11;
   s->buffer = -1;    /* empty */
-  
+
   return;
 }
 
 
+
 void arith_encode_flush(struct jbg_arenc_state *s)
 {
   unsigned long temp;
@@ -136,15 +137,15 @@ void arith_encode_flush(struct jbg_arenc_state *s)
     if (s->buffer >= 0) {
       s->byte_out(s->buffer + 1, s->file);
       if (s->buffer + 1 == MARKER_ESC)
-	s->byte_out(MARKER_STUFF, s->file);
+        s->byte_out(MARKER_STUFF, s->file);
     }
     /* output 0x00 bytes only when more non-0x00 will follow */
     if (s->c & 0x7fff800L)
       for (; s->sc; --s->sc)
-	s->byte_out(0x00, s->file);
+        s->byte_out(0x00, s->file);
   } else {
     if (s->buffer >= 0)
-      s->byte_out(s->buffer, s->file); 
+      s->byte_out(s->buffer, s->file);
     /* T.82 figure 30 says buffer+1 for the above line! Typo? */
     for (; s->sc; --s->sc) {
       s->byte_out(0xff, s->file);
@@ -159,7 +160,7 @@ void arith_encode_flush(struct jbg_arenc_state *s)
     if (s->c & 0x7f800L) {
       s->byte_out((s->c >> 11) & 0xff, s->file);
       if (((s->c >> 11) & 0xff) == MARKER_ESC)
-	s->byte_out(MARKER_STUFF, s->file);
+        s->byte_out(MARKER_STUFF, s->file);
     }
   }
 
@@ -167,7 +168,8 @@ void arith_encode_flush(struct jbg_arenc_state *s)
 }
 
 
-void arith_encode(struct jbg_arenc_state *s, int cx, int pix) 
+
+void arith_encode(struct jbg_arenc_state *s, int cx, int pix)
 {
   register unsigned lsz, ss;
   register unsigned char *st;
@@ -181,9 +183,9 @@ void arith_encode(struct jbg_arenc_state *s, int cx, int pix)
 
 #if 0
   fprintf(stderr, "pix = %d, cx = %d, mps = %d, st = %3d, lsz = 0x%04x, "
-	  "a = 0x%05lx, c = 0x%08lx, ct = %2d, buf = 0x%02x\n",
-	  pix, cx, !!(s->st[cx] & 0x80), ss, lsz, s->a, s->c, s->ct,
-	  s->buffer);
+          "a = 0x%05lx, c = 0x%08lx, ct = %2d, buf = 0x%02x\n",
+          pix, cx, !!(s->st[cx] & 0x80), ss, lsz, s->a, s->c, s->ct,
+          s->buffer);
 #endif
 
   if (((pix << 7) ^ s->st[cx]) & 0x80) {
@@ -225,44 +227,45 @@ void arith_encode(struct jbg_arenc_state *s, int cx, int pix)
       /* another byte is ready for output */
       temp = s->c >> 19;
       if (temp & 0xffffff00L) {
-	/* handle overflow over all buffered 0xff bytes */
-	if (s->buffer >= 0) {
-	  ++s->buffer;
-	  s->byte_out(s->buffer, s->file);
-	  if (s->buffer == MARKER_ESC)
-	    s->byte_out(MARKER_STUFF, s->file);
-	}
-	for (; s->sc; --s->sc)
-	  s->byte_out(0x00, s->file);
-	s->buffer = temp & 0xff;  /* new output byte, might overflow later */
-	assert(s->buffer != 0xff);
-	/* can s->buffer really never become 0xff here? */
+        /* handle overflow over all buffered 0xff bytes */
+        if (s->buffer >= 0) {
+          ++s->buffer;
+          s->byte_out(s->buffer, s->file);
+          if (s->buffer == MARKER_ESC)
+            s->byte_out(MARKER_STUFF, s->file);
+        }
+        for (; s->sc; --s->sc)
+          s->byte_out(0x00, s->file);
+        s->buffer = temp & 0xff;  /* new output byte, might overflow later */
+        assert(s->buffer != 0xff);
+        /* can s->buffer really never become 0xff here? */
       } else if (temp == 0xff) {
-	/* buffer 0xff byte (which might overflow later) */
-	++s->sc;
+        /* buffer 0xff byte (which might overflow later) */
+        ++s->sc;
       } else {
-	/* output all buffered 0xff bytes, they will not overflow any more */
-	if (s->buffer >= 0)
-	  s->byte_out(s->buffer, s->file);
-	for (; s->sc; --s->sc) {
-	  s->byte_out(0xff, s->file);
-	  s->byte_out(MARKER_STUFF, s->file);
-	}
-	s->buffer = temp;   /* buffer new output byte (can still overflow) */
+        /* output all buffered 0xff bytes, they will not overflow any more */
+        if (s->buffer >= 0)
+          s->byte_out(s->buffer, s->file);
+        for (; s->sc; --s->sc) {
+          s->byte_out(0xff, s->file);
+          s->byte_out(MARKER_STUFF, s->file);
+        }
+        s->buffer = temp;   /* buffer new output byte (can still overflow) */
       }
       s->c &= 0x7ffffL;
       s->ct = 8;
     }
   } while (s->a < 0x8000);
- 
+
   return;
 }
 
 
+
 void arith_decode_init(struct jbg_ardec_state *s, int reuse_st)
 {
   int i;
-  
+
   if (!reuse_st)
     for (i = 0; i < 4096; s->st[i++] = 0) ;
   s->c = 0;
@@ -273,6 +276,8 @@ void arith_decode_init(struct jbg_ardec_state *s, int reuse_st)
   return;
 }
 
+
+
 /*
  * Decode and return one symbol from the provided PSCD byte stream
  * that starts in s->pscd_ptr and ends in the byte before s->pscd_end.
@@ -295,7 +300,7 @@ void arith_decode_init(struct jbg_ardec_state *s, int reuse_st)
  *   decoded.
  *
  * s->pscd_ptr == s->pscd_end - 1:
- * 
+ *
  *   The decoder has used up all provided PSCD bytes except for the
  *   very last byte, because that has the value 0xff. The decoder can
  *   at this point not yet tell whether this 0xff belongs to a
@@ -336,27 +341,27 @@ int arith_decode(struct jbg_ardec_state *s, int cx)
     while (s->ct <= 8 && s->ct >= 0) {
       /* first we can move a new byte into s->c */
       if (s->pscd_ptr >= s->pscd_end) {
-	return -1;  /* more bytes needed */
+        return -1;  /* more bytes needed */
       }
-      if (*s->pscd_ptr == 0xff) 
-	if (s->pscd_ptr + 1 >= s->pscd_end) {
-	  return -1; /* final 0xff byte not processed */
-	} else {
-	  if (*(s->pscd_ptr + 1) == MARKER_STUFF) {
-	    s->c |= 0xffL << (8 - s->ct);
-	    s->ct += 8;
-	    s->pscd_ptr += 2;
-	  } else {
-	    s->ct = -1; /* start padding with zero bytes */
-	    if (s->nopadding) {
-	      s->nopadding = 0;
-	      return -2; /* subsequent symbols might depend on zero padding */
-	    }
-	  }
-	}
+      if (*s->pscd_ptr == 0xff)
+        if (s->pscd_ptr + 1 >= s->pscd_end) {
+          return -1; /* final 0xff byte not processed */
+        } else {
+          if (*(s->pscd_ptr + 1) == MARKER_STUFF) {
+            s->c |= 0xffL << (8 - s->ct);
+            s->ct += 8;
+            s->pscd_ptr += 2;
+          } else {
+            s->ct = -1; /* start padding with zero bytes */
+            if (s->nopadding) {
+              s->nopadding = 0;
+              return -2; /* subsequent symbols might depend on zero padding */
+            }
+          }
+        }
       else {
-	s->c |= (long)*(s->pscd_ptr++) << (8 - s->ct);
-	s->ct += 8;
+        s->c |= (long)*(s->pscd_ptr++) << (8 - s->ct);
+        s->ct += 8;
       }
     }
     s->c <<= 1;
@@ -373,8 +378,8 @@ int arith_decode(struct jbg_ardec_state *s, int cx)
 
 #if 0
   fprintf(stderr, "cx = %d, mps = %d, st = %3d, lsz = 0x%04x, a = 0x%05lx, "
-	  "c = 0x%08lx, ct = %2d\n",
-	  cx, !!(s->st[cx] & 0x80), ss, lsz, s->a, s->c, s->ct);
+          "c = 0x%08lx, ct = %2d\n",
+          cx, !!(s->st[cx] & 0x80), ss, lsz, s->a, s->c, s->ct);
 #endif
 
   if ((s->c >> 16) < (s->a -= lsz))
@@ -383,15 +388,15 @@ int arith_decode(struct jbg_ardec_state *s, int cx)
     else {
       /* MPS_EXCHANGE */
       if (s->a < lsz) {
-	pix = 1 - (*st >> 7);
-	/* Check whether MPS/LPS exchange is necessary
-	 * and chose next probability estimator status */
-	*st &= 0x80;
-	*st ^= nlpstab[ss];
+        pix = 1 - (*st >> 7);
+        /* Check whether MPS/LPS exchange is necessary
+         * and chose next probability estimator status */
+        *st &= 0x80;
+        *st ^= nlpstab[ss];
       } else {
-	pix = *st >> 7;
-	*st &= 0x80;
-	*st |= nmpstab[ss];
+        pix = *st >> 7;
+        *st &= 0x80;
+        *st |= nmpstab[ss];
       }
     }
   else {
@@ -415,3 +420,6 @@ int arith_decode(struct jbg_ardec_state *s, int cx)
 
   return pix;
 }
+
+
+
diff --git a/converter/other/jbig/pnmtojbig.c b/converter/other/jbig/pnmtojbig.c
index f5188c7b..ebdb4993 100644
--- a/converter/other/jbig/pnmtojbig.c
+++ b/converter/other/jbig/pnmtojbig.c
@@ -1,6 +1,6 @@
 /*
     pnmtojbig - PNM to JBIG converter
-  
+
     This program was derived from pbmtojbg.c in Markus Kuhn's
     JBIG-KIT package by Bryan Henderson on 2000.05.11
 
@@ -34,7 +34,7 @@
      bits in it.
 
 */
-  
+
 #include <stdio.h>
 #include <stdlib.h>
 #include <ctype.h>
@@ -44,7 +44,7 @@
 #include "mallocvar.h"
 #include "pnm.h"
 
-static unsigned long total_length = 0;  
+static unsigned long total_length = 0;
   /* used for determining output file length */
 
 /*
@@ -54,16 +54,17 @@ static void
 *checkedmalloc(size_t n)
 {
   void *p;
-  
+
   if ((p = malloc(n)) == NULL) {
     fprintf(stderr, "Sorry, not enough memory available!\n");
     exit(1);
   }
-  
+
   return p;
 }
 
 
+
 /*
  * Callback procedure which is used by JBIG encoder to deliver the
  * encoded data. It simply sends the bytes to the output file.
@@ -92,13 +93,13 @@ readPbm(FILE *            const fin,
     int row;
     bitmap = (unsigned char **) checkedmalloc(sizeof(unsigned char *));
     bitmap[0] = (unsigned char *) checkedmalloc(bytes_per_line * rows);
-    
+
     for (row = 0; row < rows; row++)
         pbm_readpbmrow_packed(fin, &bitmap[0][row*bytes_per_line],
                               cols, RPBM_FORMAT);
 
     *bitmapP = bitmap;
-} 
+}
 
 
 
@@ -121,7 +122,7 @@ readImage(FILE * const fin,
            pixel.  The 'bpp' bytes for each pixel are arranged MSB first
            and its numerical value is the value from the PNM input.
            The pixels are laid out in row-major format in this rectangle.
-           
+
            The point of this data structure is it is what jbg_split_planes()
            wants for input.
         */
@@ -130,7 +131,7 @@ readImage(FILE * const fin,
 
     pnm_row = pnm_allocrow(cols);  /* row buffer */
     MALLOCARRAY_NOFAIL(image, cols * rows * bpp);
-    
+
     for (row = 0; row < rows; ++row) {
         unsigned int col;
         pnm_readpnmrow(fin, pnm_row, cols, maxval, format);
@@ -145,7 +146,7 @@ readImage(FILE * const fin,
     pnm_freerow(pnm_row);
     *imageP = image;
 }
-      
+
 
 
 static void
@@ -154,12 +155,12 @@ convertImageToBitmap(unsigned char *   const image,
                      unsigned int      const encode_planes,
                      unsigned int      const bytes_per_line,
                      unsigned int      const lines) {
-    
+
     /* Convert image[] into bitmap[]  */
-    
+
     unsigned char ** bitmap;
     unsigned int i;
-    
+
     MALLOCARRAY_NOFAIL(bitmap, encode_planes);
     for (i = 0; i < encode_planes; ++i)
         MALLOCARRAY_NOFAIL(bitmap[i], bytes_per_line * lines);
@@ -193,10 +194,10 @@ readPnm(FILE *            const fin,
     jbg_split_planes(cols, rows, planes, encode_planes, image, bitmap,
                      use_graycode);
     free(image);
-    
+
     /* Invert the image if it is just one plane.  See top of this file
        for an explanation why.  Because of the separate handling of PBM,
-       this is for exceptional PGM files.  
+       this is for exceptional PGM files.
     */
 
     if (encode_planes == 1) {
@@ -206,7 +207,7 @@ readPnm(FILE *            const fin,
             for (i = 0; i < bytes_per_line; i++)
                 bitmap[0][(row*bytes_per_line) + i] ^= 0xff;
 
-            if (cols % 8 > 0) {   
+            if (cols % 8 > 0) {
                 bitmap[0][ (row+1)*bytes_per_line  -1] >>= 8-cols%8;
                 bitmap[0][ (row+1)*bytes_per_line  -1] <<= 8-cols%8;
             }
@@ -230,7 +231,7 @@ main(int argc, char **argv) {
     unsigned char **bitmap;
     /* This is an array of the planes of the image.  Each plane is a
        two-dimensional array of pixels laid out in row-major format.
-       format with each pixel being one bit.  A byte in the array 
+       format with each pixel being one bit.  A byte in the array
        contains 8 pixels left to right, msb to lsb.
     */
 
@@ -372,8 +373,8 @@ main(int argc, char **argv) {
     /* In a JBIG file, maxvals are determined only by the number of planes,
        so must be a power of 2 minus 1
     */
-  
-    if ((1UL << planes)-1 != maxval) 
+
+    if ((1UL << planes)-1 != maxval)
         pm_error("Input image has unacceptable maxval: %d.  JBIG files must "
                  "have a maxval which is a power of 2 minus 1.  Use "
                  "Ppmdepth to adjust the image's maxval", maxval);
@@ -386,8 +387,8 @@ main(int argc, char **argv) {
     if (bpp == 1 && PNM_FORMAT_TYPE(format) == PBM_TYPE)
         readPbm(fin, cols, rows, &bitmap);
     else
-        readPnm(fin, cols, rows, maxval, format, bpp, 
-                planes, encode_planes, use_graycode, 
+        readPnm(fin, cols, rows, maxval, format, bpp,
+                planes, encode_planes, use_graycode,
                 &bitmap);
 
     /* Apply JBIG algorithm and write BIE to output file */
@@ -461,3 +462,6 @@ main(int argc, char **argv) {
 
     return 0;
 }
+
+
+
diff --git a/converter/other/jpeg2000/libjasper/base/jas_debug.c b/converter/other/jpeg2000/libjasper/base/jas_debug.c
index 4248178f..1bfdef51 100644
--- a/converter/other/jpeg2000/libjasper/base/jas_debug.c
+++ b/converter/other/jpeg2000/libjasper/base/jas_debug.c
@@ -4,14 +4,14 @@
  */
 
 /* __START_OF_JASPER_LICENSE__
- * 
+ *
  * JasPer Software License
- * 
+ *
  * IMAGE POWER JPEG-2000 PUBLIC LICENSE
  * ************************************
- * 
+ *
  * GRANT:
- * 
+ *
  * Permission is hereby granted, free of charge, to any person (the "User")
  * obtaining a copy of this software and associated documentation, to deal
  * in the JasPer Software without restriction, including without limitation
@@ -19,22 +19,22 @@
  * and/or sell copies of the JasPer Software (in source and binary forms),
  * and to permit persons to whom the JasPer Software is furnished to do so,
  * provided further that the License Conditions below are met.
- * 
+ *
  * License Conditions
  * ******************
- * 
+ *
  * A.  Redistributions of source code must retain the above copyright notice,
  * and this list of conditions, and the following disclaimer.
- * 
+ *
  * B.  Redistributions in binary form must reproduce the above copyright
  * notice, and this list of conditions, and the following disclaimer in
  * the documentation and/or other materials provided with the distribution.
- * 
+ *
  * C.  Neither the name of Image Power, Inc. nor any other contributor
  * (including, but not limited to, the University of British Columbia and
  * Michael David Adams) may be used to endorse or promote products derived
  * from this software without specific prior written permission.
- * 
+ *
  * D.  User agrees that it shall not commence any action against Image Power,
  * Inc., the University of British Columbia, Michael David Adams, or any
  * other contributors (collectively "Licensors") for infringement of any
@@ -54,17 +54,17 @@
  * trade dress, or service mark rights); and (v) divisions, continuations,
  * renewals, reissues and extensions of the foregoing (as and to the extent
  * applicable) now existing, hereafter filed, issued or acquired.
- * 
+ *
  * E.  If User commences an infringement action against any Licensor(s) then
  * such Licensor(s) shall have the right to terminate User's license and
  * all sublicenses that have been granted hereunder by User to other parties.
- * 
+ *
  * F.  This software is for use only in hardware or software products that
  * are compliant with ISO/IEC 15444-1 (i.e., JPEG-2000 Part 1).  No license
  * or right to this Software is granted for products that do not comply
  * with ISO/IEC 15444-1.  The JPEG-2000 Part 1 standard can be purchased
  * from the ISO.
- * 
+ *
  * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS LICENSE.
  * NO USE OF THE JASPER SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER
  * THIS DISCLAIMER.  THE JASPER SOFTWARE IS PROVIDED BY THE LICENSORS AND
@@ -104,7 +104,7 @@
  * TECHNOLOGY OR PRODUCTS FOR HIGH RISK ACTIVITIES AND WILL ENSURE THAT ITS
  * CUSTOMERS AND END-USERS OF ITS PRODUCTS ARE PROVIDED WITH A COPY OF THE
  * NOTICE SPECIFIED IN THIS SECTION.
- * 
+ *
  * __END_OF_JASPER_LICENSE__
  */
 
@@ -132,22 +132,22 @@ static int jas_dbglevel = 0;
 /* Set the library debug level. */
 int jas_setdbglevel(int dbglevel)
 {
-	int olddbglevel;
+        int olddbglevel;
 
-	/* Save the old debug level. */
-	olddbglevel = jas_dbglevel;
+        /* Save the old debug level. */
+        olddbglevel = jas_dbglevel;
 
-	/* Change the debug level. */
-	jas_dbglevel = dbglevel;
+        /* Change the debug level. */
+        jas_dbglevel = dbglevel;
 
-	/* Return the old debug level. */
-	return olddbglevel;
+        /* Return the old debug level. */
+        return olddbglevel;
 }
 
 /* Get the library debug level. */
 int jas_getdbglevel()
 {
-	return jas_dbglevel;
+        return jas_dbglevel;
 }
 
 /******************************************************************************\
@@ -157,30 +157,30 @@ int jas_getdbglevel()
 /* Perform formatted output to standard error. */
 int jas_eprintf(const char *fmt, ...)
 {
-	int ret;
-	va_list ap;
+        int ret;
+        va_list ap;
 
-	va_start(ap, fmt);
-	ret = vfprintf(stderr, fmt, ap);
-	va_end(ap);
-	return ret;
+        va_start(ap, fmt);
+        ret = vfprintf(stderr, fmt, ap);
+        va_end(ap);
+        return ret;
 }
 
 /* Dump memory to a stream. */
 int jas_memdump(FILE *out, void *data, size_t len)
 {
-	int i;
-	int j;
-	unsigned char *dp;
-	dp = data;
-	for (i = 0; i < len; i += 16) {
-		fprintf(out, "%04x:", i);
-		for (j = 0; j < 16; ++j) {
-			if (i + j < len) {
-				fprintf(out, " %02x", dp[i + j]);
-			}
-		}
-		fprintf(out, "\n");
-	}
-	return 0;
+        int i;
+        int j;
+        unsigned char *dp;
+        dp = data;
+        for (i = 0; i < len; i += 16) {
+                fprintf(out, "%04x:", i);
+                for (j = 0; j < 16; ++j) {
+                        if (i + j < len) {
+                                fprintf(out, " %02x", dp[i + j]);
+                        }
+                }
+                fprintf(out, "\n");
+        }
+        return 0;
 }
diff --git a/converter/other/jpeg2000/libjasper/base/jas_getopt.c b/converter/other/jpeg2000/libjasper/base/jas_getopt.c
index 7f579b3e..e12340c2 100644
--- a/converter/other/jpeg2000/libjasper/base/jas_getopt.c
+++ b/converter/other/jpeg2000/libjasper/base/jas_getopt.c
@@ -2,18 +2,18 @@
  * Copyright (c) 1999-2000, Image Power, Inc. and the University of
  *   British Columbia.
  * Copyright (c) 2001-2002 Michael David Adams.
- * All rights reserved. 
+ * All rights reserved.
  */
 
 /* __START_OF_JASPER_LICENSE__
- * 
+ *
  * JasPer Software License
- * 
+ *
  * IMAGE POWER JPEG-2000 PUBLIC LICENSE
  * ************************************
- * 
+ *
  * GRANT:
- * 
+ *
  * Permission is hereby granted, free of charge, to any person (the "User")
  * obtaining a copy of this software and associated documentation, to deal
  * in the JasPer Software without restriction, including without limitation
@@ -21,22 +21,22 @@
  * and/or sell copies of the JasPer Software (in source and binary forms),
  * and to permit persons to whom the JasPer Software is furnished to do so,
  * provided further that the License Conditions below are met.
- * 
+ *
  * License Conditions
  * ******************
- * 
+ *
  * A.  Redistributions of source code must retain the above copyright notice,
  * and this list of conditions, and the following disclaimer.
- * 
+ *
  * B.  Redistributions in binary form must reproduce the above copyright
  * notice, and this list of conditions, and the following disclaimer in
  * the documentation and/or other materials provided with the distribution.
- * 
+ *
  * C.  Neither the name of Image Power, Inc. nor any other contributor
  * (including, but not limited to, the University of British Columbia and
  * Michael David Adams) may be used to endorse or promote products derived
  * from this software without specific prior written permission.
- * 
+ *
  * D.  User agrees that it shall not commence any action against Image Power,
  * Inc., the University of British Columbia, Michael David Adams, or any
  * other contributors (collectively "Licensors") for infringement of any
@@ -56,17 +56,17 @@
  * trade dress, or service mark rights); and (v) divisions, continuations,
  * renewals, reissues and extensions of the foregoing (as and to the extent
  * applicable) now existing, hereafter filed, issued or acquired.
- * 
+ *
  * E.  If User commences an infringement action against any Licensor(s) then
  * such Licensor(s) shall have the right to terminate User's license and
  * all sublicenses that have been granted hereunder by User to other parties.
- * 
+ *
  * F.  This software is for use only in hardware or software products that
  * are compliant with ISO/IEC 15444-1 (i.e., JPEG-2000 Part 1).  No license
  * or right to this Software is granted for products that do not comply
  * with ISO/IEC 15444-1.  The JPEG-2000 Part 1 standard can be purchased
  * from the ISO.
- * 
+ *
  * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS LICENSE.
  * NO USE OF THE JASPER SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER
  * THIS DISCLAIMER.  THE JASPER SOFTWARE IS PROVIDED BY THE LICENSORS AND
@@ -106,7 +106,7 @@
  * TECHNOLOGY OR PRODUCTS FOR HIGH RISK ACTIVITIES AND WILL ENSURE THAT ITS
  * CUSTOMERS AND END-USERS OF ITS PRODUCTS ARE PROVIDED WITH A COPY OF THE
  * NOTICE SPECIFIED IN THIS SECTION.
- * 
+ *
  * __END_OF_JASPER_LICENSE__
  */
 
@@ -140,78 +140,78 @@ char *jas_optarg = 0;
 
 static jas_opt_t *jas_optlookup(jas_opt_t *opts, char *name)
 {
-	jas_opt_t *opt;
+        jas_opt_t *opt;
 
-	for (opt = opts; opt->id >= 0 && opt->name; ++opt) {
-		if (!strcmp(opt->name, name)) {
-			return opt;
-		}
-	}
-	return 0;
+        for (opt = opts; opt->id >= 0 && opt->name; ++opt) {
+                if (!strcmp(opt->name, name)) {
+                        return opt;
+                }
+        }
+        return 0;
 }
 
 int jas_getopt(int argc, char **argv, jas_opt_t *opts)
 {
-	char *cp;
-	int id;
-	int hasarg;
-	jas_opt_t *opt;
-	char *s;
+        char *cp;
+        int id;
+        int hasarg;
+        jas_opt_t *opt;
+        char *s;
 
-	if (!jas_optind) {
-		jas_optind = JAS_MIN(1, argc);
-	}
-	while (jas_optind < argc) {
-		s = cp = argv[jas_optind];
-		if (*cp == '-') {
-			/* We are processing an option. */
-			++jas_optind;
-			if (*++cp == '-') {
-				/* We are processing a long option. */
-				++cp;
-				if (*cp == '\0') {
-					/* This is the end of the options. */
-					return JAS_GETOPT_EOF;
-				}
-				if (!(opt = jas_optlookup(opts, cp))) {
-					if (jas_opterr) {
-						fprintf(stderr, "unknown long option %s\n", s);
-					}
-					return JAS_GETOPT_ERR;
-				}
-				hasarg = (opt->flags & JAS_OPT_HASARG) != 0;
-				id = opt->id;
-			} else {
-				/* We are processing a short option. */
-				if (strlen(cp) != 1 ||
-				  !(opt = jas_optlookup(opts, cp))) {
-					if (jas_opterr) {
-						fprintf(stderr, "unknown short option %s\n", s);
-					}
-					return JAS_GETOPT_ERR;
-				}
-				hasarg = (opt->flags & JAS_OPT_HASARG) != 0;
-				id = opt->id;
-			}
-			if (hasarg) {
-				/* The option has an argument. */
-				if (jas_optind >= argc) {
-					if (jas_opterr) {
-						fprintf(stderr, "missing argument for option %s\n", s);
-					}
-					return JAS_GETOPT_ERR;
-				}
-				jas_optarg = argv[jas_optind];
-				++jas_optind;
-			} else {
-				/* The option does not have an argument. */
-				jas_optarg = 0;
-			}
-			return id;
-		} else {
-			/* We are not processing an option. */
-			return JAS_GETOPT_EOF;
-		}
-	}
-	return JAS_GETOPT_EOF;
+        if (!jas_optind) {
+                jas_optind = JAS_MIN(1, argc);
+        }
+        while (jas_optind < argc) {
+                s = cp = argv[jas_optind];
+                if (*cp == '-') {
+                        /* We are processing an option. */
+                        ++jas_optind;
+                        if (*++cp == '-') {
+                                /* We are processing a long option. */
+                                ++cp;
+                                if (*cp == '\0') {
+                                        /* This is the end of the options. */
+                                        return JAS_GETOPT_EOF;
+                                }
+                                if (!(opt = jas_optlookup(opts, cp))) {
+                                        if (jas_opterr) {
+                                                fprintf(stderr, "unknown long option %s\n", s);
+                                        }
+                                        return JAS_GETOPT_ERR;
+                                }
+                                hasarg = (opt->flags & JAS_OPT_HASARG) != 0;
+                                id = opt->id;
+                        } else {
+                                /* We are processing a short option. */
+                                if (strlen(cp) != 1 ||
+                                  !(opt = jas_optlookup(opts, cp))) {
+                                        if (jas_opterr) {
+                                                fprintf(stderr, "unknown short option %s\n", s);
+                                        }
+                                        return JAS_GETOPT_ERR;
+                                }
+                                hasarg = (opt->flags & JAS_OPT_HASARG) != 0;
+                                id = opt->id;
+                        }
+                        if (hasarg) {
+                                /* The option has an argument. */
+                                if (jas_optind >= argc) {
+                                        if (jas_opterr) {
+                                                fprintf(stderr, "missing argument for option %s\n", s);
+                                        }
+                                        return JAS_GETOPT_ERR;
+                                }
+                                jas_optarg = argv[jas_optind];
+                                ++jas_optind;
+                        } else {
+                                /* The option does not have an argument. */
+                                jas_optarg = 0;
+                        }
+                        return id;
+                } else {
+                        /* We are not processing an option. */
+                        return JAS_GETOPT_EOF;
+                }
+        }
+        return JAS_GETOPT_EOF;
 }
diff --git a/converter/other/jpeg2000/libjasper/base/jas_image.c b/converter/other/jpeg2000/libjasper/base/jas_image.c
index 5ee13a0d..49a0db79 100644
--- a/converter/other/jpeg2000/libjasper/base/jas_image.c
+++ b/converter/other/jpeg2000/libjasper/base/jas_image.c
@@ -6,14 +6,14 @@
  */
 
 /* __START_OF_JASPER_LICENSE__
- * 
+ *
  * JasPer Software License
- * 
+ *
  * IMAGE POWER JPEG-2000 PUBLIC LICENSE
  * ************************************
- * 
+ *
  * GRANT:
- * 
+ *
  * Permission is hereby granted, free of charge, to any person (the "User")
  * obtaining a copy of this software and associated documentation, to deal
  * in the JasPer Software without restriction, including without limitation
@@ -21,22 +21,22 @@
  * and/or sell copies of the JasPer Software (in source and binary forms),
  * and to permit persons to whom the JasPer Software is furnished to do so,
  * provided further that the License Conditions below are met.
- * 
+ *
  * License Conditions
  * ******************
- * 
+ *
  * A.  Redistributions of source code must retain the above copyright notice,
  * and this list of conditions, and the following disclaimer.
- * 
+ *
  * B.  Redistributions in binary form must reproduce the above copyright
  * notice, and this list of conditions, and the following disclaimer in
  * the documentation and/or other materials provided with the distribution.
- * 
+ *
  * C.  Neither the name of Image Power, Inc. nor any other contributor
  * (including, but not limited to, the University of British Columbia and
  * Michael David Adams) may be used to endorse or promote products derived
  * from this software without specific prior written permission.
- * 
+ *
  * D.  User agrees that it shall not commence any action against Image Power,
  * Inc., the University of British Columbia, Michael David Adams, or any
  * other contributors (collectively "Licensors") for infringement of any
@@ -56,17 +56,17 @@
  * trade dress, or service mark rights); and (v) divisions, continuations,
  * renewals, reissues and extensions of the foregoing (as and to the extent
  * applicable) now existing, hereafter filed, issued or acquired.
- * 
+ *
  * E.  If User commences an infringement action against any Licensor(s) then
  * such Licensor(s) shall have the right to terminate User's license and
  * all sublicenses that have been granted hereunder by User to other parties.
- * 
+ *
  * F.  This software is for use only in hardware or software products that
  * are compliant with ISO/IEC 15444-1 (i.e., JPEG-2000 Part 1).  No license
  * or right to this Software is granted for products that do not comply
  * with ISO/IEC 15444-1.  The JPEG-2000 Part 1 standard can be purchased
  * from the ISO.
- * 
+ *
  * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS LICENSE.
  * NO USE OF THE JASPER SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER
  * THIS DISCLAIMER.  THE JASPER SOFTWARE IS PROVIDED BY THE LICENSORS AND
@@ -106,7 +106,7 @@
  * TECHNOLOGY OR PRODUCTS FOR HIGH RISK ACTIVITIES AND WILL ENSURE THAT ITS
  * CUSTOMERS AND END-USERS OF ITS PRODUCTS ARE PROVIDED WITH A COPY OF THE
  * NOTICE SPECIFIED IN THIS SECTION.
- * 
+ *
  * __END_OF_JASPER_LICENSE__
  */
 
@@ -166,215 +166,215 @@ static jas_image_fmtinfo_t jas_image_fmtinfos[JAS_IMAGE_MAXFMTS];
 jas_image_t *jas_image_create(uint_fast16_t numcmpts, jas_image_cmptparm_t *cmptparms,
   int colorspace)
 {
-	jas_image_t *image;
-	uint_fast32_t rawsize;
-	uint_fast32_t inmem;
-	uint_fast16_t cmptno;
-	jas_image_cmptparm_t *cmptparm;
-
-	if (!(image = jas_image_create0())) {
-		return 0;
-	}
-
-	image->colorspace_ = colorspace;
-	image->maxcmpts_ = numcmpts;
-	image->inmem_ = true;
-
-	/* Allocate memory for the per-component information. */
-	if (!(image->cmpts_ = jas_malloc(image->maxcmpts_ *
-	  sizeof(jas_image_cmpt_t *)))) {
-		jas_image_destroy(image);
-		return 0;
-	}
-	/* Initialize in case of failure. */
-	for (cmptno = 0; cmptno < image->maxcmpts_; ++cmptno) {
-		image->cmpts_[cmptno] = 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);
-
-	/* Create the individual image components. */
-	for (cmptno = 0, cmptparm = cmptparms; cmptno < numcmpts; ++cmptno,
-	  ++cmptparm) {
-		if (!(image->cmpts_[cmptno] = jas_image_cmpt_create(cmptparm->tlx,
-		  cmptparm->tly, cmptparm->hstep, cmptparm->vstep,
-		  cmptparm->width, cmptparm->height, cmptparm->prec,
-		  cmptparm->sgnd, inmem))) {
-			jas_image_destroy(image);
-			return 0;
-		}
-		++image->numcmpts_;
-	}
-
-	/* Determine the bounding box for all of the components on the
-	  reference grid (i.e., the image area) */
-	jas_image_setbbox(image);
-
-	return image;
+        jas_image_t *image;
+        uint_fast32_t rawsize;
+        uint_fast32_t inmem;
+        uint_fast16_t cmptno;
+        jas_image_cmptparm_t *cmptparm;
+
+        if (!(image = jas_image_create0())) {
+                return 0;
+        }
+
+        image->colorspace_ = colorspace;
+        image->maxcmpts_ = numcmpts;
+        image->inmem_ = true;
+
+        /* Allocate memory for the per-component information. */
+        if (!(image->cmpts_ = jas_malloc(image->maxcmpts_ *
+          sizeof(jas_image_cmpt_t *)))) {
+                jas_image_destroy(image);
+                return 0;
+        }
+        /* Initialize in case of failure. */
+        for (cmptno = 0; cmptno < image->maxcmpts_; ++cmptno) {
+                image->cmpts_[cmptno] = 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);
+
+        /* Create the individual image components. */
+        for (cmptno = 0, cmptparm = cmptparms; cmptno < numcmpts; ++cmptno,
+          ++cmptparm) {
+                if (!(image->cmpts_[cmptno] = jas_image_cmpt_create(cmptparm->tlx,
+                  cmptparm->tly, cmptparm->hstep, cmptparm->vstep,
+                  cmptparm->width, cmptparm->height, cmptparm->prec,
+                  cmptparm->sgnd, inmem))) {
+                        jas_image_destroy(image);
+                        return 0;
+                }
+                ++image->numcmpts_;
+        }
+
+        /* Determine the bounding box for all of the components on the
+          reference grid (i.e., the image area) */
+        jas_image_setbbox(image);
+
+        return image;
 }
 
 jas_image_t *jas_image_create0()
 {
-	jas_image_t *image;
+        jas_image_t *image;
 
-	if (!(image = jas_malloc(sizeof(jas_image_t)))) {
-		return 0;
-	}
+        if (!(image = jas_malloc(sizeof(jas_image_t)))) {
+                return 0;
+        }
 
-	image->tlx_ = 0;
-	image->tly_ = 0;
-	image->brx_ = 0;
-	image->bry_ = 0;
-	image->colorspace_ = JAS_IMAGE_CS_UNKNOWN;
-	image->numcmpts_ = 0;
-	image->maxcmpts_ = 0;
-	image->cmpts_ = 0;
-	image->inmem_ = true;
-	image->iccp_ = 0;
-	image->iccplen_ = 0;
+        image->tlx_ = 0;
+        image->tly_ = 0;
+        image->brx_ = 0;
+        image->bry_ = 0;
+        image->colorspace_ = JAS_IMAGE_CS_UNKNOWN;
+        image->numcmpts_ = 0;
+        image->maxcmpts_ = 0;
+        image->cmpts_ = 0;
+        image->inmem_ = true;
+        image->iccp_ = 0;
+        image->iccplen_ = 0;
 
-	return image;
+        return image;
 }
 
 jas_image_t *jas_image_copy(jas_image_t *image)
 {
-	jas_image_t *newimage;
-	int cmptno;
+        jas_image_t *newimage;
+        int cmptno;
 
-	newimage = jas_image_create0();
-	if (jas_image_growcmpts(newimage, image->numcmpts_)) {
-		goto error;
-	}
-	for (cmptno = 0; cmptno < image->numcmpts_; ++cmptno) {
-		if (!(newimage->cmpts_[cmptno] = jas_image_cmpt_copy(image->cmpts_[cmptno]))) {
-			goto error;
-		}
-		++newimage->numcmpts_;
-	}
+        newimage = jas_image_create0();
+        if (jas_image_growcmpts(newimage, image->numcmpts_)) {
+                goto error;
+        }
+        for (cmptno = 0; cmptno < image->numcmpts_; ++cmptno) {
+                if (!(newimage->cmpts_[cmptno] = jas_image_cmpt_copy(image->cmpts_[cmptno]))) {
+                        goto error;
+                }
+                ++newimage->numcmpts_;
+        }
 
-	jas_image_setbbox(newimage);
+        jas_image_setbbox(newimage);
 
-	return newimage;
+        return newimage;
 error:
-	if (newimage) {
-		jas_image_destroy(newimage);
-	}
-	return 0;
+        if (newimage) {
+                jas_image_destroy(newimage);
+        }
+        return 0;
 }
 
 static jas_image_cmpt_t *jas_image_cmpt_create0()
 {
-	jas_image_cmpt_t *cmpt;
-	if (!(cmpt = jas_malloc(sizeof(jas_image_cmpt_t)))) {
-		return 0;
-	}
-	memset(cmpt, 0, sizeof(jas_image_cmpt_t));
-	cmpt->type_ = JAS_IMAGE_CT_UNKNOWN;
-	return cmpt;
+        jas_image_cmpt_t *cmpt;
+        if (!(cmpt = jas_malloc(sizeof(jas_image_cmpt_t)))) {
+                return 0;
+        }
+        memset(cmpt, 0, sizeof(jas_image_cmpt_t));
+        cmpt->type_ = JAS_IMAGE_CT_UNKNOWN;
+        return cmpt;
 }
 
 static jas_image_cmpt_t *jas_image_cmpt_copy(jas_image_cmpt_t *cmpt)
 {
-	jas_image_cmpt_t *newcmpt;
-
-	if (!(newcmpt = jas_image_cmpt_create0())) {
-		return 0;
-	}
-	newcmpt->tlx_ = cmpt->tlx_;
-	newcmpt->tly_ = cmpt->tly_;
-	newcmpt->hstep_ = cmpt->hstep_;
-	newcmpt->vstep_ = cmpt->vstep_;
-	newcmpt->width_ = cmpt->width_;
-	newcmpt->height_ = cmpt->height_;
-	newcmpt->prec_ = cmpt->prec_;
-	newcmpt->sgnd_ = cmpt->sgnd_;
-	newcmpt->cps_ = cmpt->cps_;
-	newcmpt->type_ = cmpt->type_;
-	if (!(newcmpt->stream_ = jas_stream_memopen(0, 0))) {
-		return 0;
-	}
-	if (jas_stream_seek(cmpt->stream_, 0, SEEK_SET)) {
-		return 0;
-	}
-	if (jas_stream_copy(newcmpt->stream_, cmpt->stream_, -1)) {
-		return 0;
-	}
-	if (jas_stream_seek(newcmpt->stream_, 0, SEEK_SET)) {
-		return 0;
-	}
-	return newcmpt;
+        jas_image_cmpt_t *newcmpt;
+
+        if (!(newcmpt = jas_image_cmpt_create0())) {
+                return 0;
+        }
+        newcmpt->tlx_ = cmpt->tlx_;
+        newcmpt->tly_ = cmpt->tly_;
+        newcmpt->hstep_ = cmpt->hstep_;
+        newcmpt->vstep_ = cmpt->vstep_;
+        newcmpt->width_ = cmpt->width_;
+        newcmpt->height_ = cmpt->height_;
+        newcmpt->prec_ = cmpt->prec_;
+        newcmpt->sgnd_ = cmpt->sgnd_;
+        newcmpt->cps_ = cmpt->cps_;
+        newcmpt->type_ = cmpt->type_;
+        if (!(newcmpt->stream_ = jas_stream_memopen(0, 0))) {
+                return 0;
+        }
+        if (jas_stream_seek(cmpt->stream_, 0, SEEK_SET)) {
+                return 0;
+        }
+        if (jas_stream_copy(newcmpt->stream_, cmpt->stream_, -1)) {
+                return 0;
+        }
+        if (jas_stream_seek(newcmpt->stream_, 0, SEEK_SET)) {
+                return 0;
+        }
+        return newcmpt;
 }
 
 void jas_image_destroy(jas_image_t *image)
 {
-	int i;
+        int i;
 
-	if (image->cmpts_) {
-		for (i = 0; i < image->numcmpts_; ++i) {
-			jas_image_cmpt_destroy(image->cmpts_[i]);
-			image->cmpts_[i] = 0;
-		}
-		jas_free(image->cmpts_);
-	}
-	jas_free(image);
+        if (image->cmpts_) {
+                for (i = 0; i < image->numcmpts_; ++i) {
+                        jas_image_cmpt_destroy(image->cmpts_[i]);
+                        image->cmpts_[i] = 0;
+                }
+                jas_free(image->cmpts_);
+        }
+        jas_free(image);
 }
 
 static jas_image_cmpt_t *jas_image_cmpt_create(uint_fast32_t tlx, uint_fast32_t tly,
   uint_fast32_t hstep, uint_fast32_t vstep, uint_fast32_t width, uint_fast32_t
   height, uint_fast16_t depth, bool sgnd, uint_fast32_t inmem)
 {
-	jas_image_cmpt_t *cmpt;
-	long size;
-
-	if (!(cmpt = jas_malloc(sizeof(jas_image_cmpt_t)))) {
-		return 0;
-	}
-
-	cmpt->tlx_ = tlx;
-	cmpt->tly_ = tly;
-	cmpt->hstep_ = hstep;
-	cmpt->vstep_ = vstep;
-	cmpt->width_ = width;
-	cmpt->height_ = height;
-	cmpt->prec_ = depth;
-	cmpt->sgnd_ = sgnd;
-	cmpt->stream_ = 0;
-	cmpt->cps_ = (depth + 7) / 8;
-
-	size = cmpt->width_ * cmpt->height_ * cmpt->cps_;
-	cmpt->stream_ = (inmem) ? jas_stream_memopen(0, size) : jas_stream_tmpfile();
-	if (!cmpt->stream_) {
-		jas_image_cmpt_destroy(cmpt);
-		return 0;
-	}
-
-	/* Zero the component data.  This isn't necessary, but it is
-	convenient for debugging purposes. */
-	if (jas_stream_seek(cmpt->stream_, size - 1, SEEK_SET) < 0 ||
-	  jas_stream_putc(cmpt->stream_, 0) == EOF ||
-	  jas_stream_seek(cmpt->stream_, 0, SEEK_SET) < 0) {
-		jas_image_cmpt_destroy(cmpt);
-		return 0;
-	}
-
-	return cmpt;
+        jas_image_cmpt_t *cmpt;
+        long size;
+
+        if (!(cmpt = jas_malloc(sizeof(jas_image_cmpt_t)))) {
+                return 0;
+        }
+
+        cmpt->tlx_ = tlx;
+        cmpt->tly_ = tly;
+        cmpt->hstep_ = hstep;
+        cmpt->vstep_ = vstep;
+        cmpt->width_ = width;
+        cmpt->height_ = height;
+        cmpt->prec_ = depth;
+        cmpt->sgnd_ = sgnd;
+        cmpt->stream_ = 0;
+        cmpt->cps_ = (depth + 7) / 8;
+
+        size = cmpt->width_ * cmpt->height_ * cmpt->cps_;
+        cmpt->stream_ = (inmem) ? jas_stream_memopen(0, size) : jas_stream_tmpfile();
+        if (!cmpt->stream_) {
+                jas_image_cmpt_destroy(cmpt);
+                return 0;
+        }
+
+        /* Zero the component data.  This isn't necessary, but it is
+        convenient for debugging purposes. */
+        if (jas_stream_seek(cmpt->stream_, size - 1, SEEK_SET) < 0 ||
+          jas_stream_putc(cmpt->stream_, 0) == EOF ||
+          jas_stream_seek(cmpt->stream_, 0, SEEK_SET) < 0) {
+                jas_image_cmpt_destroy(cmpt);
+                return 0;
+        }
+
+        return cmpt;
 }
 
 static void jas_image_cmpt_destroy(jas_image_cmpt_t *cmpt)
 {
-	if (cmpt->stream_) {
-		jas_stream_close(cmpt->stream_);
-	}
-	jas_free(cmpt);
+        if (cmpt->stream_) {
+                jas_stream_close(cmpt->stream_);
+        }
+        jas_free(cmpt);
 }
 
 /*****************************************************************************\
@@ -383,53 +383,53 @@ static void jas_image_cmpt_destroy(jas_image_cmpt_t *cmpt)
 
 void
 pmjas_image_decode(jas_stream_t * const in,
-				   int            const fmtArg,
-				   const char *   const optstr,
-				   jas_image_t ** const imagePP,
-				   const char **  const errorP) {
+                                   int            const fmtArg,
+                                   const char *   const optstr,
+                                   jas_image_t ** const imagePP,
+                                   const char **  const errorP) {
 /*----------------------------------------------------------------------------
   Create an image from a stream in some specified format
 -----------------------------------------------------------------------------*/
-	jas_image_fmtinfo_t *fmtinfo;
-	int fmt;
-
-	/* If possible, try to determine the format of the input data. */
-	if (fmtArg < 0) {
-		if ((fmt = jas_image_getfmt(in)) < 0) {
-			pm_asprintf(errorP, "jas_image_getfmt failed");
-			return;
-		}
-	} else
-		fmt = fmtArg;
-
-	if (!(fmtinfo = jas_image_lookupfmtbyid(fmt))) {
-		pm_asprintf(errorP, "jas_image_lookupfmtbyid of format %d failed",
-					fmt);
-		return;
-	}
-	{
-		const char * error;
-
-		(*fmtinfo->ops.decode)(in, optstr, imagePP, &error);
-		if (error) {
-			pm_asprintf(errorP, "decoder failed.  %s", error);
-			pm_strfree(error);
-		} else {
-			*errorP = NULL;
-		}
-	}
+        jas_image_fmtinfo_t *fmtinfo;
+        int fmt;
+
+        /* If possible, try to determine the format of the input data. */
+        if (fmtArg < 0) {
+                if ((fmt = jas_image_getfmt(in)) < 0) {
+                        pm_asprintf(errorP, "jas_image_getfmt failed");
+                        return;
+                }
+        } else
+                fmt = fmtArg;
+
+        if (!(fmtinfo = jas_image_lookupfmtbyid(fmt))) {
+                pm_asprintf(errorP, "jas_image_lookupfmtbyid of format %d failed",
+                                        fmt);
+                return;
+        }
+        {
+                const char * error;
+
+                (*fmtinfo->ops.decode)(in, optstr, imagePP, &error);
+                if (error) {
+                        pm_asprintf(errorP, "decoder failed.  %s", error);
+                        pm_strfree(error);
+                } else {
+                        *errorP = NULL;
+                }
+        }
 }
 
 
 
 int jas_image_encode(jas_image_t *image, jas_stream_t *out, int fmt, char *optstr)
 {
-	jas_image_fmtinfo_t *fmtinfo;
-	if (!(fmtinfo = jas_image_lookupfmtbyid(fmt))) {
-		return -1;
-	}
-	return (fmtinfo->ops.encode) ? (*fmtinfo->ops.encode)(image, out,
-	  optstr) : (-1);
+        jas_image_fmtinfo_t *fmtinfo;
+        if (!(fmtinfo = jas_image_lookupfmtbyid(fmt))) {
+                return -1;
+        }
+        return (fmtinfo->ops.encode) ? (*fmtinfo->ops.encode)(image, out,
+          optstr) : (-1);
 }
 
 /******************************************************************************\
@@ -439,137 +439,137 @@ int jas_image_encode(jas_image_t *image, jas_stream_t *out, int fmt, char *optst
 int jas_image_readcmpt(jas_image_t *image, uint_fast16_t cmptno, uint_fast32_t x, uint_fast32_t y, uint_fast32_t width,
   uint_fast32_t height, jas_matrix_t *data)
 {
-	jas_image_cmpt_t *cmpt;
-	uint_fast32_t i;
-	uint_fast32_t j;
-	int k;
-	jas_seqent_t v;
-	int c;
-	jas_seqent_t *dr;
-	jas_seqent_t *d;
-	int drs;
-
-	if (cmptno >= image->numcmpts_) {
-		return -1;
-	}
-
-	cmpt = image->cmpts_[cmptno];
-	if (x >= cmpt->width_ || y >= cmpt->height_ ||
-	  x + width > cmpt->width_ ||
-	  y + height > cmpt->height_) {
-		return -1;
-	}
-
-	if (jas_matrix_numrows(data) != height || jas_matrix_numcols(data) != width) {
-		if (jas_matrix_resize(data, height, width)) {
-			return -1;
-		}
-	}
-
-	dr = jas_matrix_getref(data, 0, 0);
-	drs = jas_matrix_rowstep(data);
-	for (i = 0; i < height; ++i, dr += drs) {
-		d = dr;
-		if (jas_stream_seek(cmpt->stream_, (cmpt->width_ * (y + i) + x)
-		  * cmpt->cps_, SEEK_SET) < 0) {
-			return -1;
-		}
-		for (j = width; j > 0; --j, ++d) {
-			v = 0;
-			for (k = cmpt->cps_; k > 0; --k) {
-				if ((c = jas_stream_getc(cmpt->stream_)) == EOF) {
-					return -1;
-				}
-				v = (v << 8) | (c & 0xff);
-			}
-			*d = bitstoint(v, cmpt->prec_, cmpt->sgnd_);
-		}
-	}
-
-	return 0;
+        jas_image_cmpt_t *cmpt;
+        uint_fast32_t i;
+        uint_fast32_t j;
+        int k;
+        jas_seqent_t v;
+        int c;
+        jas_seqent_t *dr;
+        jas_seqent_t *d;
+        int drs;
+
+        if (cmptno >= image->numcmpts_) {
+                return -1;
+        }
+
+        cmpt = image->cmpts_[cmptno];
+        if (x >= cmpt->width_ || y >= cmpt->height_ ||
+          x + width > cmpt->width_ ||
+          y + height > cmpt->height_) {
+                return -1;
+        }
+
+        if (jas_matrix_numrows(data) != height || jas_matrix_numcols(data) != width) {
+                if (jas_matrix_resize(data, height, width)) {
+                        return -1;
+                }
+        }
+
+        dr = jas_matrix_getref(data, 0, 0);
+        drs = jas_matrix_rowstep(data);
+        for (i = 0; i < height; ++i, dr += drs) {
+                d = dr;
+                if (jas_stream_seek(cmpt->stream_, (cmpt->width_ * (y + i) + x)
+                  * cmpt->cps_, SEEK_SET) < 0) {
+                        return -1;
+                }
+                for (j = width; j > 0; --j, ++d) {
+                        v = 0;
+                        for (k = cmpt->cps_; k > 0; --k) {
+                                if ((c = jas_stream_getc(cmpt->stream_)) == EOF) {
+                                        return -1;
+                                }
+                                v = (v << 8) | (c & 0xff);
+                        }
+                        *d = bitstoint(v, cmpt->prec_, cmpt->sgnd_);
+                }
+        }
+
+        return 0;
 }
 
 #if 0
 int_fast64_t jas_image_readcmpt1(jas_image_t *image, uint_fast16_t cmptno,
   uint_fast32_t x, uint_fast32_t y)
 {
-	jas_image_cmpt_t *cmpt;
-	int k;
-	int c;
-	int_fast64_t v;
-	cmpt = image->cmpts_[cmptno];
-	if (jas_stream_seek(cmpt->stream_, (cmpt->width_ * y + x) * cmpt->cps_,
-	  SEEK_SET) < 0) {
-		goto error;
-	}
-	v = 0;
-	for (k = cmpt->cps_; k > 0; --k) {
-		if ((c = jas_stream_getc(cmpt->stream_)) == EOF) {
-			goto error;
-		}
-		v = (v << 8) | (c & 0xff);
-	}
+        jas_image_cmpt_t *cmpt;
+        int k;
+        int c;
+        int_fast64_t v;
+        cmpt = image->cmpts_[cmptno];
+        if (jas_stream_seek(cmpt->stream_, (cmpt->width_ * y + x) * cmpt->cps_,
+          SEEK_SET) < 0) {
+                goto error;
+        }
+        v = 0;
+        for (k = cmpt->cps_; k > 0; --k) {
+                if ((c = jas_stream_getc(cmpt->stream_)) == EOF) {
+                        goto error;
+                }
+                v = (v << 8) | (c & 0xff);
+        }
 if (cmpt->sgnd_) {
-	abort();
+        abort();
 }
 
-	return v;
+        return v;
 
 error:
-	return 0;
+        return 0;
 }
 #endif
 
 int jas_image_writecmpt(jas_image_t *image, uint_fast16_t cmptno, uint_fast32_t x, uint_fast32_t y, uint_fast32_t width,
   uint_fast32_t height, jas_matrix_t *data)
 {
-	jas_image_cmpt_t *cmpt;
-	uint_fast32_t i;
-	uint_fast32_t j;
-	jas_seqent_t *d;
-	jas_seqent_t *dr;
-	int drs;
-	jas_seqent_t v;
-	int k;
-	int c;
-
-	if (cmptno >= image->numcmpts_) {
-		return -1;
-	}
-
-	cmpt = image->cmpts_[cmptno];
-	if (x >= cmpt->width_ || y >= cmpt->height_ ||
-	  x + width > cmpt->width_ ||
-	  y + height > cmpt->height_) {
-		return -1;
-	}
-
-	if (jas_matrix_numrows(data) != height || jas_matrix_numcols(data) != width) {
-		return -1;
-	}
-
-	dr = jas_matrix_getref(data, 0, 0);
-	drs = jas_matrix_rowstep(data);
-	for (i = 0; i < height; ++i, dr += drs) {
-		d = dr;
-		if (jas_stream_seek(cmpt->stream_, (cmpt->width_ * (y + i) + x)
-		  * cmpt->cps_, SEEK_SET) < 0) {
-			return -1;
-		}
-		for (j = width; j > 0; --j, ++d) {
-			v = inttobits(*d, cmpt->prec_, cmpt->sgnd_);
-			for (k = cmpt->cps_; k > 0; --k) {
-				c = (v >> (8 * (cmpt->cps_ - 1))) & 0xff;
-				if (jas_stream_putc(cmpt->stream_,
-				  (unsigned char) c) == EOF) {
-					return -1;
-				}
-				v <<= 8;
-			}
-		}
-	}
-
-	return 0;
+        jas_image_cmpt_t *cmpt;
+        uint_fast32_t i;
+        uint_fast32_t j;
+        jas_seqent_t *d;
+        jas_seqent_t *dr;
+        int drs;
+        jas_seqent_t v;
+        int k;
+        int c;
+
+        if (cmptno >= image->numcmpts_) {
+                return -1;
+        }
+
+        cmpt = image->cmpts_[cmptno];
+        if (x >= cmpt->width_ || y >= cmpt->height_ ||
+          x + width > cmpt->width_ ||
+          y + height > cmpt->height_) {
+                return -1;
+        }
+
+        if (jas_matrix_numrows(data) != height || jas_matrix_numcols(data) != width) {
+                return -1;
+        }
+
+        dr = jas_matrix_getref(data, 0, 0);
+        drs = jas_matrix_rowstep(data);
+        for (i = 0; i < height; ++i, dr += drs) {
+                d = dr;
+                if (jas_stream_seek(cmpt->stream_, (cmpt->width_ * (y + i) + x)
+                  * cmpt->cps_, SEEK_SET) < 0) {
+                        return -1;
+                }
+                for (j = width; j > 0; --j, ++d) {
+                        v = inttobits(*d, cmpt->prec_, cmpt->sgnd_);
+                        for (k = cmpt->cps_; k > 0; --k) {
+                                c = (v >> (8 * (cmpt->cps_ - 1))) & 0xff;
+                                if (jas_stream_putc(cmpt->stream_,
+                                  (unsigned char) c) == EOF) {
+                                        return -1;
+                                }
+                                v <<= 8;
+                        }
+                }
+        }
+
+        return 0;
 }
 
 /******************************************************************************\
@@ -578,200 +578,203 @@ int jas_image_writecmpt(jas_image_t *image, uint_fast16_t cmptno, uint_fast32_t
 
 void jas_image_clearfmts()
 {
-	int i;
-	jas_image_fmtinfo_t *fmtinfo;
-	for (i = 0; i < jas_image_numfmts; ++i) {
-		fmtinfo = &jas_image_fmtinfos[i];
-		if (fmtinfo->name) {
-			jas_free(fmtinfo->name);
-			fmtinfo->name = 0;
-		}
-		if (fmtinfo->ext) {
-			jas_free(fmtinfo->ext);
-			fmtinfo->ext = 0;
-		}
-		if (fmtinfo->desc) {
-			jas_free(fmtinfo->desc);
-			fmtinfo->desc = 0;
-		}
-	}
-	jas_image_numfmts = 0;
-}
-
-int jas_image_addfmt(int id, const char *name, const char *ext, 
+        int i;
+        jas_image_fmtinfo_t *fmtinfo;
+        for (i = 0; i < jas_image_numfmts; ++i) {
+                fmtinfo = &jas_image_fmtinfos[i];
+                if (fmtinfo->name) {
+                        jas_free(fmtinfo->name);
+                        fmtinfo->name = 0;
+                }
+                if (fmtinfo->ext) {
+                        jas_free(fmtinfo->ext);
+                        fmtinfo->ext = 0;
+                }
+                if (fmtinfo->desc) {
+                        jas_free(fmtinfo->desc);
+                        fmtinfo->desc = 0;
+                }
+        }
+        jas_image_numfmts = 0;
+}
+
+int jas_image_addfmt(int id, const char *name, const char *ext,
   const char *desc,
   jas_image_fmtops_t *ops)
 {
-	jas_image_fmtinfo_t *fmtinfo;
-	assert(id >= 0 && name && ext && ops);
-	if (jas_image_numfmts >= JAS_IMAGE_MAXFMTS) {
-		return -1;
-	}
-	fmtinfo = &jas_image_fmtinfos[jas_image_numfmts];
-	fmtinfo->id = id;
-	if (!(fmtinfo->name = jas_strdup(name))) {
-		return -1;
-	}
-	if (!(fmtinfo->ext = jas_strdup(ext))) {
-		jas_free(fmtinfo->name);
-		return -1;
-	}
-	if (!(fmtinfo->desc = jas_strdup(desc))) {
-		jas_free(fmtinfo->name);
-		jas_free(fmtinfo->ext);
-		return -1;
-	}
-	fmtinfo->ops = *ops;
-	++jas_image_numfmts;
-	return 0;
+        jas_image_fmtinfo_t *fmtinfo;
+        assert(id >= 0 && name && ext && ops);
+        if (jas_image_numfmts >= JAS_IMAGE_MAXFMTS) {
+                return -1;
+        }
+        fmtinfo = &jas_image_fmtinfos[jas_image_numfmts];
+        fmtinfo->id = id;
+        if (!(fmtinfo->name = jas_strdup(name))) {
+                return -1;
+        }
+        if (!(fmtinfo->ext = jas_strdup(ext))) {
+                jas_free(fmtinfo->name);
+                return -1;
+        }
+        if (!(fmtinfo->desc = jas_strdup(desc))) {
+                jas_free(fmtinfo->name);
+                jas_free(fmtinfo->ext);
+                return -1;
+        }
+        fmtinfo->ops = *ops;
+        ++jas_image_numfmts;
+        return 0;
 }
 
 int jas_image_strtofmt(char *name)
 {
-	jas_image_fmtinfo_t *fmtinfo;
-	if (!(fmtinfo = jas_image_lookupfmtbyname(name))) {
-		return -1;
-	}
-	return fmtinfo->id;
+        jas_image_fmtinfo_t *fmtinfo;
+        if (!(fmtinfo = jas_image_lookupfmtbyname(name))) {
+                return -1;
+        }
+        return fmtinfo->id;
 }
 
 char *jas_image_fmttostr(int fmt)
 {
-	jas_image_fmtinfo_t *fmtinfo;
-	if (!(fmtinfo = jas_image_lookupfmtbyid(fmt))) {
-		return 0;
-	}
-	return fmtinfo->name;
+        jas_image_fmtinfo_t *fmtinfo;
+        if (!(fmtinfo = jas_image_lookupfmtbyid(fmt))) {
+                return 0;
+        }
+        return fmtinfo->name;
 }
 
 int jas_image_getfmt(jas_stream_t *in)
 {
-	jas_image_fmtinfo_t *fmtinfo;
-	int found;
-	int i;
-
-	/* Check for data in each of the formats we know. */
-	found = 0;
-	for (i = 0, fmtinfo = jas_image_fmtinfos; i < jas_image_numfmts; ++i,
-	  ++fmtinfo) {
-		if (fmtinfo->ops.validate) {
-			/* Is the input data valid for this format? */
-			if (!(*fmtinfo->ops.validate)(in)) {
-				found = 1;
-				break;
-			}
-		}
-	}
-	return found ? fmtinfo->id : (-1);
+        jas_image_fmtinfo_t *fmtinfo;
+        int found;
+        int i;
+
+        /* Check for data in each of the formats we know. */
+        found = 0;
+        for (i = 0, fmtinfo = jas_image_fmtinfos; i < jas_image_numfmts; ++i,
+          ++fmtinfo) {
+                if (fmtinfo->ops.validate) {
+                        /* Is the input data valid for this format? */
+                        if (!(*fmtinfo->ops.validate)(in)) {
+                                found = 1;
+                                break;
+                        }
+                }
+        }
+        return found ? fmtinfo->id : (-1);
 }
 
 int jas_image_fmtfromname(char *name)
 {
-	int i;
-	char *ext;
-	jas_image_fmtinfo_t *fmtinfo;
-	/* Get the file name extension. */
-	if (!(ext = strrchr(name, '.'))) {
-		return -1;
-	}
-	++ext;
-	/* Try to find a format that uses this extension. */	
-	for (i = 0, fmtinfo = jas_image_fmtinfos; i < jas_image_numfmts; ++i,
-	  ++fmtinfo) {
-		/* Do we have a match? */
-		if (!strcmp(ext, fmtinfo->ext)) {
-			return fmtinfo->id;
-		}
-	}
-	return -1;
+        int i;
+        char *ext;
+        jas_image_fmtinfo_t *fmtinfo;
+        /* Get the file name extension. */
+        if (!(ext = strrchr(name, '.'))) {
+                return -1;
+        }
+        ++ext;
+        /* Try to find a format that uses this extension. */
+        for (i = 0, fmtinfo = jas_image_fmtinfos; i < jas_image_numfmts; ++i,
+          ++fmtinfo) {
+                /* Do we have a match? */
+                if (!strcmp(ext, fmtinfo->ext)) {
+                        return fmtinfo->id;
+                }
+        }
+        return -1;
 }
 
-/******************************************************************************\
+/*****************************************************************************\
 * Miscellaneous operations.
-\******************************************************************************/
+\*****************************************************************************/
 
-uint_fast32_t jas_image_rawsize(jas_image_t *image)
-{
-	uint_fast32_t rawsize;
-	uint_fast32_t cmptno;
-	jas_image_cmpt_t *cmpt;
+uint_fast32_t
+jas_image_rawsize(jas_image_t * const imageP) {
+/*----------------------------------------------------------------------------
+   The raw size of the image, i.e. the number of bytes the raster of the image
+   would take if just represented simply, with no compression.
+-----------------------------------------------------------------------------*/
+    uint_fast32_t rawsize;
+    uint_fast32_t cmptno;
 
-	rawsize = 0;
-	for (cmptno = 0; cmptno < image->numcmpts_; ++cmptno) {
-		cmpt = image->cmpts_[cmptno];
-		rawsize += (cmpt->width_ * cmpt->height_ * cmpt->prec_ +
-		  7) / 8;
-	}
-	return rawsize;
+    for (cmptno = 0, rawsize = 0; cmptno < imageP->numcmpts_; ++cmptno) {
+        jas_image_cmpt_t * const cmptP = imageP->cmpts_[cmptno];
+        rawsize += (cmptP->width_ * cmptP->height_ * cmptP->prec_ + 7) / 8;
+    }
+    return rawsize;
 }
 
+
+
 void jas_image_delcmpt(jas_image_t *image, uint_fast16_t cmptno)
 {
-	if (cmptno >= image->numcmpts_) {
-		return;
-	}
-	jas_image_cmpt_destroy(image->cmpts_[cmptno]);
-	if (cmptno < image->numcmpts_) {
-		memmove(&image->cmpts_[cmptno], &image->cmpts_[cmptno + 1],
-		  (image->numcmpts_ - 1 - cmptno) * sizeof(jas_image_cmpt_t *));
-	}
-	--image->numcmpts_;
+        if (cmptno >= image->numcmpts_) {
+                return;
+        }
+        jas_image_cmpt_destroy(image->cmpts_[cmptno]);
+        if (cmptno < image->numcmpts_) {
+                memmove(&image->cmpts_[cmptno], &image->cmpts_[cmptno + 1],
+                  (image->numcmpts_ - 1 - cmptno) * sizeof(jas_image_cmpt_t *));
+        }
+        --image->numcmpts_;
 
-	jas_image_setbbox(image);
+        jas_image_setbbox(image);
 }
 
 int jas_image_addcmpt(jas_image_t *image, uint_fast16_t cmptno,
   jas_image_cmptparm_t *cmptparm)
 {
-	jas_image_cmpt_t *newcmpt;
-	assert(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, 1))) {
-		return -1;
-	}
-	if (cmptno < image->numcmpts_) {
-		memmove(&image->cmpts_[cmptno + 1], &image->cmpts_[cmptno],
-		  (image->numcmpts_ - cmptno) * sizeof(jas_image_cmpt_t *));
-	}
-	image->cmpts_[cmptno] = newcmpt;
-	++image->numcmpts_;
-
-	jas_image_setbbox(image);
-
-	return 0;
+        jas_image_cmpt_t *newcmpt;
+        assert(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, 1))) {
+                return -1;
+        }
+        if (cmptno < image->numcmpts_) {
+                memmove(&image->cmpts_[cmptno + 1], &image->cmpts_[cmptno],
+                  (image->numcmpts_ - cmptno) * sizeof(jas_image_cmpt_t *));
+        }
+        image->cmpts_[cmptno] = newcmpt;
+        ++image->numcmpts_;
+
+        jas_image_setbbox(image);
+
+        return 0;
 }
 
 jas_image_fmtinfo_t *jas_image_lookupfmtbyid(int id)
 {
-	int i;
-	jas_image_fmtinfo_t *fmtinfo;
+        int i;
+        jas_image_fmtinfo_t *fmtinfo;
 
-	for (i = 0, fmtinfo = jas_image_fmtinfos; i < jas_image_numfmts; ++i, ++fmtinfo) {
-		if (fmtinfo->id == id) {
-			return fmtinfo;
-		}
-	}
-	return 0;
+        for (i = 0, fmtinfo = jas_image_fmtinfos; i < jas_image_numfmts; ++i, ++fmtinfo) {
+                if (fmtinfo->id == id) {
+                        return fmtinfo;
+                }
+        }
+        return 0;
 }
 
 jas_image_fmtinfo_t *jas_image_lookupfmtbyname(const char *name)
 {
-	int i;
-	jas_image_fmtinfo_t *fmtinfo;
+        int i;
+        jas_image_fmtinfo_t *fmtinfo;
 
-	for (i = 0, fmtinfo = jas_image_fmtinfos; i < jas_image_numfmts; ++i, ++fmtinfo) {
-		if (!strcmp(fmtinfo->name, name)) {
-			return fmtinfo;
-		}
-	}
-	return 0;
+        for (i = 0, fmtinfo = jas_image_fmtinfos; i < jas_image_numfmts; ++i, ++fmtinfo) {
+                if (!strcmp(fmtinfo->name, name)) {
+                        return fmtinfo;
+                }
+        }
+        return 0;
 }
 
 
@@ -780,220 +783,220 @@ jas_image_fmtinfo_t *jas_image_lookupfmtbyname(const char *name)
 
 static uint_fast32_t inttobits(jas_seqent_t v, int prec, bool sgnd)
 {
-	uint_fast32_t ret;
-	ret = ((sgnd && v < 0) ? ((1 << prec) + v) : v) & JAS_ONES(prec);
-	return ret;
+        uint_fast32_t ret;
+        ret = ((sgnd && v < 0) ? ((1 << prec) + v) : v) & JAS_ONES(prec);
+        return ret;
 }
 
 static jas_seqent_t bitstoint(uint_fast32_t v, int prec, bool sgnd)
 {
-	jas_seqent_t ret;
-	v &= JAS_ONES(prec);
-	ret = (sgnd && (v & (1 << (prec - 1)))) ? (v - (1 << prec)) : v;
-	return ret;
+        jas_seqent_t ret;
+        v &= JAS_ONES(prec);
+        ret = (sgnd && (v & (1 << (prec - 1)))) ? (v - (1 << prec)) : v;
+        return ret;
 }
 
 static void jas_image_setbbox(jas_image_t *image)
 {
-	jas_image_cmpt_t *cmpt;
-	int cmptno;
-	int_fast32_t x;
-	int_fast32_t y;
-
-	if (image->numcmpts_ > 0) {
-		/* Determine the bounding box for all of the components on the
-		  reference grid (i.e., the image area) */
-		cmpt = image->cmpts_[0];
-		image->tlx_ = cmpt->tlx_;
-		image->tly_ = cmpt->tly_;
-		image->brx_ = cmpt->tlx_ + cmpt->hstep_ * (cmpt->width_ - 1) + 1;
-		image->bry_ = cmpt->tly_ + cmpt->vstep_ * (cmpt->height_ - 1) + 1;
-		for (cmptno = 1; cmptno < image->numcmpts_; ++cmptno) {
-			cmpt = image->cmpts_[cmptno];
-			if (image->tlx_ > cmpt->tlx_) {
-				image->tlx_ = cmpt->tlx_;
-			}
-			if (image->tly_ > cmpt->tly_) {
-				image->tly_ = cmpt->tly_;
-			}
-			x = cmpt->tlx_ + cmpt->hstep_ * (cmpt->width_ - 1) + 1;
-			if (image->brx_ < x) {
-				image->brx_ = x;
-			}
-			y = cmpt->tly_ + cmpt->vstep_ * (cmpt->height_ - 1) + 1;
-			if (image->bry_ < y) {
-				image->bry_ = y;
-			}
-		}
-	} else {
-		image->tlx_ = 0;
-		image->tly_ = 0;
-		image->brx_ = 0;
-		image->bry_ = 0;
-	}
+        jas_image_cmpt_t *cmpt;
+        int cmptno;
+        int_fast32_t x;
+        int_fast32_t y;
+
+        if (image->numcmpts_ > 0) {
+                /* Determine the bounding box for all of the components on the
+                  reference grid (i.e., the image area) */
+                cmpt = image->cmpts_[0];
+                image->tlx_ = cmpt->tlx_;
+                image->tly_ = cmpt->tly_;
+                image->brx_ = cmpt->tlx_ + cmpt->hstep_ * (cmpt->width_ - 1) + 1;
+                image->bry_ = cmpt->tly_ + cmpt->vstep_ * (cmpt->height_ - 1) + 1;
+                for (cmptno = 1; cmptno < image->numcmpts_; ++cmptno) {
+                        cmpt = image->cmpts_[cmptno];
+                        if (image->tlx_ > cmpt->tlx_) {
+                                image->tlx_ = cmpt->tlx_;
+                        }
+                        if (image->tly_ > cmpt->tly_) {
+                                image->tly_ = cmpt->tly_;
+                        }
+                        x = cmpt->tlx_ + cmpt->hstep_ * (cmpt->width_ - 1) + 1;
+                        if (image->brx_ < x) {
+                                image->brx_ = x;
+                        }
+                        y = cmpt->tly_ + cmpt->vstep_ * (cmpt->height_ - 1) + 1;
+                        if (image->bry_ < y) {
+                                image->bry_ = y;
+                        }
+                }
+        } else {
+                image->tlx_ = 0;
+                image->tly_ = 0;
+                image->brx_ = 0;
+                image->bry_ = 0;
+        }
 }
 
 static int jas_image_growcmpts(jas_image_t *image, int maxcmpts)
 {
-	jas_image_cmpt_t **newcmpts;
-	int cmptno;
+        jas_image_cmpt_t **newcmpts;
+        int cmptno;
 
-	newcmpts = (!image->cmpts_) ? jas_malloc(maxcmpts * sizeof(jas_image_cmpt_t *)) :
-	  jas_realloc(image->cmpts_, maxcmpts * sizeof(jas_image_cmpt_t *));
-	if (!newcmpts) {
-		return -1;
-	}
-	image->cmpts_ = newcmpts;
-	image->maxcmpts_ = maxcmpts;
-	for (cmptno = image->numcmpts_; cmptno < image->maxcmpts_; ++cmptno) {
-		image->cmpts_[cmptno] = 0;
-	}
-	return 0;
+        newcmpts = (!image->cmpts_) ? jas_malloc(maxcmpts * sizeof(jas_image_cmpt_t *)) :
+          jas_realloc(image->cmpts_, maxcmpts * sizeof(jas_image_cmpt_t *));
+        if (!newcmpts) {
+                return -1;
+        }
+        image->cmpts_ = newcmpts;
+        image->maxcmpts_ = maxcmpts;
+        for (cmptno = image->numcmpts_; cmptno < image->maxcmpts_; ++cmptno) {
+                image->cmpts_[cmptno] = 0;
+        }
+        return 0;
 }
 
 int jas_image_copycmpt(jas_image_t *dstimage, int dstcmptno, jas_image_t *srcimage,
   int srccmptno)
 {
-	jas_image_cmpt_t *newcmpt;
-	if (dstimage->numcmpts_ >= dstimage->maxcmpts_) {
-		if (jas_image_growcmpts(dstimage, dstimage->maxcmpts_ + 128)) {
-			return -1;
-		}
-	}
-	if (!(newcmpt = jas_image_cmpt_copy(srcimage->cmpts_[srccmptno]))) {
-		return -1;
-	}
-	if (dstcmptno < dstimage->numcmpts_) {
-		memmove(&dstimage->cmpts_[dstcmptno + 1], &dstimage->cmpts_[dstcmptno],
-		  (dstimage->numcmpts_ - dstcmptno) * sizeof(jas_image_cmpt_t *));
-	}
-	dstimage->cmpts_[dstcmptno] = newcmpt;
-	++dstimage->numcmpts_;
-
-	jas_image_setbbox(dstimage);
-	return 0;
+        jas_image_cmpt_t *newcmpt;
+        if (dstimage->numcmpts_ >= dstimage->maxcmpts_) {
+                if (jas_image_growcmpts(dstimage, dstimage->maxcmpts_ + 128)) {
+                        return -1;
+                }
+        }
+        if (!(newcmpt = jas_image_cmpt_copy(srcimage->cmpts_[srccmptno]))) {
+                return -1;
+        }
+        if (dstcmptno < dstimage->numcmpts_) {
+                memmove(&dstimage->cmpts_[dstcmptno + 1], &dstimage->cmpts_[dstcmptno],
+                  (dstimage->numcmpts_ - dstcmptno) * sizeof(jas_image_cmpt_t *));
+        }
+        dstimage->cmpts_[dstcmptno] = newcmpt;
+        ++dstimage->numcmpts_;
+
+        jas_image_setbbox(dstimage);
+        return 0;
 }
 
 void jas_image_dump(jas_image_t *image, FILE *out)
 {
-	int cmptno;
-	jas_seq2d_t *data;
-	jas_image_cmpt_t *cmpt;
-	if (!(data = jas_seq2d_create(0, 0, 1, 1))) {
-		abort();
-	}
-	for (cmptno = 0; cmptno < image->numcmpts_; ++cmptno) {
-		cmpt = image->cmpts_[cmptno];
-		fprintf(out, "prec=%d sgnd=%d\n", (int)cmpt->prec_, cmpt->sgnd_);
-		if (jas_image_readcmpt(image, cmptno, 0, 0, 1, 1, data)) {
-			abort();
-		}
-		fprintf(out, "tlsample %ld\n", (long) jas_seq2d_get(data, 0, 0));
-	}
-	jas_seq2d_destroy(data);
+        int cmptno;
+        jas_seq2d_t *data;
+        jas_image_cmpt_t *cmpt;
+        if (!(data = jas_seq2d_create(0, 0, 1, 1))) {
+                abort();
+        }
+        for (cmptno = 0; cmptno < image->numcmpts_; ++cmptno) {
+                cmpt = image->cmpts_[cmptno];
+                fprintf(out, "prec=%d sgnd=%d\n", (int)cmpt->prec_, cmpt->sgnd_);
+                if (jas_image_readcmpt(image, cmptno, 0, 0, 1, 1, data)) {
+                        abort();
+                }
+                fprintf(out, "tlsample %ld\n", (long) jas_seq2d_get(data, 0, 0));
+        }
+        jas_seq2d_destroy(data);
 }
 
 int jas_image_depalettize(jas_image_t *image, int cmptno, int numlutents,
   int_fast32_t *lutents, int dtype, int newcmptno)
 {
-	jas_image_cmptparm_t cmptparms;
-	int_fast32_t v;
-	int i;
-	int j;
-	jas_image_cmpt_t *cmpt;
-
-	cmpt = image->cmpts_[cmptno];
-	cmptparms.tlx = cmpt->tlx_;
-	cmptparms.tly = cmpt->tly_;
-	cmptparms.hstep = cmpt->hstep_;
-	cmptparms.vstep = cmpt->vstep_;
-	cmptparms.width = cmpt->width_;
-	cmptparms.height = cmpt->height_;
-	cmptparms.prec = JAS_IMAGE_CDT_GETPREC(dtype);
-	cmptparms.sgnd = JAS_IMAGE_CDT_GETSGND(dtype);
-
-	if (numlutents < 1) {
-		return -1;
-	}
-
-	if (jas_image_addcmpt(image, newcmptno, &cmptparms)) {
-		return -1;
-	}
-	if (newcmptno <= cmptno) {
-		++cmptno;
-		cmpt = image->cmpts_[cmptno];
-	}
-
-	for (j = 0; j < cmpt->height_; ++j) {
-		for (i = 0; i < cmpt->width_; ++i) {
-			v = jas_image_readcmptsample(image, cmptno, i, j);
-			if (v < 0) {
-				v = 0;
-			} else if (v >= numlutents) {
-				v = numlutents - 1;
-			}
-			jas_image_writecmptsample(image, newcmptno, i, j,
-			  lutents[v]);
-		}
-	}
-	return 0;
+        jas_image_cmptparm_t cmptparms;
+        int_fast32_t v;
+        int i;
+        int j;
+        jas_image_cmpt_t *cmpt;
+
+        cmpt = image->cmpts_[cmptno];
+        cmptparms.tlx = cmpt->tlx_;
+        cmptparms.tly = cmpt->tly_;
+        cmptparms.hstep = cmpt->hstep_;
+        cmptparms.vstep = cmpt->vstep_;
+        cmptparms.width = cmpt->width_;
+        cmptparms.height = cmpt->height_;
+        cmptparms.prec = JAS_IMAGE_CDT_GETPREC(dtype);
+        cmptparms.sgnd = JAS_IMAGE_CDT_GETSGND(dtype);
+
+        if (numlutents < 1) {
+                return -1;
+        }
+
+        if (jas_image_addcmpt(image, newcmptno, &cmptparms)) {
+                return -1;
+        }
+        if (newcmptno <= cmptno) {
+                ++cmptno;
+                cmpt = image->cmpts_[cmptno];
+        }
+
+        for (j = 0; j < cmpt->height_; ++j) {
+                for (i = 0; i < cmpt->width_; ++i) {
+                        v = jas_image_readcmptsample(image, cmptno, i, j);
+                        if (v < 0) {
+                                v = 0;
+                        } else if (v >= numlutents) {
+                                v = numlutents - 1;
+                        }
+                        jas_image_writecmptsample(image, newcmptno, i, j,
+                          lutents[v]);
+                }
+        }
+        return 0;
 }
 
 int jas_image_readcmptsample(jas_image_t *image, int cmptno, int x, int y)
 {
-	jas_image_cmpt_t *cmpt;
-	uint_fast32_t v;
-	int k;
-	int c;
+        jas_image_cmpt_t *cmpt;
+        uint_fast32_t v;
+        int k;
+        int c;
 
-	cmpt = image->cmpts_[cmptno];
+        cmpt = image->cmpts_[cmptno];
 
-	if (jas_stream_seek(cmpt->stream_, (cmpt->width_ * y + x) * cmpt->cps_,
-	  SEEK_SET) < 0) {
-		return -1;
-	}
-	v = 0;
-	for (k = cmpt->cps_; k > 0; --k) {
-		if ((c = jas_stream_getc(cmpt->stream_)) == EOF) {
-			return -1;
-		}
-		v = (v << 8) | (c & 0xff);
-	}
-	return bitstoint(v, cmpt->prec_, cmpt->sgnd_);
+        if (jas_stream_seek(cmpt->stream_, (cmpt->width_ * y + x) * cmpt->cps_,
+          SEEK_SET) < 0) {
+                return -1;
+        }
+        v = 0;
+        for (k = cmpt->cps_; k > 0; --k) {
+                if ((c = jas_stream_getc(cmpt->stream_)) == EOF) {
+                        return -1;
+                }
+                v = (v << 8) | (c & 0xff);
+        }
+        return bitstoint(v, cmpt->prec_, cmpt->sgnd_);
 }
 
 void jas_image_writecmptsample(jas_image_t *image, int cmptno, int x, int y,
   int_fast32_t v)
 {
-	jas_image_cmpt_t *cmpt;
-	uint_fast32_t t;
-	int k;
-	int c;
+        jas_image_cmpt_t *cmpt;
+        uint_fast32_t t;
+        int k;
+        int c;
 
-	cmpt = image->cmpts_[cmptno];
+        cmpt = image->cmpts_[cmptno];
 
-	if (jas_stream_seek(cmpt->stream_, (cmpt->width_ * y + x) * cmpt->cps_,
-	  SEEK_SET) < 0) {
-		return;
-	}
-	t = inttobits(v, cmpt->prec_, cmpt->sgnd_);
-	for (k = cmpt->cps_; k > 0; --k) {
-		c = (t >> (8 * (cmpt->cps_ - 1))) & 0xff;
-		if (jas_stream_putc(cmpt->stream_, (unsigned char) c) == EOF) {
-			return;
-		}
-		t <<= 8;
-	}
+        if (jas_stream_seek(cmpt->stream_, (cmpt->width_ * y + x) * cmpt->cps_,
+          SEEK_SET) < 0) {
+                return;
+        }
+        t = inttobits(v, cmpt->prec_, cmpt->sgnd_);
+        for (k = cmpt->cps_; k > 0; --k) {
+                c = (t >> (8 * (cmpt->cps_ - 1))) & 0xff;
+                if (jas_stream_putc(cmpt->stream_, (unsigned char) c) == EOF) {
+                        return;
+                }
+                t <<= 8;
+        }
 }
 
 int jas_image_getcmptbytype(jas_image_t *image, int ctype)
 {
-	int cmptno;
+        int cmptno;
 
-	for (cmptno = 0; cmptno < image->numcmpts_; ++cmptno) {
-		if (image->cmpts_[cmptno]->type_ == ctype) {
-			return cmptno;
-		}
-	}
+        for (cmptno = 0; cmptno < image->numcmpts_; ++cmptno) {
+                if (image->cmpts_[cmptno]->type_ == ctype) {
+                        return cmptno;
+                }
+        }
     return -1;
 }
diff --git a/converter/other/jpeg2000/libjasper/base/jas_init.c b/converter/other/jpeg2000/libjasper/base/jas_init.c
index c1114bf7..8d79a7fe 100644
--- a/converter/other/jpeg2000/libjasper/base/jas_init.c
+++ b/converter/other/jpeg2000/libjasper/base/jas_init.c
@@ -4,14 +4,14 @@
  */
 
 /* __START_OF_JASPER_LICENSE__
- * 
+ *
  * JasPer Software License
- * 
+ *
  * IMAGE POWER JPEG-2000 PUBLIC LICENSE
  * ************************************
- * 
+ *
  * GRANT:
- * 
+ *
  * Permission is hereby granted, free of charge, to any person (the "User")
  * obtaining a copy of this software and associated documentation, to deal
  * in the JasPer Software without restriction, including without limitation
@@ -19,22 +19,22 @@
  * and/or sell copies of the JasPer Software (in source and binary forms),
  * and to permit persons to whom the JasPer Software is furnished to do so,
  * provided further that the License Conditions below are met.
- * 
+ *
  * License Conditions
  * ******************
- * 
+ *
  * A.  Redistributions of source code must retain the above copyright notice,
  * and this list of conditions, and the following disclaimer.
- * 
+ *
  * B.  Redistributions in binary form must reproduce the above copyright
  * notice, and this list of conditions, and the following disclaimer in
  * the documentation and/or other materials provided with the distribution.
- * 
+ *
  * C.  Neither the name of Image Power, Inc. nor any other contributor
  * (including, but not limited to, the University of British Columbia and
  * Michael David Adams) may be used to endorse or promote products derived
  * from this software without specific prior written permission.
- * 
+ *
  * D.  User agrees that it shall not commence any action against Image Power,
  * Inc., the University of British Columbia, Michael David Adams, or any
  * other contributors (collectively "Licensors") for infringement of any
@@ -54,17 +54,17 @@
  * trade dress, or service mark rights); and (v) divisions, continuations,
  * renewals, reissues and extensions of the foregoing (as and to the extent
  * applicable) now existing, hereafter filed, issued or acquired.
- * 
+ *
  * E.  If User commences an infringement action against any Licensor(s) then
  * such Licensor(s) shall have the right to terminate User's license and
  * all sublicenses that have been granted hereunder by User to other parties.
- * 
+ *
  * F.  This software is for use only in hardware or software products that
  * are compliant with ISO/IEC 15444-1 (i.e., JPEG-2000 Part 1).  No license
  * or right to this Software is granted for products that do not comply
  * with ISO/IEC 15444-1.  The JPEG-2000 Part 1 standard can be purchased
  * from the ISO.
- * 
+ *
  * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS LICENSE.
  * NO USE OF THE JASPER SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER
  * THIS DISCLAIMER.  THE JASPER SOFTWARE IS PROVIDED BY THE LICENSORS AND
@@ -104,7 +104,7 @@
  * TECHNOLOGY OR PRODUCTS FOR HIGH RISK ACTIVITIES AND WILL ENSURE THAT ITS
  * CUSTOMERS AND END-USERS OF ITS PRODUCTS ARE PROVIDED WITH A COPY OF THE
  * NOTICE SPECIFIED IN THIS SECTION.
- * 
+ *
  * __END_OF_JASPER_LICENSE__
  */
 
@@ -123,78 +123,78 @@
 /* Initialize the image format table. */
 int jas_init()
 {
-	jas_image_fmtops_t fmtops;
-	int fmtid;
+        jas_image_fmtops_t fmtops;
+        int fmtid;
 
-	fmtid = 0;
+        fmtid = 0;
 
 #if !defined(EXCLUDE_MIF_SUPPORT)
-	fmtops.decode = mif_decode;
-	fmtops.encode = mif_encode;
-	fmtops.validate = mif_validate;
-	jas_image_addfmt(fmtid, "mif", "mif", "My Image Format (MIF)", &fmtops);
-	++fmtid;
+        fmtops.decode = mif_decode;
+        fmtops.encode = mif_encode;
+        fmtops.validate = mif_validate;
+        jas_image_addfmt(fmtid, "mif", "mif", "My Image Format (MIF)", &fmtops);
+        ++fmtid;
 #endif
 
 #if !defined(EXCLUDE_PNM_SUPPORT)
-	fmtops.decode = pnm_decode;
-	fmtops.encode = pnm_encode;
-	fmtops.validate = pnm_validate;
-	jas_image_addfmt(fmtid, "pnm", "pnm", "Portable Graymap/Pixmap (PNM)",
-	  &fmtops);
-	jas_image_addfmt(fmtid, "pnm", "pgm", "Portable Graymap/Pixmap (PNM)",
-	  &fmtops);
-	jas_image_addfmt(fmtid, "pnm", "ppm", "Portable Graymap/Pixmap (PNM)",
-	  &fmtops);
-	++fmtid;
+        fmtops.decode = pnm_decode;
+        fmtops.encode = pnm_encode;
+        fmtops.validate = pnm_validate;
+        jas_image_addfmt(fmtid, "pnm", "pnm", "Portable Graymap/Pixmap (PNM)",
+          &fmtops);
+        jas_image_addfmt(fmtid, "pnm", "pgm", "Portable Graymap/Pixmap (PNM)",
+          &fmtops);
+        jas_image_addfmt(fmtid, "pnm", "ppm", "Portable Graymap/Pixmap (PNM)",
+          &fmtops);
+        ++fmtid;
 #endif
 
 #if !defined(EXCLUDE_BMP_SUPPORT)
-	fmtops.decode = bmp_decode;
-	fmtops.encode = bmp_encode;
-	fmtops.validate = bmp_validate;
-	jas_image_addfmt(fmtid, "bmp", "bmp", "Microsoft Bitmap (BMP)", &fmtops);
-	++fmtid;
+        fmtops.decode = bmp_decode;
+        fmtops.encode = bmp_encode;
+        fmtops.validate = bmp_validate;
+        jas_image_addfmt(fmtid, "bmp", "bmp", "Microsoft Bitmap (BMP)", &fmtops);
+        ++fmtid;
 #endif
 
 #if !defined(EXCLUDE_RAS_SUPPORT)
-	fmtops.decode = ras_decode;
-	fmtops.encode = ras_encode;
-	fmtops.validate = ras_validate;
-	jas_image_addfmt(fmtid, "ras", "ras", "Sun Rasterfile (RAS)", &fmtops);
-	++fmtid;
+        fmtops.decode = ras_decode;
+        fmtops.encode = ras_encode;
+        fmtops.validate = ras_validate;
+        jas_image_addfmt(fmtid, "ras", "ras", "Sun Rasterfile (RAS)", &fmtops);
+        ++fmtid;
 #endif
 
 #if !defined(EXCLUDE_JP2_SUPPORT)
-	fmtops.decode = jp2_decode;
-	fmtops.encode = jp2_encode;
-	fmtops.validate = jp2_validate;
-	jas_image_addfmt(fmtid, "jp2", "jp2",
-	  "JPEG-2000 JP2 File Format Syntax (ISO/IEC 15444-1)", &fmtops);
-	++fmtid;
-	fmtops.decode = jpc_decode;
-	fmtops.encode = jpc_encode;
-	fmtops.validate = jpc_validate;
-	jas_image_addfmt(fmtid, "jpc", "jpc",
-	  "JPEG-2000 Code Stream Syntax (ISO/IEC 15444-1)", &fmtops);
-	++fmtid;
+        fmtops.decode = jp2_decode;
+        fmtops.encode = jp2_encode;
+        fmtops.validate = jp2_validate;
+        jas_image_addfmt(fmtid, "jp2", "jp2",
+          "JPEG-2000 JP2 File Format Syntax (ISO/IEC 15444-1)", &fmtops);
+        ++fmtid;
+        fmtops.decode = jpc_decode;
+        fmtops.encode = jpc_encode;
+        fmtops.validate = jpc_validate;
+        jas_image_addfmt(fmtid, "jpc", "jpc",
+          "JPEG-2000 Code Stream Syntax (ISO/IEC 15444-1)", &fmtops);
+        ++fmtid;
 #endif
 
 #if !defined(EXCLUDE_JPG_SUPPORT)
-	fmtops.decode = jpg_decode;
-	fmtops.encode = jpg_encode;
-	fmtops.validate = jpg_validate;
-	jas_image_addfmt(fmtid, "jpg", "jpg", "JPEG (ISO/IEC 10918-1)", &fmtops);
-	++fmtid;
+        fmtops.decode = jpg_decode;
+        fmtops.encode = jpg_encode;
+        fmtops.validate = jpg_validate;
+        jas_image_addfmt(fmtid, "jpg", "jpg", "JPEG (ISO/IEC 10918-1)", &fmtops);
+        ++fmtid;
 #endif
 
 #if !defined(EXCLUDE_PGX_SUPPORT)
-	fmtops.decode = pgx_decode;
-	fmtops.encode = pgx_encode;
-	fmtops.validate = pgx_validate;
-	jas_image_addfmt(fmtid, "pgx", "pgx", "JPEG-2000 VM Format (PGX)", &fmtops);
-	++fmtid;
+        fmtops.decode = pgx_decode;
+        fmtops.encode = pgx_encode;
+        fmtops.validate = pgx_validate;
+        jas_image_addfmt(fmtid, "pgx", "pgx", "JPEG-2000 VM Format (PGX)", &fmtops);
+        ++fmtid;
 #endif
 
-	return 0;
+        return 0;
 }
diff --git a/converter/other/jpeg2000/libjasper/base/jas_malloc.c b/converter/other/jpeg2000/libjasper/base/jas_malloc.c
index 43c4d3cd..a8b85033 100644
--- a/converter/other/jpeg2000/libjasper/base/jas_malloc.c
+++ b/converter/other/jpeg2000/libjasper/base/jas_malloc.c
@@ -6,14 +6,14 @@
  */
 
 /* __START_OF_JASPER_LICENSE__
- * 
+ *
  * JasPer Software License
- * 
+ *
  * IMAGE POWER JPEG-2000 PUBLIC LICENSE
  * ************************************
- * 
+ *
  * GRANT:
- * 
+ *
  * Permission is hereby granted, free of charge, to any person (the "User")
  * obtaining a copy of this software and associated documentation, to deal
  * in the JasPer Software without restriction, including without limitation
@@ -21,22 +21,22 @@
  * and/or sell copies of the JasPer Software (in source and binary forms),
  * and to permit persons to whom the JasPer Software is furnished to do so,
  * provided further that the License Conditions below are met.
- * 
+ *
  * License Conditions
  * ******************
- * 
+ *
  * A.  Redistributions of source code must retain the above copyright notice,
  * and this list of conditions, and the following disclaimer.
- * 
+ *
  * B.  Redistributions in binary form must reproduce the above copyright
  * notice, and this list of conditions, and the following disclaimer in
  * the documentation and/or other materials provided with the distribution.
- * 
+ *
  * C.  Neither the name of Image Power, Inc. nor any other contributor
  * (including, but not limited to, the University of British Columbia and
  * Michael David Adams) may be used to endorse or promote products derived
  * from this software without specific prior written permission.
- * 
+ *
  * D.  User agrees that it shall not commence any action against Image Power,
  * Inc., the University of British Columbia, Michael David Adams, or any
  * other contributors (collectively "Licensors") for infringement of any
@@ -56,17 +56,17 @@
  * trade dress, or service mark rights); and (v) divisions, continuations,
  * renewals, reissues and extensions of the foregoing (as and to the extent
  * applicable) now existing, hereafter filed, issued or acquired.
- * 
+ *
  * E.  If User commences an infringement action against any Licensor(s) then
  * such Licensor(s) shall have the right to terminate User's license and
  * all sublicenses that have been granted hereunder by User to other parties.
- * 
+ *
  * F.  This software is for use only in hardware or software products that
  * are compliant with ISO/IEC 15444-1 (i.e., JPEG-2000 Part 1).  No license
  * or right to this Software is granted for products that do not comply
  * with ISO/IEC 15444-1.  The JPEG-2000 Part 1 standard can be purchased
  * from the ISO.
- * 
+ *
  * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS LICENSE.
  * NO USE OF THE JASPER SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER
  * THIS DISCLAIMER.  THE JASPER SOFTWARE IS PROVIDED BY THE LICENSORS AND
@@ -106,7 +106,7 @@
  * TECHNOLOGY OR PRODUCTS FOR HIGH RISK ACTIVITIES AND WILL ENSURE THAT ITS
  * CUSTOMERS AND END-USERS OF ITS PRODUCTS ARE PROVIDED WITH A COPY OF THE
  * NOTICE SPECIFIED IN THIS SECTION.
- * 
+ *
  * __END_OF_JASPER_LICENSE__
  */
 
@@ -139,29 +139,29 @@
 
 void *jas_malloc(size_t size)
 {
-	return malloc(size);
+        return malloc(size);
 }
 
 void jas_free(void *ptr)
 {
-	free(ptr);
+        free(ptr);
 }
 
 void *jas_realloc(void *ptr, size_t size)
 {
-	return realloc(ptr, size);
+        return realloc(ptr, size);
 }
 
 void *jas_calloc(size_t nmemb, size_t size)
 {
-	void *ptr;
-	size_t n;
-	n = nmemb * size;
-	if (!(ptr = jas_malloc(n * sizeof(char)))) {
-		return 0;
-	}
-	memset(ptr, 0, n);
-	return ptr;
+        void *ptr;
+        size_t n;
+        n = nmemb * size;
+        if (!(ptr = jas_malloc(n * sizeof(char)))) {
+                return 0;
+        }
+        memset(ptr, 0, n);
+        return ptr;
 }
 
 #endif
diff --git a/converter/other/jpeg2000/libjasper/base/jas_seq.c b/converter/other/jpeg2000/libjasper/base/jas_seq.c
index 12dc1595..5aa2a75f 100644
--- a/converter/other/jpeg2000/libjasper/base/jas_seq.c
+++ b/converter/other/jpeg2000/libjasper/base/jas_seq.c
@@ -6,14 +6,14 @@
  */
 
 /* __START_OF_JASPER_LICENSE__
- * 
+ *
  * JasPer Software License
- * 
+ *
  * IMAGE POWER JPEG-2000 PUBLIC LICENSE
  * ************************************
- * 
+ *
  * GRANT:
- * 
+ *
  * Permission is hereby granted, free of charge, to any person (the "User")
  * obtaining a copy of this software and associated documentation, to deal
  * in the JasPer Software without restriction, including without limitation
@@ -21,22 +21,22 @@
  * and/or sell copies of the JasPer Software (in source and binary forms),
  * and to permit persons to whom the JasPer Software is furnished to do so,
  * provided further that the License Conditions below are met.
- * 
+ *
  * License Conditions
  * ******************
- * 
+ *
  * A.  Redistributions of source code must retain the above copyright notice,
  * and this list of conditions, and the following disclaimer.
- * 
+ *
  * B.  Redistributions in binary form must reproduce the above copyright
  * notice, and this list of conditions, and the following disclaimer in
  * the documentation and/or other materials provided with the distribution.
- * 
+ *
  * C.  Neither the name of Image Power, Inc. nor any other contributor
  * (including, but not limited to, the University of British Columbia and
  * Michael David Adams) may be used to endorse or promote products derived
  * from this software without specific prior written permission.
- * 
+ *
  * D.  User agrees that it shall not commence any action against Image Power,
  * Inc., the University of British Columbia, Michael David Adams, or any
  * other contributors (collectively "Licensors") for infringement of any
@@ -56,17 +56,17 @@
  * trade dress, or service mark rights); and (v) divisions, continuations,
  * renewals, reissues and extensions of the foregoing (as and to the extent
  * applicable) now existing, hereafter filed, issued or acquired.
- * 
+ *
  * E.  If User commences an infringement action against any Licensor(s) then
  * such Licensor(s) shall have the right to terminate User's license and
  * all sublicenses that have been granted hereunder by User to other parties.
- * 
+ *
  * F.  This software is for use only in hardware or software products that
  * are compliant with ISO/IEC 15444-1 (i.e., JPEG-2000 Part 1).  No license
  * or right to this Software is granted for products that do not comply
  * with ISO/IEC 15444-1.  The JPEG-2000 Part 1 standard can be purchased
  * from the ISO.
- * 
+ *
  * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS LICENSE.
  * NO USE OF THE JASPER SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER
  * THIS DISCLAIMER.  THE JASPER SOFTWARE IS PROVIDED BY THE LICENSORS AND
@@ -106,7 +106,7 @@
  * TECHNOLOGY OR PRODUCTS FOR HIGH RISK ACTIVITIES AND WILL ENSURE THAT ITS
  * CUSTOMERS AND END-USERS OF ITS PRODUCTS ARE PROVIDED WITH A COPY OF THE
  * NOTICE SPECIFIED IN THIS SECTION.
- * 
+ *
  * __END_OF_JASPER_LICENSE__
  */
 
@@ -134,108 +134,108 @@
 
 jas_matrix_t *jas_seq2d_create(int xstart, int ystart, int xend, int yend)
 {
-	jas_matrix_t *matrix;
-	assert(xstart <= xend && ystart <= yend);
-	if (!(matrix = jas_matrix_create(yend - ystart, xend - xstart))) {
-		return 0;
-	}
-	matrix->xstart_ = xstart;
-	matrix->ystart_ = ystart;
-	matrix->xend_ = xend;
-	matrix->yend_ = yend;
-	return matrix;
+        jas_matrix_t *matrix;
+        assert(xstart <= xend && ystart <= yend);
+        if (!(matrix = jas_matrix_create(yend - ystart, xend - xstart))) {
+                return 0;
+        }
+        matrix->xstart_ = xstart;
+        matrix->ystart_ = ystart;
+        matrix->xend_ = xend;
+        matrix->yend_ = yend;
+        return matrix;
 }
 
 jas_matrix_t *jas_matrix_create(int numrows, int numcols)
 {
-	jas_matrix_t *matrix;
-	int i;
-
-	if (!(matrix = jas_malloc(sizeof(jas_matrix_t)))) {
-		return 0;
-	}
-	matrix->flags_ = 0;
-	matrix->numrows_ = numrows;
-	matrix->numcols_ = numcols;
-	matrix->rows_ = 0;
-	matrix->maxrows_ = numrows;
-	matrix->data_ = 0;
-	matrix->datasize_ = numrows * numcols;
-
-	if (matrix->maxrows_ > 0) {
-		if (!(matrix->rows_ = jas_malloc(matrix->maxrows_ *
-		  sizeof(jas_seqent_t *)))) {
-			jas_matrix_destroy(matrix);
-			return 0;
-		}
-	}
-
-	if (matrix->datasize_ > 0) {
-		if (!(matrix->data_ = jas_malloc(matrix->datasize_ *
-		  sizeof(jas_seqent_t)))) {
-			jas_matrix_destroy(matrix);
-			return 0;
-		}
-	}
-
-	for (i = 0; i < numrows; ++i) {
-		matrix->rows_[i] = &matrix->data_[i * matrix->numcols_];
-	}
-
-	for (i = 0; i < matrix->datasize_; ++i) {
-		matrix->data_[i] = 0;
-	}
-
-	matrix->xstart_ = 0;
-	matrix->ystart_ = 0;
-	matrix->xend_ = matrix->numcols_;
-	matrix->yend_ = matrix->numrows_;
-
-	return matrix;
+        jas_matrix_t *matrix;
+        int i;
+
+        if (!(matrix = jas_malloc(sizeof(jas_matrix_t)))) {
+                return 0;
+        }
+        matrix->flags_ = 0;
+        matrix->numrows_ = numrows;
+        matrix->numcols_ = numcols;
+        matrix->rows_ = 0;
+        matrix->maxrows_ = numrows;
+        matrix->data_ = 0;
+        matrix->datasize_ = numrows * numcols;
+
+        if (matrix->maxrows_ > 0) {
+                if (!(matrix->rows_ = jas_malloc(matrix->maxrows_ *
+                  sizeof(jas_seqent_t *)))) {
+                        jas_matrix_destroy(matrix);
+                        return 0;
+                }
+        }
+
+        if (matrix->datasize_ > 0) {
+                if (!(matrix->data_ = jas_malloc(matrix->datasize_ *
+                  sizeof(jas_seqent_t)))) {
+                        jas_matrix_destroy(matrix);
+                        return 0;
+                }
+        }
+
+        for (i = 0; i < numrows; ++i) {
+                matrix->rows_[i] = &matrix->data_[i * matrix->numcols_];
+        }
+
+        for (i = 0; i < matrix->datasize_; ++i) {
+                matrix->data_[i] = 0;
+        }
+
+        matrix->xstart_ = 0;
+        matrix->ystart_ = 0;
+        matrix->xend_ = matrix->numcols_;
+        matrix->yend_ = matrix->numrows_;
+
+        return matrix;
 }
 
 void jas_matrix_destroy(jas_matrix_t *matrix)
 {
-	if (matrix->data_) {
-		assert(!(matrix->flags_ & JAS_MATRIX_REF));
-		jas_free(matrix->data_);
-		matrix->data_ = 0;
-	}
-	if (matrix->rows_) {
-		jas_free(matrix->rows_);
-		matrix->rows_ = 0;
-	}
-	jas_free(matrix);
+        if (matrix->data_) {
+                assert(!(matrix->flags_ & JAS_MATRIX_REF));
+                jas_free(matrix->data_);
+                matrix->data_ = 0;
+        }
+        if (matrix->rows_) {
+                jas_free(matrix->rows_);
+                matrix->rows_ = 0;
+        }
+        jas_free(matrix);
 }
 
 jas_seq2d_t *jas_seq2d_copy(jas_seq2d_t *x)
 {
-	jas_matrix_t *y;
-	int i;
-	int j;
-	y = jas_seq2d_create(jas_seq2d_xstart(x), jas_seq2d_ystart(x), jas_seq2d_xend(x),
-	  jas_seq2d_yend(x));
-	assert(y);
-	for (i = 0; i < x->numrows_; ++i) {
-		for (j = 0; j < x->numcols_; ++j) {
-			*jas_matrix_getref(y, i, j) = jas_matrix_get(x, i, j);
-		}
-	}
-	return y;
+        jas_matrix_t *y;
+        int i;
+        int j;
+        y = jas_seq2d_create(jas_seq2d_xstart(x), jas_seq2d_ystart(x), jas_seq2d_xend(x),
+          jas_seq2d_yend(x));
+        assert(y);
+        for (i = 0; i < x->numrows_; ++i) {
+                for (j = 0; j < x->numcols_; ++j) {
+                        *jas_matrix_getref(y, i, j) = jas_matrix_get(x, i, j);
+                }
+        }
+        return y;
 }
 
 jas_matrix_t *jas_matrix_copy(jas_matrix_t *x)
 {
-	jas_matrix_t *y;
-	int i;
-	int j;
-	y = jas_matrix_create(x->numrows_, x->numcols_);
-	for (i = 0; i < x->numrows_; ++i) {
-		for (j = 0; j < x->numcols_; ++j) {
-			*jas_matrix_getref(y, i, j) = jas_matrix_get(x, i, j);
-		}
-	}
-	return y;
+        jas_matrix_t *y;
+        int i;
+        int j;
+        y = jas_matrix_create(x->numrows_, x->numcols_);
+        for (i = 0; i < x->numrows_; ++i) {
+                for (j = 0; j < x->numcols_; ++j) {
+                        *jas_matrix_getref(y, i, j) = jas_matrix_get(x, i, j);
+                }
+        }
+        return y;
 }
 
 /******************************************************************************\
@@ -245,39 +245,39 @@ jas_matrix_t *jas_matrix_copy(jas_matrix_t *x)
 void jas_seq2d_bindsub(jas_matrix_t *s, jas_matrix_t *s1, int xstart, int ystart,
   int xend, int yend)
 {
-	jas_matrix_bindsub(s, s1, ystart - s1->ystart_, xstart - s1->xstart_,
-	  yend - s1->ystart_ - 1, xend - s1->xstart_ - 1);
+        jas_matrix_bindsub(s, s1, ystart - s1->ystart_, xstart - s1->xstart_,
+          yend - s1->ystart_ - 1, xend - s1->xstart_ - 1);
 }
 
 void jas_matrix_bindsub(jas_matrix_t *mat0, jas_matrix_t *mat1, int r0, int c0,
   int r1, int c1)
 {
-	int i;
-
-	if (mat0->data_) {
-		if (!(mat0->flags_ & JAS_MATRIX_REF)) {
-			jas_free(mat0->data_);
-		}
-		mat0->data_ = 0;
-		mat0->datasize_ = 0;
-	}
-	if (mat0->rows_) {
-		jas_free(mat0->rows_);
-		mat0->rows_ = 0;
-	}
-	mat0->flags_ |= JAS_MATRIX_REF;
-	mat0->numrows_ = r1 - r0 + 1;
-	mat0->numcols_ = c1 - c0 + 1;
-	mat0->maxrows_ = mat0->numrows_;
-	mat0->rows_ = jas_malloc(mat0->maxrows_ * sizeof(jas_seqent_t *));
-	for (i = 0; i < mat0->numrows_; ++i) {
-		mat0->rows_[i] = mat1->rows_[r0 + i] + c0;
-	}
-
-	mat0->xstart_ = mat1->xstart_ + c0;
-	mat0->ystart_ = mat1->ystart_ + r0;
-	mat0->xend_ = mat0->xstart_ + mat0->numcols_;
-	mat0->yend_ = mat0->ystart_ + mat0->numrows_;
+        int i;
+
+        if (mat0->data_) {
+                if (!(mat0->flags_ & JAS_MATRIX_REF)) {
+                        jas_free(mat0->data_);
+                }
+                mat0->data_ = 0;
+                mat0->datasize_ = 0;
+        }
+        if (mat0->rows_) {
+                jas_free(mat0->rows_);
+                mat0->rows_ = 0;
+        }
+        mat0->flags_ |= JAS_MATRIX_REF;
+        mat0->numrows_ = r1 - r0 + 1;
+        mat0->numcols_ = c1 - c0 + 1;
+        mat0->maxrows_ = mat0->numrows_;
+        mat0->rows_ = jas_malloc(mat0->maxrows_ * sizeof(jas_seqent_t *));
+        for (i = 0; i < mat0->numrows_; ++i) {
+                mat0->rows_[i] = mat1->rows_[r0 + i] + c0;
+        }
+
+        mat0->xstart_ = mat1->xstart_ + c0;
+        mat0->ystart_ = mat1->ystart_ + r0;
+        mat0->xend_ = mat0->xstart_ + mat0->numcols_;
+        mat0->yend_ = mat0->ystart_ + mat0->numrows_;
 }
 
 /******************************************************************************\
@@ -286,102 +286,102 @@ void jas_matrix_bindsub(jas_matrix_t *mat0, jas_matrix_t *mat1, int r0, int c0,
 
 int jas_matrix_cmp(jas_matrix_t *mat0, jas_matrix_t *mat1)
 {
-	int i;
-	int j;
-
-	if (mat0->numrows_ != mat1->numrows_ || mat0->numcols_ !=
-	  mat1->numcols_) {
-		return 1;
-	}
-	for (i = 0; i < mat0->numrows_; i++) {
-		for (j = 0; j < mat0->numcols_; j++) {
-			if (jas_matrix_get(mat0, i, j) != jas_matrix_get(mat1, i, j)) {
-				return 1;
-			}
-		}
-	}
-	return 0;
+        int i;
+        int j;
+
+        if (mat0->numrows_ != mat1->numrows_ || mat0->numcols_ !=
+          mat1->numcols_) {
+                return 1;
+        }
+        for (i = 0; i < mat0->numrows_; i++) {
+                for (j = 0; j < mat0->numcols_; j++) {
+                        if (jas_matrix_get(mat0, i, j) != jas_matrix_get(mat1, i, j)) {
+                                return 1;
+                        }
+                }
+        }
+        return 0;
 }
 
 void jas_matrix_divpow2(jas_matrix_t *matrix, int n)
 {
-	int i;
-	int j;
-	jas_seqent_t *rowstart;
-	int rowstep;
-	jas_seqent_t *data;
-
-	rowstep = jas_matrix_rowstep(matrix);
-	for (i = matrix->numrows_, rowstart = matrix->rows_[0]; i > 0; --i,
-	  rowstart += rowstep) {
-		for (j = matrix->numcols_, data = rowstart; j > 0; --j,
-		  ++data) {
-			*data = (*data >= 0) ? ((*data) >> n) :
-			  (-((-(*data)) >> n));
-		}
-	}
+        int i;
+        int j;
+        jas_seqent_t *rowstart;
+        int rowstep;
+        jas_seqent_t *data;
+
+        rowstep = jas_matrix_rowstep(matrix);
+        for (i = matrix->numrows_, rowstart = matrix->rows_[0]; i > 0; --i,
+          rowstart += rowstep) {
+                for (j = matrix->numcols_, data = rowstart; j > 0; --j,
+                  ++data) {
+                        *data = (*data >= 0) ? ((*data) >> n) :
+                          (-((-(*data)) >> n));
+                }
+        }
 }
 
 void jas_matrix_clip(jas_matrix_t *matrix, jas_seqent_t minval, jas_seqent_t maxval)
 {
-	int i;
-	int j;
-	jas_seqent_t v;
-	jas_seqent_t *rowstart;
-	jas_seqent_t *data;
-	int rowstep;
-
-	rowstep = jas_matrix_rowstep(matrix);
-	for (i = matrix->numrows_, rowstart = matrix->rows_[0]; i > 0; --i,
-	  rowstart += rowstep) {
-		data = rowstart;
-		for (j = matrix->numcols_, data = rowstart; j > 0; --j,
-		  ++data) {
-			v = *data;
-			if (v < minval) {
-				*data = minval;
-			} else if (v > maxval) {
-				*data = maxval;
-			}
-		}
-	}
+        int i;
+        int j;
+        jas_seqent_t v;
+        jas_seqent_t *rowstart;
+        jas_seqent_t *data;
+        int rowstep;
+
+        rowstep = jas_matrix_rowstep(matrix);
+        for (i = matrix->numrows_, rowstart = matrix->rows_[0]; i > 0; --i,
+          rowstart += rowstep) {
+                data = rowstart;
+                for (j = matrix->numcols_, data = rowstart; j > 0; --j,
+                  ++data) {
+                        v = *data;
+                        if (v < minval) {
+                                *data = minval;
+                        } else if (v > maxval) {
+                                *data = maxval;
+                        }
+                }
+        }
 }
 
 void jas_matrix_asr(jas_matrix_t *matrix, int n)
 {
-	int i;
-	int j;
-	jas_seqent_t *rowstart;
-	int rowstep;
-	jas_seqent_t *data;
-
-	assert(n >= 0);
-	rowstep = jas_matrix_rowstep(matrix);
-	for (i = matrix->numrows_, rowstart = matrix->rows_[0]; i > 0; --i,
-	  rowstart += rowstep) {
-		for (j = matrix->numcols_, data = rowstart; j > 0; --j,
-		  ++data) {
-			*data >>= n;
-		}
-	}
+        int i;
+        int j;
+        jas_seqent_t *rowstart;
+        int rowstep;
+        jas_seqent_t *data;
+
+        assert(n >= 0);
+        rowstep = jas_matrix_rowstep(matrix);
+        for (i = matrix->numrows_, rowstart = matrix->rows_[0]; i > 0; --i,
+          rowstart += rowstep) {
+                for (j = matrix->numcols_, data = rowstart; j > 0; --j,
+                  ++data) {
+                        *data >>= n;
+                }
+        }
 }
 
 void jas_matrix_asl(jas_matrix_t *matrix, int n)
 {
-	int i;
-	int j;
-	jas_seqent_t *rowstart;
-	int rowstep;
-	jas_seqent_t *data;
-
-	rowstep = jas_matrix_rowstep(matrix);
-	for (i = matrix->numrows_, rowstart = matrix->rows_[0]; i > 0; --i,
-	  rowstart += rowstep) {
-		for (j = matrix->numcols_, data = rowstart; j > 0; --j,
-		  ++data) {
-			*data <<= n;
-		}
-	}
+        int i;
+        int j;
+        jas_seqent_t *rowstart;
+        int rowstep;
+        jas_seqent_t *data;
+
+        rowstep = jas_matrix_rowstep(matrix);
+        for (i = matrix->numrows_, rowstart = matrix->rows_[0]; i > 0; --i,
+          rowstart += rowstep) {
+                for (j = matrix->numcols_, data = rowstart; j > 0; --j,
+                  ++data) {
+                        *data <<= n;
+                }
+        }
 }
 
 /******************************************************************************\
@@ -390,87 +390,87 @@ void jas_matrix_asl(jas_matrix_t *matrix, int n)
 
 int jas_matrix_resize(jas_matrix_t *matrix, int numrows, int numcols)
 {
-	int size;
-	int i;
+        int size;
+        int i;
 
-	size = numrows * numcols;
-	if (size > matrix->datasize_ || numrows > matrix->maxrows_) {
-		return -1;
-	}
+        size = numrows * numcols;
+        if (size > matrix->datasize_ || numrows > matrix->maxrows_) {
+                return -1;
+        }
 
-	matrix->numrows_ = numrows;
-	matrix->numcols_ = numcols;
+        matrix->numrows_ = numrows;
+        matrix->numcols_ = numcols;
 
-	for (i = 0; i < numrows; ++i) {
-		matrix->rows_[i] = &matrix->data_[numcols * i];
-	}
+        for (i = 0; i < numrows; ++i) {
+                matrix->rows_[i] = &matrix->data_[numcols * i];
+        }
 
-	return 0;
+        return 0;
 }
 
 int jas_matrix_output(jas_matrix_t *matrix, FILE *out)
 {
-	int i;
-	int j;
-	jas_seqent_t x;
+        int i;
+        int j;
+        jas_seqent_t x;
 
-	fprintf(out, "%d %d\n",
+        fprintf(out, "%d %d\n",
             (int)jas_matrix_numrows(matrix), (int)jas_matrix_numcols(matrix));
-	for (i = 0; i < jas_matrix_numrows(matrix); ++i) {
-		for (j = 0; j < jas_matrix_numcols(matrix); ++j) {
-			x = jas_matrix_get(matrix, i, j);
-			fprintf(out, "%ld", JAS_CAST(long, x));
-			if (j < jas_matrix_numcols(matrix) - 1) {
-				fprintf(out, " ");
-			}
-		}
-		fprintf(out, "\n");
-	}
-	return 0;
+        for (i = 0; i < jas_matrix_numrows(matrix); ++i) {
+                for (j = 0; j < jas_matrix_numcols(matrix); ++j) {
+                        x = jas_matrix_get(matrix, i, j);
+                        fprintf(out, "%ld", JAS_CAST(long, x));
+                        if (j < jas_matrix_numcols(matrix) - 1) {
+                                fprintf(out, " ");
+                        }
+                }
+                fprintf(out, "\n");
+        }
+        return 0;
 }
 
 void jas_matrix_setall(jas_matrix_t *matrix, jas_seqent_t val)
 {
-	int i;
-	int j;
-	jas_seqent_t *rowstart;
-	int rowstep;
-	jas_seqent_t *data;
-
-	rowstep = jas_matrix_rowstep(matrix);
-	for (i = matrix->numrows_, rowstart = matrix->rows_[0]; i > 0; --i,
-	  rowstart += rowstep) {
-		for (j = matrix->numcols_, data = rowstart; j > 0; --j,
-		  ++data) {
-			*data = val;
-		}
-	}
+        int i;
+        int j;
+        jas_seqent_t *rowstart;
+        int rowstep;
+        jas_seqent_t *data;
+
+        rowstep = jas_matrix_rowstep(matrix);
+        for (i = matrix->numrows_, rowstart = matrix->rows_[0]; i > 0; --i,
+          rowstart += rowstep) {
+                for (j = matrix->numcols_, data = rowstart; j > 0; --j,
+                  ++data) {
+                        *data = val;
+                }
+        }
 }
 
 jas_matrix_t *jas_matrix_input(FILE *in)
 {
-	jas_matrix_t *matrix;
-	int i;
-	int j;
-	long x;
-	int numrows;
-	int numcols;
-
-	if (fscanf(in, "%d %d", &numrows, &numcols) != 2)
-		return 0;
-	if (!(matrix = jas_matrix_create(numrows, numcols)))
-		return 0;
-
-	/* Get matrix data. */
-	for (i = 0; i < jas_matrix_numrows(matrix); i++) {
-		for (j = 0; j < jas_matrix_numcols(matrix); j++) {
-			if (fscanf(in, "%ld", &x) != 1) {
-				jas_matrix_destroy(matrix);
-				return 0;
-			}
-			jas_matrix_set(matrix, i, j, JAS_CAST(jas_seqent_t, x));
-		}
-	}
-
-	return matrix;
+        jas_matrix_t *matrix;
+        int i;
+        int j;
+        long x;
+        int numrows;
+        int numcols;
+
+        if (fscanf(in, "%d %d", &numrows, &numcols) != 2)
+                return 0;
+        if (!(matrix = jas_matrix_create(numrows, numcols)))
+                return 0;
+
+        /* Get matrix data. */
+        for (i = 0; i < jas_matrix_numrows(matrix); i++) {
+                for (j = 0; j < jas_matrix_numcols(matrix); j++) {
+                        if (fscanf(in, "%ld", &x) != 1) {
+                                jas_matrix_destroy(matrix);
+                                return 0;
+                        }
+                        jas_matrix_set(matrix, i, j, JAS_CAST(jas_seqent_t, x));
+                }
+        }
+
+        return matrix;
 }
diff --git a/converter/other/jpeg2000/libjasper/base/jas_stream.c b/converter/other/jpeg2000/libjasper/base/jas_stream.c
index a4b3a27c..d5ddcff2 100644
--- a/converter/other/jpeg2000/libjasper/base/jas_stream.c
+++ b/converter/other/jpeg2000/libjasper/base/jas_stream.c
@@ -169,24 +169,24 @@ static int file_close(jas_stream_obj_t *obj);
 \******************************************************************************/
 
 static jas_stream_ops_t jas_stream_fileops = {
-	file_read,
-	file_write,
-	file_seek,
-	file_close
+        file_read,
+        file_write,
+        file_seek,
+        file_close
 };
 
 static jas_stream_ops_t jas_stream_sfileops = {
-	sfile_read,
-	sfile_write,
-	sfile_seek,
-	sfile_close
+        sfile_read,
+        sfile_write,
+        sfile_seek,
+        sfile_close
 };
 
 static jas_stream_ops_t jas_stream_memops = {
-	mem_read,
-	mem_write,
-	mem_seek,
-	mem_close
+        mem_read,
+        mem_write,
+        mem_seek,
+        mem_close
 };
 
 /******************************************************************************\
@@ -195,214 +195,214 @@ static jas_stream_ops_t jas_stream_memops = {
 
 static jas_stream_t *jas_stream_create()
 {
-	jas_stream_t *stream;
-
-	if (!(stream = jas_malloc(sizeof(jas_stream_t)))) {
-		return 0;
-	}
-	stream->openmode_ = 0;
-	stream->bufmode_ = 0;
-	stream->flags_ = 0;
-	stream->bufbase_ = 0;
-	stream->bufstart_ = 0;
-	stream->bufsize_ = 0;
-	stream->ptr_ = 0;
-	stream->cnt_ = 0;
-	stream->ops_ = 0;
-	stream->obj_ = 0;
-	stream->rwcnt_ = 0;
-	stream->rwlimit_ = -1;
-
-	return stream;
+        jas_stream_t *stream;
+
+        if (!(stream = jas_malloc(sizeof(jas_stream_t)))) {
+                return 0;
+        }
+        stream->openmode_ = 0;
+        stream->bufmode_ = 0;
+        stream->flags_ = 0;
+        stream->bufbase_ = 0;
+        stream->bufstart_ = 0;
+        stream->bufsize_ = 0;
+        stream->ptr_ = 0;
+        stream->cnt_ = 0;
+        stream->ops_ = 0;
+        stream->obj_ = 0;
+        stream->rwcnt_ = 0;
+        stream->rwlimit_ = -1;
+
+        return stream;
 }
 
 jas_stream_t *jas_stream_memopen(char *buf, int bufsize)
 {
-	jas_stream_t *stream;
-	jas_stream_memobj_t *obj;
-
-	if (!(stream = jas_stream_create())) {
-		return 0;
-	}
-
-	/* A stream associated with a memory buffer is always opened
-	for both reading and writing in binary mode. */
-	stream->openmode_ = JAS_STREAM_READ | JAS_STREAM_WRITE | JAS_STREAM_BINARY;
-
-	/* Since the stream data is already resident in memory, buffering
-	is not necessary. */
-	/* But... It still may be faster to use buffering anyways. */
-	jas_stream_initbuf(stream, JAS_STREAM_FULLBUF, 0, 0);
-
-	/* Select the operations for a memory stream. */
-	stream->ops_ = &jas_stream_memops;
-
-	/* Allocate memory for the underlying memory stream object. */
-	if (!(obj = jas_malloc(sizeof(jas_stream_memobj_t)))) {
-		jas_stream_destroy(stream);
-		return 0;
-	}
-	stream->obj_ = (void *) obj;
-
-	/* Initialize a few important members of the memory stream object. */
-	obj->myalloc_ = 0;
-	obj->buf_ = 0;
-
-	/* If the buffer size specified is nonpositive, then the buffer
-	is allocated internally and automatically grown as needed. */
-	if (bufsize <= 0) {
-		obj->bufsize_ = 1024;
-		obj->growable_ = 1;
-	} else {
-		obj->bufsize_ = bufsize;
-		obj->growable_ = 0;
-	}
-	if (buf) {
-		obj->buf_ = (unsigned char *) buf;
-	} else {
-		obj->buf_ = jas_malloc(obj->bufsize_ * sizeof(char));
-		obj->myalloc_ = 1;
-	}
-	if (!obj->buf_) {
-		jas_stream_close(stream);
-		return 0;
-	}
-
-	if (bufsize > 0 && buf) {
-		/* If a buffer was supplied by the caller and its length is positive,
-		  make the associated buffer data appear in the stream initially. */
-		obj->len_ = bufsize;
-	} else {
-		/* The stream is initially empty. */
-		obj->len_ = 0;
-	}
-	obj->pos_ = 0;
-
-	return stream;
+        jas_stream_t *stream;
+        jas_stream_memobj_t *obj;
+
+        if (!(stream = jas_stream_create())) {
+                return 0;
+        }
+
+        /* A stream associated with a memory buffer is always opened
+        for both reading and writing in binary mode. */
+        stream->openmode_ = JAS_STREAM_READ | JAS_STREAM_WRITE | JAS_STREAM_BINARY;
+
+        /* Since the stream data is already resident in memory, buffering
+        is not necessary. */
+        /* But... It still may be faster to use buffering anyways. */
+        jas_stream_initbuf(stream, JAS_STREAM_FULLBUF, 0, 0);
+
+        /* Select the operations for a memory stream. */
+        stream->ops_ = &jas_stream_memops;
+
+        /* Allocate memory for the underlying memory stream object. */
+        if (!(obj = jas_malloc(sizeof(jas_stream_memobj_t)))) {
+                jas_stream_destroy(stream);
+                return 0;
+        }
+        stream->obj_ = (void *) obj;
+
+        /* Initialize a few important members of the memory stream object. */
+        obj->myalloc_ = 0;
+        obj->buf_ = 0;
+
+        /* If the buffer size specified is nonpositive, then the buffer
+        is allocated internally and automatically grown as needed. */
+        if (bufsize <= 0) {
+                obj->bufsize_ = 1024;
+                obj->growable_ = 1;
+        } else {
+                obj->bufsize_ = bufsize;
+                obj->growable_ = 0;
+        }
+        if (buf) {
+                obj->buf_ = (unsigned char *) buf;
+        } else {
+                obj->buf_ = jas_malloc(obj->bufsize_ * sizeof(char));
+                obj->myalloc_ = 1;
+        }
+        if (!obj->buf_) {
+                jas_stream_close(stream);
+                return 0;
+        }
+
+        if (bufsize > 0 && buf) {
+                /* If a buffer was supplied by the caller and its length is positive,
+                  make the associated buffer data appear in the stream initially. */
+                obj->len_ = bufsize;
+        } else {
+                /* The stream is initially empty. */
+                obj->len_ = 0;
+        }
+        obj->pos_ = 0;
+
+        return stream;
 }
 
 jas_stream_t *jas_stream_fopen(const char *filename, const char *mode)
 {
-	jas_stream_t *stream;
-	int *obj;
-	int openflags;
-
-	/* Allocate a stream object. */
-	if (!(stream = jas_stream_create())) {
-		return 0;
-	}
-
-	/* Parse the mode string. */
-	stream->openmode_ = jas_strtoopenmode(mode);
-
-	/* Determine the correct flags to use for opening the file. */
-	if ((stream->openmode_ & JAS_STREAM_READ) &&
-	  (stream->openmode_ & JAS_STREAM_WRITE)) {
-		openflags = O_RDWR;
-	} else if (stream->openmode_ & JAS_STREAM_READ) {
-		openflags = O_RDONLY;
-	} else if (stream->openmode_ & JAS_STREAM_WRITE) {
-		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 |= O_CREAT | O_TRUNC;
-	}
-
-	/* Allocate space for the underlying file stream object. */
-	if (!(obj = jas_malloc(sizeof(int)))) {
-		jas_stream_destroy(stream);
-		return 0;
-	}
-	stream->obj_ = (void *) obj;
-
-	/* Select the operations for a file stream object. */
-	stream->ops_ = &jas_stream_fileops;
-
-	/* Open the underlying file. */
-	if ((*obj = open(filename, openflags, JAS_STREAM_PERMS)) < 0) {
-		jas_stream_destroy(stream);
-		return 0;
-	}
-
-	/* By default, use full buffering for this type of stream. */
-	jas_stream_initbuf(stream, JAS_STREAM_FULLBUF, 0, 0);
-
-	return stream;
+        jas_stream_t *stream;
+        int *obj;
+        int openflags;
+
+        /* Allocate a stream object. */
+        if (!(stream = jas_stream_create())) {
+                return 0;
+        }
+
+        /* Parse the mode string. */
+        stream->openmode_ = jas_strtoopenmode(mode);
+
+        /* Determine the correct flags to use for opening the file. */
+        if ((stream->openmode_ & JAS_STREAM_READ) &&
+          (stream->openmode_ & JAS_STREAM_WRITE)) {
+                openflags = O_RDWR;
+        } else if (stream->openmode_ & JAS_STREAM_READ) {
+                openflags = O_RDONLY;
+        } else if (stream->openmode_ & JAS_STREAM_WRITE) {
+                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 |= O_CREAT | O_TRUNC;
+        }
+
+        /* Allocate space for the underlying file stream object. */
+        if (!(obj = jas_malloc(sizeof(int)))) {
+                jas_stream_destroy(stream);
+                return 0;
+        }
+        stream->obj_ = (void *) obj;
+
+        /* Select the operations for a file stream object. */
+        stream->ops_ = &jas_stream_fileops;
+
+        /* Open the underlying file. */
+        if ((*obj = open(filename, openflags, JAS_STREAM_PERMS)) < 0) {
+                jas_stream_destroy(stream);
+                return 0;
+        }
+
+        /* 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;
-	int openflags;
-
-	/* Allocate a stream object. */
-	if (!(stream = jas_stream_create())) {
-		return 0;
-	}
-
-	/* Parse the mode string. */
-	stream->openmode_ = jas_strtoopenmode(mode);
-
-	/* Determine the correct flags to use for opening the file. */
-	if ((stream->openmode_ & JAS_STREAM_READ) &&
-	  (stream->openmode_ & JAS_STREAM_WRITE)) {
-		openflags = O_RDWR;
-	} else if (stream->openmode_ & JAS_STREAM_READ) {
-		openflags = O_RDONLY;
-	} else if (stream->openmode_ & JAS_STREAM_WRITE) {
-		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 |= O_CREAT | O_TRUNC;
-	}
-
-	stream->obj_ = JAS_CAST(void *, fp);
-
-	/* Select the operations for a file stream object. */
-	stream->ops_ = &jas_stream_sfileops;
-
-	/* By default, use full buffering for this type of stream. */
-	jas_stream_initbuf(stream, JAS_STREAM_FULLBUF, 0, 0);
-
-	return stream;
+        jas_stream_t *stream;
+        int openflags;
+
+        /* Allocate a stream object. */
+        if (!(stream = jas_stream_create())) {
+                return 0;
+        }
+
+        /* Parse the mode string. */
+        stream->openmode_ = jas_strtoopenmode(mode);
+
+        /* Determine the correct flags to use for opening the file. */
+        if ((stream->openmode_ & JAS_STREAM_READ) &&
+          (stream->openmode_ & JAS_STREAM_WRITE)) {
+                openflags = O_RDWR;
+        } else if (stream->openmode_ & JAS_STREAM_READ) {
+                openflags = O_RDONLY;
+        } else if (stream->openmode_ & JAS_STREAM_WRITE) {
+                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 |= O_CREAT | O_TRUNC;
+        }
+
+        stream->obj_ = JAS_CAST(void *, fp);
+
+        /* Select the operations for a file stream object. */
+        stream->ops_ = &jas_stream_sfileops;
+
+        /* By default, use full buffering for this type of stream. */
+        jas_stream_initbuf(stream, JAS_STREAM_FULLBUF, 0, 0);
+
+        return stream;
 }
 
 
 jas_stream_t *jas_stream_tmpfile()
 {
-	jas_stream_t *stream;
-	int *obj;
+        jas_stream_t *stream;
+        int *obj;
 
-	if (!(stream = jas_stream_create())) {
-		return 0;
-	}
+        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;
+        /* 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(int)))) {
-		jas_stream_destroy(stream);
-		return 0;
-	}
-	stream->obj_ = obj;
+        /* Allocate memory for the underlying temporary file object. */
+        if (!(obj = jas_malloc(sizeof(int)))) {
+                jas_stream_destroy(stream);
+                return 0;
+        }
+        stream->obj_ = obj;
 
     {
         /* This is a Netpbm enhancement.  Original Jasper library uses
@@ -423,88 +423,88 @@ jas_stream_t *jas_stream_tmpfile()
             return 0;
         }
     }
-	/* Use full buffering. */
-	jas_stream_initbuf(stream, JAS_STREAM_FULLBUF, 0, 0);
+        /* Use full buffering. */
+        jas_stream_initbuf(stream, JAS_STREAM_FULLBUF, 0, 0);
 
-	stream->ops_ = &jas_stream_fileops;
+        stream->ops_ = &jas_stream_fileops;
 
-	return stream;
+        return stream;
 }
 
 jas_stream_t *jas_stream_fdopen(int fd, const char *mode)
 {
-	jas_stream_t *stream;
-	int *obj;
+        jas_stream_t *stream;
+        int *obj;
 
-	/* Allocate a stream object. */
-	if (!(stream = jas_stream_create())) {
-		return 0;
-	}
+        /* Allocate a stream object. */
+        if (!(stream = jas_stream_create())) {
+                return 0;
+        }
 
-	/* Parse the mode string. */
-	stream->openmode_ = jas_strtoopenmode(mode);
+        /* Parse the mode string. */
+        stream->openmode_ = jas_strtoopenmode(mode);
 
 #if defined(HAVE_SETMODE) && defined(O_BINARY)
-	/* Argh!!!  Someone ought to banish text mode (i.e., O_TEXT) to the
-	  greatest depths of purgatory! */
-	/* Ensure that the file descriptor is in binary mode, if the caller
-	  has specified the binary mode flag.  Arguably, the caller ought to
-	  take care of this, but text mode is a ugly wart anyways, so we save
-	  the caller some grief by handling this within the stream library. */
-	/* This ugliness is mainly for the benefit of those who run the
-	  JasPer software under Windows from shells that insist on opening
-	  files in text mode.  For example, in the Cygwin environment,
-	  shells often open files in text mode when I/O redirection is
-	  used.  Grr... */
-	if (stream->openmode_ & JAS_STREAM_BINARY) {
-		setmode(fd, O_BINARY);
-	}
+        /* Argh!!!  Someone ought to banish text mode (i.e., O_TEXT) to the
+          greatest depths of purgatory! */
+        /* Ensure that the file descriptor is in binary mode, if the caller
+          has specified the binary mode flag.  Arguably, the caller ought to
+          take care of this, but text mode is a ugly wart anyways, so we save
+          the caller some grief by handling this within the stream library. */
+        /* This ugliness is mainly for the benefit of those who run the
+          JasPer software under Windows from shells that insist on opening
+          files in text mode.  For example, in the Cygwin environment,
+          shells often open files in text mode when I/O redirection is
+          used.  Grr... */
+        if (stream->openmode_ & JAS_STREAM_BINARY) {
+                setmode(fd, O_BINARY);
+        }
 #endif
 
-	/* Allocate space for the underlying file stream object. */
-	if (!(obj = jas_malloc(sizeof(int)))) {
-		jas_stream_destroy(stream);
-		return 0;
-	}
-	stream->obj_ = (void *) obj;
-	*obj = fd;
+        /* Allocate space for the underlying file stream object. */
+        if (!(obj = jas_malloc(sizeof(int)))) {
+                jas_stream_destroy(stream);
+                return 0;
+        }
+        stream->obj_ = (void *) obj;
+        *obj = fd;
 
-	/* By default, use full buffering for this type of stream. */
-	jas_stream_initbuf(stream, JAS_STREAM_FULLBUF, 0, 0);
+        /* By default, use full buffering for this type of stream. */
+        jas_stream_initbuf(stream, JAS_STREAM_FULLBUF, 0, 0);
 
-	/* Select the operations for a file stream object. */
-	stream->ops_ = &jas_stream_fileops;
+        /* Select the operations for a file stream object. */
+        stream->ops_ = &jas_stream_fileops;
 
 /* Do not close the underlying file descriptor when the stream is closed. */
-	stream->openmode_ |= JAS_STREAM_NOCLOSE;
+        stream->openmode_ |= JAS_STREAM_NOCLOSE;
 
-	return stream;
+        return stream;
 }
 
 static void jas_stream_destroy(jas_stream_t *stream)
 {
-	/* If the memory for the buffer was allocated with malloc, free
-	this memory. */
-	if ((stream->bufmode_ & JAS_STREAM_FREEBUF) && stream->bufbase_) {
-		jas_free(stream->bufbase_);
-		stream->bufbase_ = 0;
-	}
-	jas_free(stream);
+        /* If the memory for the buffer was allocated with malloc, free
+        this memory. */
+        if ((stream->bufmode_ & JAS_STREAM_FREEBUF) && stream->bufbase_) {
+                jas_free(stream->bufbase_);
+                stream->bufbase_ = 0;
+        }
+        jas_free(stream);
 }
 
 int jas_stream_close(jas_stream_t *stream)
 {
-	/* Flush buffer if necessary. */
-	jas_stream_flush(stream);
+        /* Flush buffer if necessary. */
+        jas_stream_flush(stream);
 
-	/* Close the underlying stream object. */
-	if (!(stream->openmode_ & JAS_STREAM_NOCLOSE)) {
-		(*stream->ops_->close_)(stream->obj_);
-	}
+        /* Close the underlying stream object. */
+        if (!(stream->openmode_ & JAS_STREAM_NOCLOSE)) {
+                (*stream->ops_->close_)(stream->obj_);
+        }
 
-	jas_stream_destroy(stream);
+        jas_stream_destroy(stream);
 
-	return 0;
+        return 0;
 }
 
 /******************************************************************************\
@@ -513,71 +513,71 @@ int jas_stream_close(jas_stream_t *stream)
 
 int jas_stream_getc_func(jas_stream_t *stream)
 {
-	assert(stream->ptr_ - stream->bufbase_ <= stream->bufsize_ +
-	  JAS_STREAM_MAXPUTBACK);
-	return jas_stream_getc_macro(stream);
+        assert(stream->ptr_ - stream->bufbase_ <= stream->bufsize_ +
+          JAS_STREAM_MAXPUTBACK);
+        return jas_stream_getc_macro(stream);
 }
 
 int jas_stream_putc_func(jas_stream_t *stream, int c)
 {
-	assert(stream->ptr_ - stream->bufstart_ <= stream->bufsize_);
-	return jas_stream_putc_macro(stream, c);
+        assert(stream->ptr_ - stream->bufstart_ <= stream->bufsize_);
+        return jas_stream_putc_macro(stream, c);
 }
 
 int jas_stream_ungetc(jas_stream_t *stream, int c)
 {
-	if (!stream->ptr_ || stream->ptr_ == stream->bufbase_) {
-		return -1;
-	}
-
-	/* Reset the EOF indicator (since we now have at least one character
-	  to read). */
-	stream->flags_ &= ~JAS_STREAM_EOF;
-
-	--stream->rwcnt_;
-	--stream->ptr_;
-	++stream->cnt_;
-	*stream->ptr_ = c;
-	return 0;
+        if (!stream->ptr_ || stream->ptr_ == stream->bufbase_) {
+                return -1;
+        }
+
+        /* Reset the EOF indicator (since we now have at least one character
+          to read). */
+        stream->flags_ &= ~JAS_STREAM_EOF;
+
+        --stream->rwcnt_;
+        --stream->ptr_;
+        ++stream->cnt_;
+        *stream->ptr_ = c;
+        return 0;
 }
 
 int jas_stream_read(jas_stream_t *stream, void *buf, int cnt)
 {
-	int n;
-	int c;
-	char *bufptr;
-
-	bufptr = buf;
-
-	n = 0;
-	while (n < cnt) {
-		if ((c = jas_stream_getc(stream)) == EOF) {
-			return n;
-		}
-		*bufptr++ = c;
-		++n;
-	}
-
-	return n;
+        int n;
+        int c;
+        char *bufptr;
+
+        bufptr = buf;
+
+        n = 0;
+        while (n < cnt) {
+                if ((c = jas_stream_getc(stream)) == EOF) {
+                        return n;
+                }
+                *bufptr++ = c;
+                ++n;
+        }
+
+        return n;
 }
 
 int jas_stream_write(jas_stream_t *stream, const void *buf, int cnt)
 {
-	int n;
-	const char *bufptr;
-
-	bufptr = buf;
-
-	n = 0;
-	while (n < cnt) {
-		if (jas_stream_putc(stream, *bufptr) == EOF) {
-			return n;
-		}
-		++bufptr;
-		++n;
-	}
+        int n;
+        const char *bufptr;
+
+        bufptr = buf;
+
+        n = 0;
+        while (n < cnt) {
+                if (jas_stream_putc(stream, *bufptr) == EOF) {
+                        return n;
+                }
+                ++bufptr;
+                ++n;
+        }
 
-	return n;
+        return n;
 }
 
 /* Note: This function uses a fixed size buffer.  Therefore, it cannot
@@ -585,59 +585,59 @@ int jas_stream_write(jas_stream_t *stream, const void *buf, int cnt)
   by the buffer. */
 int jas_stream_printf(jas_stream_t *stream, const char *fmt, ...)
 {
-	va_list ap;
-	char buf[4096];
-	int ret;
-
-	va_start(ap, fmt);
-	ret = vsprintf(buf, fmt, ap);
-	jas_stream_puts(stream, buf);
-	va_end(ap);
-	return ret;
+        va_list ap;
+        char buf[4096];
+        int ret;
+
+        va_start(ap, fmt);
+        ret = vsprintf(buf, fmt, ap);
+        jas_stream_puts(stream, buf);
+        va_end(ap);
+        return ret;
 }
 
 int jas_stream_puts(jas_stream_t *stream, const char *s)
 {
-	while (*s != '\0') {
-		if (jas_stream_putc_macro(stream, *s) == EOF) {
-			return -1;
-		}
-		++s;
-	}
-	return 0;
+        while (*s != '\0') {
+                if (jas_stream_putc_macro(stream, *s) == EOF) {
+                        return -1;
+                }
+                ++s;
+        }
+        return 0;
 }
 
 char *jas_stream_gets(jas_stream_t *stream, char *buf, int bufsize)
 {
-	int c;
-	char *bufptr;
-	assert(bufsize > 0);
-
-	bufptr = buf;
-	while (bufsize > 1) {
-		if ((c = jas_stream_getc(stream)) == EOF) {
-			break;
-		}
-		*bufptr++ = c;
-		--bufsize;
-		if (c == '\n') {
-			break;
-		}
-	}
-	*bufptr = '\0';
-	return buf;
+        int c;
+        char *bufptr;
+        assert(bufsize > 0);
+
+        bufptr = buf;
+        while (bufsize > 1) {
+                if ((c = jas_stream_getc(stream)) == EOF) {
+                        break;
+                }
+                *bufptr++ = c;
+                --bufsize;
+                if (c == '\n') {
+                        break;
+                }
+        }
+        *bufptr = '\0';
+        return buf;
 }
 
 int jas_stream_gobble(jas_stream_t *stream, int n)
 {
-	int m;
-	m = n;
-	for (m = n; m > 0; --m) {
-		if (jas_stream_getc(stream) == EOF) {
-			return n - m;
-		}
-	}
-	return n;
+        int m;
+        m = n;
+        for (m = n; m > 0; --m) {
+                if (jas_stream_getc(stream) == EOF) {
+                        return n - m;
+                }
+        }
+        return n;
 }
 
 /******************************************************************************\
@@ -646,73 +646,73 @@ int jas_stream_gobble(jas_stream_t *stream, int n)
 
 int jas_stream_isseekable(jas_stream_t *stream)
 {
-	if (stream->ops_ == &jas_stream_memops) {
-		return 1;
-	} else if (stream->ops_ == &jas_stream_fileops) {
-		if ((*stream->ops_->seek_)(stream->obj_, 0, SEEK_CUR) < 0) {
-			return 0;
-		}
-		return 1;
-	} else {
-		return 0;
-	}
+        if (stream->ops_ == &jas_stream_memops) {
+                return 1;
+        } else if (stream->ops_ == &jas_stream_fileops) {
+                if ((*stream->ops_->seek_)(stream->obj_, 0, SEEK_CUR) < 0) {
+                        return 0;
+                }
+                return 1;
+        } else {
+                return 0;
+        }
 }
 
 int jas_stream_rewind(jas_stream_t *stream)
 {
-	return jas_stream_seek(stream, 0, SEEK_SET);
+        return jas_stream_seek(stream, 0, SEEK_SET);
 }
 
 long jas_stream_seek(jas_stream_t *stream, long offset, int origin)
 {
-	long newpos;
-
-	/* The buffer cannot be in use for both reading and writing. */
-	assert(!((stream->bufmode_ & JAS_STREAM_RDBUF) && (stream->bufmode_ &
-	  JAS_STREAM_WRBUF)));
-
-	/* Reset the EOF indicator (since we may not be at the EOF anymore). */
-	stream->flags_ &= ~JAS_STREAM_EOF;
-
-	if (stream->bufmode_ & JAS_STREAM_RDBUF) {
-		if (origin == SEEK_CUR) {
-			offset -= stream->cnt_;
-		}
-	} else if (stream->bufmode_ & JAS_STREAM_WRBUF) {
-		if (jas_stream_flush(stream)) {
-			return -1;
-		}
-	}
-	stream->cnt_ = 0;
-	stream->ptr_ = stream->bufstart_;
-	stream->bufmode_ &= ~(JAS_STREAM_RDBUF | JAS_STREAM_WRBUF);
-
-	if ((newpos = (*stream->ops_->seek_)(stream->obj_, offset, origin))
-	  < 0) {
-		return -1;
-	}
-
-	return newpos;
+        long newpos;
+
+        /* The buffer cannot be in use for both reading and writing. */
+        assert(!((stream->bufmode_ & JAS_STREAM_RDBUF) && (stream->bufmode_ &
+          JAS_STREAM_WRBUF)));
+
+        /* Reset the EOF indicator (since we may not be at the EOF anymore). */
+        stream->flags_ &= ~JAS_STREAM_EOF;
+
+        if (stream->bufmode_ & JAS_STREAM_RDBUF) {
+                if (origin == SEEK_CUR) {
+                        offset -= stream->cnt_;
+                }
+        } else if (stream->bufmode_ & JAS_STREAM_WRBUF) {
+                if (jas_stream_flush(stream)) {
+                        return -1;
+                }
+        }
+        stream->cnt_ = 0;
+        stream->ptr_ = stream->bufstart_;
+        stream->bufmode_ &= ~(JAS_STREAM_RDBUF | JAS_STREAM_WRBUF);
+
+        if ((newpos = (*stream->ops_->seek_)(stream->obj_, offset, origin))
+          < 0) {
+                return -1;
+        }
+
+        return newpos;
 }
 
 long jas_stream_tell(jas_stream_t *stream)
 {
-	int adjust;
-	int offset;
-
-	if (stream->bufmode_ & JAS_STREAM_RDBUF) {
-		adjust = -stream->cnt_;
-	} else if (stream->bufmode_ & JAS_STREAM_WRBUF) {
-		adjust = stream->ptr_ - stream->bufstart_;
-	} else {
-		adjust = 0;
-	}
-
-	if ((offset = (*stream->ops_->seek_)(stream->obj_, 0, SEEK_CUR)) < 0) {
-		return -1;
-	}
-
-	return offset + adjust;
+        int adjust;
+        int offset;
+
+        if (stream->bufmode_ & JAS_STREAM_RDBUF) {
+                adjust = -stream->cnt_;
+        } else if (stream->bufmode_ & JAS_STREAM_WRBUF) {
+                adjust = stream->ptr_ - stream->bufstart_;
+        } else {
+                adjust = 0;
+        }
+
+        if ((offset = (*stream->ops_->seek_)(stream->obj_, 0, SEEK_CUR)) < 0) {
+                return -1;
+        }
+
+        return offset + adjust;
 }
 
 /******************************************************************************\
@@ -722,45 +722,45 @@ long jas_stream_tell(jas_stream_t *stream)
 static void jas_stream_initbuf(jas_stream_t *stream, int bufmode, char *buf,
   int bufsize)
 {
-	/* If this function is being called, the buffer should not have been
-	  initialized yet. */
-	assert(!stream->bufbase_);
-
-	if (bufmode != JAS_STREAM_UNBUF) {
-		/* The full- or line-buffered mode is being employed. */
-		if (!buf) {
-			/* The caller has not specified a buffer to employ, so allocate
-			  one. */
-			if ((stream->bufbase_ = jas_malloc(JAS_STREAM_BUFSIZE +
-			  JAS_STREAM_MAXPUTBACK))) {
-				stream->bufmode_ |= JAS_STREAM_FREEBUF;
-				stream->bufsize_ = JAS_STREAM_BUFSIZE;
-			} else {
-				/* The buffer allocation has failed.  Resort to unbuffered
-				  operation. */
-				stream->bufbase_ = stream->tinybuf_;
-				stream->bufsize_ = 1;
-			}
-		} else {
-			/* The caller has specified a buffer to employ. */
-			/* The buffer must be large enough to accommodate maximum
-			  putback. */
-			assert(bufsize > JAS_STREAM_MAXPUTBACK);
-			stream->bufbase_ = JAS_CAST(unsigned char *, buf);
-			stream->bufsize_ = bufsize - JAS_STREAM_MAXPUTBACK;
-		}
-	} else {
-		/* The unbuffered mode is being employed. */
-		/* A buffer should not have been supplied by the caller. */
-		assert(!buf);
-		/* Use a trivial one-character buffer. */
-		stream->bufbase_ = stream->tinybuf_;
-		stream->bufsize_ = 1;
-	}
-	stream->bufstart_ = &stream->bufbase_[JAS_STREAM_MAXPUTBACK];
-	stream->ptr_ = stream->bufstart_;
-	stream->cnt_ = 0;
-	stream->bufmode_ |= bufmode & JAS_STREAM_BUFMODEMASK;
+        /* If this function is being called, the buffer should not have been
+          initialized yet. */
+        assert(!stream->bufbase_);
+
+        if (bufmode != JAS_STREAM_UNBUF) {
+                /* The full- or line-buffered mode is being employed. */
+                if (!buf) {
+                        /* The caller has not specified a buffer to employ, so allocate
+                          one. */
+                        if ((stream->bufbase_ = jas_malloc(JAS_STREAM_BUFSIZE +
+                          JAS_STREAM_MAXPUTBACK))) {
+                                stream->bufmode_ |= JAS_STREAM_FREEBUF;
+                                stream->bufsize_ = JAS_STREAM_BUFSIZE;
+                        } else {
+                                /* The buffer allocation has failed.  Resort to unbuffered
+                                  operation. */
+                                stream->bufbase_ = stream->tinybuf_;
+                                stream->bufsize_ = 1;
+                        }
+                } else {
+                        /* The caller has specified a buffer to employ. */
+                        /* The buffer must be large enough to accommodate maximum
+                          putback. */
+                        assert(bufsize > JAS_STREAM_MAXPUTBACK);
+                        stream->bufbase_ = JAS_CAST(unsigned char *, buf);
+                        stream->bufsize_ = bufsize - JAS_STREAM_MAXPUTBACK;
+                }
+        } else {
+                /* The unbuffered mode is being employed. */
+                /* A buffer should not have been supplied by the caller. */
+                assert(!buf);
+                /* Use a trivial one-character buffer. */
+                stream->bufbase_ = stream->tinybuf_;
+                stream->bufsize_ = 1;
+        }
+        stream->bufstart_ = &stream->bufbase_[JAS_STREAM_MAXPUTBACK];
+        stream->ptr_ = stream->bufstart_;
+        stream->cnt_ = 0;
+        stream->bufmode_ |= bufmode & JAS_STREAM_BUFMODEMASK;
 }
 
 /******************************************************************************\
@@ -769,97 +769,97 @@ static void jas_stream_initbuf(jas_stream_t *stream, int bufmode, char *buf,
 
 int jas_stream_flush(jas_stream_t *stream)
 {
-	if (stream->bufmode_ & JAS_STREAM_RDBUF) {
-		return 0;
-	}
-	return jas_stream_flushbuf(stream, EOF);
+        if (stream->bufmode_ & JAS_STREAM_RDBUF) {
+                return 0;
+        }
+        return jas_stream_flushbuf(stream, EOF);
 }
 
 int jas_stream_fillbuf(jas_stream_t *stream, int getflag)
 {
-	int c;
-
-	/* The stream must not be in an error or EOF state. */
-	if ((stream->flags_ & (JAS_STREAM_ERRMASK)) != 0) {
-		return EOF;
-	}
-
-	/* The stream must be open for reading. */
-	if ((stream->openmode_ & JAS_STREAM_READ) == 0) {
-		return EOF;
-	}
-
-	/* Make a half-hearted attempt to confirm that the buffer is not
-	currently being used for writing.  This check is not intended
-	to be foolproof! */
-	assert((stream->bufmode_ & JAS_STREAM_WRBUF) == 0);
-
-	assert(stream->ptr_ - stream->bufstart_ <= stream->bufsize_);
-
-	/* Mark the buffer as being used for reading. */
-	stream->bufmode_ |= JAS_STREAM_RDBUF;
-
-	/* Read new data into the buffer. */
-	stream->ptr_ = stream->bufstart_;
-	if ((stream->cnt_ = (*stream->ops_->read_)(stream->obj_,
-	  (char *) stream->bufstart_, stream->bufsize_)) <= 0) {
-		if (stream->cnt_ < 0) {
-			stream->flags_ |= JAS_STREAM_ERR;
-		} else {
-			stream->flags_ |= JAS_STREAM_EOF;
-		}
-		stream->cnt_ = 0;
-		return EOF;
-	}
-
-	assert(stream->cnt_ > 0);
-	/* Get or peek at the first character in the buffer. */
-	c = (getflag) ? jas_stream_getc2(stream) : (*stream->ptr_);
-
-	return c;
+        int c;
+
+        /* The stream must not be in an error or EOF state. */
+        if ((stream->flags_ & (JAS_STREAM_ERRMASK)) != 0) {
+                return EOF;
+        }
+
+        /* The stream must be open for reading. */
+        if ((stream->openmode_ & JAS_STREAM_READ) == 0) {
+                return EOF;
+        }
+
+        /* Make a half-hearted attempt to confirm that the buffer is not
+        currently being used for writing.  This check is not intended
+        to be foolproof! */
+        assert((stream->bufmode_ & JAS_STREAM_WRBUF) == 0);
+
+        assert(stream->ptr_ - stream->bufstart_ <= stream->bufsize_);
+
+        /* Mark the buffer as being used for reading. */
+        stream->bufmode_ |= JAS_STREAM_RDBUF;
+
+        /* Read new data into the buffer. */
+        stream->ptr_ = stream->bufstart_;
+        if ((stream->cnt_ = (*stream->ops_->read_)(stream->obj_,
+          (char *) stream->bufstart_, stream->bufsize_)) <= 0) {
+                if (stream->cnt_ < 0) {
+                        stream->flags_ |= JAS_STREAM_ERR;
+                } else {
+                        stream->flags_ |= JAS_STREAM_EOF;
+                }
+                stream->cnt_ = 0;
+                return EOF;
+        }
+
+        assert(stream->cnt_ > 0);
+        /* Get or peek at the first character in the buffer. */
+        c = (getflag) ? jas_stream_getc2(stream) : (*stream->ptr_);
+
+        return c;
 }
 
 int jas_stream_flushbuf(jas_stream_t *stream, int c)
 {
-	int len;
-	int n;
-
-	/* The stream should not be in an error or EOF state. */
-	if ((stream->flags_ & (JAS_STREAM_ERRMASK)) != 0) {
-		return EOF;
-	}
-
-	/* The stream must be open for writing. */
-	if ((stream->openmode_ & (JAS_STREAM_WRITE | JAS_STREAM_APPEND)) == 0) {
-		return EOF;
-	}
-
-	/* The buffer should not currently be in use for reading. */
-	assert(!(stream->bufmode_ & JAS_STREAM_RDBUF));
-
-	/* Note: Do not use the quantity stream->cnt to determine the number
-	of characters in the buffer!  Depending on how this function was
-	called, the stream->cnt value may be "off-by-one". */
-	len = stream->ptr_ - stream->bufstart_;
-	if (len > 0) {
-		n = (*stream->ops_->write_)(stream->obj_, (char *)
-		  stream->bufstart_, len);
-		if (n != len) {
-			stream->flags_ |= JAS_STREAM_ERR;
-			return EOF;
-		}
-	}
-	stream->cnt_ = stream->bufsize_;
-	stream->ptr_ = stream->bufstart_;
-
-	stream->bufmode_ |= JAS_STREAM_WRBUF;
-
-	if (c != EOF) {
-		assert(stream->cnt_ > 0);
-		jas_stream_putc2(stream, c);
-	}
-
-	return 0;
+        int len;
+        int n;
+
+        /* The stream should not be in an error or EOF state. */
+        if ((stream->flags_ & (JAS_STREAM_ERRMASK)) != 0) {
+                return EOF;
+        }
+
+        /* The stream must be open for writing. */
+        if ((stream->openmode_ & (JAS_STREAM_WRITE | JAS_STREAM_APPEND)) == 0) {
+                return EOF;
+        }
+
+        /* The buffer should not currently be in use for reading. */
+        assert(!(stream->bufmode_ & JAS_STREAM_RDBUF));
+
+        /* Note: Do not use the quantity stream->cnt to determine the number
+        of characters in the buffer!  Depending on how this function was
+        called, the stream->cnt value may be "off-by-one". */
+        len = stream->ptr_ - stream->bufstart_;
+        if (len > 0) {
+                n = (*stream->ops_->write_)(stream->obj_, (char *)
+                  stream->bufstart_, len);
+                if (n != len) {
+                        stream->flags_ |= JAS_STREAM_ERR;
+                        return EOF;
+                }
+        }
+        stream->cnt_ = stream->bufsize_;
+        stream->ptr_ = stream->bufstart_;
+
+        stream->bufmode_ |= JAS_STREAM_WRBUF;
+
+        if (c != EOF) {
+                assert(stream->cnt_ > 0);
+                jas_stream_putc2(stream, c);
+        }
+
+        return 0;
 }
 
 /******************************************************************************\
@@ -868,134 +868,134 @@ int jas_stream_flushbuf(jas_stream_t *stream, int c)
 
 static int jas_strtoopenmode(const char *s)
 {
-	int openmode = 0;
-	while (*s != '\0') {
-		switch (*s) {
-		case 'r':
-			openmode |= JAS_STREAM_READ;
-			break;
-		case 'w':
-			openmode |= JAS_STREAM_WRITE | JAS_STREAM_CREATE;
-			break;
-		case 'b':
-			openmode |= JAS_STREAM_BINARY;
-			break;
-		case 'a':
-			openmode |= JAS_STREAM_APPEND;
-			break;
-		case '+':
-			openmode |= JAS_STREAM_READ | JAS_STREAM_WRITE;
-			break;
-		default:
-			break;
-		}
-		++s;
-	}
-	return openmode;
+        int openmode = 0;
+        while (*s != '\0') {
+                switch (*s) {
+                case 'r':
+                        openmode |= JAS_STREAM_READ;
+                        break;
+                case 'w':
+                        openmode |= JAS_STREAM_WRITE | JAS_STREAM_CREATE;
+                        break;
+                case 'b':
+                        openmode |= JAS_STREAM_BINARY;
+                        break;
+                case 'a':
+                        openmode |= JAS_STREAM_APPEND;
+                        break;
+                case '+':
+                        openmode |= JAS_STREAM_READ | JAS_STREAM_WRITE;
+                        break;
+                default:
+                        break;
+                }
+                ++s;
+        }
+        return openmode;
 }
 
 int jas_stream_copy(jas_stream_t *out, jas_stream_t *in, int n)
 {
-	int all;
-	int c;
-	int m;
-
-	all = (n < 0) ? 1 : 0;
-
-	m = n;
-	while (all || m > 0) {
-		if ((c = jas_stream_getc_macro(in)) == EOF) {
-			/* The next character of input could not be read. */
-			/* Return with an error if an I/O error occurred
-			  (not including EOF) or if an explicit copy count
-			  was specified. */
-			return (!all || jas_stream_error(in)) ? (-1) : 0;
-		}
-		if (jas_stream_putc_macro(out, c) == EOF) {
-			return -1;
-		}
-		--m;
-	}
-	return 0;
+        int all;
+        int c;
+        int m;
+
+        all = (n < 0) ? 1 : 0;
+
+        m = n;
+        while (all || m > 0) {
+                if ((c = jas_stream_getc_macro(in)) == EOF) {
+                        /* The next character of input could not be read. */
+                        /* Return with an error if an I/O error occurred
+                          (not including EOF) or if an explicit copy count
+                          was specified. */
+                        return (!all || jas_stream_error(in)) ? (-1) : 0;
+                }
+                if (jas_stream_putc_macro(out, c) == EOF) {
+                        return -1;
+                }
+                --m;
+        }
+        return 0;
 }
 
 long jas_stream_setrwcount(jas_stream_t *stream, long rwcnt)
 {
-	int old;
+        int old;
 
-	old = stream->rwcnt_;
-	stream->rwcnt_ = rwcnt;
-	return old;
+        old = stream->rwcnt_;
+        stream->rwcnt_ = rwcnt;
+        return old;
 }
 
 int jas_stream_display(jas_stream_t *stream, FILE *fp, int n)
 {
-	unsigned char buf[16];
-	int i;
-	int j;
-	int m;
-	int c;
-	int display;
-	int cnt;
-
-	cnt = n - (n % 16);
-	display = 1;
-
-	for (i = 0; i < n; i += 16) {
-		if (n > 16 && i > 0) {
-			display = (i >= cnt) ? 1 : 0;
-		}
-		if (display) {
-			fprintf(fp, "%08x:", i);
-		}
-		m = JAS_MIN(n - i, 16);
-		for (j = 0; j < m; ++j) {
-			if ((c = jas_stream_getc(stream)) == EOF) {
-				abort();
-				return -1;
-			}
-			buf[j] = c;
-		}
-		if (display) {
-			for (j = 0; j < m; ++j) {
-				fprintf(fp, " %02x", buf[j]);
-			}
-			fputc(' ', fp);
-			for (; j < 16; ++j) {
-				fprintf(fp, "   ");
-			}
-			for (j = 0; j < m; ++j) {
-				if (isprint(buf[j])) {
-					fputc(buf[j], fp);
-				} else {
-					fputc(' ', fp);
-				}
-			}
-			fprintf(fp, "\n");
-		}
-
-
-	}
-	return 0;
+        unsigned char buf[16];
+        int i;
+        int j;
+        int m;
+        int c;
+        int display;
+        int cnt;
+
+        cnt = n - (n % 16);
+        display = 1;
+
+        for (i = 0; i < n; i += 16) {
+                if (n > 16 && i > 0) {
+                        display = (i >= cnt) ? 1 : 0;
+                }
+                if (display) {
+                        fprintf(fp, "%08x:", i);
+                }
+                m = JAS_MIN(n - i, 16);
+                for (j = 0; j < m; ++j) {
+                        if ((c = jas_stream_getc(stream)) == EOF) {
+                                abort();
+                                return -1;
+                        }
+                        buf[j] = c;
+                }
+                if (display) {
+                        for (j = 0; j < m; ++j) {
+                                fprintf(fp, " %02x", buf[j]);
+                        }
+                        fputc(' ', fp);
+                        for (; j < 16; ++j) {
+                                fprintf(fp, "   ");
+                        }
+                        for (j = 0; j < m; ++j) {
+                                if (isprint(buf[j])) {
+                                        fputc(buf[j], fp);
+                                } else {
+                                        fputc(' ', fp);
+                                }
+                        }
+                        fprintf(fp, "\n");
+                }
+
+
+        }
+        return 0;
 }
 
 long jas_stream_length(jas_stream_t *stream)
 {
-	long oldpos;
-	long pos;
-	if ((oldpos = jas_stream_tell(stream)) < 0) {
-		return -1;
-	}
-	if (jas_stream_seek(stream, 0, SEEK_END) < 0) {
-		return -1;
-	}
-	if ((pos = jas_stream_tell(stream)) < 0) {
-		return -1;
-	}
-	if (jas_stream_seek(stream, oldpos, SEEK_SET) < 0) {
-		return -1;
-	}
-	return pos;
+        long oldpos;
+        long pos;
+        if ((oldpos = jas_stream_tell(stream)) < 0) {
+                return -1;
+        }
+        if (jas_stream_seek(stream, 0, SEEK_END) < 0) {
+                return -1;
+        }
+        if ((pos = jas_stream_tell(stream)) < 0) {
+                return -1;
+        }
+        if (jas_stream_seek(stream, oldpos, SEEK_SET) < 0) {
+                return -1;
+        }
+        return pos;
 }
 
 /******************************************************************************\
@@ -1004,109 +1004,109 @@ long jas_stream_length(jas_stream_t *stream)
 
 static int mem_read(jas_stream_obj_t *obj, char *buf, int cnt)
 {
-	int n;
-	jas_stream_memobj_t *m = (jas_stream_memobj_t *)obj;
-	n = m->len_ - m->pos_;
-	cnt = JAS_MIN(n, cnt);
-	memcpy(buf, &m->buf_[m->pos_], cnt);
-	m->pos_ += cnt;
-	return cnt;
+        int n;
+        jas_stream_memobj_t *m = (jas_stream_memobj_t *)obj;
+        n = m->len_ - m->pos_;
+        cnt = JAS_MIN(n, cnt);
+        memcpy(buf, &m->buf_[m->pos_], cnt);
+        m->pos_ += cnt;
+        return cnt;
 }
 
 static int mem_resize(jas_stream_memobj_t *m, int bufsize)
 {
-	unsigned char *buf;
-
-	assert(m->buf_);
-	if (!(buf = jas_realloc(m->buf_, bufsize * sizeof(unsigned char)))) {
-		return -1;
-	}
-	m->buf_ = buf;
-	m->bufsize_ = bufsize;
-	return 0;
+        unsigned char *buf;
+
+        assert(m->buf_);
+        if (!(buf = jas_realloc(m->buf_, bufsize * sizeof(unsigned char)))) {
+                return -1;
+        }
+        m->buf_ = buf;
+        m->bufsize_ = bufsize;
+        return 0;
 }
 
 static int mem_write(jas_stream_obj_t *obj, char *buf, int cnt)
 {
-	int n;
-	int ret;
-	jas_stream_memobj_t *m = (jas_stream_memobj_t *)obj;
-	long newbufsize;
-	long newpos;
-
-	newpos = m->pos_ + cnt;
-	if (newpos > m->bufsize_ && m->growable_) {
-		newbufsize = m->bufsize_;
-		while (newbufsize < newpos) {
-			newbufsize <<= 1;
-			assert(newbufsize >= 0);
-		}
-		if (mem_resize(m, newbufsize)) {
-			return -1;
-		}
-	}
-	if (m->pos_ > m->len_) {
-		/* The current position is beyond the end of the file, so
-		  pad the file to the current position with zeros. */
-		n = JAS_MIN(m->pos_, m->bufsize_) - m->len_;
-		if (n > 0) {
-			memset(&m->buf_[m->len_], 0, n);
-			m->len_ += n;
-		}
-		if (m->pos_ != m->len_) {
-			/* The buffer is not big enough. */
-			return 0;
-		}
-	}
-	n = m->bufsize_ - m->pos_;
-	ret = JAS_MIN(n, cnt);
-	if (ret > 0) {
-		memcpy(&m->buf_[m->pos_], buf, ret);
-		m->pos_ += ret;
-	}
-	if (m->pos_ > m->len_) {
-		m->len_ = m->pos_;
-	}
+        int n;
+        int ret;
+        jas_stream_memobj_t *m = (jas_stream_memobj_t *)obj;
+        long newbufsize;
+        long newpos;
+
+        newpos = m->pos_ + cnt;
+        if (newpos > m->bufsize_ && m->growable_) {
+                newbufsize = m->bufsize_;
+                while (newbufsize < newpos) {
+                        newbufsize <<= 1;
+                        assert(newbufsize >= 0);
+                }
+                if (mem_resize(m, newbufsize)) {
+                        return -1;
+                }
+        }
+        if (m->pos_ > m->len_) {
+                /* The current position is beyond the end of the file, so
+                  pad the file to the current position with zeros. */
+                n = JAS_MIN(m->pos_, m->bufsize_) - m->len_;
+                if (n > 0) {
+                        memset(&m->buf_[m->len_], 0, n);
+                        m->len_ += n;
+                }
+                if (m->pos_ != m->len_) {
+                        /* The buffer is not big enough. */
+                        return 0;
+                }
+        }
+        n = m->bufsize_ - m->pos_;
+        ret = JAS_MIN(n, cnt);
+        if (ret > 0) {
+                memcpy(&m->buf_[m->pos_], buf, ret);
+                m->pos_ += ret;
+        }
+        if (m->pos_ > m->len_) {
+                m->len_ = m->pos_;
+        }
 assert(ret == cnt);
-	return ret;
+        return ret;
 }
 
 static long mem_seek(jas_stream_obj_t *obj, long offset, int origin)
 {
-	jas_stream_memobj_t *m = (jas_stream_memobj_t *)obj;
-	long newpos;
-
-	switch (origin) {
-	case SEEK_SET:
-		newpos = offset;
-		break;
-	case SEEK_END:
-		newpos = m->len_ - offset;
-		break;
-	case SEEK_CUR:
-		newpos = m->pos_ + offset;
-		break;
-	default:
-		abort();
-		break;
-	}
-	if (newpos < 0) {
-		return -1;
-	}
-	m->pos_ = newpos;
-
-	return m->pos_;
+        jas_stream_memobj_t *m = (jas_stream_memobj_t *)obj;
+        long newpos;
+
+        switch (origin) {
+        case SEEK_SET:
+                newpos = offset;
+                break;
+        case SEEK_END:
+                newpos = m->len_ - offset;
+                break;
+        case SEEK_CUR:
+                newpos = m->pos_ + offset;
+                break;
+        default:
+                abort();
+                break;
+        }
+        if (newpos < 0) {
+                return -1;
+        }
+        m->pos_ = newpos;
+
+        return m->pos_;
 }
 
 static int mem_close(jas_stream_obj_t *obj)
 {
-	jas_stream_memobj_t *m = (jas_stream_memobj_t *)obj;
-	if (m->myalloc_ && m->buf_) {
-		jas_free(m->buf_);
-		m->buf_ = 0;
-	}
-	jas_free(obj);
-	return 0;
+        jas_stream_memobj_t *m = (jas_stream_memobj_t *)obj;
+        if (m->myalloc_ && m->buf_) {
+                jas_free(m->buf_);
+                m->buf_ = 0;
+        }
+        jas_free(obj);
+        return 0;
 }
 
 /******************************************************************************\
@@ -1115,31 +1115,31 @@ static int mem_close(jas_stream_obj_t *obj)
 
 static int file_read(jas_stream_obj_t *obj, char *buf, int cnt)
 {
-	int fd;
-	fd = *((int *)obj);
-	return read(fd, buf, cnt);
+        int fd;
+        fd = *((int *)obj);
+        return read(fd, buf, cnt);
 }
 
 static int file_write(jas_stream_obj_t *obj, char *buf, int cnt)
 {
-	int fd;
-	fd = *((int *)obj);
-	return write(fd, buf, cnt);
+        int fd;
+        fd = *((int *)obj);
+        return write(fd, buf, cnt);
 }
 
 static long file_seek(jas_stream_obj_t *obj, long offset, int origin)
 {
-	int fd;
-	fd = *((int *)obj);
-	return lseek(fd, offset, origin);
+        int fd;
+        fd = *((int *)obj);
+        return lseek(fd, offset, origin);
 }
 
 static int file_close(jas_stream_obj_t *obj)
 {
-	int fd;
-	fd = *((int *)obj);
-	jas_free(obj);
-	return close(fd);
+        int fd;
+        fd = *((int *)obj);
+        jas_free(obj);
+        return close(fd);
 }
 
 /******************************************************************************\
@@ -1148,28 +1148,28 @@ static int file_close(jas_stream_obj_t *obj)
 
 static int sfile_read(jas_stream_obj_t *obj, char *buf, int cnt)
 {
-	FILE *fp;
-	fp = JAS_CAST(FILE *, obj);
-	return fread(buf, 1, cnt, fp);
+        FILE *fp;
+        fp = JAS_CAST(FILE *, obj);
+        return fread(buf, 1, cnt, fp);
 }
 
 static int sfile_write(jas_stream_obj_t *obj, char *buf, int cnt)
 {
-	FILE *fp;
-	fp = JAS_CAST(FILE *, obj);
-	return fwrite(buf, 1, cnt, fp);
+        FILE *fp;
+        fp = JAS_CAST(FILE *, obj);
+        return fwrite(buf, 1, cnt, fp);
 }
 
 static long sfile_seek(jas_stream_obj_t *obj, long offset, int origin)
 {
-	FILE *fp;
-	fp = JAS_CAST(FILE *, obj);
-	return fseek(fp, offset, origin);
+        FILE *fp;
+        fp = JAS_CAST(FILE *, obj);
+        return fseek(fp, offset, origin);
 }
 
 static int sfile_close(jas_stream_obj_t *obj)
 {
-	FILE *fp;
-	fp = JAS_CAST(FILE *, obj);
-	return fclose(fp);
+        FILE *fp;
+        fp = JAS_CAST(FILE *, obj);
+        return fclose(fp);
 }
diff --git a/converter/other/jpeg2000/libjasper/base/jas_string.c b/converter/other/jpeg2000/libjasper/base/jas_string.c
index 945731a1..b3c45b78 100644
--- a/converter/other/jpeg2000/libjasper/base/jas_string.c
+++ b/converter/other/jpeg2000/libjasper/base/jas_string.c
@@ -6,14 +6,14 @@
  */
 
 /* __START_OF_JASPER_LICENSE__
- * 
+ *
  * JasPer Software License
- * 
+ *
  * IMAGE POWER JPEG-2000 PUBLIC LICENSE
  * ************************************
- * 
+ *
  * GRANT:
- * 
+ *
  * Permission is hereby granted, free of charge, to any person (the "User")
  * obtaining a copy of this software and associated documentation, to deal
  * in the JasPer Software without restriction, including without limitation
@@ -21,22 +21,22 @@
  * and/or sell copies of the JasPer Software (in source and binary forms),
  * and to permit persons to whom the JasPer Software is furnished to do so,
  * provided further that the License Conditions below are met.
- * 
+ *
  * License Conditions
  * ******************
- * 
+ *
  * A.  Redistributions of source code must retain the above copyright notice,
  * and this list of conditions, and the following disclaimer.
- * 
+ *
  * B.  Redistributions in binary form must reproduce the above copyright
  * notice, and this list of conditions, and the following disclaimer in
  * the documentation and/or other materials provided with the distribution.
- * 
+ *
  * C.  Neither the name of Image Power, Inc. nor any other contributor
  * (including, but not limited to, the University of British Columbia and
  * Michael David Adams) may be used to endorse or promote products derived
  * from this software without specific prior written permission.
- * 
+ *
  * D.  User agrees that it shall not commence any action against Image Power,
  * Inc., the University of British Columbia, Michael David Adams, or any
  * other contributors (collectively "Licensors") for infringement of any
@@ -56,17 +56,17 @@
  * trade dress, or service mark rights); and (v) divisions, continuations,
  * renewals, reissues and extensions of the foregoing (as and to the extent
  * applicable) now existing, hereafter filed, issued or acquired.
- * 
+ *
  * E.  If User commences an infringement action against any Licensor(s) then
  * such Licensor(s) shall have the right to terminate User's license and
  * all sublicenses that have been granted hereunder by User to other parties.
- * 
+ *
  * F.  This software is for use only in hardware or software products that
  * are compliant with ISO/IEC 15444-1 (i.e., JPEG-2000 Part 1).  No license
  * or right to this Software is granted for products that do not comply
  * with ISO/IEC 15444-1.  The JPEG-2000 Part 1 standard can be purchased
  * from the ISO.
- * 
+ *
  * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS LICENSE.
  * NO USE OF THE JASPER SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER
  * THIS DISCLAIMER.  THE JASPER SOFTWARE IS PROVIDED BY THE LICENSORS AND
@@ -106,7 +106,7 @@
  * TECHNOLOGY OR PRODUCTS FOR HIGH RISK ACTIVITIES AND WILL ENSURE THAT ITS
  * CUSTOMERS AND END-USERS OF ITS PRODUCTS ARE PROVIDED WITH A COPY OF THE
  * NOTICE SPECIFIED IN THIS SECTION.
- * 
+ *
  * __END_OF_JASPER_LICENSE__
  */
 
@@ -134,12 +134,12 @@
 
 char *jas_strdup(const char *s)
 {
-	int n;
-	char *p;
-	n = strlen(s) + 1;
-	if (!(p = jas_malloc(n * sizeof(char)))) {
-		return 0;
-	}
-	strcpy(p, s);
-	return p;
+        int n;
+        char *p;
+        n = strlen(s) + 1;
+        if (!(p = jas_malloc(n * sizeof(char)))) {
+                return 0;
+        }
+        strcpy(p, s);
+        return p;
 }
diff --git a/converter/other/jpeg2000/libjasper/base/jas_tvp.c b/converter/other/jpeg2000/libjasper/base/jas_tvp.c
index aab12703..43b2fd41 100644
--- a/converter/other/jpeg2000/libjasper/base/jas_tvp.c
+++ b/converter/other/jpeg2000/libjasper/base/jas_tvp.c
@@ -4,14 +4,14 @@
  */
 
 /* __START_OF_JASPER_LICENSE__
- * 
+ *
  * JasPer Software License
- * 
+ *
  * IMAGE POWER JPEG-2000 PUBLIC LICENSE
  * ************************************
- * 
+ *
  * GRANT:
- * 
+ *
  * Permission is hereby granted, free of charge, to any person (the "User")
  * obtaining a copy of this software and associated documentation, to deal
  * in the JasPer Software without restriction, including without limitation
@@ -19,22 +19,22 @@
  * and/or sell copies of the JasPer Software (in source and binary forms),
  * and to permit persons to whom the JasPer Software is furnished to do so,
  * provided further that the License Conditions below are met.
- * 
+ *
  * License Conditions
  * ******************
- * 
+ *
  * A.  Redistributions of source code must retain the above copyright notice,
  * and this list of conditions, and the following disclaimer.
- * 
+ *
  * B.  Redistributions in binary form must reproduce the above copyright
  * notice, and this list of conditions, and the following disclaimer in
  * the documentation and/or other materials provided with the distribution.
- * 
+ *
  * C.  Neither the name of Image Power, Inc. nor any other contributor
  * (including, but not limited to, the University of British Columbia and
  * Michael David Adams) may be used to endorse or promote products derived
  * from this software without specific prior written permission.
- * 
+ *
  * D.  User agrees that it shall not commence any action against Image Power,
  * Inc., the University of British Columbia, Michael David Adams, or any
  * other contributors (collectively "Licensors") for infringement of any
@@ -54,17 +54,17 @@
  * trade dress, or service mark rights); and (v) divisions, continuations,
  * renewals, reissues and extensions of the foregoing (as and to the extent
  * applicable) now existing, hereafter filed, issued or acquired.
- * 
+ *
  * E.  If User commences an infringement action against any Licensor(s) then
  * such Licensor(s) shall have the right to terminate User's license and
  * all sublicenses that have been granted hereunder by User to other parties.
- * 
+ *
  * F.  This software is for use only in hardware or software products that
  * are compliant with ISO/IEC 15444-1 (i.e., JPEG-2000 Part 1).  No license
  * or right to this Software is granted for products that do not comply
  * with ISO/IEC 15444-1.  The JPEG-2000 Part 1 standard can be purchased
  * from the ISO.
- * 
+ *
  * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS LICENSE.
  * NO USE OF THE JASPER SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER
  * THIS DISCLAIMER.  THE JASPER SOFTWARE IS PROVIDED BY THE LICENSORS AND
@@ -104,7 +104,7 @@
  * TECHNOLOGY OR PRODUCTS FOR HIGH RISK ACTIVITIES AND WILL ENSURE THAT ITS
  * CUSTOMERS AND END-USERS OF ITS PRODUCTS ARE PROVIDED WITH A COPY OF THE
  * NOTICE SPECIFIED IN THIS SECTION.
- * 
+ *
  * __END_OF_JASPER_LICENSE__
  */
 
@@ -132,8 +132,8 @@
 \******************************************************************************/
 
 /* Is the specified character valid for a tag name? */
-#define	JAS_TVP_ISTAG(x) \
-	(isalpha(x) || (x) == '_' || isdigit(x))
+#define JAS_TVP_ISTAG(x) \
+        (isalpha(x) || (x) == '_' || isdigit(x))
 
 /******************************************************************************\
 * Code for creating and destroying a tag-value parser.
@@ -141,26 +141,26 @@
 
 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;
+        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);
+        if (tvp->buf) {
+                jas_free(tvp->buf);
+        }
+        jas_free(tvp);
 }
 
 /******************************************************************************\
@@ -170,73 +170,73 @@ void jas_tvparser_destroy(jas_tvparser_t *tvp)
 /* Get the next tag-value pair. */
 int jas_tvparser_next(jas_tvparser_t *tvp)
 {
-	char *p;
-	char *tag;
-	const char *val;
+        char *p;
+        char *tag;
+        const char *val;
 
-	/* Skip any leading whitespace. */
-	p = tvp->pos;
-	while (*p != '\0' && isspace(*p)) {
-		++p;
-	}
+        /* Skip any leading whitespace. */
+        p = tvp->pos;
+        while (*p != '\0' && isspace(*p)) {
+                ++p;
+        }
 
-	/* Has the end of the input data been reached? */
-	if (*p == '\0') {
-		/* No more tags are present. */
-		tvp->pos = p;
-		return 1;
-	}
+        /* 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(*p)) {
-		return -1;
-	}
+        /* Does the tag name begin with a valid character? */
+        if (!JAS_TVP_ISTAG(*p)) {
+                return -1;
+        }
 
-	/* Remember where the tag name begins. */
-	tag = p;
+        /* Remember where the tag name begins. */
+        tag = p;
 
-	/* Find the end of the tag name. */
-	while (*p != '\0' && JAS_TVP_ISTAG(*p)) {
-		++p;
-	}
+        /* Find the end of the tag name. */
+        while (*p != '\0' && JAS_TVP_ISTAG(*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;
-	}
+        /* 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(*p)) {
-			return -1;
-		}
-		*p++ = '\0';
-		tvp->tag = tag;
-		tvp->val = "";
-		tvp->pos = p;
-		return 0;
-	}
+        /* Is a value field not present? */
+        if (*p != '=') {
+                if (*p != '\0' && !isspace(*p)) {
+                        return -1;
+                }
+                *p++ = '\0';
+                tvp->tag = tag;
+                tvp->val = "";
+                tvp->pos = p;
+                return 0;
+        }
 
-	*p++ = '\0';
+        *p++ = '\0';
 
-	val = p;
-	while (*p != '\0' && !isspace(*p)) {
-		++p;
-	}
+        val = p;
+        while (*p != '\0' && !isspace(*p)) {
+                ++p;
+        }
 
-	if (*p != '\0') {
-		*p++ = '\0';
-	}
+        if (*p != '\0') {
+                *p++ = '\0';
+        }
 
-	tvp->pos = p;
-	tvp->tag = tag;
-	tvp->val = val;
+        tvp->pos = p;
+        tvp->tag = tag;
+        tvp->val = val;
 
-	return 0;
+        return 0;
 }
 
 /******************************************************************************\
@@ -246,13 +246,13 @@ int jas_tvparser_next(jas_tvparser_t *tvp)
 /* Get the current tag. */
 char *jas_tvparser_gettag(jas_tvparser_t *tvp)
 {
-	return tvp->tag;
+        return tvp->tag;
 }
 
 /* Get the current value. */
 const char *jas_tvparser_getval(jas_tvparser_t *tvp)
 {
-	return tvp->val;
+        return tvp->val;
 }
 
 /******************************************************************************\
@@ -262,15 +262,15 @@ const char *jas_tvparser_getval(jas_tvparser_t *tvp)
 /* Lookup a tag by name. */
 jas_taginfo_t *jas_taginfos_lookup(jas_taginfo_t *taginfos, const char *name)
 {
-	jas_taginfo_t *taginfo;
-	taginfo = taginfos;
-	while (taginfo->id >= 0) {
-		if (!strcmp(taginfo->name, name)) {
-			return taginfo;
-		}
-		++taginfo;
-	}
-	return 0;
+        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. */
@@ -278,9 +278,9 @@ jas_taginfo_t *jas_taginfos_lookup(jas_taginfo_t *taginfos, const char *name)
   using this function.   This function never returns a null pointer.  */
 jas_taginfo_t *jas_taginfo_nonull(jas_taginfo_t *taginfo)
 {
-	static jas_taginfo_t invalidtaginfo = {
-		-1, 0
-	};
-	
-	return taginfo ? taginfo : &invalidtaginfo;
+        static jas_taginfo_t invalidtaginfo = {
+                -1, 0
+        };
+       
+        return taginfo ? taginfo : &invalidtaginfo;
 }
diff --git a/converter/other/jpeg2000/libjasper/base/jas_version.c b/converter/other/jpeg2000/libjasper/base/jas_version.c
index 5608c4d4..675a3883 100644
--- a/converter/other/jpeg2000/libjasper/base/jas_version.c
+++ b/converter/other/jpeg2000/libjasper/base/jas_version.c
@@ -4,14 +4,14 @@
  */
 
 /* __START_OF_JASPER_LICENSE__
- * 
+ *
  * JasPer Software License
- * 
+ *
  * IMAGE POWER JPEG-2000 PUBLIC LICENSE
  * ************************************
- * 
+ *
  * GRANT:
- * 
+ *
  * Permission is hereby granted, free of charge, to any person (the "User")
  * obtaining a copy of this software and associated documentation, to deal
  * in the JasPer Software without restriction, including without limitation
@@ -19,22 +19,22 @@
  * and/or sell copies of the JasPer Software (in source and binary forms),
  * and to permit persons to whom the JasPer Software is furnished to do so,
  * provided further that the License Conditions below are met.
- * 
+ *
  * License Conditions
  * ******************
- * 
+ *
  * A.  Redistributions of source code must retain the above copyright notice,
  * and this list of conditions, and the following disclaimer.
- * 
+ *
  * B.  Redistributions in binary form must reproduce the above copyright
  * notice, and this list of conditions, and the following disclaimer in
  * the documentation and/or other materials provided with the distribution.
- * 
+ *
  * C.  Neither the name of Image Power, Inc. nor any other contributor
  * (including, but not limited to, the University of British Columbia and
  * Michael David Adams) may be used to endorse or promote products derived
  * from this software without specific prior written permission.
- * 
+ *
  * D.  User agrees that it shall not commence any action against Image Power,
  * Inc., the University of British Columbia, Michael David Adams, or any
  * other contributors (collectively "Licensors") for infringement of any
@@ -54,17 +54,17 @@
  * trade dress, or service mark rights); and (v) divisions, continuations,
  * renewals, reissues and extensions of the foregoing (as and to the extent
  * applicable) now existing, hereafter filed, issued or acquired.
- * 
+ *
  * E.  If User commences an infringement action against any Licensor(s) then
  * such Licensor(s) shall have the right to terminate User's license and
  * all sublicenses that have been granted hereunder by User to other parties.
- * 
+ *
  * F.  This software is for use only in hardware or software products that
  * are compliant with ISO/IEC 15444-1 (i.e., JPEG-2000 Part 1).  No license
  * or right to this Software is granted for products that do not comply
  * with ISO/IEC 15444-1.  The JPEG-2000 Part 1 standard can be purchased
  * from the ISO.
- * 
+ *
  * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS LICENSE.
  * NO USE OF THE JASPER SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER
  * THIS DISCLAIMER.  THE JASPER SOFTWARE IS PROVIDED BY THE LICENSORS AND
@@ -104,7 +104,7 @@
  * TECHNOLOGY OR PRODUCTS FOR HIGH RISK ACTIVITIES AND WILL ENSURE THAT ITS
  * CUSTOMERS AND END-USERS OF ITS PRODUCTS ARE PROVIDED WITH A COPY OF THE
  * NOTICE SPECIFIED IN THIS SECTION.
- * 
+ *
  * __END_OF_JASPER_LICENSE__
  */
 
@@ -112,5 +112,5 @@
 
 const char *jas_getversion()
 {
-	return JAS_VERSION;
+        return JAS_VERSION;
 }
diff --git a/converter/other/jpeg2000/libjasper/common.mk b/converter/other/jpeg2000/libjasper/common.mk
index a333f5d6..194ce3c1 100644
--- a/converter/other/jpeg2000/libjasper/common.mk
+++ b/converter/other/jpeg2000/libjasper/common.mk
@@ -24,8 +24,7 @@ INCLUDES := -I$(JASPERSRCDIR)/include $(INCLUDES)
 DEFS = -DHAVE_LIBM=1 -DSTDC_HEADERS=1 -DHAVE_FCNTL_H=1 -DHAVE_LIMITS_H=1 -DHAVE_UNISTD_H=1 -DHAVE_SYS_TYPES_H=1 -DHAVE_STDLIB_H=1 -DHAVE_STDDEF_H=1 -DEXCLUDE_BMP_SUPPORT -DEXCLUDE_RAS_SUPPORT -DEXCLUDE_MIF_SUPPORT -DEXCLUDE_JPG_SUPPORT -DEXCLUDE_PGX_SUPPORT -DEXCLUDE_PNM_SUPPORT
 
 $(LIB_OBJECTS):%.o:%.c
-	$(CC) -c $(INCLUDES) $(DEFS) $(CPPFLAGS) $(CFLAGS) \
-	  $(CFLAGS_PERSONAL) $(CADD) $<
+	$(CC) -c $(INCLUDES) $(DEFS) $(CFLAGS_ALL) $<
 
 $(LIB_OBJECTS): importinc
 
diff --git a/converter/other/jpeg2000/libjasper/include/jasper/jas_debug.h b/converter/other/jpeg2000/libjasper/include/jasper/jas_debug.h
index 6c597c59..77b65967 100644
--- a/converter/other/jpeg2000/libjasper/include/jasper/jas_debug.h
+++ b/converter/other/jpeg2000/libjasper/include/jasper/jas_debug.h
@@ -4,14 +4,14 @@
  */
 
 /* __START_OF_JASPER_LICENSE__
- * 
+ *
  * JasPer Software License
- * 
+ *
  * IMAGE POWER JPEG-2000 PUBLIC LICENSE
  * ************************************
- * 
+ *
  * GRANT:
- * 
+ *
  * Permission is hereby granted, free of charge, to any person (the "User")
  * obtaining a copy of this software and associated documentation, to deal
  * in the JasPer Software without restriction, including without limitation
@@ -19,22 +19,22 @@
  * and/or sell copies of the JasPer Software (in source and binary forms),
  * and to permit persons to whom the JasPer Software is furnished to do so,
  * provided further that the License Conditions below are met.
- * 
+ *
  * License Conditions
  * ******************
- * 
+ *
  * A.  Redistributions of source code must retain the above copyright notice,
  * and this list of conditions, and the following disclaimer.
- * 
+ *
  * B.  Redistributions in binary form must reproduce the above copyright
  * notice, and this list of conditions, and the following disclaimer in
  * the documentation and/or other materials provided with the distribution.
- * 
+ *
  * C.  Neither the name of Image Power, Inc. nor any other contributor
  * (including, but not limited to, the University of British Columbia and
  * Michael David Adams) may be used to endorse or promote products derived
  * from this software without specific prior written permission.
- * 
+ *
  * D.  User agrees that it shall not commence any action against Image Power,
  * Inc., the University of British Columbia, Michael David Adams, or any
  * other contributors (collectively "Licensors") for infringement of any
@@ -54,17 +54,17 @@
  * trade dress, or service mark rights); and (v) divisions, continuations,
  * renewals, reissues and extensions of the foregoing (as and to the extent
  * applicable) now existing, hereafter filed, issued or acquired.
- * 
+ *
  * E.  If User commences an infringement action against any Licensor(s) then
  * such Licensor(s) shall have the right to terminate User's license and
  * all sublicenses that have been granted hereunder by User to other parties.
- * 
+ *
  * F.  This software is for use only in hardware or software products that
  * are compliant with ISO/IEC 15444-1 (i.e., JPEG-2000 Part 1).  No license
  * or right to this Software is granted for products that do not comply
  * with ISO/IEC 15444-1.  The JPEG-2000 Part 1 standard can be purchased
  * from the ISO.
- * 
+ *
  * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS LICENSE.
  * NO USE OF THE JASPER SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER
  * THIS DISCLAIMER.  THE JASPER SOFTWARE IS PROVIDED BY THE LICENSORS AND
@@ -104,7 +104,7 @@
  * TECHNOLOGY OR PRODUCTS FOR HIGH RISK ACTIVITIES AND WILL ENSURE THAT ITS
  * CUSTOMERS AND END-USERS OF ITS PRODUCTS ARE PROVIDED WITH A COPY OF THE
  * NOTICE SPECIFIED IN THIS SECTION.
- * 
+ *
  * __END_OF_JASPER_LICENSE__
  */
 
@@ -136,10 +136,10 @@ extern "C" {
 /* Output debugging information to standard error provided that the debug
   level is set sufficiently high. */
 #if defined(DEBUG)
-#define	JAS_DBGLOG(n, x) \
-	((jas_getdbglevel() >= (n)) ? (jas_eprintf x) : 0)
+#define JAS_DBGLOG(n, x) \
+        ((jas_getdbglevel() >= (n)) ? (jas_eprintf x) : 0)
 #else
-#define	JAS_DBGLOG(n, x)
+#define JAS_DBGLOG(n, x)
 #endif
 
 /* Get the library debug level. */
diff --git a/converter/other/jpeg2000/libjasper/include/jasper/jas_fix.h b/converter/other/jpeg2000/libjasper/include/jasper/jas_fix.h
index 9599eb1c..7816b13e 100644
--- a/converter/other/jpeg2000/libjasper/include/jasper/jas_fix.h
+++ b/converter/other/jpeg2000/libjasper/include/jasper/jas_fix.h
@@ -6,14 +6,14 @@
  */
 
 /* __START_OF_JASPER_LICENSE__
- * 
+ *
  * JasPer Software License
- * 
+ *
  * IMAGE POWER JPEG-2000 PUBLIC LICENSE
  * ************************************
- * 
+ *
  * GRANT:
- * 
+ *
  * Permission is hereby granted, free of charge, to any person (the "User")
  * obtaining a copy of this software and associated documentation, to deal
  * in the JasPer Software without restriction, including without limitation
@@ -21,22 +21,22 @@
  * and/or sell copies of the JasPer Software (in source and binary forms),
  * and to permit persons to whom the JasPer Software is furnished to do so,
  * provided further that the License Conditions below are met.
- * 
+ *
  * License Conditions
  * ******************
- * 
+ *
  * A.  Redistributions of source code must retain the above copyright notice,
  * and this list of conditions, and the following disclaimer.
- * 
+ *
  * B.  Redistributions in binary form must reproduce the above copyright
  * notice, and this list of conditions, and the following disclaimer in
  * the documentation and/or other materials provided with the distribution.
- * 
+ *
  * C.  Neither the name of Image Power, Inc. nor any other contributor
  * (including, but not limited to, the University of British Columbia and
  * Michael David Adams) may be used to endorse or promote products derived
  * from this software without specific prior written permission.
- * 
+ *
  * D.  User agrees that it shall not commence any action against Image Power,
  * Inc., the University of British Columbia, Michael David Adams, or any
  * other contributors (collectively "Licensors") for infringement of any
@@ -56,17 +56,17 @@
  * trade dress, or service mark rights); and (v) divisions, continuations,
  * renewals, reissues and extensions of the foregoing (as and to the extent
  * applicable) now existing, hereafter filed, issued or acquired.
- * 
+ *
  * E.  If User commences an infringement action against any Licensor(s) then
  * such Licensor(s) shall have the right to terminate User's license and
  * all sublicenses that have been granted hereunder by User to other parties.
- * 
+ *
  * F.  This software is for use only in hardware or software products that
  * are compliant with ISO/IEC 15444-1 (i.e., JPEG-2000 Part 1).  No license
  * or right to this Software is granted for products that do not comply
  * with ISO/IEC 15444-1.  The JPEG-2000 Part 1 standard can be purchased
  * from the ISO.
- * 
+ *
  * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS LICENSE.
  * NO USE OF THE JASPER SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER
  * THIS DISCLAIMER.  THE JASPER SOFTWARE IS PROVIDED BY THE LICENSORS AND
@@ -106,7 +106,7 @@
  * TECHNOLOGY OR PRODUCTS FOR HIGH RISK ACTIVITIES AND WILL ENSURE THAT ITS
  * CUSTOMERS AND END-USERS OF ITS PRODUCTS ARE PROVIDED WITH A COPY OF THE
  * NOTICE SPECIFIED IN THIS SECTION.
- * 
+ *
  * __END_OF_JASPER_LICENSE__
  */
 
@@ -138,16 +138,16 @@ extern "C" {
 \******************************************************************************/
 
 /* The representation of the value zero. */
-#define	JAS_FIX_ZERO(fix_t, fracbits) \
-	JAS_CAST(fix_t, 0)
+#define JAS_FIX_ZERO(fix_t, fracbits) \
+        JAS_CAST(fix_t, 0)
 
 /* The representation of the value one. */
-#define	JAS_FIX_ONE(fix_t, fracbits) \
-	(JAS_CAST(fix_t, 1) << (fracbits))
+#define JAS_FIX_ONE(fix_t, fracbits) \
+        (JAS_CAST(fix_t, 1) << (fracbits))
 
 /* The representation of the value one half. */
-#define	JAS_FIX_HALF(fix_t, fracbits) \
-	(JAS_CAST(fix_t, 1) << ((fracbits) - 1))
+#define JAS_FIX_HALF(fix_t, fracbits) \
+        (JAS_CAST(fix_t, 1) << ((fracbits) - 1))
 
 /******************************************************************************\
 * Conversion operations.
@@ -155,19 +155,19 @@ extern "C" {
 
 /* Convert an int to a fixed-point number. */
 #define JAS_INTTOFIX(fix_t, fracbits, x) \
-	JAS_CAST(fix_t, (x) << (fracbits))
+        JAS_CAST(fix_t, (x) << (fracbits))
 
 /* Convert a fixed-point number to an int. */
 #define JAS_FIXTOINT(fix_t, fracbits, x) \
-	JAS_CAST(int, (x) >> (fracbits))
+        JAS_CAST(int, (x) >> (fracbits))
 
 /* Convert a fixed-point number to a double. */
 #define JAS_FIXTODBL(fix_t, fracbits, x) \
-	(JAS_CAST(double, x) / (JAS_CAST(fix_t, 1) << (fracbits)))
+        (JAS_CAST(double, x) / (JAS_CAST(fix_t, 1) << (fracbits)))
 
 /* Convert a double to a fixed-point number. */
 #define JAS_DBLTOFIX(fix_t, fracbits, x) \
-	JAS_CAST(fix_t, ((x) * JAS_CAST(double, JAS_CAST(fix_t, 1) << (fracbits))))
+        JAS_CAST(fix_t, ((x) * JAS_CAST(double, JAS_CAST(fix_t, 1) << (fracbits))))
 
 /******************************************************************************\
 * Basic arithmetic operations.
@@ -181,128 +181,128 @@ extern "C" {
 
 /* Calculate the sum of two fixed-point numbers. */
 #if !defined(DEBUG_OVERFLOW)
-#define JAS_FIX_ADD			JAS_FIX_ADD_FAST
+#define JAS_FIX_ADD                     JAS_FIX_ADD_FAST
 #else
-#define JAS_FIX_ADD			JAS_FIX_ADD_OFLOW
+#define JAS_FIX_ADD                     JAS_FIX_ADD_OFLOW
 #endif
 
 /* Calculate the sum of two fixed-point numbers without overflow checking. */
-#define	JAS_FIX_ADD_FAST(fix_t, fracbits, x, y)	((x) + (y))
+#define JAS_FIX_ADD_FAST(fix_t, fracbits, x, y) ((x) + (y))
 
 /* Calculate the sum of two fixed-point numbers with overflow checking. */
-#define	JAS_FIX_ADD_OFLOW(fix_t, fracbits, x, y) \
-	((x) >= 0) ? \
-	  (((y) >= 0) ? ((x) + (y) >= 0 || JAS_FIX_OFLOW(), (x) + (y)) : \
-	  ((x) + (y))) : \
-	  (((y) >= 0) ? ((x) + (y)) : ((x) + (y) < 0 || JAS_FIX_OFLOW(), \
-	  (x) + (y)))
+#define JAS_FIX_ADD_OFLOW(fix_t, fracbits, x, y) \
+        ((x) >= 0) ? \
+          (((y) >= 0) ? ((x) + (y) >= 0 || JAS_FIX_OFLOW(), (x) + (y)) : \
+          ((x) + (y))) : \
+          (((y) >= 0) ? ((x) + (y)) : ((x) + (y) < 0 || JAS_FIX_OFLOW(), \
+          (x) + (y)))
 
 /* Calculate the product of two fixed-point numbers. */
 #if !defined(DEBUG_OVERFLOW)
-#define JAS_FIX_MUL			JAS_FIX_MUL_FAST
+#define JAS_FIX_MUL                     JAS_FIX_MUL_FAST
 #else
-#define JAS_FIX_MUL			JAS_FIX_MUL_OFLOW
+#define JAS_FIX_MUL                     JAS_FIX_MUL_OFLOW
 #endif
 
 /* Calculate the product of two fixed-point numbers without overflow
   checking. */
-#define	JAS_FIX_MUL_FAST(fix_t, fracbits, bigfix_t, x, y) \
-	JAS_CAST(fix_t, (JAS_CAST(bigfix_t, x) * JAS_CAST(bigfix_t, y)) >> \
-	  (fracbits))
+#define JAS_FIX_MUL_FAST(fix_t, fracbits, bigfix_t, x, y) \
+        JAS_CAST(fix_t, (JAS_CAST(bigfix_t, x) * JAS_CAST(bigfix_t, y)) >> \
+          (fracbits))
 
 /* Calculate the product of two fixed-point numbers with overflow
   checking. */
 #define JAS_FIX_MUL_OFLOW(fix_t, fracbits, bigfix_t, x, y) \
-	((JAS_CAST(bigfix_t, x) * JAS_CAST(bigfix_t, y) >> (fracbits)) == \
-	  JAS_CAST(fix_t, (JAS_CAST(bigfix_t, x) * JAS_CAST(bigfix_t, y) >> \
-	  (fracbits))) ? \
-	  JAS_CAST(fix_t, (JAS_CAST(bigfix_t, x) * JAS_CAST(bigfix_t, y) >> \
-	  (fracbits))) : JAS_FIX_OFLOW())
+        ((JAS_CAST(bigfix_t, x) * JAS_CAST(bigfix_t, y) >> (fracbits)) == \
+          JAS_CAST(fix_t, (JAS_CAST(bigfix_t, x) * JAS_CAST(bigfix_t, y) >> \
+          (fracbits))) ? \
+          JAS_CAST(fix_t, (JAS_CAST(bigfix_t, x) * JAS_CAST(bigfix_t, y) >> \
+          (fracbits))) : JAS_FIX_OFLOW())
 
 /* Calculate the product of a fixed-point number and an int. */
 #if !defined(DEBUG_OVERFLOW)
-#define	JAS_FIX_MULBYINT	JAS_FIX_MULBYINT_FAST
+#define JAS_FIX_MULBYINT        JAS_FIX_MULBYINT_FAST
 #else
-#define	JAS_FIX_MULBYINT	JAS_FIX_MULBYINT_OFLOW
+#define JAS_FIX_MULBYINT        JAS_FIX_MULBYINT_OFLOW
 #endif
 
 /* Calculate the product of a fixed-point number and an int without overflow
   checking. */
-#define	JAS_FIX_MULBYINT_FAST(fix_t, fracbits, x, y) \
-	JAS_CAST(fix_t, ((x) * (y)))
+#define JAS_FIX_MULBYINT_FAST(fix_t, fracbits, x, y) \
+        JAS_CAST(fix_t, ((x) * (y)))
 
 /* Calculate the product of a fixed-point number and an int with overflow
   checking. */
-#define	JAS_FIX_MULBYINT_OFLOW(fix_t, fracbits, x, y) \
-	JAS_FIX_MULBYINT_FAST(fix_t, fracbits, x, y)
+#define JAS_FIX_MULBYINT_OFLOW(fix_t, fracbits, x, y) \
+        JAS_FIX_MULBYINT_FAST(fix_t, fracbits, x, y)
 
 /* Calculate the quotient of two fixed-point numbers. */
 #if !defined(DEBUG_OVERFLOW)
-#define JAS_FIX_DIV			JAS_FIX_DIV_FAST
+#define JAS_FIX_DIV                     JAS_FIX_DIV_FAST
 #else
-#define JAS_FIX_DIV			JAS_FIX_DIV_UFLOW
+#define JAS_FIX_DIV                     JAS_FIX_DIV_UFLOW
 #endif
 
 /* Calculate the quotient of two fixed-point numbers without underflow
   checking. */
-#define	JAS_FIX_DIV_FAST(fix_t, fracbits, bigfix_t, x, y) \
-	JAS_CAST(fix_t, (JAS_CAST(bigfix_t, x) << (fracbits)) / (y))
+#define JAS_FIX_DIV_FAST(fix_t, fracbits, bigfix_t, x, y) \
+        JAS_CAST(fix_t, (JAS_CAST(bigfix_t, x) << (fracbits)) / (y))
 
 /* Calculate the quotient of two fixed-point numbers with underflow
   checking. */
 #define JAS_FIX_DIV_UFLOW(fix_t, fracbits, bigfix_t, x, y) \
-	JAS_FIX_DIV_FAST(fix_t, fracbits, bigfix_t, x, y)
+        JAS_FIX_DIV_FAST(fix_t, fracbits, bigfix_t, x, y)
 
 /* Negate a fixed-point number. */
 #if !defined(DEBUG_OVERFLOW)
-#define	JAS_FIX_NEG			JAS_FIX_NEG_FAST
+#define JAS_FIX_NEG                     JAS_FIX_NEG_FAST
 #else
-#define	JAS_FIX_NEG			JAS_FIX_NEG_OFLOW
+#define JAS_FIX_NEG                     JAS_FIX_NEG_OFLOW
 #endif
 
 /* Negate a fixed-point number without overflow checking. */
-#define	JAS_FIX_NEG_FAST(fix_t, fracbits, x) \
-	(-(x))
+#define JAS_FIX_NEG_FAST(fix_t, fracbits, x) \
+        (-(x))
 
 /* Negate a fixed-point number with overflow checking. */
 /* Yes, overflow is actually possible for two's complement representations,
   although highly unlikely to occur. */
-#define	JAS_FIX_NEG_OFLOW(fix_t, fracbits, x) \
-	(((x) < 0) ? (-(x) > 0 || JAS_FIX_OFLOW(), -(x)) : (-(x)))
+#define JAS_FIX_NEG_OFLOW(fix_t, fracbits, x) \
+        (((x) < 0) ? (-(x) > 0 || JAS_FIX_OFLOW(), -(x)) : (-(x)))
 
 /* Perform an arithmetic shift left of a fixed-point number. */
 #if !defined(DEBUG_OVERFLOW)
-#define	JAS_FIX_ASL			JAS_FIX_ASL_FAST
+#define JAS_FIX_ASL                     JAS_FIX_ASL_FAST
 #else
-#define	JAS_FIX_ASL			JAS_FIX_ASL_OFLOW
+#define JAS_FIX_ASL                     JAS_FIX_ASL_OFLOW
 #endif
 
 /* Perform an arithmetic shift left of a fixed-point number without overflow
   checking. */
-#define	JAS_FIX_ASL_FAST(fix_t, fracbits, x, n) \
-	((x) << (n))
+#define JAS_FIX_ASL_FAST(fix_t, fracbits, x, n) \
+        ((x) << (n))
 
 /* Perform an arithmetic shift left of a fixed-point number with overflow
   checking. */
-#define	JAS_FIX_ASL_OFLOW(fix_t, fracbits, x, n) \
-	((((x) << (n)) >> (n)) == (x) || JAS_FIX_OFLOW(), (x) << (n))
+#define JAS_FIX_ASL_OFLOW(fix_t, fracbits, x, n) \
+        ((((x) << (n)) >> (n)) == (x) || JAS_FIX_OFLOW(), (x) << (n))
 
 /* Perform an arithmetic shift right of a fixed-point number. */
 #if !defined(DEBUG_OVERFLOW)
-#define	JAS_FIX_ASR			JAS_FIX_ASR_FAST
+#define JAS_FIX_ASR                     JAS_FIX_ASR_FAST
 #else
-#define	JAS_FIX_ASR			JAS_FIX_ASR_UFLOW
+#define JAS_FIX_ASR                     JAS_FIX_ASR_UFLOW
 #endif
 
 /* Perform an arithmetic shift right of a fixed-point number without underflow
   checking. */
-#define	JAS_FIX_ASR_FAST(fix_t, fracbits, x, n) \
-	((x) >> (n))
+#define JAS_FIX_ASR_FAST(fix_t, fracbits, x, n) \
+        ((x) >> (n))
 
 /* Perform an arithmetic shift right of a fixed-point number with underflow
   checking. */
-#define	JAS_FIX_ASR_UFLOW(fix_t, fracbits, x, n) \
-	JAS_FIX_ASR_FAST(fix_t, fracbits, x, n)
+#define JAS_FIX_ASR_UFLOW(fix_t, fracbits, x, n) \
+        JAS_FIX_ASR_FAST(fix_t, fracbits, x, n)
 
 /******************************************************************************\
 * Other basic arithmetic operations.
@@ -310,35 +310,35 @@ extern "C" {
 
 /* 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))
+        JAS_FIX_ADD(fix_t, fracbits, x, JAS_FIX_NEG(fix_t, fracbits, y))
 
 /* Add one fixed-point number to another. */
 #define JAS_FIX_PLUSEQ(fix_t, fracbits, x, y) \
-	((x) = JAS_FIX_ADD(fix_t, fracbits, x, y))
+        ((x) = JAS_FIX_ADD(fix_t, fracbits, x, y))
 
 /* Subtract one fixed-point number from another. */
 #define JAS_FIX_MINUSEQ(fix_t, fracbits, x, y) \
-	((x) = JAS_FIX_SUB(fix_t, fracbits, x, y))
+        ((x) = JAS_FIX_SUB(fix_t, fracbits, x, y))
 
 /* Multiply one fixed-point number by another. */
-#define	JAS_FIX_MULEQ(fix_t, fracbits, bigfix_t, x, y) \
-	((x) = JAS_FIX_MUL(fix_t, fracbits, bigfix_t, x, y))
+#define JAS_FIX_MULEQ(fix_t, fracbits, bigfix_t, x, y) \
+        ((x) = JAS_FIX_MUL(fix_t, fracbits, bigfix_t, x, y))
 
 /******************************************************************************\
 * Miscellaneous operations.
 \******************************************************************************/
 
 /* Calculate the absolute value of a fixed-point number. */
-#define	JAS_FIX_ABS(fix_t, fracbits, x) \
-	(((x) >= 0) ? (x) : (JAS_FIX_NEG(fix_t, fracbits, x)))
+#define JAS_FIX_ABS(fix_t, fracbits, x) \
+        (((x) >= 0) ? (x) : (JAS_FIX_NEG(fix_t, fracbits, x)))
 
 /* Is a fixed-point number an integer? */
-#define	JAS_FIX_ISINT(fix_t, fracbits, x) \
-	(JAS_FIX_FLOOR(fix_t, fracbits, x) == (x))
+#define JAS_FIX_ISINT(fix_t, fracbits, x) \
+        (JAS_FIX_FLOOR(fix_t, fracbits, x) == (x))
 
 /* Get the sign of a fixed-point number. */
 #define JAS_FIX_SGN(fix_t, fracbits, x) \
-	((x) >= 0 ? 1 : (-1))
+        ((x) >= 0 ? 1 : (-1))
 
 /******************************************************************************\
 * Relational operations.
@@ -346,45 +346,45 @@ extern "C" {
 
 /* Compare two fixed-point numbers. */
 #define JAS_FIX_CMP(fix_t, fracbits, x, y) \
-	((x) > (y) ? 1 : (((x) == (y)) ? 0 : (-1)))
+        ((x) > (y) ? 1 : (((x) == (y)) ? 0 : (-1)))
 
 /* Less than. */
-#define	JAS_FIX_LT(fix_t, fracbits, x, y) \
-	((x) < (y))
+#define JAS_FIX_LT(fix_t, fracbits, x, y) \
+        ((x) < (y))
 
 /* Less than or equal. */
-#define	JAS_FIX_LTE(fix_t, fracbits, x, y) \
-	((x) <= (y))
+#define JAS_FIX_LTE(fix_t, fracbits, x, y) \
+        ((x) <= (y))
 
 /* Greater than. */
-#define	JAS_FIX_GT(fix_t, fracbits, x, y) \
-	((x) > (y))
+#define JAS_FIX_GT(fix_t, fracbits, x, y) \
+        ((x) > (y))
 
 /* Greater than or equal. */
-#define	JAS_FIX_GTE(fix_t, fracbits, x, y) \
-	((x) >= (y))
+#define JAS_FIX_GTE(fix_t, fracbits, x, y) \
+        ((x) >= (y))
 
 /******************************************************************************\
 * Rounding functions.
 \******************************************************************************/
 
 /* Round a fixed-point number to the nearest integer. */
-#define	JAS_FIX_ROUND(fix_t, fracbits, x) \
-	(((x) < 0) ? JAS_FIX_FLOOR(fix_t, fracbits, JAS_FIX_ADD(fix_t, fracbits, \
-	  (x), JAS_FIX_HALF(fix_t, fracbits))) : \
-	  JAS_FIX_NEG(fix_t, fracbits, JAS_FIX_FLOOR(fix_t, fracbits, \
-	  JAS_FIX_ADD(fix_t, fracbits, (-(x)), JAS_FIX_HALF(fix_t, fracbits)))))
+#define JAS_FIX_ROUND(fix_t, fracbits, x) \
+        (((x) < 0) ? JAS_FIX_FLOOR(fix_t, fracbits, JAS_FIX_ADD(fix_t, fracbits, \
+          (x), JAS_FIX_HALF(fix_t, fracbits))) : \
+          JAS_FIX_NEG(fix_t, fracbits, JAS_FIX_FLOOR(fix_t, fracbits, \
+          JAS_FIX_ADD(fix_t, fracbits, (-(x)), JAS_FIX_HALF(fix_t, fracbits)))))
 
 /* Round a fixed-point number to the nearest integer in the direction of
   negative infinity (i.e., the floor function). */
-#define	JAS_FIX_FLOOR(fix_t, fracbits, x) \
-	((x) & (~((JAS_CAST(fix_t, 1) << (fracbits)) - 1)))
+#define JAS_FIX_FLOOR(fix_t, fracbits, x) \
+        ((x) & (~((JAS_CAST(fix_t, 1) << (fracbits)) - 1)))
 
 /* Round a fixed-point number to the nearest integer in the direction
   of zero. */
 #define JAS_FIX_TRUNC(fix_t, fracbits, x) \
-	(((x) >= 0) ? JAS_FIX_FLOOR(fix_t, fracbits, x) : \
-	  JAS_FIX_CEIL(fix_t, fracbits, x))
+        (((x) >= 0) ? JAS_FIX_FLOOR(fix_t, fracbits, x) : \
+          JAS_FIX_CEIL(fix_t, fracbits, x))
 
 /******************************************************************************\
 * The below macros are for internal library use only.  Do not invoke them
@@ -392,12 +392,12 @@ extern "C" {
 \******************************************************************************/
 
 /* Handle overflow. */
-#define	JAS_FIX_OFLOW() \
-	fprintf(stderr, "overflow error: file %s, line %d\n", __FILE__, __LINE__)
+#define JAS_FIX_OFLOW() \
+        fprintf(stderr, "overflow error: file %s, line %d\n", __FILE__, __LINE__)
 
 /* Handle underflow. */
-#define	JAS_FIX_UFLOW() \
-	fprintf(stderr, "underflow error: file %s, line %d\n", __FILE__, __LINE__)
+#define JAS_FIX_UFLOW() \
+        fprintf(stderr, "underflow error: file %s, line %d\n", __FILE__, __LINE__)
 
 #ifdef __cplusplus
 }
diff --git a/converter/other/jpeg2000/libjasper/include/jasper/jas_getopt.h b/converter/other/jpeg2000/libjasper/include/jasper/jas_getopt.h
index 4f272dc9..31087948 100644
--- a/converter/other/jpeg2000/libjasper/include/jasper/jas_getopt.h
+++ b/converter/other/jpeg2000/libjasper/include/jasper/jas_getopt.h
@@ -6,14 +6,14 @@
  */
 
 /* __START_OF_JASPER_LICENSE__
- * 
+ *
  * JasPer Software License
- * 
+ *
  * IMAGE POWER JPEG-2000 PUBLIC LICENSE
  * ************************************
- * 
+ *
  * GRANT:
- * 
+ *
  * Permission is hereby granted, free of charge, to any person (the "User")
  * obtaining a copy of this software and associated documentation, to deal
  * in the JasPer Software without restriction, including without limitation
@@ -21,22 +21,22 @@
  * and/or sell copies of the JasPer Software (in source and binary forms),
  * and to permit persons to whom the JasPer Software is furnished to do so,
  * provided further that the License Conditions below are met.
- * 
+ *
  * License Conditions
  * ******************
- * 
+ *
  * A.  Redistributions of source code must retain the above copyright notice,
  * and this list of conditions, and the following disclaimer.
- * 
+ *
  * B.  Redistributions in binary form must reproduce the above copyright
  * notice, and this list of conditions, and the following disclaimer in
  * the documentation and/or other materials provided with the distribution.
- * 
+ *
  * C.  Neither the name of Image Power, Inc. nor any other contributor
  * (including, but not limited to, the University of British Columbia and
  * Michael David Adams) may be used to endorse or promote products derived
  * from this software without specific prior written permission.
- * 
+ *
  * D.  User agrees that it shall not commence any action against Image Power,
  * Inc., the University of British Columbia, Michael David Adams, or any
  * other contributors (collectively "Licensors") for infringement of any
@@ -56,17 +56,17 @@
  * trade dress, or service mark rights); and (v) divisions, continuations,
  * renewals, reissues and extensions of the foregoing (as and to the extent
  * applicable) now existing, hereafter filed, issued or acquired.
- * 
+ *
  * E.  If User commences an infringement action against any Licensor(s) then
  * such Licensor(s) shall have the right to terminate User's license and
  * all sublicenses that have been granted hereunder by User to other parties.
- * 
+ *
  * F.  This software is for use only in hardware or software products that
  * are compliant with ISO/IEC 15444-1 (i.e., JPEG-2000 Part 1).  No license
  * or right to this Software is granted for products that do not comply
  * with ISO/IEC 15444-1.  The JPEG-2000 Part 1 standard can be purchased
  * from the ISO.
- * 
+ *
  * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS LICENSE.
  * NO USE OF THE JASPER SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER
  * THIS DISCLAIMER.  THE JASPER SOFTWARE IS PROVIDED BY THE LICENSORS AND
@@ -106,7 +106,7 @@
  * TECHNOLOGY OR PRODUCTS FOR HIGH RISK ACTIVITIES AND WILL ENSURE THAT ITS
  * CUSTOMERS AND END-USERS OF ITS PRODUCTS ARE PROVIDED WITH A COPY OF THE
  * NOTICE SPECIFIED IN THIS SECTION.
- * 
+ *
  * __END_OF_JASPER_LICENSE__
  */
 
@@ -127,11 +127,11 @@ extern "C" {
 * Constants.
 \******************************************************************************/
 
-#define	JAS_GETOPT_EOF	(-1)
-#define	JAS_GETOPT_ERR	'?'
+#define JAS_GETOPT_EOF  (-1)
+#define JAS_GETOPT_ERR  '?'
 
 /* option flags. */
-#define	JAS_OPT_HASARG	0x01	/* option has argument */
+#define JAS_OPT_HASARG  0x01    /* option has argument */
 
 /******************************************************************************\
 * Types.
@@ -140,14 +140,14 @@ extern "C" {
 /* Command line option type. */
 typedef struct {
 
-	int id;
-	/* The unique identifier for this option. */
+        int id;
+        /* The unique identifier for this option. */
 
-	char *name;
-	/* The name of this option. */
+        char *name;
+        /* The name of this option. */
 
-	int flags;
-	/* option flags. */
+        int flags;
+        /* option flags. */
 
 } jas_opt_t;
 
diff --git a/converter/other/jpeg2000/libjasper/include/jasper/jas_image.h b/converter/other/jpeg2000/libjasper/include/jasper/jas_image.h
index 20170986..56bb6cdf 100644
--- a/converter/other/jpeg2000/libjasper/include/jasper/jas_image.h
+++ b/converter/other/jpeg2000/libjasper/include/jasper/jas_image.h
@@ -6,14 +6,14 @@
  */
 
 /* __START_OF_JASPER_LICENSE__
- * 
+ *
  * JasPer Software License
- * 
+ *
  * IMAGE POWER JPEG-2000 PUBLIC LICENSE
  * ************************************
- * 
+ *
  * GRANT:
- * 
+ *
  * Permission is hereby granted, free of charge, to any person (the "User")
  * obtaining a copy of this software and associated documentation, to deal
  * in the JasPer Software without restriction, including without limitation
@@ -21,22 +21,22 @@
  * and/or sell copies of the JasPer Software (in source and binary forms),
  * and to permit persons to whom the JasPer Software is furnished to do so,
  * provided further that the License Conditions below are met.
- * 
+ *
  * License Conditions
  * ******************
- * 
+ *
  * A.  Redistributions of source code must retain the above copyright notice,
  * and this list of conditions, and the following disclaimer.
- * 
+ *
  * B.  Redistributions in binary form must reproduce the above copyright
  * notice, and this list of conditions, and the following disclaimer in
  * the documentation and/or other materials provided with the distribution.
- * 
+ *
  * C.  Neither the name of Image Power, Inc. nor any other contributor
  * (including, but not limited to, the University of British Columbia and
  * Michael David Adams) may be used to endorse or promote products derived
  * from this software without specific prior written permission.
- * 
+ *
  * D.  User agrees that it shall not commence any action against Image Power,
  * Inc., the University of British Columbia, Michael David Adams, or any
  * other contributors (collectively "Licensors") for infringement of any
@@ -56,17 +56,17 @@
  * trade dress, or service mark rights); and (v) divisions, continuations,
  * renewals, reissues and extensions of the foregoing (as and to the extent
  * applicable) now existing, hereafter filed, issued or acquired.
- * 
+ *
  * E.  If User commences an infringement action against any Licensor(s) then
  * such Licensor(s) shall have the right to terminate User's license and
  * all sublicenses that have been granted hereunder by User to other parties.
- * 
+ *
  * F.  This software is for use only in hardware or software products that
  * are compliant with ISO/IEC 15444-1 (i.e., JPEG-2000 Part 1).  No license
  * or right to this Software is granted for products that do not comply
  * with ISO/IEC 15444-1.  The JPEG-2000 Part 1 standard can be purchased
  * from the ISO.
- * 
+ *
  * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS LICENSE.
  * NO USE OF THE JASPER SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER
  * THIS DISCLAIMER.  THE JASPER SOFTWARE IS PROVIDED BY THE LICENSORS AND
@@ -106,7 +106,7 @@
  * TECHNOLOGY OR PRODUCTS FOR HIGH RISK ACTIVITIES AND WILL ENSURE THAT ITS
  * CUSTOMERS AND END-USERS OF ITS PRODUCTS ARE PROVIDED WITH A COPY OF THE
  * NOTICE SPECIFIED IN THIS SECTION.
- * 
+ *
  * __END_OF_JASPER_LICENSE__
  */
 
@@ -140,36 +140,36 @@ extern "C" {
  */
 
 /* The threshold at which image data is no longer stored in memory. */
-#define JAS_IMAGE_INMEMTHRESH	(16 * 1024 * 1024)
+#define JAS_IMAGE_INMEMTHRESH   (16 * 1024 * 1024)
 
 /*
  * Color models.
  */
 
-#define JAS_IMAGE_CS_UNKNOWN	0	/* Unknown */
-#define	JAS_IMAGE_CS_GRAY	1	/* Standard Gray */
-#define	JAS_IMAGE_CS_RGB	2	/* Standard RGB */
-#define	JAS_IMAGE_CS_YCBCR	3	/* Standard YCC */
+#define JAS_IMAGE_CS_UNKNOWN    0       /* Unknown */
+#define JAS_IMAGE_CS_GRAY       1       /* Standard Gray */
+#define JAS_IMAGE_CS_RGB        2       /* Standard RGB */
+#define JAS_IMAGE_CS_YCBCR      3       /* Standard YCC */
 #if 0
-#define	JAS_IMAGE_CM_ICC	4	/* ICC Profile */
+#define JAS_IMAGE_CM_ICC        4       /* ICC Profile */
 #endif
 /*
  * Component types
  */
 
-#define	JAS_IMAGE_CT_UNKNOWN	0x10000
-#define	JAS_IMAGE_CT_COLOR(n)	((n) & 0x7fff)
-#define	JAS_IMAGE_CT_OPACITY	0x08000
+#define JAS_IMAGE_CT_UNKNOWN    0x10000
+#define JAS_IMAGE_CT_COLOR(n)   ((n) & 0x7fff)
+#define JAS_IMAGE_CT_OPACITY    0x08000
 
-#define	JAS_IMAGE_CT_RGB_R	0
-#define	JAS_IMAGE_CT_RGB_G	1
-#define	JAS_IMAGE_CT_RGB_B	2
+#define JAS_IMAGE_CT_RGB_R      0
+#define JAS_IMAGE_CT_RGB_G      1
+#define JAS_IMAGE_CT_RGB_B      2
 
-#define	JAS_IMAGE_CT_YCBCR_Y	0
-#define	JAS_IMAGE_CT_YCBCR_CB	1
-#define	JAS_IMAGE_CT_YCBCR_CR	2
+#define JAS_IMAGE_CT_YCBCR_Y    0
+#define JAS_IMAGE_CT_YCBCR_CB   1
+#define JAS_IMAGE_CT_YCBCR_CR   2
 
-#define	JAS_IMAGE_CT_GRAY_Y	0
+#define JAS_IMAGE_CT_GRAY_Y     0
 
 /*****************************************************************************\
 * Image class and supporting classes.
@@ -179,40 +179,40 @@ extern "C" {
 
 typedef struct {
 
-	uint_fast32_t tlx_;
-	/* The x-coordinate of the top-left corner of the component. */
+        uint_fast32_t tlx_;
+        /* The x-coordinate of the top-left corner of the component. */
 
-	uint_fast32_t tly_;
-	/* The y-coordinate of the top-left corner of the component. */
+        uint_fast32_t tly_;
+        /* The y-coordinate of the top-left corner of the component. */
 
-	uint_fast32_t hstep_;
-	/* The horizontal sampling period in units of the reference grid. */
+        uint_fast32_t hstep_;
+        /* The horizontal sampling period in units of the reference grid. */
 
-	uint_fast32_t vstep_;
-	/* The vertical sampling period in units of the reference grid. */
+        uint_fast32_t vstep_;
+        /* The vertical sampling period in units of the reference grid. */
 
-	uint_fast32_t width_;
-	/* The component width in samples. */
+        uint_fast32_t width_;
+        /* The component width in samples. */
 
-	uint_fast32_t height_;
-	/* The component height in samples. */
+        uint_fast32_t height_;
+        /* The component height in samples. */
 
-	uint_fast16_t 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. */
+        uint_fast16_t 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. */
 
-	uint_fast8_t sgnd_;
-	/* The signedness of the sample data. */
+        uint_fast8_t sgnd_;
+        /* The signedness of the sample data. */
 
-	jas_stream_t *stream_;
-	/* The stream containing the component data. */
+        jas_stream_t *stream_;
+        /* The stream containing the component data. */
 
-	int cps_;
-	/* The number of characters per sample in the stream. */
+        int cps_;
+        /* The number of characters per sample in the stream. */
 
-	uint_fast32_t type_;
-	/* The type of component (e.g., opacity, red, green, blue, luma). */
+        uint_fast32_t type_;
+        /* The type of component (e.g., opacity, red, green, blue, luma). */
 
 } jas_image_cmpt_t;
 
@@ -220,40 +220,40 @@ typedef struct {
 
 typedef struct {
 
-	uint_fast32_t tlx_;
-	/* The x-coordinate of the top-left corner of the image bounding box. */
+        uint_fast32_t tlx_;
+        /* The x-coordinate of the top-left corner of the image bounding box. */
 
-	uint_fast32_t tly_;
-	/* The y-coordinate of the top-left corner of the image bounding box. */
+        uint_fast32_t tly_;
+        /* The y-coordinate of the top-left corner of the image bounding box. */
 
-	uint_fast32_t brx_;
-	/* The x-coordinate of the bottom-right corner of the image bounding
-	  box (plus one). */
+        uint_fast32_t brx_;
+        /* The x-coordinate of the bottom-right corner of the image bounding
+          box (plus one). */
 
-	uint_fast32_t bry_;
-	/* The y-coordinate of the bottom-right corner of the image bounding
-	  box (plus one). */
+        uint_fast32_t bry_;
+        /* The y-coordinate of the bottom-right corner of the image bounding
+          box (plus one). */
 
-	uint_fast16_t numcmpts_;
-	/* The number of components. */
+        uint_fast16_t numcmpts_;
+        /* The number of components. */
 
-	uint_fast16_t maxcmpts_;
-	/* The maximum number of components that this image can have (i.e., the
-	  allocated size of the components array). */
+        uint_fast16_t maxcmpts_;
+        /* The maximum number of components that this image can have (i.e., the
+          allocated size of the components array). */
 
-	jas_image_cmpt_t **cmpts_;
-	/* Per-component information. */
+        jas_image_cmpt_t **cmpts_;
+        /* Per-component information. */
 
-	int colorspace_;
-	/* The color space used (e.g., RGB, YCbCr, gray).  This field is only
-	of particular relevance in the case of a multi-component image. */
+        int colorspace_;
+        /* The color space used (e.g., RGB, YCbCr, gray).  This field is only
+        of particular relevance in the case of a multi-component image. */
 
-	unsigned char *iccp_;
-	/* ICC profile information. */
+        unsigned char *iccp_;
+        /* ICC profile information. */
 
-	int iccplen_;
+        int iccplen_;
 
-	bool inmem_;
+        bool inmem_;
 
 } jas_image_t;
 
@@ -263,29 +263,29 @@ typedef struct {
 
 typedef struct {
 
-	uint_fast32_t tlx;
-	/* The x-coordinate of the top-left corner of the component. */
+        uint_fast32_t tlx;
+        /* The x-coordinate of the top-left corner of the component. */
 
-	uint_fast32_t tly;
-	/* The y-coordinate of the top-left corner of the component. */
+        uint_fast32_t tly;
+        /* The y-coordinate of the top-left corner of the component. */
 
-	uint_fast32_t hstep;
-	/* The horizontal sampling period in units of the reference grid. */
+        uint_fast32_t hstep;
+        /* The horizontal sampling period in units of the reference grid. */
 
-	uint_fast32_t vstep;
-	/* The vertical sampling period in units of the reference grid. */
+        uint_fast32_t vstep;
+        /* The vertical sampling period in units of the reference grid. */
 
-	uint_fast32_t width;
-	/* The width of the component in samples. */
+        uint_fast32_t width;
+        /* The width of the component in samples. */
 
-	uint_fast32_t height;
-	/* The height of the component in samples. */
+        uint_fast32_t height;
+        /* The height of the component in samples. */
 
-	uint_fast16_t prec;
-	/* The precision of the component sample data. */
+        uint_fast16_t prec;
+        /* The precision of the component sample data. */
 
-	bool sgnd;
-	/* The signedness of the component sample data. */
+        bool sgnd;
+        /* The signedness of the component sample data. */
 
 } jas_image_cmptparm_t;
 
@@ -293,24 +293,24 @@ typedef struct {
 * File format related classes.
 \******************************************************************************/
 
-#define	JAS_IMAGE_MAXFMTS	32
+#define JAS_IMAGE_MAXFMTS       32
 /* The maximum number of image data formats we can handle. */
 
 /* Image format-dependent operations. */
 
 typedef struct {
 
-	void (*decode)(jas_stream_t * const in,
-				   const char *   const opts,
-				   jas_image_t ** const imagePP,
-				   const char **  const errorP);
-	/* Decode image data from a stream. */
+        void (*decode)(jas_stream_t * const in,
+                                   const char *   const opts,
+                                   jas_image_t ** const imagePP,
+                                   const char **  const errorP);
+        /* Decode image data from a stream. */
 
-	int (*encode)(jas_image_t *image, jas_stream_t *out, char *opts);
-	/* Encode image data to a stream. */
+        int (*encode)(jas_image_t *image, jas_stream_t *out, char *opts);
+        /* Encode image data to a stream. */
 
-	int (*validate)(jas_stream_t *in);
-	/* 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;
 
@@ -318,20 +318,20 @@ typedef struct {
 
 typedef struct {
 
-	int id;
-	/* The ID for this format. */
+        int id;
+        /* The ID for this format. */
 
-	char *name;
-	/* The name by which this format is identified. */
+        char *name;
+        /* The name by which this format is identified. */
 
-	char *ext;
-	/* The file name extension associated with this format. */
+        char *ext;
+        /* The file name extension associated with this format. */
 
-	char *desc;
-	/* A brief description of the format. */
+        char *desc;
+        /* A brief description of the format. */
 
-	jas_image_fmtops_t ops;
-	/* The operations for this format. */
+        jas_image_fmtops_t ops;
+        /* The operations for this format. */
 
 } jas_image_fmtinfo_t;
 
@@ -354,92 +354,92 @@ void jas_image_destroy(jas_image_t *image);
 
 /* Get the width of the image in units of the image reference grid. */
 #define jas_image_width(image) \
-	((image)->brx_ - (image)->tlx_)
+        ((image)->brx_ - (image)->tlx_)
 
 /* Get the height of the image in units of the image reference grid. */
-#define	jas_image_height(image) \
-	((image)->bry_ - (image)->tly_)
+#define jas_image_height(image) \
+        ((image)->bry_ - (image)->tly_)
 
 /* Get the x-coordinate of the top-left corner of the image bounding box
   on the reference grid. */
 #define jas_image_tlx(image) \
-	((image)->tlx_)
+        ((image)->tlx_)
 
 /* Get the y-coordinate of the top-left corner of the image bounding box
   on the reference grid. */
 #define jas_image_tly(image) \
-	((image)->tly_)
+        ((image)->tly_)
 
 /* Get the x-coordinate of the bottom-right corner of the image bounding box
   on the reference grid (plus one). */
 #define jas_image_brx(image) \
-	((image)->brx_)
+        ((image)->brx_)
 
 /* Get the y-coordinate of the bottom-right corner of the image bounding box
   on the reference grid (plus one). */
 #define jas_image_bry(image) \
-	((image)->bry_)
+        ((image)->bry_)
 
 /* Get the number of image components. */
-#define	jas_image_numcmpts(image) \
-	((image)->numcmpts_)
+#define jas_image_numcmpts(image) \
+        ((image)->numcmpts_)
 
 /* Get the color model used by the image. */
-#define	jas_image_colorspace(image) \
-	((image)->colorspace_)
+#define jas_image_colorspace(image) \
+        ((image)->colorspace_)
 
 /* Set the color model for an image. */
 #define jas_image_setcolorspace(image, colorspace) \
-	((image)->colorspace_ = (colorspace))
+        ((image)->colorspace_ = (colorspace))
 
 #define jas_image_cmpttype(image, cmptno) \
-	((image)->cmpts_[(cmptno)]->type_)
+        ((image)->cmpts_[(cmptno)]->type_)
 #define jas_image_setcmpttype(image, cmptno, type) \
-	((image)->cmpts_[(cmptno)]->type_ = (type))
+        ((image)->cmpts_[(cmptno)]->type_ = (type))
 
 /* Get the width of a component. */
-#define	jas_image_cmptwidth(image, cmptno) \
-	((image)->cmpts_[cmptno]->width_)
+#define jas_image_cmptwidth(image, cmptno) \
+        ((image)->cmpts_[cmptno]->width_)
 
 /* Get the height of a component. */
-#define	jas_image_cmptheight(image, cmptno) \
-	((image)->cmpts_[cmptno]->height_)
+#define jas_image_cmptheight(image, cmptno) \
+        ((image)->cmpts_[cmptno]->height_)
 
 /* Get the signedness of the sample data for a component. */
-#define	jas_image_cmptsgnd(image, cmptno) \
-	((image)->cmpts_[cmptno]->sgnd_)
+#define jas_image_cmptsgnd(image, cmptno) \
+        ((image)->cmpts_[cmptno]->sgnd_)
 
 /* Get the precision of the sample data for a component. */
-#define	jas_image_cmptprec(image, cmptno) \
-	((image)->cmpts_[cmptno]->prec_)
+#define jas_image_cmptprec(image, cmptno) \
+        ((image)->cmpts_[cmptno]->prec_)
 
 /* Get the horizontal subsampling factor for a component. */
-#define	jas_image_cmpthstep(image, cmptno) \
-	((image)->cmpts_[cmptno]->hstep_)
+#define jas_image_cmpthstep(image, cmptno) \
+        ((image)->cmpts_[cmptno]->hstep_)
 
 /* Get the vertical subsampling factor for a component. */
-#define	jas_image_cmptvstep(image, cmptno) \
-	((image)->cmpts_[cmptno]->vstep_)
+#define jas_image_cmptvstep(image, cmptno) \
+        ((image)->cmpts_[cmptno]->vstep_)
 
 /* Get the x-coordinate of the top-left corner of a component. */
-#define	jas_image_cmpttlx(image, cmptno) \
-	((image)->cmpts_[cmptno]->tlx_)
+#define jas_image_cmpttlx(image, cmptno) \
+        ((image)->cmpts_[cmptno]->tlx_)
 
 /* Get the y-coordinate of the top-left corner of a component. */
-#define	jas_image_cmpttly(image, cmptno) \
-	((image)->cmpts_[cmptno]->tly_)
+#define jas_image_cmpttly(image, cmptno) \
+        ((image)->cmpts_[cmptno]->tly_)
 
 /* Get the x-coordinate of the bottom-right corner of a component
   (plus "one"). */
-#define	jas_image_cmptbrx(image, cmptno) \
-	((image)->cmpts_[cmptno]->tlx_ + (image)->cmpts_[cmptno]->width_ * \
-	  (image)->cmpts_[cmptno]->hstep_)
+#define jas_image_cmptbrx(image, cmptno) \
+        ((image)->cmpts_[cmptno]->tlx_ + (image)->cmpts_[cmptno]->width_ * \
+          (image)->cmpts_[cmptno]->hstep_)
 
 /* Get the y-coordinate of the bottom-right corner of a component
   (plus "one"). */
-#define	jas_image_cmptbry(image, cmptno) \
-	((image)->cmpts_[cmptno]->tly_ + (image)->cmpts_[cmptno]->height_ * \
-	  (image)->cmpts_[cmptno]->vstep_)
+#define jas_image_cmptbry(image, cmptno) \
+        ((image)->cmpts_[cmptno]->tly_ + (image)->cmpts_[cmptno]->height_ * \
+          (image)->cmpts_[cmptno]->vstep_)
 
 /* Get the raw size of an image (i.e., the nominal size of the image without
   any compression. */
@@ -449,10 +449,10 @@ uint_fast32_t jas_image_rawsize(jas_image_t *image);
 
 void
 pmjas_image_decode(jas_stream_t * const in,
-				   int            const fmt,
-				   const char *   const optstr,
-				   jas_image_t ** const imagePP,
-				   const char **  const errorP);
+                                   int            const fmt,
+                                   const char *   const optstr,
+                                   jas_image_t ** const imagePP,
+                                   const char **  const errorP);
 
 /* Write an image to a stream in a specified format. */
 int jas_image_encode(jas_image_t *image, jas_stream_t *out, int fmt,
@@ -486,13 +486,13 @@ int_fast64_t jas_image_readcmpt1(jas_image_t *image, uint_fast16_t cmptno,
   uint_fast32_t x, uint_fast32_t y);
 #endif
 
-#define	JAS_IMAGE_CDT_GETSGND(dtype) (((dtype) >> 7) & 1)
-#define	JAS_IMAGE_CDT_SETSGND(dtype) (((dtype) & 1) << 7)
-#define	JAS_IMAGE_CDT_GETPREC(dtype) ((dtype) & 0x7f)
-#define	JAS_IMAGE_CDT_SETPREC(dtype) ((dtype) & 0x7f)
+#define JAS_IMAGE_CDT_GETSGND(dtype) (((dtype) >> 7) & 1)
+#define JAS_IMAGE_CDT_SETSGND(dtype) (((dtype) & 1) << 7)
+#define JAS_IMAGE_CDT_GETPREC(dtype) ((dtype) & 0x7f)
+#define JAS_IMAGE_CDT_SETPREC(dtype) ((dtype) & 0x7f)
 
-#define	jas_image_cmptdtype(image, cmptno) \
-	(JAS_IMAGE_CDT_SETSGND((image)->cmpts_[cmptno]->sgnd_) | JAS_IMAGE_CDT_SETPREC((image)->cmpts_[cmptno]->prec_))
+#define jas_image_cmptdtype(image, cmptno) \
+        (JAS_IMAGE_CDT_SETSGND((image)->cmpts_[cmptno]->sgnd_) | JAS_IMAGE_CDT_SETPREC((image)->cmpts_[cmptno]->prec_))
 
 void jas_image_dump(jas_image_t *image, FILE *out);
 
@@ -513,7 +513,7 @@ int jas_image_getcmptbytype(jas_image_t *image, int ctype);
 void jas_image_clearfmts(void);
 
 /* Add entry to table of image formats. */
-int jas_image_addfmt(int id, const char *name, const char *ext, 
+int jas_image_addfmt(int id, const char *name, const char *ext,
   const char *desc,
   jas_image_fmtops_t *ops);
 
@@ -578,9 +578,9 @@ int bmp_validate(jas_stream_t *in);
 /* Format-dependent operations for JP2 capability. */
 void
 jp2_decode(jas_stream_t * const in,
-		   const char *   const optstr,
-		   jas_image_t ** const imagePP,
-		   const char **  const errorP);
+                   const char *   const optstr,
+                   jas_image_t ** const imagePP,
+                   const char **  const errorP);
 int jp2_encode(jas_image_t *image, jas_stream_t *out, char *optstr);
 int jp2_validate(jas_stream_t *in);
 #endif
diff --git a/converter/other/jpeg2000/libjasper/include/jasper/jas_init.h b/converter/other/jpeg2000/libjasper/include/jasper/jas_init.h
index 4ebeaa87..8d84a10b 100644
--- a/converter/other/jpeg2000/libjasper/include/jasper/jas_init.h
+++ b/converter/other/jpeg2000/libjasper/include/jasper/jas_init.h
@@ -4,14 +4,14 @@
  */
 
 /* __START_OF_JASPER_LICENSE__
- * 
+ *
  * JasPer Software License
- * 
+ *
  * IMAGE POWER JPEG-2000 PUBLIC LICENSE
  * ************************************
- * 
+ *
  * GRANT:
- * 
+ *
  * Permission is hereby granted, free of charge, to any person (the "User")
  * obtaining a copy of this software and associated documentation, to deal
  * in the JasPer Software without restriction, including without limitation
@@ -19,22 +19,22 @@
  * and/or sell copies of the JasPer Software (in source and binary forms),
  * and to permit persons to whom the JasPer Software is furnished to do so,
  * provided further that the License Conditions below are met.
- * 
+ *
  * License Conditions
  * ******************
- * 
+ *
  * A.  Redistributions of source code must retain the above copyright notice,
  * and this list of conditions, and the following disclaimer.
- * 
+ *
  * B.  Redistributions in binary form must reproduce the above copyright
  * notice, and this list of conditions, and the following disclaimer in
  * the documentation and/or other materials provided with the distribution.
- * 
+ *
  * C.  Neither the name of Image Power, Inc. nor any other contributor
  * (including, but not limited to, the University of British Columbia and
  * Michael David Adams) may be used to endorse or promote products derived
  * from this software without specific prior written permission.
- * 
+ *
  * D.  User agrees that it shall not commence any action against Image Power,
  * Inc., the University of British Columbia, Michael David Adams, or any
  * other contributors (collectively "Licensors") for infringement of any
@@ -54,17 +54,17 @@
  * trade dress, or service mark rights); and (v) divisions, continuations,
  * renewals, reissues and extensions of the foregoing (as and to the extent
  * applicable) now existing, hereafter filed, issued or acquired.
- * 
+ *
  * E.  If User commences an infringement action against any Licensor(s) then
  * such Licensor(s) shall have the right to terminate User's license and
  * all sublicenses that have been granted hereunder by User to other parties.
- * 
+ *
  * F.  This software is for use only in hardware or software products that
  * are compliant with ISO/IEC 15444-1 (i.e., JPEG-2000 Part 1).  No license
  * or right to this Software is granted for products that do not comply
  * with ISO/IEC 15444-1.  The JPEG-2000 Part 1 standard can be purchased
  * from the ISO.
- * 
+ *
  * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS LICENSE.
  * NO USE OF THE JASPER SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER
  * THIS DISCLAIMER.  THE JASPER SOFTWARE IS PROVIDED BY THE LICENSORS AND
@@ -104,7 +104,7 @@
  * TECHNOLOGY OR PRODUCTS FOR HIGH RISK ACTIVITIES AND WILL ENSURE THAT ITS
  * CUSTOMERS AND END-USERS OF ITS PRODUCTS ARE PROVIDED WITH A COPY OF THE
  * NOTICE SPECIFIED IN THIS SECTION.
- * 
+ *
  * __END_OF_JASPER_LICENSE__
  */
 
diff --git a/converter/other/jpeg2000/libjasper/include/jasper/jas_malloc.h b/converter/other/jpeg2000/libjasper/include/jasper/jas_malloc.h
index fe5b6172..c2a32581 100644
--- a/converter/other/jpeg2000/libjasper/include/jasper/jas_malloc.h
+++ b/converter/other/jpeg2000/libjasper/include/jasper/jas_malloc.h
@@ -6,14 +6,14 @@
  */
 
 /* __START_OF_JASPER_LICENSE__
- * 
+ *
  * JasPer Software License
- * 
+ *
  * IMAGE POWER JPEG-2000 PUBLIC LICENSE
  * ************************************
- * 
+ *
  * GRANT:
- * 
+ *
  * Permission is hereby granted, free of charge, to any person (the "User")
  * obtaining a copy of this software and associated documentation, to deal
  * in the JasPer Software without restriction, including without limitation
@@ -21,22 +21,22 @@
  * and/or sell copies of the JasPer Software (in source and binary forms),
  * and to permit persons to whom the JasPer Software is furnished to do so,
  * provided further that the License Conditions below are met.
- * 
+ *
  * License Conditions
  * ******************
- * 
+ *
  * A.  Redistributions of source code must retain the above copyright notice,
  * and this list of conditions, and the following disclaimer.
- * 
+ *
  * B.  Redistributions in binary form must reproduce the above copyright
  * notice, and this list of conditions, and the following disclaimer in
  * the documentation and/or other materials provided with the distribution.
- * 
+ *
  * C.  Neither the name of Image Power, Inc. nor any other contributor
  * (including, but not limited to, the University of British Columbia and
  * Michael David Adams) may be used to endorse or promote products derived
  * from this software without specific prior written permission.
- * 
+ *
  * D.  User agrees that it shall not commence any action against Image Power,
  * Inc., the University of British Columbia, Michael David Adams, or any
  * other contributors (collectively "Licensors") for infringement of any
@@ -56,17 +56,17 @@
  * trade dress, or service mark rights); and (v) divisions, continuations,
  * renewals, reissues and extensions of the foregoing (as and to the extent
  * applicable) now existing, hereafter filed, issued or acquired.
- * 
+ *
  * E.  If User commences an infringement action against any Licensor(s) then
  * such Licensor(s) shall have the right to terminate User's license and
  * all sublicenses that have been granted hereunder by User to other parties.
- * 
+ *
  * F.  This software is for use only in hardware or software products that
  * are compliant with ISO/IEC 15444-1 (i.e., JPEG-2000 Part 1).  No license
  * or right to this Software is granted for products that do not comply
  * with ISO/IEC 15444-1.  The JPEG-2000 Part 1 standard can be purchased
  * from the ISO.
- * 
+ *
  * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS LICENSE.
  * NO USE OF THE JASPER SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER
  * THIS DISCLAIMER.  THE JASPER SOFTWARE IS PROVIDED BY THE LICENSORS AND
@@ -106,7 +106,7 @@
  * TECHNOLOGY OR PRODUCTS FOR HIGH RISK ACTIVITIES AND WILL ENSURE THAT ITS
  * CUSTOMERS AND END-USERS OF ITS PRODUCTS ARE PROVIDED WITH A COPY OF THE
  * NOTICE SPECIFIED IN THIS SECTION.
- * 
+ *
  * __END_OF_JASPER_LICENSE__
  */
 
@@ -138,10 +138,10 @@ extern "C" {
 /* This is somewhat of a hack, but it's a useful hack. :-) */
 /* Use my own custom memory allocator for debugging. */
 #include "../../../../local/src/memalloc.h"
-#define jas_malloc	MEMALLOC
-#define	jas_free	MEMFREE
-#define	jas_realloc	MEMREALLOC
-#define	jas_calloc	MEMCALLOC
+#define jas_malloc      MEMALLOC
+#define jas_free        MEMFREE
+#define jas_realloc     MEMREALLOC
+#define jas_calloc      MEMCALLOC
 #endif
 
 /******************************************************************************\
diff --git a/converter/other/jpeg2000/libjasper/include/jasper/jas_math.h b/converter/other/jpeg2000/libjasper/include/jasper/jas_math.h
index a43051e5..2baac725 100644
--- a/converter/other/jpeg2000/libjasper/include/jasper/jas_math.h
+++ b/converter/other/jpeg2000/libjasper/include/jasper/jas_math.h
@@ -6,14 +6,14 @@
  */
 
 /* __START_OF_JASPER_LICENSE__
- * 
+ *
  * JasPer Software License
- * 
+ *
  * IMAGE POWER JPEG-2000 PUBLIC LICENSE
  * ************************************
- * 
+ *
  * GRANT:
- * 
+ *
  * Permission is hereby granted, free of charge, to any person (the "User")
  * obtaining a copy of this software and associated documentation, to deal
  * in the JasPer Software without restriction, including without limitation
@@ -21,22 +21,22 @@
  * and/or sell copies of the JasPer Software (in source and binary forms),
  * and to permit persons to whom the JasPer Software is furnished to do so,
  * provided further that the License Conditions below are met.
- * 
+ *
  * License Conditions
  * ******************
- * 
+ *
  * A.  Redistributions of source code must retain the above copyright notice,
  * and this list of conditions, and the following disclaimer.
- * 
+ *
  * B.  Redistributions in binary form must reproduce the above copyright
  * notice, and this list of conditions, and the following disclaimer in
  * the documentation and/or other materials provided with the distribution.
- * 
+ *
  * C.  Neither the name of Image Power, Inc. nor any other contributor
  * (including, but not limited to, the University of British Columbia and
  * Michael David Adams) may be used to endorse or promote products derived
  * from this software without specific prior written permission.
- * 
+ *
  * D.  User agrees that it shall not commence any action against Image Power,
  * Inc., the University of British Columbia, Michael David Adams, or any
  * other contributors (collectively "Licensors") for infringement of any
@@ -56,17 +56,17 @@
  * trade dress, or service mark rights); and (v) divisions, continuations,
  * renewals, reissues and extensions of the foregoing (as and to the extent
  * applicable) now existing, hereafter filed, issued or acquired.
- * 
+ *
  * E.  If User commences an infringement action against any Licensor(s) then
  * such Licensor(s) shall have the right to terminate User's license and
  * all sublicenses that have been granted hereunder by User to other parties.
- * 
+ *
  * F.  This software is for use only in hardware or software products that
  * are compliant with ISO/IEC 15444-1 (i.e., JPEG-2000 Part 1).  No license
  * or right to this Software is granted for products that do not comply
  * with ISO/IEC 15444-1.  The JPEG-2000 Part 1 standard can be purchased
  * from the ISO.
- * 
+ *
  * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS LICENSE.
  * NO USE OF THE JASPER SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER
  * THIS DISCLAIMER.  THE JASPER SOFTWARE IS PROVIDED BY THE LICENSORS AND
@@ -106,7 +106,7 @@
  * TECHNOLOGY OR PRODUCTS FOR HIGH RISK ACTIVITIES AND WILL ENSURE THAT ITS
  * CUSTOMERS AND END-USERS OF ITS PRODUCTS ARE PROVIDED WITH A COPY OF THE
  * NOTICE SPECIFIED IN THIS SECTION.
- * 
+ *
  * __END_OF_JASPER_LICENSE__
  */
 
@@ -116,16 +116,16 @@
  * $Id$
  */
 
-#ifndef	JAS_MATH_H
-#define	JAS_MATH_H
+#ifndef JAS_MATH_H
+#define JAS_MATH_H
 
 /******************************************************************************\
 * Includes
 \******************************************************************************/
 
-#include	<assert.h>
-#include	<stdio.h>
-#include	<string.h>
+#include        <assert.h>
+#include        <stdio.h>
+#include        <string.h>
 
 #ifdef __cplusplus
 extern "C" {
@@ -136,25 +136,25 @@ extern "C" {
 \******************************************************************************/
 
 /* Compute the absolute value. */
-#define	JAS_ABS(x) \
-	(((x) >= 0) ? (x) : (-(x)))
+#define JAS_ABS(x) \
+        (((x) >= 0) ? (x) : (-(x)))
 
 /* Compute the minimum of two values. */
-#define	JAS_MIN(x, y) \
-	(((x) < (y)) ? (x) : (y))
+#define JAS_MIN(x, y) \
+        (((x) < (y)) ? (x) : (y))
 
 /* Compute the maximum of two values. */
-#define	JAS_MAX(x, y) \
-	(((x) > (y)) ? (x) : (y))
+#define JAS_MAX(x, y) \
+        (((x) > (y)) ? (x) : (y))
 
 /* Compute the remainder from division (where division is defined such
   that the remainder is always nonnegative). */
-#define	JAS_MOD(x, y) \
-	(((x) < 0) ? (((-x) % (y)) ? ((y) - ((-(x)) % (y))) : (0)) : ((x) % (y)))
+#define JAS_MOD(x, y) \
+        (((x) < 0) ? (((-x) % (y)) ? ((y) - ((-(x)) % (y))) : (0)) : ((x) % (y)))
 
 /* Compute the integer with the specified number of least significant bits
   set to one. */
-#define	JAS_ONES(n) \
+#define JAS_ONES(n) \
   ((1 << (n)) - 1)
 
 #ifdef __cplusplus
diff --git a/converter/other/jpeg2000/libjasper/include/jasper/jas_seq.h b/converter/other/jpeg2000/libjasper/include/jasper/jas_seq.h
index 4599f50c..502470d0 100644
--- a/converter/other/jpeg2000/libjasper/include/jasper/jas_seq.h
+++ b/converter/other/jpeg2000/libjasper/include/jasper/jas_seq.h
@@ -6,14 +6,14 @@
  */
 
 /* __START_OF_JASPER_LICENSE__
- * 
+ *
  * JasPer Software License
- * 
+ *
  * IMAGE POWER JPEG-2000 PUBLIC LICENSE
  * ************************************
- * 
+ *
  * GRANT:
- * 
+ *
  * Permission is hereby granted, free of charge, to any person (the "User")
  * obtaining a copy of this software and associated documentation, to deal
  * in the JasPer Software without restriction, including without limitation
@@ -21,22 +21,22 @@
  * and/or sell copies of the JasPer Software (in source and binary forms),
  * and to permit persons to whom the JasPer Software is furnished to do so,
  * provided further that the License Conditions below are met.
- * 
+ *
  * License Conditions
  * ******************
- * 
+ *
  * A.  Redistributions of source code must retain the above copyright notice,
  * and this list of conditions, and the following disclaimer.
- * 
+ *
  * B.  Redistributions in binary form must reproduce the above copyright
  * notice, and this list of conditions, and the following disclaimer in
  * the documentation and/or other materials provided with the distribution.
- * 
+ *
  * C.  Neither the name of Image Power, Inc. nor any other contributor
  * (including, but not limited to, the University of British Columbia and
  * Michael David Adams) may be used to endorse or promote products derived
  * from this software without specific prior written permission.
- * 
+ *
  * D.  User agrees that it shall not commence any action against Image Power,
  * Inc., the University of British Columbia, Michael David Adams, or any
  * other contributors (collectively "Licensors") for infringement of any
@@ -56,17 +56,17 @@
  * trade dress, or service mark rights); and (v) divisions, continuations,
  * renewals, reissues and extensions of the foregoing (as and to the extent
  * applicable) now existing, hereafter filed, issued or acquired.
- * 
+ *
  * E.  If User commences an infringement action against any Licensor(s) then
  * such Licensor(s) shall have the right to terminate User's license and
  * all sublicenses that have been granted hereunder by User to other parties.
- * 
+ *
  * F.  This software is for use only in hardware or software products that
  * are compliant with ISO/IEC 15444-1 (i.e., JPEG-2000 Part 1).  No license
  * or right to this Software is granted for products that do not comply
  * with ISO/IEC 15444-1.  The JPEG-2000 Part 1 standard can be purchased
  * from the ISO.
- * 
+ *
  * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS LICENSE.
  * NO USE OF THE JASPER SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER
  * THIS DISCLAIMER.  THE JASPER SOFTWARE IS PROVIDED BY THE LICENSORS AND
@@ -106,7 +106,7 @@
  * TECHNOLOGY OR PRODUCTS FOR HIGH RISK ACTIVITIES AND WILL ENSURE THAT ITS
  * CUSTOMERS AND END-USERS OF ITS PRODUCTS ARE PROVIDED WITH A COPY OF THE
  * NOTICE SPECIFIED IN THIS SECTION.
- * 
+ *
  * __END_OF_JASPER_LICENSE__
  */
 
@@ -135,7 +135,7 @@ extern "C" {
 \******************************************************************************/
 
 /* This matrix is a reference to another matrix. */
-#define JAS_MATRIX_REF	0x0001
+#define JAS_MATRIX_REF  0x0001
 
 /******************************************************************************\
 * Types.
@@ -151,38 +151,38 @@ typedef int_fast32_t jas_matent_t;
 
 typedef struct {
 
-	/* Additional state information. */
-	int flags_;
+        /* Additional state information. */
+        int flags_;
 
-	/* The starting horizontal index. */
-	int_fast32_t xstart_;
+        /* The starting horizontal index. */
+        int_fast32_t xstart_;
 
-	/* The starting vertical index. */
-	int_fast32_t ystart_;
+        /* The starting vertical index. */
+        int_fast32_t ystart_;
 
-	/* The ending horizontal index. */
-	int_fast32_t xend_;
+        /* The ending horizontal index. */
+        int_fast32_t xend_;
 
-	/* The ending vertical index. */
-	int_fast32_t yend_;
+        /* The ending vertical index. */
+        int_fast32_t yend_;
 
-	/* The number of rows in the matrix. */
-	int_fast32_t numrows_;
+        /* The number of rows in the matrix. */
+        int_fast32_t numrows_;
 
-	/* The number of columns in the matrix. */
-	int_fast32_t numcols_;
+        /* The number of columns in the matrix. */
+        int_fast32_t numcols_;
 
-	/* Pointers to the start of each row. */
-	jas_seqent_t **rows_;
+        /* Pointers to the start of each row. */
+        jas_seqent_t **rows_;
 
-	/* The allocated size of the rows array. */
-	int_fast32_t maxrows_;
+        /* The allocated size of the rows array. */
+        int_fast32_t maxrows_;
 
-	/* The matrix data buffer. */
-	jas_seqent_t *data_;
+        /* The matrix data buffer. */
+        jas_seqent_t *data_;
 
-	/* The allocated size of the data array. */
-	int_fast32_t datasize_;
+        /* The allocated size of the data array. */
+        int_fast32_t datasize_;
 
 } jas_matrix_t;
 
@@ -195,39 +195,39 @@ typedef jas_matrix_t jas_seq_t;
 
 /* Get the number of rows. */
 #define jas_matrix_numrows(matrix) \
-	((matrix)->numrows_)
+        ((matrix)->numrows_)
 
 /* Get the number of columns. */
 #define jas_matrix_numcols(matrix) \
-	((matrix)->numcols_)
+        ((matrix)->numcols_)
 
 /* Get a matrix element. */
 #define jas_matrix_get(matrix, i, j) \
-	((matrix)->rows_[i][j])
+        ((matrix)->rows_[i][j])
 
 /* Set a matrix element. */
 #define jas_matrix_set(matrix, i, j, v) \
-	((matrix)->rows_[i][j] = (v))
+        ((matrix)->rows_[i][j] = (v))
 
 /* Get an element from a matrix that is known to be a row or column vector. */
 #define jas_matrix_getv(matrix, i) \
-	(((matrix)->numrows_ == 1) ? ((matrix)->rows_[0][i]) : \
-	  ((matrix)->rows_[i][0]))
+        (((matrix)->numrows_ == 1) ? ((matrix)->rows_[0][i]) : \
+          ((matrix)->rows_[i][0]))
 
 /* Set an element in a matrix that is known to be a row or column vector. */
 #define jas_matrix_setv(matrix, i, v) \
-	(((matrix)->numrows_ == 1) ? ((matrix)->rows_[0][i] = (v)) : \
-	  ((matrix)->rows_[i][0] = (v)))
+        (((matrix)->numrows_ == 1) ? ((matrix)->rows_[0][i] = (v)) : \
+          ((matrix)->rows_[i][0] = (v)))
 
 /* Get the address of an element in a matrix. */
-#define	jas_matrix_getref(matrix, i, j) \
-	(&(matrix)->rows_[i][j])
+#define jas_matrix_getref(matrix, i, j) \
+        (&(matrix)->rows_[i][j])
 
-#define	jas_matrix_getvref(matrix, i) \
-	(((matrix)->numrows_ > 1) ? jas_matrix_getref(matrix, i, 0) : jas_matrix_getref(matrix, 0, i))
+#define jas_matrix_getvref(matrix, i) \
+        (((matrix)->numrows_ > 1) ? jas_matrix_getref(matrix, i, 0) : jas_matrix_getref(matrix, 0, i))
 
 #define jas_matrix_length(matrix) \
-	(max((matrix)->numrows_, (matrix)->numcols_))
+        (max((matrix)->numrows_, (matrix)->numcols_))
 
 /* Create a matrix with the specified dimensions. */
 jas_matrix_t *jas_matrix_create(int numrows, int numcols);
@@ -273,12 +273,12 @@ void jas_matrix_divpow2(jas_matrix_t *matrix, int n);
 void jas_matrix_setall(jas_matrix_t *matrix, jas_seqent_t val);
 
 /* The spacing between rows of a matrix. */
-#define	jas_matrix_rowstep(matrix) \
-	(((matrix)->numrows_ > 1) ? ((matrix)->rows_[1] - (matrix)->rows_[0]) : (0))
+#define jas_matrix_rowstep(matrix) \
+        (((matrix)->numrows_ > 1) ? ((matrix)->rows_[1] - (matrix)->rows_[0]) : (0))
 
 /* The spacing between columns of a matrix. */
-#define	jas_matrix_step(matrix) \
-	(((matrix)->numrows_ > 1) ? (jas_matrix_rowstep(matrix)) : (1))
+#define jas_matrix_step(matrix) \
+        (((matrix)->numrows_ > 1) ? (jas_matrix_rowstep(matrix)) : (1))
 
 /* Compare two matrices for equality. */
 int jas_matrix_cmp(jas_matrix_t *mat0, jas_matrix_t *mat1);
@@ -291,31 +291,31 @@ jas_seq2d_t *jas_seq2d_copy(jas_seq2d_t *x);
 
 jas_matrix_t *jas_seq2d_create(int xstart, int ystart, int xend, int yend);
 
-#define	jas_seq2d_destroy(s) \
-	jas_matrix_destroy(s)
-
-#define	jas_seq2d_xstart(s) \
-	((s)->xstart_)
-#define	jas_seq2d_ystart(s) \
-	((s)->ystart_)
-#define	jas_seq2d_xend(s) \
-	((s)->xend_)
-#define	jas_seq2d_yend(s) \
-	((s)->yend_)
-#define	jas_seq2d_getref(s, x, y) \
-	(jas_matrix_getref(s, (y) - (s)->ystart_, (x) - (s)->xstart_))
-#define	jas_seq2d_get(s, x, y) \
-	(jas_matrix_get(s, (y) - (s)->ystart_, (x) - (s)->xstart_))
-#define	jas_seq2d_rowstep(s) \
-	jas_matrix_rowstep(s)
-#define	jas_seq2d_width(s) \
-	((s)->xend_ - (s)->xstart_)
-#define	jas_seq2d_height(s) \
-	((s)->yend_ - (s)->ystart_)
-#define	jas_seq2d_setshift(s, x, y) \
-	((s)->xstart_ = (x), (s)->ystart_ = (y), \
-	  (s)->xend_ = (s)->xstart_ + (s)->numcols_, \
-	  (s)->yend_ = (s)->ystart_ + (s)->numrows_)
+#define jas_seq2d_destroy(s) \
+        jas_matrix_destroy(s)
+
+#define jas_seq2d_xstart(s) \
+        ((s)->xstart_)
+#define jas_seq2d_ystart(s) \
+        ((s)->ystart_)
+#define jas_seq2d_xend(s) \
+        ((s)->xend_)
+#define jas_seq2d_yend(s) \
+        ((s)->yend_)
+#define jas_seq2d_getref(s, x, y) \
+        (jas_matrix_getref(s, (y) - (s)->ystart_, (x) - (s)->xstart_))
+#define jas_seq2d_get(s, x, y) \
+        (jas_matrix_get(s, (y) - (s)->ystart_, (x) - (s)->xstart_))
+#define jas_seq2d_rowstep(s) \
+        jas_matrix_rowstep(s)
+#define jas_seq2d_width(s) \
+        ((s)->xend_ - (s)->xstart_)
+#define jas_seq2d_height(s) \
+        ((s)->yend_ - (s)->ystart_)
+#define jas_seq2d_setshift(s, x, y) \
+        ((s)->xstart_ = (x), (s)->ystart_ = (y), \
+          (s)->xend_ = (s)->xstart_ + (s)->numcols_, \
+          (s)->yend_ = (s)->ystart_ + (s)->numrows_)
 
 void jas_seq2d_bindsub(jas_matrix_t *s, jas_matrix_t *s1, int xstart,
   int ystart, int xend, int yend);
@@ -324,22 +324,22 @@ void jas_seq2d_bindsub(jas_matrix_t *s, jas_matrix_t *s1, int xstart,
 * Functions/macros for 1-D sequence class.
 \******************************************************************************/
 
-#define	jas_seq_create(start, end) \
-	(jas_seq2d_create(start, 0, end, 1))
+#define jas_seq_create(start, end) \
+        (jas_seq2d_create(start, 0, end, 1))
 
-#define	jas_seq_destroy(seq) \
-	(jas_seq2d_destroy(seq))
+#define jas_seq_destroy(seq) \
+        (jas_seq2d_destroy(seq))
 
 #define jas_seq_set(seq, i, v) \
-	((seq)->rows_[0][(i) - (seq)->xstart_] = (v))
-#define	jas_seq_getref(seq, i) \
-	(&(seq)->rows_[0][(i) - (seq)->xstart_])
-#define	jas_seq_get(seq, i) \
-	((seq)->rows_[0][(i) - (seq)->xstart_])
-#define	jas_seq_start(seq) \
-	((seq)->xstart_)
-#define	jas_seq_end(seq) \
-	((seq)->xend_)
+        ((seq)->rows_[0][(i) - (seq)->xstart_] = (v))
+#define jas_seq_getref(seq, i) \
+        (&(seq)->rows_[0][(i) - (seq)->xstart_])
+#define jas_seq_get(seq, i) \
+        ((seq)->rows_[0][(i) - (seq)->xstart_])
+#define jas_seq_start(seq) \
+        ((seq)->xstart_)
+#define jas_seq_end(seq) \
+        ((seq)->xend_)
 
 #ifdef __cplusplus
 }
diff --git a/converter/other/jpeg2000/libjasper/include/jasper/jas_stream.h b/converter/other/jpeg2000/libjasper/include/jasper/jas_stream.h
index 1062fe1d..8d4d4a77 100644
--- a/converter/other/jpeg2000/libjasper/include/jasper/jas_stream.h
+++ b/converter/other/jpeg2000/libjasper/include/jasper/jas_stream.h
@@ -6,14 +6,14 @@
  */
 
 /* __START_OF_JASPER_LICENSE__
- * 
+ *
  * JasPer Software License
- * 
+ *
  * IMAGE POWER JPEG-2000 PUBLIC LICENSE
  * ************************************
- * 
+ *
  * GRANT:
- * 
+ *
  * Permission is hereby granted, free of charge, to any person (the "User")
  * obtaining a copy of this software and associated documentation, to deal
  * in the JasPer Software without restriction, including without limitation
@@ -21,22 +21,22 @@
  * and/or sell copies of the JasPer Software (in source and binary forms),
  * and to permit persons to whom the JasPer Software is furnished to do so,
  * provided further that the License Conditions below are met.
- * 
+ *
  * License Conditions
  * ******************
- * 
+ *
  * A.  Redistributions of source code must retain the above copyright notice,
  * and this list of conditions, and the following disclaimer.
- * 
+ *
  * B.  Redistributions in binary form must reproduce the above copyright
  * notice, and this list of conditions, and the following disclaimer in
  * the documentation and/or other materials provided with the distribution.
- * 
+ *
  * C.  Neither the name of Image Power, Inc. nor any other contributor
  * (including, but not limited to, the University of British Columbia and
  * Michael David Adams) may be used to endorse or promote products derived
  * from this software without specific prior written permission.
- * 
+ *
  * D.  User agrees that it shall not commence any action against Image Power,
  * Inc., the University of British Columbia, Michael David Adams, or any
  * other contributors (collectively "Licensors") for infringement of any
@@ -56,17 +56,17 @@
  * trade dress, or service mark rights); and (v) divisions, continuations,
  * renewals, reissues and extensions of the foregoing (as and to the extent
  * applicable) now existing, hereafter filed, issued or acquired.
- * 
+ *
  * E.  If User commences an infringement action against any Licensor(s) then
  * such Licensor(s) shall have the right to terminate User's license and
  * all sublicenses that have been granted hereunder by User to other parties.
- * 
+ *
  * F.  This software is for use only in hardware or software products that
  * are compliant with ISO/IEC 15444-1 (i.e., JPEG-2000 Part 1).  No license
  * or right to this Software is granted for products that do not comply
  * with ISO/IEC 15444-1.  The JPEG-2000 Part 1 standard can be purchased
  * from the ISO.
- * 
+ *
  * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS LICENSE.
  * NO USE OF THE JASPER SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER
  * THIS DISCLAIMER.  THE JASPER SOFTWARE IS PROVIDED BY THE LICENSORS AND
@@ -106,7 +106,7 @@
  * TECHNOLOGY OR PRODUCTS FOR HIGH RISK ACTIVITIES AND WILL ENSURE THAT ITS
  * CUSTOMERS AND END-USERS OF ITS PRODUCTS ARE PROVIDED WITH A COPY OF THE
  * NOTICE SPECIFIED IN THIS SECTION.
- * 
+ *
  * __END_OF_JASPER_LICENSE__
  */
 
@@ -141,7 +141,7 @@ extern "C" {
 
 /* On most UNIX systems, we probably need to define O_BINARY ourselves. */
 #ifndef O_BINARY
-#define O_BINARY	0
+#define O_BINARY        0
 #endif
 
 /*
@@ -149,64 +149,64 @@ extern "C" {
  */
 
 /* The stream was opened for reading. */
-#define JAS_STREAM_READ	0x0001
+#define JAS_STREAM_READ 0x0001
 /* The stream was opened for writing. */
-#define JAS_STREAM_WRITE	0x0002
+#define JAS_STREAM_WRITE        0x0002
 /* The stream was opened for appending. */
-#define JAS_STREAM_APPEND	0x0004
+#define JAS_STREAM_APPEND       0x0004
 /* The stream was opened in binary mode. */
-#define JAS_STREAM_BINARY	0x0008
+#define JAS_STREAM_BINARY       0x0008
 /* The stream should be created/truncated. */
-#define JAS_STREAM_CREATE	0x0010
+#define JAS_STREAM_CREATE       0x0010
 
-#define JAS_STREAM_NOCLOSE	0x0020
+#define JAS_STREAM_NOCLOSE      0x0020
 
 /*
  * Stream buffering flags.
  */
 
 /* The stream is unbuffered. */
-#define JAS_STREAM_UNBUF	0x0000
+#define JAS_STREAM_UNBUF        0x0000
 /* The stream is line buffered. */
-#define JAS_STREAM_LINEBUF	0x0001
+#define JAS_STREAM_LINEBUF      0x0001
 /* The stream is fully buffered. */
-#define JAS_STREAM_FULLBUF	0x0002
+#define JAS_STREAM_FULLBUF      0x0002
 /* The buffering mode mask. */
-#define	JAS_STREAM_BUFMODEMASK	0x000f
+#define JAS_STREAM_BUFMODEMASK  0x000f
 
 /* The memory associated with the buffer needs to be deallocated when the
   stream is destroyed. */
-#define JAS_STREAM_FREEBUF	0x0008
+#define JAS_STREAM_FREEBUF      0x0008
 /* The buffer is currently being used for reading. */
-#define JAS_STREAM_RDBUF	0x0010
+#define JAS_STREAM_RDBUF        0x0010
 /* The buffer is currently being used for writing. */
-#define JAS_STREAM_WRBUF	0x0020
+#define JAS_STREAM_WRBUF        0x0020
 
 /*
  * Stream error flags.
  */
 
 /* The end-of-file has been encountered (on reading). */
-#define JAS_STREAM_EOF	0x0001
+#define JAS_STREAM_EOF  0x0001
 /* An I/O error has been encountered on the stream. */
-#define JAS_STREAM_ERR	0x0002
+#define JAS_STREAM_ERR  0x0002
 /* The read/write limit has been exceeded. */
-#define	JAS_STREAM_RWLIMIT	0x0004
+#define JAS_STREAM_RWLIMIT      0x0004
 /* The error mask. */
 #define JAS_STREAM_ERRMASK \
-	(JAS_STREAM_EOF | JAS_STREAM_ERR | JAS_STREAM_RWLIMIT)
+        (JAS_STREAM_EOF | JAS_STREAM_ERR | JAS_STREAM_RWLIMIT)
 
 /*
  * Other miscellaneous constants.
  */
 
 /* The default buffer size (for fully-buffered operation). */
-#define JAS_STREAM_BUFSIZE	8192
+#define JAS_STREAM_BUFSIZE      8192
 /* The default permission mask for file creation. */
-#define JAS_STREAM_PERMS	0666
+#define JAS_STREAM_PERMS        0666
 
 /* The maximum number of characters that can always be put back on a stream. */
-#define	JAS_STREAM_MAXPUTBACK	16
+#define JAS_STREAM_MAXPUTBACK   16
 
 /******************************************************************************\
 * Types.
@@ -224,17 +224,17 @@ typedef void jas_stream_obj_t;
 
 typedef struct {
 
-	/* Read characters from a file object. */
-	int (*read_)(jas_stream_obj_t *obj, char *buf, int cnt);
+        /* Read characters from a file object. */
+        int (*read_)(jas_stream_obj_t *obj, char *buf, int cnt);
 
-	/* Write characters to a file object. */
-	int (*write_)(jas_stream_obj_t *obj, char *buf, int cnt);
+        /* Write characters to a file object. */
+        int (*write_)(jas_stream_obj_t *obj, char *buf, int cnt);
 
-	/* Set the position for a file object. */
-	long (*seek_)(jas_stream_obj_t *obj, long offset, int origin);
+        /* Set the position for a file object. */
+        long (*seek_)(jas_stream_obj_t *obj, long offset, int origin);
 
-	/* Close a file object. */
-	int (*close_)(jas_stream_obj_t *obj);
+        /* Close a file object. */
+        int (*close_)(jas_stream_obj_t *obj);
 
 } jas_stream_ops_t;
 
@@ -244,46 +244,46 @@ typedef struct {
 
 typedef struct {
 
-	/* The mode in which the stream was opened. */
-	int openmode_;
+        /* The mode in which the stream was opened. */
+        int openmode_;
 
-	/* The buffering mode. */
-	int bufmode_;
+        /* The buffering mode. */
+        int bufmode_;
 
-	/* The stream status. */
-	int flags_;
+        /* The stream status. */
+        int flags_;
 
-	/* The start of the buffer area to use for reading/writing. */
-	unsigned char *bufbase_;
+        /* The start of the buffer area to use for reading/writing. */
+        unsigned char *bufbase_;
 
-	/* The start of the buffer area excluding the extra initial space for
-	  character putback. */
-	unsigned char *bufstart_;
+        /* The start of the buffer area excluding the extra initial space for
+          character putback. */
+        unsigned char *bufstart_;
 
-	/* The buffer size. */
-	int bufsize_;
+        /* The buffer size. */
+        int bufsize_;
 
-	/* The current position in the buffer. */
-	unsigned char *ptr_;
+        /* The current position in the buffer. */
+        unsigned char *ptr_;
 
-	/* The number of characters that must be read/written before
-	the buffer needs to be filled/flushed. */
-	int cnt_;
+        /* The number of characters that must be read/written before
+        the buffer needs to be filled/flushed. */
+        int cnt_;
 
-	/* A trivial buffer to be used for unbuffered operation. */
-	unsigned char tinybuf_[JAS_STREAM_MAXPUTBACK + 1];
+        /* A trivial buffer to be used for unbuffered operation. */
+        unsigned char tinybuf_[JAS_STREAM_MAXPUTBACK + 1];
 
-	/* The operations for the underlying stream file object. */
-	jas_stream_ops_t *ops_;
+        /* The operations for the underlying stream file object. */
+        jas_stream_ops_t *ops_;
 
-	/* The underlying stream file object. */
-	jas_stream_obj_t *obj_;
+        /* The underlying stream file object. */
+        jas_stream_obj_t *obj_;
 
-	/* The number of characters read/written. */
-	long rwcnt_;
+        /* The number of characters read/written. */
+        long rwcnt_;
 
-	/* The maximum number of characters that may be read/written. */
-	long rwlimit_;
+        /* The maximum number of characters that may be read/written. */
+        long rwlimit_;
 
 } jas_stream_t;
 
@@ -300,23 +300,23 @@ typedef int jas_stream_fileobj_t;
 
 typedef struct {
 
-	/* The data associated with this file. */
-	unsigned char *buf_;
+        /* The data associated with this file. */
+        unsigned char *buf_;
 
-	/* The allocated size of the buffer for holding file data. */
-	int bufsize_;
+        /* The allocated size of the buffer for holding file data. */
+        int bufsize_;
 
-	/* The length of the file. */
-	int_fast32_t len_;
+        /* The length of the file. */
+        int_fast32_t len_;
 
-	/* The seek position. */
-	int_fast32_t pos_;
+        /* The seek position. */
+        int_fast32_t pos_;
 
-	/* Is the buffer growable? */
-	int growable_;
+        /* Is the buffer growable? */
+        int growable_;
 
-	/* Was the buffer allocated internally? */
-	int myalloc_;
+        /* Was the buffer allocated internally? */
+        int myalloc_;
 
 } jas_stream_memobj_t;
 
@@ -348,26 +348,26 @@ int jas_stream_close(jas_stream_t *stream);
 
 /* Get the EOF indicator for a stream. */
 #define jas_stream_eof(stream) \
-	(((stream)->flags_ & JAS_STREAM_EOF) != 0)
+        (((stream)->flags_ & JAS_STREAM_EOF) != 0)
 
 /* Get the error indicator for a stream. */
 #define jas_stream_error(stream) \
-	(((stream)->flags_ & JAS_STREAM_ERR) != 0)
+        (((stream)->flags_ & JAS_STREAM_ERR) != 0)
 
 /* Clear the error indicator for a stream. */
 #define jas_stream_clearerr(stream) \
-	((stream)->flags_ &= ~(JAS_STREAM_ERR | JAS_STREAM_EOF))
+        ((stream)->flags_ &= ~(JAS_STREAM_ERR | JAS_STREAM_EOF))
 
 /* Get the read/write limit for a stream. */
-#define	jas_stream_getrwlimit(stream) \
-	(((const jas_stream_t *)(stream))->rwlimit_)
+#define jas_stream_getrwlimit(stream) \
+        (((const jas_stream_t *)(stream))->rwlimit_)
 
 /* Set the read/write limit for a stream. */
 int jas_stream_setrwlimit(jas_stream_t *stream, long rwlimit);
 
 /* Get the read/write count for a stream. */
-#define	jas_stream_getrwcount(stream) \
-	(((const jas_stream_t *)(stream))->rwcnt_)
+#define jas_stream_getrwcount(stream) \
+        (((const jas_stream_t *)(stream))->rwcnt_)
 
 /* Set the read/write count for a stream. */
 long jas_stream_setrwcount(jas_stream_t *stream, long rwcnt);
@@ -378,16 +378,16 @@ long jas_stream_setrwcount(jas_stream_t *stream, long rwcnt);
 
 /* Read a character from a stream. */
 #if defined(DEBUG)
-#define	jas_stream_getc(stream)	jas_stream_getc_func(stream)
+#define jas_stream_getc(stream) jas_stream_getc_func(stream)
 #else
-#define jas_stream_getc(stream)	jas_stream_getc_macro(stream)
+#define jas_stream_getc(stream) jas_stream_getc_macro(stream)
 #endif
 
 /* Write a character to a stream. */
 #if defined(DEBUG)
-#define jas_stream_putc(stream, c)	jas_stream_putc_func(stream, c)
+#define jas_stream_putc(stream, c)      jas_stream_putc_func(stream, c)
 #else
-#define jas_stream_putc(stream, c)	jas_stream_putc_macro(stream, c)
+#define jas_stream_putc(stream, c)      jas_stream_putc_macro(stream, c)
 #endif
 
 /* Read characters from a stream into a buffer. */
@@ -407,9 +407,9 @@ char *jas_stream_gets(jas_stream_t *stream, char *buf, int bufsize);
 
 /* Look at the next character to be read from a stream without actually
   removing it from the stream. */
-#define	jas_stream_peekc(stream) \
-	(((stream)->cnt_ <= 0) ? jas_stream_fillbuf(stream, 0) : \
-	  ((int)(*(stream)->ptr_)))
+#define jas_stream_peekc(stream) \
+        (((stream)->cnt_ <= 0) ? jas_stream_fillbuf(stream, 0) : \
+          ((int)(*(stream)->ptr_)))
 
 /* Put a character back on a stream. */
 int jas_stream_ungetc(jas_stream_t *stream, int c);
@@ -463,26 +463,26 @@ directly, you will die a horrible, miserable, and painful death! */
 
 /* Read a character from a stream. */
 #define jas_stream_getc_macro(stream) \
-	((!((stream)->flags_ & (JAS_STREAM_ERR | JAS_STREAM_EOF | \
-	  JAS_STREAM_RWLIMIT))) ? \
-	  (((stream)->rwlimit_ >= 0 && (stream)->rwcnt_ >= (stream)->rwlimit_) ? \
-	  (stream->flags_ |= JAS_STREAM_RWLIMIT, EOF) : \
-	  jas_stream_getc2(stream)) : EOF)
+        ((!((stream)->flags_ & (JAS_STREAM_ERR | JAS_STREAM_EOF | \
+          JAS_STREAM_RWLIMIT))) ? \
+          (((stream)->rwlimit_ >= 0 && (stream)->rwcnt_ >= (stream)->rwlimit_) ? \
+          (stream->flags_ |= JAS_STREAM_RWLIMIT, EOF) : \
+          jas_stream_getc2(stream)) : EOF)
 #define jas_stream_getc2(stream) \
-	((--(stream)->cnt_ < 0) ? jas_stream_fillbuf(stream, 1) : \
-	  (++(stream)->rwcnt_, (int)(*(stream)->ptr_++)))
+        ((--(stream)->cnt_ < 0) ? jas_stream_fillbuf(stream, 1) : \
+          (++(stream)->rwcnt_, (int)(*(stream)->ptr_++)))
 
 /* Write a character to a stream. */
 #define jas_stream_putc_macro(stream, c) \
-	((!((stream)->flags_ & (JAS_STREAM_ERR | JAS_STREAM_EOF | \
-	  JAS_STREAM_RWLIMIT))) ? \
-	  (((stream)->rwlimit_ >= 0 && (stream)->rwcnt_ >= (stream)->rwlimit_) ? \
-	  (stream->flags_ |= JAS_STREAM_RWLIMIT, EOF) : \
-	  jas_stream_putc2(stream, c)) : EOF)
+        ((!((stream)->flags_ & (JAS_STREAM_ERR | JAS_STREAM_EOF | \
+          JAS_STREAM_RWLIMIT))) ? \
+          (((stream)->rwlimit_ >= 0 && (stream)->rwcnt_ >= (stream)->rwlimit_) ? \
+          (stream->flags_ |= JAS_STREAM_RWLIMIT, EOF) : \
+          jas_stream_putc2(stream, c)) : EOF)
 #define jas_stream_putc2(stream, c) \
-	(((stream)->bufmode_ |= JAS_STREAM_WRBUF, --(stream)->cnt_ < 0) ? \
-	  jas_stream_flushbuf((stream), (unsigned char)(c)) : \
-	  (++(stream)->rwcnt_, (int)(*(stream)->ptr_++ = (c))))
+        (((stream)->bufmode_ |= JAS_STREAM_WRBUF, --(stream)->cnt_ < 0) ? \
+          jas_stream_flushbuf((stream), (unsigned char)(c)) : \
+          (++(stream)->rwcnt_, (int)(*(stream)->ptr_++ = (c))))
 
 /* These prototypes need to be here for the sake of the stream_getc and
 stream_putc macros. */
diff --git a/converter/other/jpeg2000/libjasper/include/jasper/jas_string.h b/converter/other/jpeg2000/libjasper/include/jasper/jas_string.h
index 55b611ba..ff2d3af4 100644
--- a/converter/other/jpeg2000/libjasper/include/jasper/jas_string.h
+++ b/converter/other/jpeg2000/libjasper/include/jasper/jas_string.h
@@ -6,14 +6,14 @@
  */
 
 /* __START_OF_JASPER_LICENSE__
- * 
+ *
  * JasPer Software License
- * 
+ *
  * IMAGE POWER JPEG-2000 PUBLIC LICENSE
  * ************************************
- * 
+ *
  * GRANT:
- * 
+ *
  * Permission is hereby granted, free of charge, to any person (the "User")
  * obtaining a copy of this software and associated documentation, to deal
  * in the JasPer Software without restriction, including without limitation
@@ -21,22 +21,22 @@
  * and/or sell copies of the JasPer Software (in source and binary forms),
  * and to permit persons to whom the JasPer Software is furnished to do so,
  * provided further that the License Conditions below are met.
- * 
+ *
  * License Conditions
  * ******************
- * 
+ *
  * A.  Redistributions of source code must retain the above copyright notice,
  * and this list of conditions, and the following disclaimer.
- * 
+ *
  * B.  Redistributions in binary form must reproduce the above copyright
  * notice, and this list of conditions, and the following disclaimer in
  * the documentation and/or other materials provided with the distribution.
- * 
+ *
  * C.  Neither the name of Image Power, Inc. nor any other contributor
  * (including, but not limited to, the University of British Columbia and
  * Michael David Adams) may be used to endorse or promote products derived
  * from this software without specific prior written permission.
- * 
+ *
  * D.  User agrees that it shall not commence any action against Image Power,
  * Inc., the University of British Columbia, Michael David Adams, or any
  * other contributors (collectively "Licensors") for infringement of any
@@ -56,17 +56,17 @@
  * trade dress, or service mark rights); and (v) divisions, continuations,
  * renewals, reissues and extensions of the foregoing (as and to the extent
  * applicable) now existing, hereafter filed, issued or acquired.
- * 
+ *
  * E.  If User commences an infringement action against any Licensor(s) then
  * such Licensor(s) shall have the right to terminate User's license and
  * all sublicenses that have been granted hereunder by User to other parties.
- * 
+ *
  * F.  This software is for use only in hardware or software products that
  * are compliant with ISO/IEC 15444-1 (i.e., JPEG-2000 Part 1).  No license
  * or right to this Software is granted for products that do not comply
  * with ISO/IEC 15444-1.  The JPEG-2000 Part 1 standard can be purchased
  * from the ISO.
- * 
+ *
  * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS LICENSE.
  * NO USE OF THE JASPER SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER
  * THIS DISCLAIMER.  THE JASPER SOFTWARE IS PROVIDED BY THE LICENSORS AND
@@ -106,7 +106,7 @@
  * TECHNOLOGY OR PRODUCTS FOR HIGH RISK ACTIVITIES AND WILL ENSURE THAT ITS
  * CUSTOMERS AND END-USERS OF ITS PRODUCTS ARE PROVIDED WITH A COPY OF THE
  * NOTICE SPECIFIED IN THIS SECTION.
- * 
+ *
  * __END_OF_JASPER_LICENSE__
  */
 
@@ -116,8 +116,8 @@
  * $Id$
  */
 
-#ifndef	JAS_STRING_H
-#define	JAS_STRING_H
+#ifndef JAS_STRING_H
+#define JAS_STRING_H
 
 /******************************************************************************\
 * Includes.
diff --git a/converter/other/jpeg2000/libjasper/include/jasper/jas_tvp.h b/converter/other/jpeg2000/libjasper/include/jasper/jas_tvp.h
index 9ac50dbd..34e389bf 100644
--- a/converter/other/jpeg2000/libjasper/include/jasper/jas_tvp.h
+++ b/converter/other/jpeg2000/libjasper/include/jasper/jas_tvp.h
@@ -4,14 +4,14 @@
  */
 
 /* __START_OF_JASPER_LICENSE__
- * 
+ *
  * JasPer Software License
- * 
+ *
  * IMAGE POWER JPEG-2000 PUBLIC LICENSE
  * ************************************
- * 
+ *
  * GRANT:
- * 
+ *
  * Permission is hereby granted, free of charge, to any person (the "User")
  * obtaining a copy of this software and associated documentation, to deal
  * in the JasPer Software without restriction, including without limitation
@@ -19,22 +19,22 @@
  * and/or sell copies of the JasPer Software (in source and binary forms),
  * and to permit persons to whom the JasPer Software is furnished to do so,
  * provided further that the License Conditions below are met.
- * 
+ *
  * License Conditions
  * ******************
- * 
+ *
  * A.  Redistributions of source code must retain the above copyright notice,
  * and this list of conditions, and the following disclaimer.
- * 
+ *
  * B.  Redistributions in binary form must reproduce the above copyright
  * notice, and this list of conditions, and the following disclaimer in
  * the documentation and/or other materials provided with the distribution.
- * 
+ *
  * C.  Neither the name of Image Power, Inc. nor any other contributor
  * (including, but not limited to, the University of British Columbia and
  * Michael David Adams) may be used to endorse or promote products derived
  * from this software without specific prior written permission.
- * 
+ *
  * D.  User agrees that it shall not commence any action against Image Power,
  * Inc., the University of British Columbia, Michael David Adams, or any
  * other contributors (collectively "Licensors") for infringement of any
@@ -54,17 +54,17 @@
  * trade dress, or service mark rights); and (v) divisions, continuations,
  * renewals, reissues and extensions of the foregoing (as and to the extent
  * applicable) now existing, hereafter filed, issued or acquired.
- * 
+ *
  * E.  If User commences an infringement action against any Licensor(s) then
  * such Licensor(s) shall have the right to terminate User's license and
  * all sublicenses that have been granted hereunder by User to other parties.
- * 
+ *
  * F.  This software is for use only in hardware or software products that
  * are compliant with ISO/IEC 15444-1 (i.e., JPEG-2000 Part 1).  No license
  * or right to this Software is granted for products that do not comply
  * with ISO/IEC 15444-1.  The JPEG-2000 Part 1 standard can be purchased
  * from the ISO.
- * 
+ *
  * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS LICENSE.
  * NO USE OF THE JASPER SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER
  * THIS DISCLAIMER.  THE JASPER SOFTWARE IS PROVIDED BY THE LICENSORS AND
@@ -104,7 +104,7 @@
  * TECHNOLOGY OR PRODUCTS FOR HIGH RISK ACTIVITIES AND WILL ENSURE THAT ITS
  * CUSTOMERS AND END-USERS OF ITS PRODUCTS ARE PROVIDED WITH A COPY OF THE
  * NOTICE SPECIFIED IN THIS SECTION.
- * 
+ *
  * __END_OF_JASPER_LICENSE__
  */
 
@@ -133,11 +133,11 @@ extern "C" {
 
 typedef struct {
 
-	int id;
-	/* The ID for the tag. */
+        int id;
+        /* The ID for the tag. */
 
-	const char *name;
-	/* The name of the tag. */
+        const char *name;
+        /* The name of the tag. */
 
 } jas_taginfo_t;
 
@@ -145,17 +145,17 @@ typedef struct {
 
 typedef struct {
 
-	char *buf;
-	/* The parsing buffer. */
+        char *buf;
+        /* The parsing buffer. */
 
-	char *tag;
-	/* The current tag name. */
+        char *tag;
+        /* The current tag name. */
 
-	const char *val;
-	/* The current value. */
+        const char *val;
+        /* The current value. */
 
-	char *pos;
-	/* The current position in the parsing buffer. */
+        char *pos;
+        /* The current position in the parsing buffer. */
 
 } jas_tvparser_t;
 
diff --git a/converter/other/jpeg2000/libjasper/include/jasper/jas_types.h b/converter/other/jpeg2000/libjasper/include/jasper/jas_types.h
index fbcb2ffb..ce12e083 100644
--- a/converter/other/jpeg2000/libjasper/include/jasper/jas_types.h
+++ b/converter/other/jpeg2000/libjasper/include/jasper/jas_types.h
@@ -10,5 +10,5 @@
 /* The below macro is intended to be used for type casts.  By using this
   macro, type casts can be easily located in the source code with
   tools like "grep". */
-#define	JAS_CAST(t, e) \
-	((t) (e))
+#define JAS_CAST(t, e) \
+        ((t) (e))
diff --git a/converter/other/jpeg2000/libjasper/include/jasper/jas_version.h b/converter/other/jpeg2000/libjasper/include/jasper/jas_version.h
index 2178257c..28442f51 100644
--- a/converter/other/jpeg2000/libjasper/include/jasper/jas_version.h
+++ b/converter/other/jpeg2000/libjasper/include/jasper/jas_version.h
@@ -6,14 +6,14 @@
  */
 
 /* __START_OF_JASPER_LICENSE__
- * 
+ *
  * JasPer Software License
- * 
+ *
  * IMAGE POWER JPEG-2000 PUBLIC LICENSE
  * ************************************
- * 
+ *
  * GRANT:
- * 
+ *
  * Permission is hereby granted, free of charge, to any person (the "User")
  * obtaining a copy of this software and associated documentation, to deal
  * in the JasPer Software without restriction, including without limitation
@@ -21,22 +21,22 @@
  * and/or sell copies of the JasPer Software (in source and binary forms),
  * and to permit persons to whom the JasPer Software is furnished to do so,
  * provided further that the License Conditions below are met.
- * 
+ *
  * License Conditions
  * ******************
- * 
+ *
  * A.  Redistributions of source code must retain the above copyright notice,
  * and this list of conditions, and the following disclaimer.
- * 
+ *
  * B.  Redistributions in binary form must reproduce the above copyright
  * notice, and this list of conditions, and the following disclaimer in
  * the documentation and/or other materials provided with the distribution.
- * 
+ *
  * C.  Neither the name of Image Power, Inc. nor any other contributor
  * (including, but not limited to, the University of British Columbia and
  * Michael David Adams) may be used to endorse or promote products derived
  * from this software without specific prior written permission.
- * 
+ *
  * D.  User agrees that it shall not commence any action against Image Power,
  * Inc., the University of British Columbia, Michael David Adams, or any
  * other contributors (collectively "Licensors") for infringement of any
@@ -56,17 +56,17 @@
  * trade dress, or service mark rights); and (v) divisions, continuations,
  * renewals, reissues and extensions of the foregoing (as and to the extent
  * applicable) now existing, hereafter filed, issued or acquired.
- * 
+ *
  * E.  If User commences an infringement action against any Licensor(s) then
  * such Licensor(s) shall have the right to terminate User's license and
  * all sublicenses that have been granted hereunder by User to other parties.
- * 
+ *
  * F.  This software is for use only in hardware or software products that
  * are compliant with ISO/IEC 15444-1 (i.e., JPEG-2000 Part 1).  No license
  * or right to this Software is granted for products that do not comply
  * with ISO/IEC 15444-1.  The JPEG-2000 Part 1 standard can be purchased
  * from the ISO.
- * 
+ *
  * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS LICENSE.
  * NO USE OF THE JASPER SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER
  * THIS DISCLAIMER.  THE JASPER SOFTWARE IS PROVIDED BY THE LICENSORS AND
@@ -106,7 +106,7 @@
  * TECHNOLOGY OR PRODUCTS FOR HIGH RISK ACTIVITIES AND WILL ENSURE THAT ITS
  * CUSTOMERS AND END-USERS OF ITS PRODUCTS ARE PROVIDED WITH A COPY OF THE
  * NOTICE SPECIFIED IN THIS SECTION.
- * 
+ *
  * __END_OF_JASPER_LICENSE__
  */
 
@@ -128,28 +128,28 @@ extern "C" {
 #if !defined(JAS_VERSION)
 /* The version information below should match that specified in
   the "configure.in" file! */
-#define	JAS_VERSION		"1.600.0"
+#define JAS_VERSION             "1.600.0"
 #endif
 
-#define	JAS_COPYRIGHT \
-	"Copyright (c) 1999-2000 Image Power, Inc. and the University of\n" \
-	"  British Columbia.\n" \
-	"Copyright (c) 2001-2002 Michael David Adams.\n" \
-	"All rights reserved.\n"
+#define JAS_COPYRIGHT \
+        "Copyright (c) 1999-2000 Image Power, Inc. and the University of\n" \
+        "  British Columbia.\n" \
+        "Copyright (c) 2001-2002 Michael David Adams.\n" \
+        "All rights reserved.\n"
 
-#define	JAS_NOTES \
-	"For more information about this software, please visit the following\n" \
-	"web sites/pages:\n" \
-	"    http://www.ece.ubc.ca/~mdadams/jasper\n" \
-	"    http://www.jpeg.org/software\n" \
-	"To be added to the (moderated) JasPer software announcements\n" \
-	"mailing list, send an email to:\n" \
-	"    jasper-announce-subscribe@yahoogroups.com\n" \
-	"To be added to the (unmoderated) JasPer software discussion\n" \
-	"mailing list, send an email to:\n" \
-	"    jasper-discussion-subscribe@yahoogroups.com\n" \
-	"Please send any bug reports to:\n" \
-	"    mdadams@ieee.org\n"
+#define JAS_NOTES \
+        "For more information about this software, please visit the following\n" \
+        "web sites/pages:\n" \
+        "    http://www.ece.ubc.ca/~mdadams/jasper\n" \
+        "    http://www.jpeg.org/software\n" \
+        "To be added to the (moderated) JasPer software announcements\n" \
+        "mailing list, send an email to:\n" \
+        "    jasper-announce-subscribe@yahoogroups.com\n" \
+        "To be added to the (unmoderated) JasPer software discussion\n" \
+        "mailing list, send an email to:\n" \
+        "    jasper-discussion-subscribe@yahoogroups.com\n" \
+        "Please send any bug reports to:\n" \
+        "    mdadams@ieee.org\n"
 
 /******************************************************************************\
 * Functions.
diff --git a/converter/other/jpeg2000/libjasper/include/jasper/jasper.h b/converter/other/jpeg2000/libjasper/include/jasper/jasper.h
index b003acfa..68986c65 100644
--- a/converter/other/jpeg2000/libjasper/include/jasper/jasper.h
+++ b/converter/other/jpeg2000/libjasper/include/jasper/jasper.h
@@ -4,14 +4,14 @@
  */
 
 /* __START_OF_JASPER_LICENSE__
- * 
+ *
  * JasPer Software License
- * 
+ *
  * IMAGE POWER JPEG-2000 PUBLIC LICENSE
  * ************************************
- * 
+ *
  * GRANT:
- * 
+ *
  * Permission is hereby granted, free of charge, to any person (the "User")
  * obtaining a copy of this software and associated documentation, to deal
  * in the JasPer Software without restriction, including without limitation
@@ -19,22 +19,22 @@
  * and/or sell copies of the JasPer Software (in source and binary forms),
  * and to permit persons to whom the JasPer Software is furnished to do so,
  * provided further that the License Conditions below are met.
- * 
+ *
  * License Conditions
  * ******************
- * 
+ *
  * A.  Redistributions of source code must retain the above copyright notice,
  * and this list of conditions, and the following disclaimer.
- * 
+ *
  * B.  Redistributions in binary form must reproduce the above copyright
  * notice, and this list of conditions, and the following disclaimer in
  * the documentation and/or other materials provided with the distribution.
- * 
+ *
  * C.  Neither the name of Image Power, Inc. nor any other contributor
  * (including, but not limited to, the University of British Columbia and
  * Michael David Adams) may be used to endorse or promote products derived
  * from this software without specific prior written permission.
- * 
+ *
  * D.  User agrees that it shall not commence any action against Image Power,
  * Inc., the University of British Columbia, Michael David Adams, or any
  * other contributors (collectively "Licensors") for infringement of any
@@ -54,17 +54,17 @@
  * trade dress, or service mark rights); and (v) divisions, continuations,
  * renewals, reissues and extensions of the foregoing (as and to the extent
  * applicable) now existing, hereafter filed, issued or acquired.
- * 
+ *
  * E.  If User commences an infringement action against any Licensor(s) then
  * such Licensor(s) shall have the right to terminate User's license and
  * all sublicenses that have been granted hereunder by User to other parties.
- * 
+ *
  * F.  This software is for use only in hardware or software products that
  * are compliant with ISO/IEC 15444-1 (i.e., JPEG-2000 Part 1).  No license
  * or right to this Software is granted for products that do not comply
  * with ISO/IEC 15444-1.  The JPEG-2000 Part 1 standard can be purchased
  * from the ISO.
- * 
+ *
  * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS LICENSE.
  * NO USE OF THE JASPER SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER
  * THIS DISCLAIMER.  THE JASPER SOFTWARE IS PROVIDED BY THE LICENSORS AND
@@ -104,7 +104,7 @@
  * TECHNOLOGY OR PRODUCTS FOR HIGH RISK ACTIVITIES AND WILL ENSURE THAT ITS
  * CUSTOMERS AND END-USERS OF ITS PRODUCTS ARE PROVIDED WITH A COPY OF THE
  * NOTICE SPECIFIED IN THIS SECTION.
- * 
+ *
  * __END_OF_JASPER_LICENSE__
  */
 
diff --git a/converter/other/jpeg2000/libjasper/jp2/jp2_cod.c b/converter/other/jpeg2000/libjasper/jp2/jp2_cod.c
index c99c9608..510c01a4 100644
--- a/converter/other/jpeg2000/libjasper/jp2/jp2_cod.c
+++ b/converter/other/jpeg2000/libjasper/jp2/jp2_cod.c
@@ -6,14 +6,14 @@
  */
 
 /* __START_OF_JASPER_LICENSE__
- * 
+ *
  * JasPer Software License
- * 
+ *
  * IMAGE POWER JPEG-2000 PUBLIC LICENSE
  * ************************************
- * 
+ *
  * GRANT:
- * 
+ *
  * Permission is hereby granted, free of charge, to any person (the "User")
  * obtaining a copy of this software and associated documentation, to deal
  * in the JasPer Software without restriction, including without limitation
@@ -21,22 +21,22 @@
  * and/or sell copies of the JasPer Software (in source and binary forms),
  * and to permit persons to whom the JasPer Software is furnished to do so,
  * provided further that the License Conditions below are met.
- * 
+ *
  * License Conditions
  * ******************
- * 
+ *
  * A.  Redistributions of source code must retain the above copyright notice,
  * and this list of conditions, and the following disclaimer.
- * 
+ *
  * B.  Redistributions in binary form must reproduce the above copyright
  * notice, and this list of conditions, and the following disclaimer in
  * the documentation and/or other materials provided with the distribution.
- * 
+ *
  * C.  Neither the name of Image Power, Inc. nor any other contributor
  * (including, but not limited to, the University of British Columbia and
  * Michael David Adams) may be used to endorse or promote products derived
  * from this software without specific prior written permission.
- * 
+ *
  * D.  User agrees that it shall not commence any action against Image Power,
  * Inc., the University of British Columbia, Michael David Adams, or any
  * other contributors (collectively "Licensors") for infringement of any
@@ -56,17 +56,17 @@
  * trade dress, or service mark rights); and (v) divisions, continuations,
  * renewals, reissues and extensions of the foregoing (as and to the extent
  * applicable) now existing, hereafter filed, issued or acquired.
- * 
+ *
  * E.  If User commences an infringement action against any Licensor(s) then
  * such Licensor(s) shall have the right to terminate User's license and
  * all sublicenses that have been granted hereunder by User to other parties.
- * 
+ *
  * F.  This software is for use only in hardware or software products that
  * are compliant with ISO/IEC 15444-1 (i.e., JPEG-2000 Part 1).  No license
  * or right to this Software is granted for products that do not comply
  * with ISO/IEC 15444-1.  The JPEG-2000 Part 1 standard can be purchased
  * from the ISO.
- * 
+ *
  * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS LICENSE.
  * NO USE OF THE JASPER SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER
  * THIS DISCLAIMER.  THE JASPER SOFTWARE IS PROVIDED BY THE LICENSORS AND
@@ -106,7 +106,7 @@
  * TECHNOLOGY OR PRODUCTS FOR HIGH RISK ACTIVITIES AND WILL ENSURE THAT ITS
  * CUSTOMERS AND END-USERS OF ITS PRODUCTS ARE PROVIDED WITH A COPY OF THE
  * NOTICE SPECIFIED IN THIS SECTION.
- * 
+ *
  * __END_OF_JASPER_LICENSE__
  */
 
@@ -794,7 +794,7 @@ static int jp2_cmap_getdata(jp2_box_t *box, jas_stream_t *in)
             return -1;
         }
     }
-    
+   
     return 0;
 }
 
diff --git a/converter/other/jpeg2000/libjasper/jp2/jp2_cod.h b/converter/other/jpeg2000/libjasper/jp2/jp2_cod.h
index 96b48d12..86c4c3ee 100644
--- a/converter/other/jpeg2000/libjasper/jp2/jp2_cod.h
+++ b/converter/other/jpeg2000/libjasper/jp2/jp2_cod.h
@@ -6,14 +6,14 @@
  */
 
 /* __START_OF_JASPER_LICENSE__
- * 
+ *
  * JasPer Software License
- * 
+ *
  * IMAGE POWER JPEG-2000 PUBLIC LICENSE
  * ************************************
- * 
+ *
  * GRANT:
- * 
+ *
  * Permission is hereby granted, free of charge, to any person (the "User")
  * obtaining a copy of this software and associated documentation, to deal
  * in the JasPer Software without restriction, including without limitation
@@ -21,22 +21,22 @@
  * and/or sell copies of the JasPer Software (in source and binary forms),
  * and to permit persons to whom the JasPer Software is furnished to do so,
  * provided further that the License Conditions below are met.
- * 
+ *
  * License Conditions
  * ******************
- * 
+ *
  * A.  Redistributions of source code must retain the above copyright notice,
  * and this list of conditions, and the following disclaimer.
- * 
+ *
  * B.  Redistributions in binary form must reproduce the above copyright
  * notice, and this list of conditions, and the following disclaimer in
  * the documentation and/or other materials provided with the distribution.
- * 
+ *
  * C.  Neither the name of Image Power, Inc. nor any other contributor
  * (including, but not limited to, the University of British Columbia and
  * Michael David Adams) may be used to endorse or promote products derived
  * from this software without specific prior written permission.
- * 
+ *
  * D.  User agrees that it shall not commence any action against Image Power,
  * Inc., the University of British Columbia, Michael David Adams, or any
  * other contributors (collectively "Licensors") for infringement of any
@@ -56,17 +56,17 @@
  * trade dress, or service mark rights); and (v) divisions, continuations,
  * renewals, reissues and extensions of the foregoing (as and to the extent
  * applicable) now existing, hereafter filed, issued or acquired.
- * 
+ *
  * E.  If User commences an infringement action against any Licensor(s) then
  * such Licensor(s) shall have the right to terminate User's license and
  * all sublicenses that have been granted hereunder by User to other parties.
- * 
+ *
  * F.  This software is for use only in hardware or software products that
  * are compliant with ISO/IEC 15444-1 (i.e., JPEG-2000 Part 1).  No license
  * or right to this Software is granted for products that do not comply
  * with ISO/IEC 15444-1.  The JPEG-2000 Part 1 standard can be purchased
  * from the ISO.
- * 
+ *
  * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS LICENSE.
  * NO USE OF THE JASPER SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER
  * THIS DISCLAIMER.  THE JASPER SOFTWARE IS PROVIDED BY THE LICENSORS AND
@@ -106,7 +106,7 @@
  * TECHNOLOGY OR PRODUCTS FOR HIGH RISK ACTIVITIES AND WILL ENSURE THAT ITS
  * CUSTOMERS AND END-USERS OF ITS PRODUCTS ARE PROVIDED WITH A COPY OF THE
  * NOTICE SPECIFIED IN THIS SECTION.
- * 
+ *
  * __END_OF_JASPER_LICENSE__
  */
 
@@ -129,188 +129,188 @@
 * Macros.
 \******************************************************************************/
 
-#define	JP2_SPTOBPC(s, p) \
-	((((p) - 1) & 0x7f) | (((s) & 1) << 7))
+#define JP2_SPTOBPC(s, p) \
+        ((((p) - 1) & 0x7f) | (((s) & 1) << 7))
 
 /******************************************************************************\
 * Box class.
 \******************************************************************************/
 
-#define	JP2_BOX_HDRLEN	8
+#define JP2_BOX_HDRLEN  8
 
 /* Box types. */
-#define	JP2_BOX_JP		0x6a502020	/* Signature */
-#define JP2_BOX_FTYP	0x66747970	/* File Type */
-#define	JP2_BOX_JP2H	0x6a703268	/* JP2 Header */
-#define	JP2_BOX_IHDR	0x69686472	/* Image Header */
-#define	JP2_BOX_BPCC	0x62706363	/* Bits Per Component */
-#define	JP2_BOX_COLR	0x636f6c72	/* Color Specification */
-#define	JP2_BOX_PCLR	0x70636c72	/* Palette */
-#define	JP2_BOX_CMAP	0x636d6170	/* Component Mapping */
-#define	JP2_BOX_CDEF	0x63646566	/* Channel Definition */
-#define	JP2_BOX_RES		0x72657320	/* Resolution */
-#define	JP2_BOX_RESC	0x72657363	/* Capture Resolution */
-#define	JP2_BOX_RESD	0x72657364	/* Default Display Resolution */
-#define	JP2_BOX_JP2C	0x6a703263	/* Contiguous Code Stream */
-#define	JP2_BOX_JP2I	0x6a703269	/* Intellectual Property */
-#define	JP2_BOX_XML		0x786d6c20	/* XML */
-#define	JP2_BOX_UUID	0x75756964	/* UUID */
-#define	JP2_BOX_UINF	0x75696e66	/* UUID Info */
-#define	JP2_BOX_ULST	0x75637374	/* UUID List */
-#define	JP2_BOX_URL		0x75726c20	/* URL */
-
-#define	JP2_BOX_SUPER	0x01
-#define	JP2_BOX_NODATA	0x02
+#define JP2_BOX_JP              0x6a502020      /* Signature */
+#define JP2_BOX_FTYP    0x66747970      /* File Type */
+#define JP2_BOX_JP2H    0x6a703268      /* JP2 Header */
+#define JP2_BOX_IHDR    0x69686472      /* Image Header */
+#define JP2_BOX_BPCC    0x62706363      /* Bits Per Component */
+#define JP2_BOX_COLR    0x636f6c72      /* Color Specification */
+#define JP2_BOX_PCLR    0x70636c72      /* Palette */
+#define JP2_BOX_CMAP    0x636d6170      /* Component Mapping */
+#define JP2_BOX_CDEF    0x63646566      /* Channel Definition */
+#define JP2_BOX_RES             0x72657320      /* Resolution */
+#define JP2_BOX_RESC    0x72657363      /* Capture Resolution */
+#define JP2_BOX_RESD    0x72657364      /* Default Display Resolution */
+#define JP2_BOX_JP2C    0x6a703263      /* Contiguous Code Stream */
+#define JP2_BOX_JP2I    0x6a703269      /* Intellectual Property */
+#define JP2_BOX_XML             0x786d6c20      /* XML */
+#define JP2_BOX_UUID    0x75756964      /* UUID */
+#define JP2_BOX_UINF    0x75696e66      /* UUID Info */
+#define JP2_BOX_ULST    0x75637374      /* UUID List */
+#define JP2_BOX_URL             0x75726c20      /* URL */
+
+#define JP2_BOX_SUPER   0x01
+#define JP2_BOX_NODATA  0x02
 
 /* JP box data. */
 
-#define	JP2_JP_MAGIC	0x0d0a870a
-#define	JP2_JP_LEN		12
+#define JP2_JP_MAGIC    0x0d0a870a
+#define JP2_JP_LEN              12
 
 typedef struct {
-	uint_fast32_t magic;
+        uint_fast32_t magic;
 } jp2_jp_t;
 
 /* FTYP box data. */
 
-#define	JP2_FTYP_MAXCOMPATCODES	32
-#define	JP2_FTYP_MAJVER		0x6a703220
-#define	JP2_FTYP_MINVER		0
-#define	JP2_FTYP_COMPATCODE		JP2_FTYP_MAJVER
+#define JP2_FTYP_MAXCOMPATCODES 32
+#define JP2_FTYP_MAJVER         0x6a703220
+#define JP2_FTYP_MINVER         0
+#define JP2_FTYP_COMPATCODE             JP2_FTYP_MAJVER
 
 typedef struct {
-	uint_fast32_t majver;
-	uint_fast32_t minver;
-	uint_fast32_t numcompatcodes;
-	uint_fast32_t compatcodes[JP2_FTYP_MAXCOMPATCODES];
+        uint_fast32_t majver;
+        uint_fast32_t minver;
+        uint_fast32_t numcompatcodes;
+        uint_fast32_t compatcodes[JP2_FTYP_MAXCOMPATCODES];
 } jp2_ftyp_t;
 
 /* IHDR box data. */
 
-#define	JP2_IHDR_COMPTYPE	7
-#define	JP2_IHDR_BPCNULL	255
+#define JP2_IHDR_COMPTYPE       7
+#define JP2_IHDR_BPCNULL        255
 
 typedef struct {
-	uint_fast32_t width;
-	uint_fast32_t height;
-	uint_fast16_t numcmpts;
-	uint_fast8_t bpc;
-	uint_fast8_t comptype;
-	uint_fast8_t csunk;
-	uint_fast8_t ipr;
+        uint_fast32_t width;
+        uint_fast32_t height;
+        uint_fast16_t numcmpts;
+        uint_fast8_t bpc;
+        uint_fast8_t comptype;
+        uint_fast8_t csunk;
+        uint_fast8_t ipr;
 } jp2_ihdr_t;
 
 /* BPCC box data. */
 
 typedef struct {
-	uint_fast16_t numcmpts;
-	uint_fast8_t *bpcs;
+        uint_fast16_t numcmpts;
+        uint_fast8_t *bpcs;
 } jp2_bpcc_t;
 
 /* COLR box data. */
 
-#define	JP2_COLR_ENUM	1
-#define	JP2_COLR_ICC	2
-#define	JP2_COLR_PRI	0
+#define JP2_COLR_ENUM   1
+#define JP2_COLR_ICC    2
+#define JP2_COLR_PRI    0
 
-#define	JP2_COLR_SRGB	16
-#define	JP2_COLR_SGRAY	17
-#define	JP2_COLR_SYCC	18
+#define JP2_COLR_SRGB   16
+#define JP2_COLR_SGRAY  17
+#define JP2_COLR_SYCC   18
 
 typedef struct {
-	uint_fast8_t method;
-	uint_fast8_t pri;
-	uint_fast8_t approx;
-	uint_fast32_t csid;
-	uint_fast8_t *iccp;
-	int iccplen;
-	/* XXX - Someday we ought to add ICC profile data here. */
+        uint_fast8_t method;
+        uint_fast8_t pri;
+        uint_fast8_t approx;
+        uint_fast32_t csid;
+        uint_fast8_t *iccp;
+        int iccplen;
+        /* XXX - Someday we ought to add ICC profile data here. */
 } jp2_colr_t;
 
 /* PCLR box data. */
 
 typedef struct {
-	uint_fast16_t numlutents;
-	uint_fast8_t numchans;
-	int_fast32_t *lutdata;
-	uint_fast8_t *bpc;
+        uint_fast16_t numlutents;
+        uint_fast8_t numchans;
+        int_fast32_t *lutdata;
+        uint_fast8_t *bpc;
 } jp2_pclr_t;
 
 /* CDEF box per-channel data. */
 
-#define JP2_CDEF_RGB_R	1
-#define JP2_CDEF_RGB_G	2
-#define JP2_CDEF_RGB_B	3
+#define JP2_CDEF_RGB_R  1
+#define JP2_CDEF_RGB_G  2
+#define JP2_CDEF_RGB_B  3
 
-#define JP2_CDEF_YCBCR_Y	1
-#define JP2_CDEF_YCBCR_CB	2
-#define JP2_CDEF_YCBCR_CR	3
+#define JP2_CDEF_YCBCR_Y        1
+#define JP2_CDEF_YCBCR_CB       2
+#define JP2_CDEF_YCBCR_CR       3
 
-#define	JP2_CDEF_GRAY_Y	1
+#define JP2_CDEF_GRAY_Y 1
 
-#define	JP2_CDEF_TYPE_COLOR	0
-#define	JP2_CDEF_TYPE_OPACITY	1
-#define	JP2_CDEF_TYPE_UNSPEC	65535
-#define	JP2_CDEF_ASOC_ALL	0
-#define	JP2_CDEF_ASOC_NONE	65535
+#define JP2_CDEF_TYPE_COLOR     0
+#define JP2_CDEF_TYPE_OPACITY   1
+#define JP2_CDEF_TYPE_UNSPEC    65535
+#define JP2_CDEF_ASOC_ALL       0
+#define JP2_CDEF_ASOC_NONE      65535
 
 typedef struct {
-	uint_fast16_t channo;
-	uint_fast16_t type;
-	uint_fast16_t assoc;
+        uint_fast16_t channo;
+        uint_fast16_t type;
+        uint_fast16_t assoc;
 } jp2_cdefchan_t;
 
 /* CDEF box data. */
 
 typedef struct {
-	uint_fast16_t numchans;
-	jp2_cdefchan_t *ents;
+        uint_fast16_t numchans;
+        jp2_cdefchan_t *ents;
 } jp2_cdef_t;
 
 typedef struct {
-	uint_fast16_t cmptno;
-	uint_fast8_t map;
-	uint_fast8_t pcol;
+        uint_fast16_t cmptno;
+        uint_fast8_t map;
+        uint_fast8_t pcol;
 } jp2_cmapent_t;
 
 typedef struct {
-	uint_fast16_t numchans;
-	jp2_cmapent_t *ents;
+        uint_fast16_t numchans;
+        jp2_cmapent_t *ents;
 } jp2_cmap_t;
 
-#define	JP2_CMAP_DIRECT		0
-#define	JP2_CMAP_PALETTE	1
+#define JP2_CMAP_DIRECT         0
+#define JP2_CMAP_PALETTE        1
 
 /* Generic box. */
 
 struct jp2_boxops_s;
 typedef struct {
 
-	struct jp2_boxops_s *ops;
-	struct jp2_boxinfo_s *info;
+        struct jp2_boxops_s *ops;
+        struct jp2_boxinfo_s *info;
 
-	uint_fast32_t type;
-	uint_fast32_t len;
+        uint_fast32_t type;
+        uint_fast32_t len;
 
-	union {
-		jp2_jp_t jp;
-		jp2_ftyp_t ftyp;
-		jp2_ihdr_t ihdr;
-		jp2_bpcc_t bpcc;
-		jp2_colr_t colr;
-		jp2_pclr_t pclr;
-		jp2_cdef_t cdef;
-		jp2_cmap_t cmap;
-	} data;
+        union {
+                jp2_jp_t jp;
+                jp2_ftyp_t ftyp;
+                jp2_ihdr_t ihdr;
+                jp2_bpcc_t bpcc;
+                jp2_colr_t colr;
+                jp2_pclr_t pclr;
+                jp2_cdef_t cdef;
+                jp2_cmap_t cmap;
+        } data;
 
 } jp2_box_t;
 
 typedef struct jp2_boxops_s {
-	void (*init)(jp2_box_t *box);
-	void (*destroy)(jp2_box_t *box);
-	int (*getdata)(jp2_box_t *box, jas_stream_t *in);
-	int (*putdata)(jp2_box_t *box, jas_stream_t *out);
-	void (*dumpdata)(jp2_box_t *box, FILE *out);
+        void (*init)(jp2_box_t *box);
+        void (*destroy)(jp2_box_t *box);
+        int (*getdata)(jp2_box_t *box, jas_stream_t *in);
+        int (*putdata)(jp2_box_t *box, jas_stream_t *out);
+        void (*dumpdata)(jp2_box_t *box, FILE *out);
 } jp2_boxops_t;
 
 /******************************************************************************\
@@ -318,10 +318,10 @@ typedef struct jp2_boxops_s {
 \******************************************************************************/
 
 typedef struct jp2_boxinfo_s {
-	int type;
-	const char *name;
-	int flags;
-	jp2_boxops_t ops;
+        int type;
+        const char *name;
+        int flags;
+        jp2_boxops_t ops;
 } jp2_boxinfo_t;
 
 /******************************************************************************\
@@ -335,12 +335,12 @@ int jp2_box_put(jp2_box_t *box, jas_stream_t *out);
 
 #define JP2_DTYPETOBPC(dtype) \
   ((JAS_IMAGE_CDT_GETSGND(dtype) << 7) | (JAS_IMAGE_CDT_GETPREC(dtype) - 1))
-#define	JP2_BPCTODTYPE(bpc) \
+#define JP2_BPCTODTYPE(bpc) \
   (JAS_IMAGE_CDT_SETSGND(bpc >> 7) | JAS_IMAGE_CDT_SETPREC((bpc & 0x7f) + 1))
 
-#define ICC_CS_RGB	0x52474220
-#define ICC_CS_YCBCR	0x59436272
-#define ICC_CS_GRAY	0x47524159
+#define ICC_CS_RGB      0x52474220
+#define ICC_CS_YCBCR    0x59436272
+#define ICC_CS_GRAY     0x47524159
 
 jp2_cdefchan_t *jp2_cdef_lookup(jp2_cdef_t *cdef, int channo);
 
diff --git a/converter/other/jpeg2000/libjasper/jp2/jp2_dec.c b/converter/other/jpeg2000/libjasper/jp2/jp2_dec.c
index e8d71b0a..b056cfa9 100644
--- a/converter/other/jpeg2000/libjasper/jp2/jp2_dec.c
+++ b/converter/other/jpeg2000/libjasper/jp2/jp2_dec.c
@@ -6,14 +6,14 @@
  */
 
 /* __START_OF_JASPER_LICENSE__
- * 
+ *
  * JasPer Software License
- * 
+ *
  * IMAGE POWER JPEG-2000 PUBLIC LICENSE
  * ************************************
- * 
+ *
  * GRANT:
- * 
+ *
  * Permission is hereby granted, free of charge, to any person (the "User")
  * obtaining a copy of this software and associated documentation, to deal
  * in the JasPer Software without restriction, including without limitation
@@ -21,22 +21,22 @@
  * and/or sell copies of the JasPer Software (in source and binary forms),
  * and to permit persons to whom the JasPer Software is furnished to do so,
  * provided further that the License Conditions below are met.
- * 
+ *
  * License Conditions
  * ******************
- * 
+ *
  * A.  Redistributions of source code must retain the above copyright notice,
  * and this list of conditions, and the following disclaimer.
- * 
+ *
  * B.  Redistributions in binary form must reproduce the above copyright
  * notice, and this list of conditions, and the following disclaimer in
  * the documentation and/or other materials provided with the distribution.
- * 
+ *
  * C.  Neither the name of Image Power, Inc. nor any other contributor
  * (including, but not limited to, the University of British Columbia and
  * Michael David Adams) may be used to endorse or promote products derived
  * from this software without specific prior written permission.
- * 
+ *
  * D.  User agrees that it shall not commence any action against Image Power,
  * Inc., the University of British Columbia, Michael David Adams, or any
  * other contributors (collectively "Licensors") for infringement of any
@@ -56,17 +56,17 @@
  * trade dress, or service mark rights); and (v) divisions, continuations,
  * renewals, reissues and extensions of the foregoing (as and to the extent
  * applicable) now existing, hereafter filed, issued or acquired.
- * 
+ *
  * E.  If User commences an infringement action against any Licensor(s) then
  * such Licensor(s) shall have the right to terminate User's license and
  * all sublicenses that have been granted hereunder by User to other parties.
- * 
+ *
  * F.  This software is for use only in hardware or software products that
  * are compliant with ISO/IEC 15444-1 (i.e., JPEG-2000 Part 1).  No license
  * or right to this Software is granted for products that do not comply
  * with ISO/IEC 15444-1.  The JPEG-2000 Part 1 standard can be purchased
  * from the ISO.
- * 
+ *
  * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS LICENSE.
  * NO USE OF THE JASPER SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER
  * THIS DISCLAIMER.  THE JASPER SOFTWARE IS PROVIDED BY THE LICENSORS AND
@@ -106,7 +106,7 @@
  * TECHNOLOGY OR PRODUCTS FOR HIGH RISK ACTIVITIES AND WILL ENSURE THAT ITS
  * CUSTOMERS AND END-USERS OF ITS PRODUCTS ARE PROVIDED WITH A COPY OF THE
  * NOTICE SPECIFIED IN THIS SECTION.
- * 
+ *
  * __END_OF_JASPER_LICENSE__
  */
 
@@ -256,7 +256,7 @@ jp2_getcs(jp2_colr_t *colr) {
 
 static int
 fromiccpcs(int cs) {
-    
+   
     switch (cs) {
     case ICC_CS_RGB:
         return JAS_IMAGE_CS_RGB;
@@ -505,7 +505,7 @@ jp2_decode(jas_stream_t * const in,
     /* Determine the number of channels (which is essentially the number
       of components after any palette mappings have been applied). */
     dec->numchans = dec->cmap ?
-        dec->cmap->data.cmap.numchans : 
+        dec->cmap->data.cmap.numchans :
         jas_image_numcmpts(dec->image);
 
     /* Perform a basic sanity check on the CMAP box if present. */
diff --git a/converter/other/jpeg2000/libjasper/jp2/jp2_dec.h b/converter/other/jpeg2000/libjasper/jp2/jp2_dec.h
index 300be107..0da2b85f 100644
--- a/converter/other/jpeg2000/libjasper/jp2/jp2_dec.h
+++ b/converter/other/jpeg2000/libjasper/jp2/jp2_dec.h
@@ -6,14 +6,14 @@
  */
 
 /* __START_OF_JASPER_LICENSE__
- * 
+ *
  * JasPer Software License
- * 
+ *
  * IMAGE POWER JPEG-2000 PUBLIC LICENSE
  * ************************************
- * 
+ *
  * GRANT:
- * 
+ *
  * Permission is hereby granted, free of charge, to any person (the "User")
  * obtaining a copy of this software and associated documentation, to deal
  * in the JasPer Software without restriction, including without limitation
@@ -21,22 +21,22 @@
  * and/or sell copies of the JasPer Software (in source and binary forms),
  * and to permit persons to whom the JasPer Software is furnished to do so,
  * provided further that the License Conditions below are met.
- * 
+ *
  * License Conditions
  * ******************
- * 
+ *
  * A.  Redistributions of source code must retain the above copyright notice,
  * and this list of conditions, and the following disclaimer.
- * 
+ *
  * B.  Redistributions in binary form must reproduce the above copyright
  * notice, and this list of conditions, and the following disclaimer in
  * the documentation and/or other materials provided with the distribution.
- * 
+ *
  * C.  Neither the name of Image Power, Inc. nor any other contributor
  * (including, but not limited to, the University of British Columbia and
  * Michael David Adams) may be used to endorse or promote products derived
  * from this software without specific prior written permission.
- * 
+ *
  * D.  User agrees that it shall not commence any action against Image Power,
  * Inc., the University of British Columbia, Michael David Adams, or any
  * other contributors (collectively "Licensors") for infringement of any
@@ -56,17 +56,17 @@
  * trade dress, or service mark rights); and (v) divisions, continuations,
  * renewals, reissues and extensions of the foregoing (as and to the extent
  * applicable) now existing, hereafter filed, issued or acquired.
- * 
+ *
  * E.  If User commences an infringement action against any Licensor(s) then
  * such Licensor(s) shall have the right to terminate User's license and
  * all sublicenses that have been granted hereunder by User to other parties.
- * 
+ *
  * F.  This software is for use only in hardware or software products that
  * are compliant with ISO/IEC 15444-1 (i.e., JPEG-2000 Part 1).  No license
  * or right to this Software is granted for products that do not comply
  * with ISO/IEC 15444-1.  The JPEG-2000 Part 1 standard can be purchased
  * from the ISO.
- * 
+ *
  * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS LICENSE.
  * NO USE OF THE JASPER SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER
  * THIS DISCLAIMER.  THE JASPER SOFTWARE IS PROVIDED BY THE LICENSORS AND
@@ -106,7 +106,7 @@
  * TECHNOLOGY OR PRODUCTS FOR HIGH RISK ACTIVITIES AND WILL ENSURE THAT ITS
  * CUSTOMERS AND END-USERS OF ITS PRODUCTS ARE PROVIDED WITH A COPY OF THE
  * NOTICE SPECIFIED IN THIS SECTION.
- * 
+ *
  * __END_OF_JASPER_LICENSE__
  */
 
@@ -119,15 +119,15 @@
 
 typedef struct {
 
-	jp2_box_t *pclr;
-	jp2_box_t *cdef;
-	jp2_box_t *ihdr;
-	jp2_box_t *bpcc;
-	jp2_box_t *cmap;
-	jp2_box_t *colr;
-	jas_image_t *image;
-	uint_fast16_t numchans;
-	uint_fast16_t *chantocmptlut;
+        jp2_box_t *pclr;
+        jp2_box_t *cdef;
+        jp2_box_t *ihdr;
+        jp2_box_t *bpcc;
+        jp2_box_t *cmap;
+        jp2_box_t *colr;
+        jas_image_t *image;
+        uint_fast16_t numchans;
+        uint_fast16_t *chantocmptlut;
 
 } jp2_dec_t;
 
diff --git a/converter/other/jpeg2000/libjasper/jp2/jp2_enc.c b/converter/other/jpeg2000/libjasper/jp2/jp2_enc.c
index 12538248..f57233f1 100644
--- a/converter/other/jpeg2000/libjasper/jp2/jp2_enc.c
+++ b/converter/other/jpeg2000/libjasper/jp2/jp2_enc.c
@@ -6,14 +6,14 @@
  */
 
 /* __START_OF_JASPER_LICENSE__
- * 
+ *
  * JasPer Software License
- * 
+ *
  * IMAGE POWER JPEG-2000 PUBLIC LICENSE
  * ************************************
- * 
+ *
  * GRANT:
- * 
+ *
  * Permission is hereby granted, free of charge, to any person (the "User")
  * obtaining a copy of this software and associated documentation, to deal
  * in the JasPer Software without restriction, including without limitation
@@ -21,22 +21,22 @@
  * and/or sell copies of the JasPer Software (in source and binary forms),
  * and to permit persons to whom the JasPer Software is furnished to do so,
  * provided further that the License Conditions below are met.
- * 
+ *
  * License Conditions
  * ******************
- * 
+ *
  * A.  Redistributions of source code must retain the above copyright notice,
  * and this list of conditions, and the following disclaimer.
- * 
+ *
  * B.  Redistributions in binary form must reproduce the above copyright
  * notice, and this list of conditions, and the following disclaimer in
  * the documentation and/or other materials provided with the distribution.
- * 
+ *
  * C.  Neither the name of Image Power, Inc. nor any other contributor
  * (including, but not limited to, the University of British Columbia and
  * Michael David Adams) may be used to endorse or promote products derived
  * from this software without specific prior written permission.
- * 
+ *
  * D.  User agrees that it shall not commence any action against Image Power,
  * Inc., the University of British Columbia, Michael David Adams, or any
  * other contributors (collectively "Licensors") for infringement of any
@@ -56,17 +56,17 @@
  * trade dress, or service mark rights); and (v) divisions, continuations,
  * renewals, reissues and extensions of the foregoing (as and to the extent
  * applicable) now existing, hereafter filed, issued or acquired.
- * 
+ *
  * E.  If User commences an infringement action against any Licensor(s) then
  * such Licensor(s) shall have the right to terminate User's license and
  * all sublicenses that have been granted hereunder by User to other parties.
- * 
+ *
  * F.  This software is for use only in hardware or software products that
  * are compliant with ISO/IEC 15444-1 (i.e., JPEG-2000 Part 1).  No license
  * or right to this Software is granted for products that do not comply
  * with ISO/IEC 15444-1.  The JPEG-2000 Part 1 standard can be purchased
  * from the ISO.
- * 
+ *
  * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS LICENSE.
  * NO USE OF THE JASPER SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER
  * THIS DISCLAIMER.  THE JASPER SOFTWARE IS PROVIDED BY THE LICENSORS AND
@@ -106,7 +106,7 @@
  * TECHNOLOGY OR PRODUCTS FOR HIGH RISK ACTIVITIES AND WILL ENSURE THAT ITS
  * CUSTOMERS AND END-USERS OF ITS PRODUCTS ARE PROVIDED WITH A COPY OF THE
  * NOTICE SPECIFIED IN THIS SECTION.
- * 
+ *
  * __END_OF_JASPER_LICENSE__
  */
 
@@ -134,281 +134,281 @@ static uint_fast32_t jp2_gettypeasoc(int colorspace, int ctype);
 
 int jp2_encode(jas_image_t *image, jas_stream_t *out, 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;
-	int i;
-	uint_fast32_t typeasoc;
-
-	box = 0;
-	tmpstream = 0;
-
-	/* Output the signature box. */
-
-	if (!(box = jp2_box_create(JP2_BOX_JP))) {
-		goto error;
-	}
-	box->data.jp.magic = JP2_JP_MAGIC;
-	if (jp2_box_put(box, out)) {
-		goto error;
-	}
-	jp2_box_destroy(box);
-	box = 0;
-
-	/* Output the file type box. */
-
-	if (!(box = jp2_box_create(JP2_BOX_FTYP))) {
-		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)) {
-		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))) {
-		goto error;
-	}
-
-	/* Generate image header box. */
-
-	if (!(box = jp2_box_create(JP2_BOX_IHDR))) {
-		goto error;
-	}
-	ihdr = &box->data.ihdr;
-	ihdr->width = jas_image_width(image);
-	ihdr->height = jas_image_height(image);
-	ihdr->numcmpts = jas_image_numcmpts(image);
-	allcmptssame = 0;
-	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)) {
-		goto error;
-	}
-	jp2_box_destroy(box);
-	box = 0;
-
-	/* Generate bits per component box. */
-
-	if (!allcmptssame) {
-		if (!(box = jp2_box_create(JP2_BOX_BPCC))) {
-			goto error;
-		}
-		bpcc = &box->data.bpcc;
-		bpcc->numcmpts = jas_image_numcmpts(image);
-		if (!(bpcc->bpcs = jas_malloc(bpcc->numcmpts *
-		  sizeof(uint_fast8_t)))) {
-			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)) {
-			goto error;
-		}
-		jp2_box_destroy(box);
-		box = 0;
-	}
-
-	/* Generate color specification box. */
-
-	if (!(box = jp2_box_create(JP2_BOX_COLR))) {
-		goto error;
-	}
-	colr = &box->data.colr;
-	colr->method = JP2_COLR_ENUM;
-	colr->pri = JP2_COLR_PRI;
-	colr->approx = 0;
-	colr->csid = (jas_image_colorspace(image) == JAS_IMAGE_CS_RGB) ? JP2_COLR_SRGB :
-	  JP2_COLR_SGRAY;
-	if (jp2_box_put(box, tmpstream)) {
-		goto error;
-	}
-	jp2_box_destroy(box);
-	box = 0;
-
-	if (!(jas_image_colorspace(image) == JAS_IMAGE_CS_RGB &&
-	  jas_image_numcmpts(image) == 3 &&
-	  jas_image_getcmptbytype(image, 0) ==
-	  JAS_IMAGE_CT_COLOR(JAS_IMAGE_CT_RGB_R) &&
-	  jas_image_getcmptbytype(image, 1) ==
-	  JAS_IMAGE_CT_COLOR(JAS_IMAGE_CT_RGB_G) &&
-	  jas_image_getcmptbytype(image, 2) ==
-	  JAS_IMAGE_CT_COLOR(JAS_IMAGE_CT_RGB_B)) &&
-	  !(jas_image_colorspace(image) == JAS_IMAGE_CS_YCBCR &&
-	  jas_image_numcmpts(image) != 3 &&
-	  jas_image_getcmptbytype(image, 0) ==
-	  JAS_IMAGE_CT_COLOR(JAS_IMAGE_CT_YCBCR_Y) &&
-	  jas_image_getcmptbytype(image, 1) ==
-	  JAS_IMAGE_CT_COLOR(JAS_IMAGE_CT_YCBCR_CB) &&
-	  jas_image_getcmptbytype(image, 2) ==
-	  JAS_IMAGE_CT_COLOR(JAS_IMAGE_CT_YCBCR_CR)) &&
-	  !(jas_image_colorspace(image) == JAS_IMAGE_CS_GRAY &&
-	  jas_image_numcmpts(image) == 1 &&
-	  jas_image_getcmptbytype(image, 0) ==
-	  JAS_IMAGE_CT_COLOR(JAS_IMAGE_CT_GRAY_Y))) {
-
-		if (!(box = jp2_box_create(JP2_BOX_CDEF))) {
-			goto error;
-		}
-		cdef = &box->data.cdef;
-		cdef->numchans = jas_image_numcmpts(image);
-		cdef->ents = jas_malloc(cdef->numchans * sizeof(jp2_cdefchan_t));
-		for (i = 0; i < jas_image_numcmpts(image); ++i) {
-			cdefchanent = &cdef->ents[i];
-			cdefchanent->channo = i;
-			typeasoc = jp2_gettypeasoc(jas_image_colorspace(image), jas_image_cmpttype(image, i));
-			cdefchanent->type = typeasoc >> 16;
-			cdefchanent->assoc = typeasoc & 0x7fff;
-		}
-		jp2_box_destroy(box);
-		box = 0;
-	}
-
-	/* 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))) {
-		goto error;
-	}
-	box->len = len + JP2_BOX_HDRLEN;
-	if (jp2_box_put(box, out)) {
-		goto error;
-	}
-	jp2_box_destroy(box);
-	box = 0;
-
-	if (jas_stream_copy(out, tmpstream, len)) {
-		goto error;
-	}
-
-	jas_stream_close(tmpstream);
-	tmpstream = 0;
-
-	/*
-	 * Output the contiguous code stream box.
-	 */
-
-	if (!(box = jp2_box_create(JP2_BOX_JP2C))) {
-		goto error;
-	}
-	box->len = 0;
-	if (jp2_box_put(box, out)) {
-		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)) {
-		goto error;
-	}
-
-	return 0;
-	abort();
+        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;
+        int i;
+        uint_fast32_t typeasoc;
+
+        box = 0;
+        tmpstream = 0;
+
+        /* Output the signature box. */
+
+        if (!(box = jp2_box_create(JP2_BOX_JP))) {
+                goto error;
+        }
+        box->data.jp.magic = JP2_JP_MAGIC;
+        if (jp2_box_put(box, out)) {
+                goto error;
+        }
+        jp2_box_destroy(box);
+        box = 0;
+
+        /* Output the file type box. */
+
+        if (!(box = jp2_box_create(JP2_BOX_FTYP))) {
+                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)) {
+                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))) {
+                goto error;
+        }
+
+        /* Generate image header box. */
+
+        if (!(box = jp2_box_create(JP2_BOX_IHDR))) {
+                goto error;
+        }
+        ihdr = &box->data.ihdr;
+        ihdr->width = jas_image_width(image);
+        ihdr->height = jas_image_height(image);
+        ihdr->numcmpts = jas_image_numcmpts(image);
+        allcmptssame = 0;
+        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)) {
+                goto error;
+        }
+        jp2_box_destroy(box);
+        box = 0;
+
+        /* Generate bits per component box. */
+
+        if (!allcmptssame) {
+                if (!(box = jp2_box_create(JP2_BOX_BPCC))) {
+                        goto error;
+                }
+                bpcc = &box->data.bpcc;
+                bpcc->numcmpts = jas_image_numcmpts(image);
+                if (!(bpcc->bpcs = jas_malloc(bpcc->numcmpts *
+                  sizeof(uint_fast8_t)))) {
+                        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)) {
+                        goto error;
+                }
+                jp2_box_destroy(box);
+                box = 0;
+        }
+
+        /* Generate color specification box. */
+
+        if (!(box = jp2_box_create(JP2_BOX_COLR))) {
+                goto error;
+        }
+        colr = &box->data.colr;
+        colr->method = JP2_COLR_ENUM;
+        colr->pri = JP2_COLR_PRI;
+        colr->approx = 0;
+        colr->csid = (jas_image_colorspace(image) == JAS_IMAGE_CS_RGB) ? JP2_COLR_SRGB :
+          JP2_COLR_SGRAY;
+        if (jp2_box_put(box, tmpstream)) {
+                goto error;
+        }
+        jp2_box_destroy(box);
+        box = 0;
+
+        if (!(jas_image_colorspace(image) == JAS_IMAGE_CS_RGB &&
+          jas_image_numcmpts(image) == 3 &&
+          jas_image_getcmptbytype(image, 0) ==
+          JAS_IMAGE_CT_COLOR(JAS_IMAGE_CT_RGB_R) &&
+          jas_image_getcmptbytype(image, 1) ==
+          JAS_IMAGE_CT_COLOR(JAS_IMAGE_CT_RGB_G) &&
+          jas_image_getcmptbytype(image, 2) ==
+          JAS_IMAGE_CT_COLOR(JAS_IMAGE_CT_RGB_B)) &&
+          !(jas_image_colorspace(image) == JAS_IMAGE_CS_YCBCR &&
+          jas_image_numcmpts(image) != 3 &&
+          jas_image_getcmptbytype(image, 0) ==
+          JAS_IMAGE_CT_COLOR(JAS_IMAGE_CT_YCBCR_Y) &&
+          jas_image_getcmptbytype(image, 1) ==
+          JAS_IMAGE_CT_COLOR(JAS_IMAGE_CT_YCBCR_CB) &&
+          jas_image_getcmptbytype(image, 2) ==
+          JAS_IMAGE_CT_COLOR(JAS_IMAGE_CT_YCBCR_CR)) &&
+          !(jas_image_colorspace(image) == JAS_IMAGE_CS_GRAY &&
+          jas_image_numcmpts(image) == 1 &&
+          jas_image_getcmptbytype(image, 0) ==
+          JAS_IMAGE_CT_COLOR(JAS_IMAGE_CT_GRAY_Y))) {
+
+                if (!(box = jp2_box_create(JP2_BOX_CDEF))) {
+                        goto error;
+                }
+                cdef = &box->data.cdef;
+                cdef->numchans = jas_image_numcmpts(image);
+                cdef->ents = jas_malloc(cdef->numchans * sizeof(jp2_cdefchan_t));
+                for (i = 0; i < jas_image_numcmpts(image); ++i) {
+                        cdefchanent = &cdef->ents[i];
+                        cdefchanent->channo = i;
+                        typeasoc = jp2_gettypeasoc(jas_image_colorspace(image), jas_image_cmpttype(image, i));
+                        cdefchanent->type = typeasoc >> 16;
+                        cdefchanent->assoc = typeasoc & 0x7fff;
+                }
+                jp2_box_destroy(box);
+                box = 0;
+        }
+
+        /* 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))) {
+                goto error;
+        }
+        box->len = len + JP2_BOX_HDRLEN;
+        if (jp2_box_put(box, out)) {
+                goto error;
+        }
+        jp2_box_destroy(box);
+        box = 0;
+
+        if (jas_stream_copy(out, tmpstream, len)) {
+                goto error;
+        }
+
+        jas_stream_close(tmpstream);
+        tmpstream = 0;
+
+        /*
+         * Output the contiguous code stream box.
+         */
+
+        if (!(box = jp2_box_create(JP2_BOX_JP2C))) {
+                goto error;
+        }
+        box->len = 0;
+        if (jp2_box_put(box, out)) {
+                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)) {
+                goto error;
+        }
+
+        return 0;
+        abort();
 
 error:
 
-	if (box) {
-		jp2_box_destroy(box);
-	}
-	if (tmpstream) {
-		jas_stream_close(tmpstream);
-	}
-	return -1;
+        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 (colorspace) {
-	case JAS_IMAGE_CS_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_IMAGE_CS_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_IMAGE_CS_GRAY:
-		type = JP2_CDEF_TYPE_COLOR;
-		asoc = JP2_CDEF_GRAY_Y;
-		break;
-	}
+        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 (colorspace) {
+        case JAS_IMAGE_CS_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_IMAGE_CS_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_IMAGE_CS_GRAY:
+                type = JP2_CDEF_TYPE_COLOR;
+                asoc = JP2_CDEF_GRAY_Y;
+                break;
+        }
 
 done:
-	return (type << 16) | asoc;
+        return (type << 16) | asoc;
 }
 
diff --git a/converter/other/jpeg2000/libjasper/jpc/jpc_bs.c b/converter/other/jpeg2000/libjasper/jpc/jpc_bs.c
index c66fcd99..3f693fff 100644
--- a/converter/other/jpeg2000/libjasper/jpc/jpc_bs.c
+++ b/converter/other/jpeg2000/libjasper/jpc/jpc_bs.c
@@ -6,14 +6,14 @@
  */
 
 /* __START_OF_JASPER_LICENSE__
- * 
+ *
  * JasPer Software License
- * 
+ *
  * IMAGE POWER JPEG-2000 PUBLIC LICENSE
  * ************************************
- * 
+ *
  * GRANT:
- * 
+ *
  * Permission is hereby granted, free of charge, to any person (the "User")
  * obtaining a copy of this software and associated documentation, to deal
  * in the JasPer Software without restriction, including without limitation
@@ -21,22 +21,22 @@
  * and/or sell copies of the JasPer Software (in source and binary forms),
  * and to permit persons to whom the JasPer Software is furnished to do so,
  * provided further that the License Conditions below are met.
- * 
+ *
  * License Conditions
  * ******************
- * 
+ *
  * A.  Redistributions of source code must retain the above copyright notice,
  * and this list of conditions, and the following disclaimer.
- * 
+ *
  * B.  Redistributions in binary form must reproduce the above copyright
  * notice, and this list of conditions, and the following disclaimer in
  * the documentation and/or other materials provided with the distribution.
- * 
+ *
  * C.  Neither the name of Image Power, Inc. nor any other contributor
  * (including, but not limited to, the University of British Columbia and
  * Michael David Adams) may be used to endorse or promote products derived
  * from this software without specific prior written permission.
- * 
+ *
  * D.  User agrees that it shall not commence any action against Image Power,
  * Inc., the University of British Columbia, Michael David Adams, or any
  * other contributors (collectively "Licensors") for infringement of any
@@ -56,17 +56,17 @@
  * trade dress, or service mark rights); and (v) divisions, continuations,
  * renewals, reissues and extensions of the foregoing (as and to the extent
  * applicable) now existing, hereafter filed, issued or acquired.
- * 
+ *
  * E.  If User commences an infringement action against any Licensor(s) then
  * such Licensor(s) shall have the right to terminate User's license and
  * all sublicenses that have been granted hereunder by User to other parties.
- * 
+ *
  * F.  This software is for use only in hardware or software products that
  * are compliant with ISO/IEC 15444-1 (i.e., JPEG-2000 Part 1).  No license
  * or right to this Software is granted for products that do not comply
  * with ISO/IEC 15444-1.  The JPEG-2000 Part 1 standard can be purchased
  * from the ISO.
- * 
+ *
  * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS LICENSE.
  * NO USE OF THE JASPER SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER
  * THIS DISCLAIMER.  THE JASPER SOFTWARE IS PROVIDED BY THE LICENSORS AND
@@ -106,7 +106,7 @@
  * TECHNOLOGY OR PRODUCTS FOR HIGH RISK ACTIVITIES AND WILL ENSURE THAT ITS
  * CUSTOMERS AND END-USERS OF ITS PRODUCTS ARE PROVIDED WITH A COPY OF THE
  * NOTICE SPECIFIED IN THIS SECTION.
- * 
+ *
  * __END_OF_JASPER_LICENSE__
  */
 
@@ -137,66 +137,66 @@
 /* Allocate a new bit stream. */
 static jpc_bitstream_t *jpc_bitstream_alloc()
 {
-	jpc_bitstream_t *bitstream;
-
-	/* Allocate memory for the new bit stream object. */
-	if (!(bitstream = jas_malloc(sizeof(jpc_bitstream_t)))) {
-		return 0;
-	}
-	/* Initialize all of the data members. */
-	bitstream->stream_ = 0;
-	bitstream->cnt_ = 0;
-	bitstream->flags_ = 0;
-	bitstream->openmode_ = 0;
-
-	return bitstream;
+        jpc_bitstream_t *bitstream;
+
+        /* Allocate memory for the new bit stream object. */
+        if (!(bitstream = jas_malloc(sizeof(jpc_bitstream_t)))) {
+                return 0;
+        }
+        /* Initialize all of the data members. */
+        bitstream->stream_ = 0;
+        bitstream->cnt_ = 0;
+        bitstream->flags_ = 0;
+        bitstream->openmode_ = 0;
+
+        return bitstream;
 }
 
 /* Open a bit stream from a stream. */
 jpc_bitstream_t *jpc_bitstream_sopen(jas_stream_t *stream, const char *mode)
 {
-	jpc_bitstream_t *bitstream;
+        jpc_bitstream_t *bitstream;
 
-	if (!(bitstream = jpc_bitstream_alloc())) {
-		return 0;
-	}
+        if (!(bitstream = jpc_bitstream_alloc())) {
+                return 0;
+        }
 
-	/* By default, do not close the underlying (character) stream, upon
-	  the close of the bit stream. */
-	bitstream->flags_ = JPC_BITSTREAM_NOCLOSE;
+        /* By default, do not close the underlying (character) stream, upon
+          the close of the bit stream. */
+        bitstream->flags_ = JPC_BITSTREAM_NOCLOSE;
 
-	bitstream->stream_ = stream;
-	bitstream->openmode_ = (mode[0] == 'w') ? JPC_BITSTREAM_WRITE :
-	  JPC_BITSTREAM_READ;
+        bitstream->stream_ = stream;
+        bitstream->openmode_ = (mode[0] == 'w') ? JPC_BITSTREAM_WRITE :
+          JPC_BITSTREAM_READ;
 
-	/* Mark the data buffer as empty. */
-	bitstream->cnt_ = (bitstream->openmode_ == JPC_BITSTREAM_READ) ? 0 : 8;
-	bitstream->buf_ = 0;
+        /* Mark the data buffer as empty. */
+        bitstream->cnt_ = (bitstream->openmode_ == JPC_BITSTREAM_READ) ? 0 : 8;
+        bitstream->buf_ = 0;
 
-	return bitstream;
+        return bitstream;
 }
 
 /* Close a bit stream. */
 int jpc_bitstream_close(jpc_bitstream_t *bitstream)
 {
-	int ret = 0;
-
-	/* Align to the next byte boundary while considering the effects of
-	  bit stuffing. */
-	if (jpc_bitstream_align(bitstream)) {
-		ret = -1;
-	}
-
-	/* If necessary, close the underlying (character) stream. */
-	if (!(bitstream->flags_ & JPC_BITSTREAM_NOCLOSE) && bitstream->stream_) {
-		if (jas_stream_close(bitstream->stream_)) {
-			ret = -1;
-		}
-		bitstream->stream_ = 0;
-	}
-
-	jas_free(bitstream);
-	return ret;
+        int ret = 0;
+
+        /* Align to the next byte boundary while considering the effects of
+          bit stuffing. */
+        if (jpc_bitstream_align(bitstream)) {
+                ret = -1;
+        }
+
+        /* If necessary, close the underlying (character) stream. */
+        if (!(bitstream->flags_ & JPC_BITSTREAM_NOCLOSE) && bitstream->stream_) {
+                if (jas_stream_close(bitstream->stream_)) {
+                        ret = -1;
+                }
+                bitstream->stream_ = 0;
+        }
+
+        jas_free(bitstream);
+        return ret;
 }
 
 /******************************************************************************\
@@ -206,64 +206,64 @@ int jpc_bitstream_close(jpc_bitstream_t *bitstream)
 /* Get a bit from a bit stream. */
 int jpc_bitstream_getbit_func(jpc_bitstream_t *bitstream)
 {
-	int ret;
-	JAS_DBGLOG(1000, ("jpc_bitstream_getbit_func(%p)\n", bitstream));
-	ret = jpc_bitstream_getbit_macro(bitstream);
-	JAS_DBGLOG(1000, ("jpc_bitstream_getbit_func -> %d\n", ret));
-	return ret;
+        int ret;
+        JAS_DBGLOG(1000, ("jpc_bitstream_getbit_func(%p)\n", bitstream));
+        ret = jpc_bitstream_getbit_macro(bitstream);
+        JAS_DBGLOG(1000, ("jpc_bitstream_getbit_func -> %d\n", ret));
+        return ret;
 }
 
 /* Put a bit to a bit stream. */
 int jpc_bitstream_putbit_func(jpc_bitstream_t *bitstream, int b)
 {
-	int ret;
-	JAS_DBGLOG(1000, ("jpc_bitstream_putbit_func(%p, %d)\n", bitstream, b));
-	ret = jpc_bitstream_putbit_macro(bitstream, b);
-	JAS_DBGLOG(1000, ("jpc_bitstream_putbit_func() -> %d\n", ret));
-	return ret;
+        int ret;
+        JAS_DBGLOG(1000, ("jpc_bitstream_putbit_func(%p, %d)\n", bitstream, b));
+        ret = jpc_bitstream_putbit_macro(bitstream, b);
+        JAS_DBGLOG(1000, ("jpc_bitstream_putbit_func() -> %d\n", ret));
+        return ret;
 }
 
 /* Get one or more bits from a bit stream. */
 long jpc_bitstream_getbits(jpc_bitstream_t *bitstream, int n)
 {
-	long v;
-	int u;
-
-	/* We can reliably get at most 31 bits since ISO/IEC 9899 only
-	  guarantees that a long can represent values up to 2^31-1. */
-	assert(n >= 0 && n < 32);
-
-	/* Get the number of bits requested from the specified bit stream. */
-	v = 0;
-	while (--n >= 0) {
-		if ((u = jpc_bitstream_getbit(bitstream)) < 0) {
-			return -1;
-		}
-		v = (v << 1) | u;
-	}
-	return v;
+        long v;
+        int u;
+
+        /* We can reliably get at most 31 bits since ISO/IEC 9899 only
+          guarantees that a long can represent values up to 2^31-1. */
+        assert(n >= 0 && n < 32);
+
+        /* Get the number of bits requested from the specified bit stream. */
+        v = 0;
+        while (--n >= 0) {
+                if ((u = jpc_bitstream_getbit(bitstream)) < 0) {
+                        return -1;
+                }
+                v = (v << 1) | u;
+        }
+        return v;
 }
 
 /* Put one or more bits to a bit stream. */
 int jpc_bitstream_putbits(jpc_bitstream_t *bitstream, int n, long v)
 {
-	int m;
-
-	/* We can reliably put at most 31 bits since ISO/IEC 9899 only
-	  guarantees that a long can represent values up to 2^31-1. */
-	assert(n >= 0 && n < 32);
-	/* Ensure that only the bits to be output are nonzero. */
-	assert(!(v & (~JAS_ONES(n))));
-
-	/* Put the desired number of bits to the specified bit stream. */
-	m = n - 1;
-	while (--n >= 0) {
-		if (jpc_bitstream_putbit(bitstream, (v >> m) & 1) == EOF) {
-			return EOF;
-		}
-		v <<= 1;
-	}
-	return 0;
+        int m;
+
+        /* We can reliably put at most 31 bits since ISO/IEC 9899 only
+          guarantees that a long can represent values up to 2^31-1. */
+        assert(n >= 0 && n < 32);
+        /* Ensure that only the bits to be output are nonzero. */
+        assert(!(v & (~JAS_ONES(n))));
+
+        /* Put the desired number of bits to the specified bit stream. */
+        m = n - 1;
+        while (--n >= 0) {
+                if (jpc_bitstream_putbit(bitstream, (v >> m) & 1) == EOF) {
+                        return EOF;
+                }
+                v <<= 1;
+        }
+        return 0;
 }
 
 /******************************************************************************\
@@ -273,30 +273,30 @@ int jpc_bitstream_putbits(jpc_bitstream_t *bitstream, int n, long v)
 /* Fill the buffer for a bit stream. */
 int jpc_bitstream_fillbuf(jpc_bitstream_t *bitstream)
 {
-	int c;
-	/* Note: The count has already been decremented by the caller. */
-	assert(bitstream->openmode_ & JPC_BITSTREAM_READ);
-	assert(bitstream->cnt_ <= 0);
-
-	if (bitstream->flags_ & JPC_BITSTREAM_ERR) {
-		bitstream->cnt_ = 0;
-		return -1;
-	}
-
-	if (bitstream->flags_ & JPC_BITSTREAM_EOF) {
-		bitstream->buf_ = 0x7f;
-		bitstream->cnt_ = 7;
-		return 1;
-	}
-
-	bitstream->buf_ = (bitstream->buf_ << 8) & 0xffff;
-	if ((c = jas_stream_getc((bitstream)->stream_)) == EOF) {
-		bitstream->flags_ |= JPC_BITSTREAM_EOF;
-		return 1;
-	}
-	bitstream->cnt_ = (bitstream->buf_ == 0xff00) ? 6 : 7;
-	bitstream->buf_ |= c & ((1 << (bitstream->cnt_ + 1)) - 1);
-	return (bitstream->buf_ >> bitstream->cnt_) & 1;
+        int c;
+        /* Note: The count has already been decremented by the caller. */
+        assert(bitstream->openmode_ & JPC_BITSTREAM_READ);
+        assert(bitstream->cnt_ <= 0);
+
+        if (bitstream->flags_ & JPC_BITSTREAM_ERR) {
+                bitstream->cnt_ = 0;
+                return -1;
+        }
+
+        if (bitstream->flags_ & JPC_BITSTREAM_EOF) {
+                bitstream->buf_ = 0x7f;
+                bitstream->cnt_ = 7;
+                return 1;
+        }
+
+        bitstream->buf_ = (bitstream->buf_ << 8) & 0xffff;
+        if ((c = jas_stream_getc((bitstream)->stream_)) == EOF) {
+                bitstream->flags_ |= JPC_BITSTREAM_EOF;
+                return 1;
+        }
+        bitstream->cnt_ = (bitstream->buf_ == 0xff00) ? 6 : 7;
+        bitstream->buf_ |= c & ((1 << (bitstream->cnt_ + 1)) - 1);
+        return (bitstream->buf_ >> bitstream->cnt_) & 1;
 }
 
 
@@ -308,167 +308,167 @@ int jpc_bitstream_fillbuf(jpc_bitstream_t *bitstream)
   the effects of bit stuffing)? */
 int jpc_bitstream_needalign(jpc_bitstream_t *bitstream)
 {
-	if (bitstream->openmode_ & JPC_BITSTREAM_READ) {
-		/* The bit stream is open for reading. */
-		/* If there are any bits buffered for reading, or the
-		  previous byte forced a stuffed bit, alignment is
-		  required. */
-		if ((bitstream->cnt_ < 8 && bitstream->cnt_ > 0) ||
-		  ((bitstream->buf_ >> 8) & 0xff) == 0xff) {
-			return 1;
-		}
-	} else if (bitstream->openmode_ & JPC_BITSTREAM_WRITE) {
-		/* The bit stream is open for writing. */
-		/* If there are any bits buffered for writing, or the
-		  previous byte forced a stuffed bit, alignment is
-		  required. */
-		if ((bitstream->cnt_ < 8 && bitstream->cnt_ >= 0) ||
-		  ((bitstream->buf_ >> 8) & 0xff) == 0xff) {
-			return 1;
-		}
-	} else {
-		/* This should not happen.  Famous last words, eh? :-) */
-		assert(0);
-		return -1;
-	}
-	return 0;
+        if (bitstream->openmode_ & JPC_BITSTREAM_READ) {
+                /* The bit stream is open for reading. */
+                /* If there are any bits buffered for reading, or the
+                  previous byte forced a stuffed bit, alignment is
+                  required. */
+                if ((bitstream->cnt_ < 8 && bitstream->cnt_ > 0) ||
+                  ((bitstream->buf_ >> 8) & 0xff) == 0xff) {
+                        return 1;
+                }
+        } else if (bitstream->openmode_ & JPC_BITSTREAM_WRITE) {
+                /* The bit stream is open for writing. */
+                /* If there are any bits buffered for writing, or the
+                  previous byte forced a stuffed bit, alignment is
+                  required. */
+                if ((bitstream->cnt_ < 8 && bitstream->cnt_ >= 0) ||
+                  ((bitstream->buf_ >> 8) & 0xff) == 0xff) {
+                        return 1;
+                }
+        } else {
+                /* This should not happen.  Famous last words, eh? :-) */
+                assert(0);
+                return -1;
+        }
+        return 0;
 }
 
 /* How many additional bytes would be output if we align the bit stream? */
 int jpc_bitstream_pending(jpc_bitstream_t *bitstream)
 {
-	if (bitstream->openmode_ & JPC_BITSTREAM_WRITE) {
-		/* The bit stream is being used for writing. */
+        if (bitstream->openmode_ & JPC_BITSTREAM_WRITE) {
+                /* The bit stream is being used for writing. */
 #if 1
-		/* XXX - Is this really correct?  Check someday... */
-		if (bitstream->cnt_ < 8) {
-			return 1;
-		}
+                /* XXX - Is this really correct?  Check someday... */
+                if (bitstream->cnt_ < 8) {
+                        return 1;
+                }
 #else
-		if (bitstream->cnt_ < 8) {
-			if (((bitstream->buf_ >> 8) & 0xff) == 0xff) {
-				return 2;
-			}
-			return 1;
-		}
+                if (bitstream->cnt_ < 8) {
+                        if (((bitstream->buf_ >> 8) & 0xff) == 0xff) {
+                                return 2;
+                        }
+                        return 1;
+                }
 #endif
-		return 0;
-	} else {
-		/* This operation should not be invoked on a bit stream that
-		  is being used for reading. */
-		return -1;
-	}
+                return 0;
+        } else {
+                /* This operation should not be invoked on a bit stream that
+                  is being used for reading. */
+                return -1;
+        }
 }
 
 /* Align the bit stream to a byte boundary. */
 int jpc_bitstream_align(jpc_bitstream_t *bitstream)
 {
-	int ret;
-	if (bitstream->openmode_ & JPC_BITSTREAM_READ) {
-		ret = jpc_bitstream_inalign(bitstream, 0, 0);
-	} else if (bitstream->openmode_ & JPC_BITSTREAM_WRITE) {
-		ret = jpc_bitstream_outalign(bitstream, 0);
-	}
-	return ret;
+        int ret;
+        if (bitstream->openmode_ & JPC_BITSTREAM_READ) {
+                ret = jpc_bitstream_inalign(bitstream, 0, 0);
+        } else if (bitstream->openmode_ & JPC_BITSTREAM_WRITE) {
+                ret = jpc_bitstream_outalign(bitstream, 0);
+        }
+        return ret;
 }
 
 /* Align a bit stream in the input case. */
 int jpc_bitstream_inalign(jpc_bitstream_t *bitstream, int fillmask,
   int filldata)
 {
-	int n;
-	int v;
-	int u;
-	int numfill;
-	int m;
-
-	numfill = 7;
-	m = 0;
-	v = 0;
-	if (bitstream->cnt_ > 0) {
-		n = bitstream->cnt_;
-	} else if (!bitstream->cnt_) {
-		n = ((bitstream->buf_ & 0xff) == 0xff) ? 7 : 0;
-	} else {
-		n = 0;
-	}
-	if (n > 0) {
-		if ((u = jpc_bitstream_getbits(bitstream, n)) < 0) {
-			return -1;
-		}
-		m += n;
-		v = (v << n) | u;
-	}
-	if ((bitstream->buf_ & 0xff) == 0xff) {
-		if ((u = jpc_bitstream_getbits(bitstream, 7)) < 0) {
-			return -1;
-		}
-		v = (v << 7) | u;
-		m += 7;
-	}
-	if (m > numfill) {
-		v >>= m - numfill;
-	} else {
-		filldata >>= numfill - m;
-		fillmask >>= numfill - m;
-	}
-	if (((~(v ^ filldata)) & fillmask) != fillmask) {
-		/* The actual fill pattern does not match the expected one. */
-		return 1;
-	}
-
-	return 0;
+        int n;
+        int v;
+        int u;
+        int numfill;
+        int m;
+
+        numfill = 7;
+        m = 0;
+        v = 0;
+        if (bitstream->cnt_ > 0) {
+                n = bitstream->cnt_;
+        } else if (!bitstream->cnt_) {
+                n = ((bitstream->buf_ & 0xff) == 0xff) ? 7 : 0;
+        } else {
+                n = 0;
+        }
+        if (n > 0) {
+                if ((u = jpc_bitstream_getbits(bitstream, n)) < 0) {
+                        return -1;
+                }
+                m += n;
+                v = (v << n) | u;
+        }
+        if ((bitstream->buf_ & 0xff) == 0xff) {
+                if ((u = jpc_bitstream_getbits(bitstream, 7)) < 0) {
+                        return -1;
+                }
+                v = (v << 7) | u;
+                m += 7;
+        }
+        if (m > numfill) {
+                v >>= m - numfill;
+        } else {
+                filldata >>= numfill - m;
+                fillmask >>= numfill - m;
+        }
+        if (((~(v ^ filldata)) & fillmask) != fillmask) {
+                /* The actual fill pattern does not match the expected one. */
+                return 1;
+        }
+
+        return 0;
 }
 
 /* Align a bit stream in the output case. */
 int jpc_bitstream_outalign(jpc_bitstream_t *bitstream, int filldata)
 {
-	int n;
-	int v;
-
-	/* Ensure that this bit stream is open for writing. */
-	assert(bitstream->openmode_ & JPC_BITSTREAM_WRITE);
-
-	/* Ensure that the first bit of fill data is zero. */
-	/* Note: The first bit of fill data must be zero.  If this were not
-	  the case, the fill data itself could cause further bit stuffing to
-	  be required (which would cause numerous complications). */
-	assert(!(filldata & (~0x3f)));
-
-	if (!bitstream->cnt_) {
-		if ((bitstream->buf_ & 0xff) == 0xff) {
-			n = 7;
-			v = filldata;
-		} else {
-			n = 0;
-			v = 0;
-		}
-	} else if (bitstream->cnt_ > 0 && bitstream->cnt_ < 8) {
-		n = bitstream->cnt_;
-		v = filldata >> (7 - n);
-	} else {
-		n = 0;
-		v = 0;
-		return 0;
-	}
-
-	/* Write the appropriate fill data to the bit stream. */
-	if (n > 0) {
-		if (jpc_bitstream_putbits(bitstream, n, v)) {
-			return -1;
-		}
-	}
-	if (bitstream->cnt_ < 8) {
-		assert(bitstream->cnt_ >= 0 && bitstream->cnt_ < 8);
-		assert((bitstream->buf_ & 0xff) != 0xff);
-		/* Force the pending byte of output to be written to the
-		  underlying (character) stream. */
-		if (jas_stream_putc(bitstream->stream_, bitstream->buf_ & 0xff) == EOF) {
-			return -1;
-		}
-		bitstream->cnt_ = 8;
-		bitstream->buf_ = (bitstream->buf_ << 8) & 0xffff;
-	}
-
-	return 0;
+        int n;
+        int v;
+
+        /* Ensure that this bit stream is open for writing. */
+        assert(bitstream->openmode_ & JPC_BITSTREAM_WRITE);
+
+        /* Ensure that the first bit of fill data is zero. */
+        /* Note: The first bit of fill data must be zero.  If this were not
+          the case, the fill data itself could cause further bit stuffing to
+          be required (which would cause numerous complications). */
+        assert(!(filldata & (~0x3f)));
+
+        if (!bitstream->cnt_) {
+                if ((bitstream->buf_ & 0xff) == 0xff) {
+                        n = 7;
+                        v = filldata;
+                } else {
+                        n = 0;
+                        v = 0;
+                }
+        } else if (bitstream->cnt_ > 0 && bitstream->cnt_ < 8) {
+                n = bitstream->cnt_;
+                v = filldata >> (7 - n);
+        } else {
+                n = 0;
+                v = 0;
+                return 0;
+        }
+
+        /* Write the appropriate fill data to the bit stream. */
+        if (n > 0) {
+                if (jpc_bitstream_putbits(bitstream, n, v)) {
+                        return -1;
+                }
+        }
+        if (bitstream->cnt_ < 8) {
+                assert(bitstream->cnt_ >= 0 && bitstream->cnt_ < 8);
+                assert((bitstream->buf_ & 0xff) != 0xff);
+                /* Force the pending byte of output to be written to the
+                  underlying (character) stream. */
+                if (jas_stream_putc(bitstream->stream_, bitstream->buf_ & 0xff) == EOF) {
+                        return -1;
+                }
+                bitstream->cnt_ = 8;
+                bitstream->buf_ = (bitstream->buf_ << 8) & 0xffff;
+        }
+
+        return 0;
 }
diff --git a/converter/other/jpeg2000/libjasper/jpc/jpc_bs.h b/converter/other/jpeg2000/libjasper/jpc/jpc_bs.h
index edb0a2df..2137a435 100644
--- a/converter/other/jpeg2000/libjasper/jpc/jpc_bs.h
+++ b/converter/other/jpeg2000/libjasper/jpc/jpc_bs.h
@@ -6,14 +6,14 @@
  */
 
 /* __START_OF_JASPER_LICENSE__
- * 
+ *
  * JasPer Software License
- * 
+ *
  * IMAGE POWER JPEG-2000 PUBLIC LICENSE
  * ************************************
- * 
+ *
  * GRANT:
- * 
+ *
  * Permission is hereby granted, free of charge, to any person (the "User")
  * obtaining a copy of this software and associated documentation, to deal
  * in the JasPer Software without restriction, including without limitation
@@ -21,22 +21,22 @@
  * and/or sell copies of the JasPer Software (in source and binary forms),
  * and to permit persons to whom the JasPer Software is furnished to do so,
  * provided further that the License Conditions below are met.
- * 
+ *
  * License Conditions
  * ******************
- * 
+ *
  * A.  Redistributions of source code must retain the above copyright notice,
  * and this list of conditions, and the following disclaimer.
- * 
+ *
  * B.  Redistributions in binary form must reproduce the above copyright
  * notice, and this list of conditions, and the following disclaimer in
  * the documentation and/or other materials provided with the distribution.
- * 
+ *
  * C.  Neither the name of Image Power, Inc. nor any other contributor
  * (including, but not limited to, the University of British Columbia and
  * Michael David Adams) may be used to endorse or promote products derived
  * from this software without specific prior written permission.
- * 
+ *
  * D.  User agrees that it shall not commence any action against Image Power,
  * Inc., the University of British Columbia, Michael David Adams, or any
  * other contributors (collectively "Licensors") for infringement of any
@@ -56,17 +56,17 @@
  * trade dress, or service mark rights); and (v) divisions, continuations,
  * renewals, reissues and extensions of the foregoing (as and to the extent
  * applicable) now existing, hereafter filed, issued or acquired.
- * 
+ *
  * E.  If User commences an infringement action against any Licensor(s) then
  * such Licensor(s) shall have the right to terminate User's license and
  * all sublicenses that have been granted hereunder by User to other parties.
- * 
+ *
  * F.  This software is for use only in hardware or software products that
  * are compliant with ISO/IEC 15444-1 (i.e., JPEG-2000 Part 1).  No license
  * or right to this Software is granted for products that do not comply
  * with ISO/IEC 15444-1.  The JPEG-2000 Part 1 standard can be purchased
  * from the ISO.
- * 
+ *
  * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS LICENSE.
  * NO USE OF THE JASPER SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER
  * THIS DISCLAIMER.  THE JASPER SOFTWARE IS PROVIDED BY THE LICENSORS AND
@@ -106,7 +106,7 @@
  * TECHNOLOGY OR PRODUCTS FOR HIGH RISK ACTIVITIES AND WILL ENSURE THAT ITS
  * CUSTOMERS AND END-USERS OF ITS PRODUCTS ARE PROVIDED WITH A COPY OF THE
  * NOTICE SPECIFIED IN THIS SECTION.
- * 
+ *
  * __END_OF_JASPER_LICENSE__
  */
 
@@ -137,20 +137,20 @@
  */
 
 /* Bit stream open for reading. */
-#define	JPC_BITSTREAM_READ	0x01
+#define JPC_BITSTREAM_READ      0x01
 /* Bit stream open for writing. */
-#define	JPC_BITSTREAM_WRITE	0x02
+#define JPC_BITSTREAM_WRITE     0x02
 
 /*
  * Bit stream flags.
  */
 
 /* Do not close underlying character stream. */
-#define	JPC_BITSTREAM_NOCLOSE	0x01
+#define JPC_BITSTREAM_NOCLOSE   0x01
 /* End of file has been reached while reading. */
-#define	JPC_BITSTREAM_EOF	0x02
+#define JPC_BITSTREAM_EOF       0x02
 /* An I/O error has occurred. */
-#define	JPC_BITSTREAM_ERR	0x04
+#define JPC_BITSTREAM_ERR       0x04
 
 /******************************************************************************\
 * Types.
@@ -160,20 +160,20 @@
 
 typedef struct {
 
-	/* Some miscellaneous flags. */
-	int flags_;
+        /* Some miscellaneous flags. */
+        int flags_;
 
-	/* The input/output buffer. */
-	uint_fast16_t buf_;
+        /* The input/output buffer. */
+        uint_fast16_t buf_;
 
-	/* The number of bits remaining in the byte being read/written. */
-	int cnt_;
+        /* The number of bits remaining in the byte being read/written. */
+        int cnt_;
 
-	/* The underlying stream associated with this bit stream. */
-	jas_stream_t *stream_;
+        /* The underlying stream associated with this bit stream. */
+        jas_stream_t *stream_;
 
-	/* The mode in which this bit stream was opened. */
-	int openmode_;
+        /* The mode in which this bit stream was opened. */
+        int openmode_;
 
 } jpc_bitstream_t;
 
@@ -193,20 +193,20 @@ int jpc_bitstream_close(jpc_bitstream_t *bitstream);
 
 /* Read a bit from a bit stream. */
 #if defined(DEBUG)
-#define	jpc_bitstream_getbit(bitstream) \
-	jpc_bitstream_getbit_func(bitstream)
+#define jpc_bitstream_getbit(bitstream) \
+        jpc_bitstream_getbit_func(bitstream)
 #else
 #define jpc_bitstream_getbit(bitstream) \
-	jpc_bitstream_getbit_macro(bitstream)
+        jpc_bitstream_getbit_macro(bitstream)
 #endif
 
 /* Write a bit to a bit stream. */
 #if defined(DEBUG)
-#define	jpc_bitstream_putbit(bitstream, v) \
-	jpc_bitstream_putbit_func(bitstream, v)
+#define jpc_bitstream_putbit(bitstream, v) \
+        jpc_bitstream_putbit_func(bitstream, v)
 #else
-#define	jpc_bitstream_putbit(bitstream, v) \
-	jpc_bitstream_putbit_macro(bitstream, v)
+#define jpc_bitstream_putbit(bitstream, v) \
+        jpc_bitstream_putbit_macro(bitstream, v)
 #endif
 
 /* Read one or more bits from a bit stream. */
@@ -245,7 +245,7 @@ int jpc_bitstream_pending(jpc_bitstream_t *bitstream);
 
 /* Has EOF been encountered on a bit stream? */
 #define jpc_bitstream_eof(bitstream) \
-	((bitstream)->flags_ & JPC_BITSTREAM_EOF)
+        ((bitstream)->flags_ & JPC_BITSTREAM_EOF)
 
 /******************************************************************************\
 * Internals.
@@ -260,21 +260,21 @@ int jpc_bitstream_putbit_func(jpc_bitstream_t *bitstream, int v);
 
 int jpc_bitstream_fillbuf(jpc_bitstream_t *bitstream);
 
-#define	jpc_bitstream_getbit_macro(bitstream) \
-	(assert((bitstream)->openmode_ & JPC_BITSTREAM_READ), \
-	  (--(bitstream)->cnt_ >= 0) ? \
-	  (((bitstream)->buf_ >> (bitstream)->cnt_) & 1) : \
-	  jpc_bitstream_fillbuf(bitstream))
+#define jpc_bitstream_getbit_macro(bitstream) \
+        (assert((bitstream)->openmode_ & JPC_BITSTREAM_READ), \
+          (--(bitstream)->cnt_ >= 0) ? \
+          (((bitstream)->buf_ >> (bitstream)->cnt_) & 1) : \
+          jpc_bitstream_fillbuf(bitstream))
 
 #define jpc_bitstream_putbit_macro(bitstream, bit) \
-	(assert((bitstream)->openmode_ & JPC_BITSTREAM_WRITE), \
-	  (--(bitstream)->cnt_ < 0) ? \
-	  ((bitstream)->buf_ = ((bitstream)->buf_ << 8) & 0xffff, \
-	  (bitstream)->cnt_ = ((bitstream)->buf_ == 0xff00) ? 6 : 7, \
-	  (bitstream)->buf_ |= ((bit) & 1) << (bitstream)->cnt_, \
-	  (jas_stream_putc((bitstream)->stream_, (bitstream)->buf_ >> 8) == EOF) \
-	  ? (EOF) : ((bit) & 1)) : \
-	  ((bitstream)->buf_ |= ((bit) & 1) << (bitstream)->cnt_, \
-	  (bit) & 1))
+        (assert((bitstream)->openmode_ & JPC_BITSTREAM_WRITE), \
+          (--(bitstream)->cnt_ < 0) ? \
+          ((bitstream)->buf_ = ((bitstream)->buf_ << 8) & 0xffff, \
+          (bitstream)->cnt_ = ((bitstream)->buf_ == 0xff00) ? 6 : 7, \
+          (bitstream)->buf_ |= ((bit) & 1) << (bitstream)->cnt_, \
+          (jas_stream_putc((bitstream)->stream_, (bitstream)->buf_ >> 8) == EOF) \
+          ? (EOF) : ((bit) & 1)) : \
+          ((bitstream)->buf_ |= ((bit) & 1) << (bitstream)->cnt_, \
+          (bit) & 1))
 
 #endif
diff --git a/converter/other/jpeg2000/libjasper/jpc/jpc_cod.h b/converter/other/jpeg2000/libjasper/jpc/jpc_cod.h
index 9b3ddbee..cff7e72b 100644
--- a/converter/other/jpeg2000/libjasper/jpc/jpc_cod.h
+++ b/converter/other/jpeg2000/libjasper/jpc/jpc_cod.h
@@ -6,14 +6,14 @@
  */
 
 /* __START_OF_JASPER_LICENSE__
- * 
+ *
  * JasPer Software License
- * 
+ *
  * IMAGE POWER JPEG-2000 PUBLIC LICENSE
  * ************************************
- * 
+ *
  * GRANT:
- * 
+ *
  * Permission is hereby granted, free of charge, to any person (the "User")
  * obtaining a copy of this software and associated documentation, to deal
  * in the JasPer Software without restriction, including without limitation
@@ -21,22 +21,22 @@
  * and/or sell copies of the JasPer Software (in source and binary forms),
  * and to permit persons to whom the JasPer Software is furnished to do so,
  * provided further that the License Conditions below are met.
- * 
+ *
  * License Conditions
  * ******************
- * 
+ *
  * A.  Redistributions of source code must retain the above copyright notice,
  * and this list of conditions, and the following disclaimer.
- * 
+ *
  * B.  Redistributions in binary form must reproduce the above copyright
  * notice, and this list of conditions, and the following disclaimer in
  * the documentation and/or other materials provided with the distribution.
- * 
+ *
  * C.  Neither the name of Image Power, Inc. nor any other contributor
  * (including, but not limited to, the University of British Columbia and
  * Michael David Adams) may be used to endorse or promote products derived
  * from this software without specific prior written permission.
- * 
+ *
  * D.  User agrees that it shall not commence any action against Image Power,
  * Inc., the University of British Columbia, Michael David Adams, or any
  * other contributors (collectively "Licensors") for infringement of any
@@ -56,17 +56,17 @@
  * trade dress, or service mark rights); and (v) divisions, continuations,
  * renewals, reissues and extensions of the foregoing (as and to the extent
  * applicable) now existing, hereafter filed, issued or acquired.
- * 
+ *
  * E.  If User commences an infringement action against any Licensor(s) then
  * such Licensor(s) shall have the right to terminate User's license and
  * all sublicenses that have been granted hereunder by User to other parties.
- * 
+ *
  * F.  This software is for use only in hardware or software products that
  * are compliant with ISO/IEC 15444-1 (i.e., JPEG-2000 Part 1).  No license
  * or right to this Software is granted for products that do not comply
  * with ISO/IEC 15444-1.  The JPEG-2000 Part 1 standard can be purchased
  * from the ISO.
- * 
+ *
  * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS LICENSE.
  * NO USE OF THE JASPER SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER
  * THIS DISCLAIMER.  THE JASPER SOFTWARE IS PROVIDED BY THE LICENSORS AND
@@ -106,7 +106,7 @@
  * TECHNOLOGY OR PRODUCTS FOR HIGH RISK ACTIVITIES AND WILL ENSURE THAT ITS
  * CUSTOMERS AND END-USERS OF ITS PRODUCTS ARE PROVIDED WITH A COPY OF THE
  * NOTICE SPECIFIED IN THIS SECTION.
- * 
+ *
  * __END_OF_JASPER_LICENSE__
  */
 
@@ -122,6 +122,6 @@
 \******************************************************************************/
 
 /* The nominal word size used by this implementation. */
-#define	JPC_PREC	32
+#define JPC_PREC        32
 
 #endif
diff --git a/converter/other/jpeg2000/libjasper/jpc/jpc_cs.c b/converter/other/jpeg2000/libjasper/jpc/jpc_cs.c
index 559f36cf..441f8995 100644
--- a/converter/other/jpeg2000/libjasper/jpc/jpc_cs.c
+++ b/converter/other/jpeg2000/libjasper/jpc/jpc_cs.c
@@ -6,14 +6,14 @@
  */
 
 /* __START_OF_JASPER_LICENSE__
- * 
+ *
  * JasPer Software License
- * 
+ *
  * IMAGE POWER JPEG-2000 PUBLIC LICENSE
  * ************************************
- * 
+ *
  * GRANT:
- * 
+ *
  * Permission is hereby granted, free of charge, to any person (the "User")
  * obtaining a copy of this software and associated documentation, to deal
  * in the JasPer Software without restriction, including without limitation
@@ -21,22 +21,22 @@
  * and/or sell copies of the JasPer Software (in source and binary forms),
  * and to permit persons to whom the JasPer Software is furnished to do so,
  * provided further that the License Conditions below are met.
- * 
+ *
  * License Conditions
  * ******************
- * 
+ *
  * A.  Redistributions of source code must retain the above copyright notice,
  * and this list of conditions, and the following disclaimer.
- * 
+ *
  * B.  Redistributions in binary form must reproduce the above copyright
  * notice, and this list of conditions, and the following disclaimer in
  * the documentation and/or other materials provided with the distribution.
- * 
+ *
  * C.  Neither the name of Image Power, Inc. nor any other contributor
  * (including, but not limited to, the University of British Columbia and
  * Michael David Adams) may be used to endorse or promote products derived
  * from this software without specific prior written permission.
- * 
+ *
  * D.  User agrees that it shall not commence any action against Image Power,
  * Inc., the University of British Columbia, Michael David Adams, or any
  * other contributors (collectively "Licensors") for infringement of any
@@ -56,17 +56,17 @@
  * trade dress, or service mark rights); and (v) divisions, continuations,
  * renewals, reissues and extensions of the foregoing (as and to the extent
  * applicable) now existing, hereafter filed, issued or acquired.
- * 
+ *
  * E.  If User commences an infringement action against any Licensor(s) then
  * such Licensor(s) shall have the right to terminate User's license and
  * all sublicenses that have been granted hereunder by User to other parties.
- * 
+ *
  * F.  This software is for use only in hardware or software products that
  * are compliant with ISO/IEC 15444-1 (i.e., JPEG-2000 Part 1).  No license
  * or right to this Software is granted for products that do not comply
  * with ISO/IEC 15444-1.  The JPEG-2000 Part 1 standard can be purchased
  * from the ISO.
- * 
+ *
  * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS LICENSE.
  * NO USE OF THE JASPER SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER
  * THIS DISCLAIMER.  THE JASPER SOFTWARE IS PROVIDED BY THE LICENSORS AND
@@ -106,7 +106,7 @@
  * TECHNOLOGY OR PRODUCTS FOR HIGH RISK ACTIVITIES AND WILL ENSURE THAT ITS
  * CUSTOMERS AND END-USERS OF ITS PRODUCTS ARE PROVIDED WITH A COPY OF THE
  * NOTICE SPECIFIED IN THIS SECTION.
- * 
+ *
  * __END_OF_JASPER_LICENSE__
  */
 
diff --git a/converter/other/jpeg2000/libjasper/jpc/jpc_cs.h b/converter/other/jpeg2000/libjasper/jpc/jpc_cs.h
index 4bff677c..13787d40 100644
--- a/converter/other/jpeg2000/libjasper/jpc/jpc_cs.h
+++ b/converter/other/jpeg2000/libjasper/jpc/jpc_cs.h
@@ -6,14 +6,14 @@
  */
 
 /* __START_OF_JASPER_LICENSE__
- * 
+ *
  * JasPer Software License
- * 
+ *
  * IMAGE POWER JPEG-2000 PUBLIC LICENSE
  * ************************************
- * 
+ *
  * GRANT:
- * 
+ *
  * Permission is hereby granted, free of charge, to any person (the "User")
  * obtaining a copy of this software and associated documentation, to deal
  * in the JasPer Software without restriction, including without limitation
@@ -21,22 +21,22 @@
  * and/or sell copies of the JasPer Software (in source and binary forms),
  * and to permit persons to whom the JasPer Software is furnished to do so,
  * provided further that the License Conditions below are met.
- * 
+ *
  * License Conditions
  * ******************
- * 
+ *
  * A.  Redistributions of source code must retain the above copyright notice,
  * and this list of conditions, and the following disclaimer.
- * 
+ *
  * B.  Redistributions in binary form must reproduce the above copyright
  * notice, and this list of conditions, and the following disclaimer in
  * the documentation and/or other materials provided with the distribution.
- * 
+ *
  * C.  Neither the name of Image Power, Inc. nor any other contributor
  * (including, but not limited to, the University of British Columbia and
  * Michael David Adams) may be used to endorse or promote products derived
  * from this software without specific prior written permission.
- * 
+ *
  * D.  User agrees that it shall not commence any action against Image Power,
  * Inc., the University of British Columbia, Michael David Adams, or any
  * other contributors (collectively "Licensors") for infringement of any
@@ -56,17 +56,17 @@
  * trade dress, or service mark rights); and (v) divisions, continuations,
  * renewals, reissues and extensions of the foregoing (as and to the extent
  * applicable) now existing, hereafter filed, issued or acquired.
- * 
+ *
  * E.  If User commences an infringement action against any Licensor(s) then
  * such Licensor(s) shall have the right to terminate User's license and
  * all sublicenses that have been granted hereunder by User to other parties.
- * 
+ *
  * F.  This software is for use only in hardware or software products that
  * are compliant with ISO/IEC 15444-1 (i.e., JPEG-2000 Part 1).  No license
  * or right to this Software is granted for products that do not comply
  * with ISO/IEC 15444-1.  The JPEG-2000 Part 1 standard can be purchased
  * from the ISO.
- * 
+ *
  * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS LICENSE.
  * NO USE OF THE JASPER SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER
  * THIS DISCLAIMER.  THE JASPER SOFTWARE IS PROVIDED BY THE LICENSORS AND
@@ -106,7 +106,7 @@
  * TECHNOLOGY OR PRODUCTS FOR HIGH RISK ACTIVITIES AND WILL ENSURE THAT ITS
  * CUSTOMERS AND END-USERS OF ITS PRODUCTS ARE PROVIDED WITH A COPY OF THE
  * NOTICE SPECIFIED IN THIS SECTION.
- * 
+ *
  * __END_OF_JASPER_LICENSE__
  */
 
@@ -133,13 +133,13 @@
 \******************************************************************************/
 
 /* The maximum number of resolution levels. */
-#define	JPC_MAXRLVLS	33
+#define JPC_MAXRLVLS    33
 
 /* The maximum number of bands. */
-#define	JPC_MAXBANDS	(3 * JPC_MAXRLVLS + 1)
+#define JPC_MAXBANDS    (3 * JPC_MAXRLVLS + 1)
 
 /* The maximum number of layers. */
-#define JPC_MAXLYRS	16384
+#define JPC_MAXLYRS     16384
 
 /**************************************\
 * Code stream.
@@ -150,15 +150,15 @@
  */
 
 /* Initial. */
-#define	JPC_CS_INIT	0
+#define JPC_CS_INIT     0
 /* Main header. */
-#define	JPC_CS_MHDR	1
+#define JPC_CS_MHDR     1
 /* Tile-part header. */
-#define	JPC_CS_THDR	2
+#define JPC_CS_THDR     2
 /* Main trailer. */
-#define	JPC_CS_MTLR	3
+#define JPC_CS_MTLR     3
 /* Tile-part data. */
-#define	JPC_CS_TDATA	4
+#define JPC_CS_TDATA    4
 
 /*
  * Unfortunately, the code stream syntax was not designed in such a way that
@@ -174,8 +174,8 @@
 
 typedef struct {
 
-	/* The number of components. */
-	int numcomps;
+        /* The number of components. */
+        int numcomps;
 
 } jpc_cstate_t;
 
@@ -185,18 +185,18 @@ typedef struct {
 
 typedef struct {
 
-	/* The tile number. */
-	uint_fast16_t tileno;
+        /* The tile number. */
+        uint_fast16_t tileno;
 
-	/* The combined length of the marker segment and its auxiliary data
-	  (i.e., packet data). */
-	uint_fast32_t len;
+        /* The combined length of the marker segment and its auxiliary data
+          (i.e., packet data). */
+        uint_fast32_t len;
 
-	/* The tile-part instance. */
-	uint_fast8_t partno;
+        /* The tile-part instance. */
+        uint_fast8_t partno;
 
-	/* The number of tile-parts. */
-	uint_fast8_t numparts;
+        /* The number of tile-parts. */
+        uint_fast8_t numparts;
 
 } jpc_sot_t;
 
@@ -208,19 +208,19 @@ typedef struct {
 
 typedef struct {
 
-	/* The precision of the samples. */
-	uint_fast8_t prec;
+        /* The precision of the samples. */
+        uint_fast8_t prec;
 
-	/* The signedness of the samples. */
-	uint_fast8_t sgnd;
+        /* The signedness of the samples. */
+        uint_fast8_t sgnd;
 
-	/* The horizontal separation of samples with respect to the reference
-	  grid. */
-	uint_fast8_t hsamp;
+        /* The horizontal separation of samples with respect to the reference
+          grid. */
+        uint_fast8_t hsamp;
 
-	/* The vertical separation of samples with respect to the reference
-	  grid. */
-	uint_fast8_t vsamp;
+        /* The vertical separation of samples with respect to the reference
+          grid. */
+        uint_fast8_t vsamp;
 
 } jpc_sizcomp_t;
 
@@ -228,42 +228,42 @@ typedef struct {
 
 typedef struct {
 
-	/* The code stream capabilities. */
-	uint_fast16_t caps;
+        /* The code stream capabilities. */
+        uint_fast16_t caps;
 
-	/* The width of the image in units of the reference grid. */
-	uint_fast32_t width;
+        /* The width of the image in units of the reference grid. */
+        uint_fast32_t width;
 
-	/* The height of the image in units of the reference grid. */
-	uint_fast32_t height;
+        /* The height of the image in units of the reference grid. */
+        uint_fast32_t height;
 
-	/* The horizontal offset from the origin of the reference grid to the
-	  left side of the image area. */
-	uint_fast32_t xoff;
+        /* The horizontal offset from the origin of the reference grid to the
+          left side of the image area. */
+        uint_fast32_t xoff;
 
-	/* The vertical offset from the origin of the reference grid to the
-	  top side of the image area. */
-	uint_fast32_t yoff;
+        /* The vertical offset from the origin of the reference grid to the
+          top side of the image area. */
+        uint_fast32_t yoff;
 
-	/* The nominal width of a tile in units of the reference grid. */
-	uint_fast32_t tilewidth;
+        /* The nominal width of a tile in units of the reference grid. */
+        uint_fast32_t tilewidth;
 
-	/* The nominal height of a tile in units of the reference grid. */
-	uint_fast32_t tileheight;
+        /* The nominal height of a tile in units of the reference grid. */
+        uint_fast32_t tileheight;
 
-	/* The horizontal offset from the origin of the reference grid to the
-	  left side of the first tile. */
-	uint_fast32_t tilexoff;
+        /* The horizontal offset from the origin of the reference grid to the
+          left side of the first tile. */
+        uint_fast32_t tilexoff;
 
-	/* The vertical offset from the origin of the reference grid to the
-	  top side of the first tile. */
-	uint_fast32_t tileyoff;
+        /* The vertical offset from the origin of the reference grid to the
+          top side of the first tile. */
+        uint_fast32_t tileyoff;
 
-	/* The number of components. */
-	uint_fast16_t numcomps;
+        /* The number of components. */
+        uint_fast16_t numcomps;
 
-	/* The per-component information. */
-	jpc_sizcomp_t *comps;
+        /* The per-component information. */
+        jpc_sizcomp_t *comps;
 
 } jpc_siz_t;
 
@@ -276,11 +276,11 @@ typedef struct {
  */
 
 /* Precincts may be used. */
-#define	JPC_COX_PRT	0x01
+#define JPC_COX_PRT     0x01
 /* SOP marker segments may be used. */
-#define	JPC_COD_SOP	0x02
+#define JPC_COD_SOP     0x02
 /* EPH marker segments may be used. */
-#define	JPC_COD_EPH	0x04
+#define JPC_COD_EPH     0x04
 
 /*
  * Progression order constants.
@@ -288,50 +288,50 @@ typedef struct {
 
 /* Layer-resolution-component-precinct progressive
   (i.e., progressive by fidelity). */
-#define	JPC_COD_LRCPPRG	0
+#define JPC_COD_LRCPPRG 0
 /* Resolution-layer-component-precinct progressive
   (i.e., progressive by resolution). */
-#define	JPC_COD_RLCPPRG	1
+#define JPC_COD_RLCPPRG 1
 /* Resolution-precinct-component-layer progressive. */
-#define	JPC_COD_RPCLPRG	2
+#define JPC_COD_RPCLPRG 2
 /* Precinct-component-resolution-layer progressive. */
-#define	JPC_COD_PCRLPRG	3
+#define JPC_COD_PCRLPRG 3
 /* Component-position-resolution-layer progressive. */
-#define	JPC_COD_CPRLPRG	4
+#define JPC_COD_CPRLPRG 4
 
 /*
  * Code block style constants.
  */
 
-#define	JPC_COX_LAZY	0x01 /* Selective arithmetic coding bypass. */
-#define	JPC_COX_RESET	0x02 /* Reset context probabilities. */
-#define	JPC_COX_TERMALL	0x04 /* Terminate all coding passes. */
-#define	JPC_COX_VSC		0x08 /* Vertical stripe causal context formation. */
-#define	JPC_COX_PTERM	0x10 /* Predictable termination. */
-#define	JPC_COX_SEGSYM	0x20 /* Use segmentation symbols. */
+#define JPC_COX_LAZY    0x01 /* Selective arithmetic coding bypass. */
+#define JPC_COX_RESET   0x02 /* Reset context probabilities. */
+#define JPC_COX_TERMALL 0x04 /* Terminate all coding passes. */
+#define JPC_COX_VSC             0x08 /* Vertical stripe causal context formation. */
+#define JPC_COX_PTERM   0x10 /* Predictable termination. */
+#define JPC_COX_SEGSYM  0x20 /* Use segmentation symbols. */
 
 /* Transform constants. */
-#define	JPC_COX_INS	0x00 /* Irreversible 9/7. */
-#define	JPC_COX_RFT	0x01 /* Reversible 5/3. */
+#define JPC_COX_INS     0x00 /* Irreversible 9/7. */
+#define JPC_COX_RFT     0x01 /* Reversible 5/3. */
 
 /* Multicomponent transform constants. */
-#define	JPC_COD_NOMCT	0x00 /* No multicomponent transform. */
-#define	JPC_COD_MCT		0x01 /* Multicomponent transform. */
+#define JPC_COD_NOMCT   0x00 /* No multicomponent transform. */
+#define JPC_COD_MCT             0x01 /* Multicomponent transform. */
 
 /* Get the code block size value from the code block size exponent. */
-#define	JPC_COX_CBLKSIZEEXPN(x)		((x) - 2)
+#define JPC_COX_CBLKSIZEEXPN(x)         ((x) - 2)
 /* Get the code block size exponent from the code block size value. */
-#define	JPC_COX_GETCBLKSIZEEXPN(x)	((x) + 2)
+#define JPC_COX_GETCBLKSIZEEXPN(x)      ((x) + 2)
 
 /* Per resolution-level information. */
 
 typedef struct {
 
-	/* The packet partition width. */
-	uint_fast8_t parwidthval;
+        /* The packet partition width. */
+        uint_fast8_t parwidthval;
 
-	/* The packet partition height. */
-	uint_fast8_t parheightval;
+        /* The packet partition height. */
+        uint_fast8_t parheightval;
 
 } jpc_coxrlvl_t;
 
@@ -339,29 +339,29 @@ typedef struct {
 
 typedef struct {
 
-	/* The coding style. */
-	uint_fast8_t csty;
+        /* The coding style. */
+        uint_fast8_t csty;
 
-	/* The number of decomposition levels. */
-	uint_fast8_t numdlvls;
+        /* The number of decomposition levels. */
+        uint_fast8_t numdlvls;
 
-	/* The nominal code block width specifier. */
-	uint_fast8_t cblkwidthval;
+        /* The nominal code block width specifier. */
+        uint_fast8_t cblkwidthval;
 
-	/* The nominal code block height specifier. */
-	uint_fast8_t cblkheightval;
+        /* The nominal code block height specifier. */
+        uint_fast8_t cblkheightval;
 
-	/* The style of coding passes. */
-	uint_fast8_t cblksty;
+        /* The style of coding passes. */
+        uint_fast8_t cblksty;
 
-	/* The QMFB employed. */
-	uint_fast8_t qmfbid;
+        /* The QMFB employed. */
+        uint_fast8_t qmfbid;
 
-	/* The number of resolution levels. */
-	int numrlvls;
+        /* The number of resolution levels. */
+        int numrlvls;
 
-	/* The per-resolution-level information. */
-	jpc_coxrlvl_t rlvls[JPC_MAXRLVLS];
+        /* The per-resolution-level information. */
+        jpc_coxrlvl_t rlvls[JPC_MAXRLVLS];
 
 } jpc_coxcp_t;
 
@@ -369,20 +369,20 @@ typedef struct {
 
 typedef struct {
 
-	/* The general coding style. */
-	uint_fast8_t csty;
+        /* The general coding style. */
+        uint_fast8_t csty;
 
-	/* The progression order. */
-	uint_fast8_t prg;
+        /* The progression order. */
+        uint_fast8_t prg;
 
-	/* The number of layers. */
-	uint_fast16_t numlyrs;
+        /* The number of layers. */
+        uint_fast16_t numlyrs;
 
-	/* The multicomponent transform. */
-	uint_fast8_t mctrans;
+        /* The multicomponent transform. */
+        uint_fast8_t mctrans;
 
-	/* Component-related parameters. */
-	jpc_coxcp_t compparms;
+        /* Component-related parameters. */
+        jpc_coxcp_t compparms;
 
 } jpc_cod_t;
 
@@ -390,11 +390,11 @@ typedef struct {
 
 typedef struct {
 
-	/* The component number. */
-	uint_fast16_t compno;
+        /* The component number. */
+        uint_fast16_t compno;
 
-	/* Component-related parameters. */
-	jpc_coxcp_t compparms;
+        /* Component-related parameters. */
+        jpc_coxcp_t compparms;
 
 } jpc_coc_t;
 
@@ -403,18 +403,18 @@ typedef struct {
 \**************************************/
 
 /* The maxshift ROI style. */
-#define	JPC_RGN_MAXSHIFT	0x00
+#define JPC_RGN_MAXSHIFT        0x00
 
 typedef struct {
 
-	/* The component to which the marker applies. */
-	uint_fast16_t compno;
+        /* The component to which the marker applies. */
+        uint_fast16_t compno;
 
-	/* The ROI style. */
-	uint_fast8_t roisty;
+        /* The ROI style. */
+        uint_fast8_t roisty;
 
-	/* The ROI shift value. */
-	uint_fast8_t roishift;
+        /* The ROI shift value. */
+        uint_fast8_t roishift;
 
 } jpc_rgn_t;
 
@@ -426,34 +426,34 @@ typedef struct {
  * Quantization style constants.
  */
 
-#define	JPC_QCX_NOQNT	0 /* No quantization. */
-#define	JPC_QCX_SIQNT	1 /* Scalar quantization, implicit. */
-#define	JPC_QCX_SEQNT	2 /* Scalar quantization, explicit. */
+#define JPC_QCX_NOQNT   0 /* No quantization. */
+#define JPC_QCX_SIQNT   1 /* Scalar quantization, implicit. */
+#define JPC_QCX_SEQNT   2 /* Scalar quantization, explicit. */
 
 /*
  * Stepsize manipulation macros.
  */
 
-#define	JPC_QCX_GETEXPN(x)	((x) >> 11)
-#define	JPC_QCX_GETMANT(x)	((x) & 0x07ff)
-#define	JPC_QCX_EXPN(x)		(assert(!((x) & (~0x1f))), (((x) & 0x1f) << 11))
-#define	JPC_QCX_MANT(x)		(assert(!((x) & (~0x7ff))), ((x) & 0x7ff))
+#define JPC_QCX_GETEXPN(x)      ((x) >> 11)
+#define JPC_QCX_GETMANT(x)      ((x) & 0x07ff)
+#define JPC_QCX_EXPN(x)         (assert(!((x) & (~0x1f))), (((x) & 0x1f) << 11))
+#define JPC_QCX_MANT(x)         (assert(!((x) & (~0x7ff))), ((x) & 0x7ff))
 
 /* Per component information. */
 
 typedef struct {
 
-	/* The quantization style. */
-	uint_fast8_t qntsty;
+        /* The quantization style. */
+        uint_fast8_t qntsty;
 
-	/* The number of step sizes. */
-	int numstepsizes;
+        /* The number of step sizes. */
+        int numstepsizes;
 
-	/* The step sizes. */
-	uint_fast16_t *stepsizes;
+        /* The step sizes. */
+        uint_fast16_t *stepsizes;
 
-	/* The number of guard bits. */
-	uint_fast8_t numguard;
+        /* The number of guard bits. */
+        uint_fast8_t numguard;
 
 } jpc_qcxcp_t;
 
@@ -461,11 +461,11 @@ typedef struct {
 
 typedef struct {
 
-	/* The component associated with this marker segment. */
-	uint_fast16_t compno;
+        /* The component associated with this marker segment. */
+        uint_fast16_t compno;
 
-	/* The parameters. */
-	jpc_qcxcp_t compparms;
+        /* The parameters. */
+        jpc_qcxcp_t compparms;
 
 } jpc_qcc_t;
 
@@ -473,8 +473,8 @@ typedef struct {
 
 typedef struct {
 
-	/* The parameters. */
-	jpc_qcxcp_t compparms;
+        /* The parameters. */
+        jpc_qcxcp_t compparms;
 
 } jpc_qcd_t;
 
@@ -484,28 +484,28 @@ typedef struct {
 
 typedef struct {
 
-	/* The progression order. */
-	uint_fast8_t prgord;
+        /* The progression order. */
+        uint_fast8_t prgord;
 
-	/* The lower bound (inclusive) on the resolution level for the
-	  progression order volume. */
-	uint_fast8_t rlvlnostart;
+        /* The lower bound (inclusive) on the resolution level for the
+          progression order volume. */
+        uint_fast8_t rlvlnostart;
 
-	/* The upper bound (exclusive) on the resolution level for the
-	  progression order volume. */
-	uint_fast8_t rlvlnoend;
+        /* The upper bound (exclusive) on the resolution level for the
+          progression order volume. */
+        uint_fast8_t rlvlnoend;
 
-	/* The lower bound (inclusive) on the component for the progression
-	  order volume. */
-	uint_fast16_t compnostart;
+        /* The lower bound (inclusive) on the component for the progression
+          order volume. */
+        uint_fast16_t compnostart;
 
-	/* The upper bound (exclusive) on the component for the progression
-	  order volume. */
-	uint_fast16_t compnoend;
+        /* The upper bound (exclusive) on the component for the progression
+          order volume. */
+        uint_fast16_t compnoend;
 
-	/* The upper bound (exclusive) on the layer for the progression
-	  order volume. */
-	uint_fast16_t lyrnoend;
+        /* The upper bound (exclusive) on the layer for the progression
+          order volume. */
+        uint_fast16_t lyrnoend;
 
 } jpc_pocpchg_t;
 
@@ -516,11 +516,11 @@ typedef jpc_pocpchg_t jpc_pchg_t;
 
 typedef struct {
 
-	/* The number of progression order changes. */
-	int numpchgs;
+        /* The number of progression order changes. */
+        int numpchgs;
 
-	/* The per-progression-order-change information. */
-	jpc_pocpchg_t *pchgs;
+        /* The per-progression-order-change information. */
+        jpc_pocpchg_t *pchgs;
 
 } jpc_poc_t;
 
@@ -532,14 +532,14 @@ typedef struct {
 
 typedef struct {
 
-	/* The index. */
-	uint_fast8_t ind;
+        /* The index. */
+        uint_fast8_t ind;
 
-	/* The length. */
-	uint_fast16_t len;
+        /* The length. */
+        uint_fast16_t len;
 
-	/* The data. */
-	unsigned char *data;
+        /* The data. */
+        unsigned char *data;
 
 } jpc_ppm_t;
 
@@ -547,14 +547,14 @@ typedef struct {
 
 typedef struct {
 
-	/* The index. */
-	uint_fast8_t ind;
+        /* The index. */
+        uint_fast8_t ind;
 
-	/* The length. */
-	uint_fast32_t len;
+        /* The length. */
+        uint_fast32_t len;
 
-	/* The data. */
-	unsigned char *data;
+        /* The data. */
+        unsigned char *data;
 
 } jpc_ppt_t;
 
@@ -566,19 +566,19 @@ typedef struct {
  * Registration IDs.
  */
 
-#define	JPC_COM_BIN		0x00
-#define	JPC_COM_LATIN	0x01
+#define JPC_COM_BIN             0x00
+#define JPC_COM_LATIN   0x01
 
 typedef struct {
 
-	/* The registration ID. */
-	uint_fast16_t regid;
+        /* The registration ID. */
+        uint_fast16_t regid;
 
-	/* The length of the data in bytes. */
-	uint_fast16_t len;
+        /* The length of the data in bytes. */
+        uint_fast16_t len;
 
-	/* The data. */
-	unsigned char *data;
+        /* The data. */
+        unsigned char *data;
 
 } jpc_com_t;
 
@@ -588,8 +588,8 @@ typedef struct {
 
 typedef struct {
 
-	/* The sequence number. */
-	uint_fast16_t seqno;
+        /* The sequence number. */
+        uint_fast16_t seqno;
 
 } jpc_sop_t;
 
@@ -601,21 +601,21 @@ typedef struct {
 
 typedef struct {
 
-	/* The horizontal offset. */
-	uint_fast16_t hoff;
+        /* The horizontal offset. */
+        uint_fast16_t hoff;
 
-	/* The vertical offset. */
-	uint_fast16_t voff;
+        /* The vertical offset. */
+        uint_fast16_t voff;
 
 } jpc_crgcomp_t;
 
 typedef struct {
 
-	/* The number of components. */
-	int numcomps;
+        /* The number of components. */
+        int numcomps;
 
-	/* Per component information. */
-	jpc_crgcomp_t *comps;
+        /* Per component information. */
+        jpc_crgcomp_t *comps;
 
 } jpc_crg_t;
 
@@ -625,11 +625,11 @@ typedef struct {
 
 typedef struct {
 
-	/* The data. */
-	unsigned char *data;
+        /* The data. */
+        unsigned char *data;
 
-	/* The length. */
-	uint_fast16_t len;
+        /* The length. */
+        uint_fast16_t len;
 
 } jpc_unk_t;
 
@@ -638,26 +638,26 @@ typedef struct {
 \**************************************/
 
 typedef union {
-	int soc;	/* unused */
-	jpc_sot_t sot;
-	int sod;	/* unused */
-	int eoc;	/* unused */
-	jpc_siz_t siz;
-	jpc_cod_t cod;
-	jpc_coc_t coc;
-	jpc_rgn_t rgn;
-	jpc_qcd_t qcd;
-	jpc_qcc_t qcc;
-	jpc_poc_t poc;
-	/* jpc_plm_t plm; */
-	/* jpc_plt_t plt; */
-	jpc_ppm_t ppm;
-	jpc_ppt_t ppt;
-	jpc_sop_t sop;
-	int eph;	/* unused */
-	jpc_com_t com;
-	jpc_crg_t crg;
-	jpc_unk_t unk;
+        int soc;        /* unused */
+        jpc_sot_t sot;
+        int sod;        /* unused */
+        int eoc;        /* unused */
+        jpc_siz_t siz;
+        jpc_cod_t cod;
+        jpc_coc_t coc;
+        jpc_rgn_t rgn;
+        jpc_qcd_t qcd;
+        jpc_qcc_t qcc;
+        jpc_poc_t poc;
+        /* jpc_plm_t plm; */
+        /* jpc_plt_t plt; */
+        jpc_ppm_t ppm;
+        jpc_ppt_t ppt;
+        jpc_sop_t sop;
+        int eph;        /* unused */
+        jpc_com_t com;
+        jpc_crg_t crg;
+        jpc_unk_t unk;
 } jpc_msparms_t;
 
 /**************************************\
@@ -667,47 +667,47 @@ typedef union {
 /* Marker segment IDs. */
 
 /* The smallest valid marker value. */
-#define	JPC_MS_MIN	0xff00
+#define JPC_MS_MIN      0xff00
 
 /* The largest valid marker value. */
-#define	JPC_MS_MAX	0xffff
+#define JPC_MS_MAX      0xffff
 
 /* The minimum marker value that cannot occur within packet data. */
-#define	JPC_MS_INMIN	0xff80
+#define JPC_MS_INMIN    0xff80
 /* The maximum marker value that cannot occur within packet data. */
-#define	JPC_MS_INMAX	0xffff
+#define JPC_MS_INMAX    0xffff
 
 /* Delimiting marker segments. */
-#define	JPC_MS_SOC	0xff4f /* Start of code stream (SOC). */
-#define	JPC_MS_SOT	0xff90 /* Start of tile-part (SOT). */
-#define	JPC_MS_SOD	0xff93 /* Start of data (SOD). */
-#define	JPC_MS_EOC	0xffd9 /* End of code stream (EOC). */
+#define JPC_MS_SOC      0xff4f /* Start of code stream (SOC). */
+#define JPC_MS_SOT      0xff90 /* Start of tile-part (SOT). */
+#define JPC_MS_SOD      0xff93 /* Start of data (SOD). */
+#define JPC_MS_EOC      0xffd9 /* End of code stream (EOC). */
 
 /* Fixed information marker segments. */
-#define	JPC_MS_SIZ	0xff51 /* Image and tile size (SIZ). */
+#define JPC_MS_SIZ      0xff51 /* Image and tile size (SIZ). */
 
 /* Functional marker segments. */
-#define	JPC_MS_COD	0xff52 /* Coding style default (COD). */
-#define JPC_MS_COC	0xff53 /* Coding style component (COC). */
-#define	JPC_MS_RGN	0xff5e /* Region of interest (RGN). */
-#define JPC_MS_QCD	0xff5c /* Quantization default (QCD). */
-#define JPC_MS_QCC	0xff5d /* Quantization component (QCC). */
-#define JPC_MS_POC	0xff5f /* Progression order default (POC). */
+#define JPC_MS_COD      0xff52 /* Coding style default (COD). */
+#define JPC_MS_COC      0xff53 /* Coding style component (COC). */
+#define JPC_MS_RGN      0xff5e /* Region of interest (RGN). */
+#define JPC_MS_QCD      0xff5c /* Quantization default (QCD). */
+#define JPC_MS_QCC      0xff5d /* Quantization component (QCC). */
+#define JPC_MS_POC      0xff5f /* Progression order default (POC). */
 
 /* Pointer marker segments. */
-#define	JPC_MS_TLM	0xff55 /* Tile-part lengths, main header (TLM). */
-#define	JPC_MS_PLM	0xff57 /* Packet length, main header (PLM). */
-#define	JPC_MS_PLT	0xff58 /* Packet length, tile-part header (PLT). */
-#define	JPC_MS_PPM	0xff60 /* Packed packet headers, main header (PPM). */
-#define	JPC_MS_PPT	0xff61 /* Packet packet headers, tile-part header (PPT). */
+#define JPC_MS_TLM      0xff55 /* Tile-part lengths, main header (TLM). */
+#define JPC_MS_PLM      0xff57 /* Packet length, main header (PLM). */
+#define JPC_MS_PLT      0xff58 /* Packet length, tile-part header (PLT). */
+#define JPC_MS_PPM      0xff60 /* Packed packet headers, main header (PPM). */
+#define JPC_MS_PPT      0xff61 /* Packet packet headers, tile-part header (PPT). */
 
 /* In bit stream marker segments. */
-#define	JPC_MS_SOP	0xff91	/* Start of packet (SOP). */
-#define	JPC_MS_EPH	0xff92	/* End of packet header (EPH). */
+#define JPC_MS_SOP      0xff91  /* Start of packet (SOP). */
+#define JPC_MS_EPH      0xff92  /* End of packet header (EPH). */
 
 /* Informational marker segments. */
-#define	JPC_MS_CRG	0xff63 /* Component registration (CRG). */
-#define JPC_MS_COM	0xff64 /* Comment (COM). */
+#define JPC_MS_CRG      0xff63 /* Component registration (CRG). */
+#define JPC_MS_COM      0xff64 /* Comment (COM). */
 
 /* Forward declaration. */
 struct jpc_msops_s;
@@ -716,20 +716,20 @@ struct jpc_msops_s;
 
 typedef struct {
 
-	/* The type of marker segment. */
-	uint_fast16_t id;
+        /* The type of marker segment. */
+        uint_fast16_t id;
 
-	/* The length of the marker segment. */
-	uint_fast16_t len;
+        /* The length of the marker segment. */
+        uint_fast16_t len;
 
-	/* The starting offset within the stream. */
-	uint_fast32_t off;
+        /* The starting offset within the stream. */
+        uint_fast32_t off;
 
-	/* The parameters of the marker segment. */
-	jpc_msparms_t parms;
+        /* The parameters of the marker segment. */
+        jpc_msparms_t parms;
 
-	/* The marker segment operations. */
-	struct jpc_msops_s *ops;
+        /* The marker segment operations. */
+        struct jpc_msops_s *ops;
 
 } jpc_ms_t;
 
@@ -737,17 +737,17 @@ typedef struct {
 
 typedef struct jpc_msops_s {
 
-	/* Destroy the marker segment parameters. */
-	void (*destroyparms)(jpc_ms_t *ms);
+        /* Destroy the marker segment parameters. */
+        void (*destroyparms)(jpc_ms_t *ms);
 
-	/* Get the marker segment parameters from a stream. */
-	int (*getparms)(jpc_ms_t *ms, jpc_cstate_t *cstate, jas_stream_t *in);
+        /* Get the marker segment parameters from a stream. */
+        int (*getparms)(jpc_ms_t *ms, jpc_cstate_t *cstate, jas_stream_t *in);
 
-	/* Put the marker segment parameters to a stream. */
-	int (*putparms)(jpc_ms_t *ms, jpc_cstate_t *cstate, jas_stream_t *out);
+        /* Put the marker segment parameters to a stream. */
+        int (*putparms)(jpc_ms_t *ms, jpc_cstate_t *cstate, jas_stream_t *out);
 
-	/* Dump the marker segment parameters (for debugging). */
-	int (*dumpparms)(jpc_ms_t *ms, FILE *out);
+        /* Dump the marker segment parameters (for debugging). */
+        int (*dumpparms)(jpc_ms_t *ms, FILE *out);
 
 } jpc_msops_t;
 
@@ -768,13 +768,13 @@ jpc_ms_t *jpc_ms_create(int type);
 void jpc_ms_destroy(jpc_ms_t *ms);
 
 /* Does a marker segment have parameters? */
-#define	JPC_MS_HASPARMS(x) \
-	(!((x) == JPC_MS_SOC || (x) == JPC_MS_SOD || (x) == JPC_MS_EOC || \
-	  (x) == JPC_MS_EPH || ((x) >= 0xff30 && (x) <= 0xff3f)))
+#define JPC_MS_HASPARMS(x) \
+        (!((x) == JPC_MS_SOC || (x) == JPC_MS_SOD || (x) == JPC_MS_EOC || \
+          (x) == JPC_MS_EPH || ((x) >= 0xff30 && (x) <= 0xff3f)))
 
 /* Get the marker segment type. */
-#define	jpc_ms_gettype(ms) \
-	((ms)->id)
+#define jpc_ms_gettype(ms) \
+        ((ms)->id)
 
 /* Read a marker segment from a stream. */
 jpc_ms_t *jpc_getms(jas_stream_t *in, jpc_cstate_t *cstate);
diff --git a/converter/other/jpeg2000/libjasper/jpc/jpc_dec.c b/converter/other/jpeg2000/libjasper/jpc/jpc_dec.c
index 140169ec..1cca46b7 100644
--- a/converter/other/jpeg2000/libjasper/jpc/jpc_dec.c
+++ b/converter/other/jpeg2000/libjasper/jpc/jpc_dec.c
@@ -6,14 +6,14 @@
  */
 
 /* __START_OF_JASPER_LICENSE__
- * 
+ *
  * JasPer Software License
- * 
+ *
  * IMAGE POWER JPEG-2000 PUBLIC LICENSE
  * ************************************
- * 
+ *
  * GRANT:
- * 
+ *
  * Permission is hereby granted, free of charge, to any person (the "User")
  * obtaining a copy of this software and associated documentation, to deal
  * in the JasPer Software without restriction, including without limitation
@@ -21,22 +21,22 @@
  * and/or sell copies of the JasPer Software (in source and binary forms),
  * and to permit persons to whom the JasPer Software is furnished to do so,
  * provided further that the License Conditions below are met.
- * 
+ *
  * License Conditions
  * ******************
- * 
+ *
  * A.  Redistributions of source code must retain the above copyright notice,
  * and this list of conditions, and the following disclaimer.
- * 
+ *
  * B.  Redistributions in binary form must reproduce the above copyright
  * notice, and this list of conditions, and the following disclaimer in
  * the documentation and/or other materials provided with the distribution.
- * 
+ *
  * C.  Neither the name of Image Power, Inc. nor any other contributor
  * (including, but not limited to, the University of British Columbia and
  * Michael David Adams) may be used to endorse or promote products derived
  * from this software without specific prior written permission.
- * 
+ *
  * D.  User agrees that it shall not commence any action against Image Power,
  * Inc., the University of British Columbia, Michael David Adams, or any
  * other contributors (collectively "Licensors") for infringement of any
@@ -56,17 +56,17 @@
  * trade dress, or service mark rights); and (v) divisions, continuations,
  * renewals, reissues and extensions of the foregoing (as and to the extent
  * applicable) now existing, hereafter filed, issued or acquired.
- * 
+ *
  * E.  If User commences an infringement action against any Licensor(s) then
  * such Licensor(s) shall have the right to terminate User's license and
  * all sublicenses that have been granted hereunder by User to other parties.
- * 
+ *
  * F.  This software is for use only in hardware or software products that
  * are compliant with ISO/IEC 15444-1 (i.e., JPEG-2000 Part 1).  No license
  * or right to this Software is granted for products that do not comply
  * with ISO/IEC 15444-1.  The JPEG-2000 Part 1 standard can be purchased
  * from the ISO.
- * 
+ *
  * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS LICENSE.
  * NO USE OF THE JASPER SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER
  * THIS DISCLAIMER.  THE JASPER SOFTWARE IS PROVIDED BY THE LICENSORS AND
@@ -106,7 +106,7 @@
  * TECHNOLOGY OR PRODUCTS FOR HIGH RISK ACTIVITIES AND WILL ENSURE THAT ITS
  * CUSTOMERS AND END-USERS OF ITS PRODUCTS ARE PROVIDED WITH A COPY OF THE
  * NOTICE SPECIFIED IN THIS SECTION.
- * 
+ *
  * __END_OF_JASPER_LICENSE__
  */
 
@@ -793,7 +793,7 @@ rlvl->bands = 0;
                 rlvl->numhprcs = 0;
                 rlvl->numvprcs = 0;
                 continue;
-            }   
+            }  
             if (!rlvlno) {
                 tlcbgxstart = tlprcxstart;
                 tlcbgystart = tlprcystart;
diff --git a/converter/other/jpeg2000/libjasper/jpc/jpc_dec.h b/converter/other/jpeg2000/libjasper/jpc/jpc_dec.h
index fe0e9616..11fceb36 100644
--- a/converter/other/jpeg2000/libjasper/jpc/jpc_dec.h
+++ b/converter/other/jpeg2000/libjasper/jpc/jpc_dec.h
@@ -6,14 +6,14 @@
  */
 
 /* __START_OF_JASPER_LICENSE__
- * 
+ *
  * JasPer Software License
- * 
+ *
  * IMAGE POWER JPEG-2000 PUBLIC LICENSE
  * ************************************
- * 
+ *
  * GRANT:
- * 
+ *
  * Permission is hereby granted, free of charge, to any person (the "User")
  * obtaining a copy of this software and associated documentation, to deal
  * in the JasPer Software without restriction, including without limitation
@@ -21,22 +21,22 @@
  * and/or sell copies of the JasPer Software (in source and binary forms),
  * and to permit persons to whom the JasPer Software is furnished to do so,
  * provided further that the License Conditions below are met.
- * 
+ *
  * License Conditions
  * ******************
- * 
+ *
  * A.  Redistributions of source code must retain the above copyright notice,
  * and this list of conditions, and the following disclaimer.
- * 
+ *
  * B.  Redistributions in binary form must reproduce the above copyright
  * notice, and this list of conditions, and the following disclaimer in
  * the documentation and/or other materials provided with the distribution.
- * 
+ *
  * C.  Neither the name of Image Power, Inc. nor any other contributor
  * (including, but not limited to, the University of British Columbia and
  * Michael David Adams) may be used to endorse or promote products derived
  * from this software without specific prior written permission.
- * 
+ *
  * D.  User agrees that it shall not commence any action against Image Power,
  * Inc., the University of British Columbia, Michael David Adams, or any
  * other contributors (collectively "Licensors") for infringement of any
@@ -56,17 +56,17 @@
  * trade dress, or service mark rights); and (v) divisions, continuations,
  * renewals, reissues and extensions of the foregoing (as and to the extent
  * applicable) now existing, hereafter filed, issued or acquired.
- * 
+ *
  * E.  If User commences an infringement action against any Licensor(s) then
  * such Licensor(s) shall have the right to terminate User's license and
  * all sublicenses that have been granted hereunder by User to other parties.
- * 
+ *
  * F.  This software is for use only in hardware or software products that
  * are compliant with ISO/IEC 15444-1 (i.e., JPEG-2000 Part 1).  No license
  * or right to this Software is granted for products that do not comply
  * with ISO/IEC 15444-1.  The JPEG-2000 Part 1 standard can be purchased
  * from the ISO.
- * 
+ *
  * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS LICENSE.
  * NO USE OF THE JASPER SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER
  * THIS DISCLAIMER.  THE JASPER SOFTWARE IS PROVIDED BY THE LICENSORS AND
@@ -106,7 +106,7 @@
  * TECHNOLOGY OR PRODUCTS FOR HIGH RISK ACTIVITIES AND WILL ENSURE THAT ITS
  * CUSTOMERS AND END-USERS OF ITS PRODUCTS ARE PROVIDED WITH A COPY OF THE
  * NOTICE SPECIFIED IN THIS SECTION.
- * 
+ *
  * __END_OF_JASPER_LICENSE__
  */
 
@@ -141,14 +141,14 @@
 
 typedef struct {
 
-	/* The index for this entry. */
-	uint_fast16_t ind;
+        /* The index for this entry. */
+        uint_fast16_t ind;
 
-	/* The data length. */
-	uint_fast32_t len;
+        /* The data length. */
+        uint_fast32_t len;
 
-	/* The data. */
-	unsigned char *data;
+        /* The data. */
+        unsigned char *data;
 
 } jpc_ppxstabent_t;
 
@@ -156,15 +156,15 @@ typedef struct {
 
 typedef struct {
 
-	/* The number of entries. */
-	int numents;
+        /* The number of entries. */
+        int numents;
 
-	/* The maximum number of entries (i.e., the allocated size of the array
-	  below). */
-	int maxents;
+        /* The maximum number of entries (i.e., the allocated size of the array
+          below). */
+        int maxents;
 
-	/* The table entries. */
-	jpc_ppxstabent_t **ents;
+        /* The table entries. */
+        jpc_ppxstabent_t **ents;
 
 } jpc_ppxstab_t;
 
@@ -172,15 +172,15 @@ typedef struct {
 
 typedef struct {
 
-	/* The number of streams in this list. */
-	int numstreams;
+        /* The number of streams in this list. */
+        int numstreams;
 
-	/* The maximum number of streams that can be accommodated without
-	  growing the streams array. */
-	int maxstreams;
+        /* The maximum number of streams that can be accommodated without
+          growing the streams array. */
+        int maxstreams;
 
-	/* The streams. */
-	jas_stream_t **streams;
+        /* The streams. */
+        jas_stream_t **streams;
 
 } jpc_streamlist_t;
 
@@ -192,47 +192,47 @@ typedef struct {
 
 typedef struct {
 
-	/* How were various coding parameters set? */
-	int flags;
+        /* How were various coding parameters set? */
+        int flags;
 
-	/* Per-component coding style parameters (e.g., explicit precinct sizes) */
-	uint_fast8_t csty;
+        /* Per-component coding style parameters (e.g., explicit precinct sizes) */
+        uint_fast8_t csty;
 
-	/* The number of resolution levels. */
-	uint_fast8_t numrlvls;
+        /* The number of resolution levels. */
+        uint_fast8_t numrlvls;
 
-	/* The code block width exponent. */
-	uint_fast8_t cblkwidthexpn;
+        /* The code block width exponent. */
+        uint_fast8_t cblkwidthexpn;
 
-	/* The code block height exponent. */
-	uint_fast8_t cblkheightexpn;
+        /* The code block height exponent. */
+        uint_fast8_t cblkheightexpn;
 
-	/* The QMFB ID. */
-	uint_fast8_t qmfbid;
+        /* The QMFB ID. */
+        uint_fast8_t qmfbid;
 
-	/* The quantization style. */
-	uint_fast8_t qsty;
+        /* The quantization style. */
+        uint_fast8_t qsty;
 
-	/* The number of quantizer step sizes. */
-	uint_fast16_t numstepsizes;
+        /* The number of quantizer step sizes. */
+        uint_fast16_t numstepsizes;
 
-	/* The step sizes. */
-	uint_fast16_t stepsizes[3 * JPC_MAXRLVLS + 1];
+        /* The step sizes. */
+        uint_fast16_t stepsizes[3 * JPC_MAXRLVLS + 1];
 
-	/* The number of guard bits. */
-	uint_fast8_t numguardbits;
+        /* The number of guard bits. */
+        uint_fast8_t numguardbits;
 
-	/* The ROI shift value. */
-	uint_fast8_t roishift;
+        /* The ROI shift value. */
+        uint_fast8_t roishift;
 
-	/* The code block parameters. */
-	uint_fast8_t cblkctx;
+        /* The code block parameters. */
+        uint_fast8_t cblkctx;
 
-	/* The precinct width exponents. */
-	uint_fast8_t prcwidthexpns[JPC_MAXRLVLS];
+        /* The precinct width exponents. */
+        uint_fast8_t prcwidthexpns[JPC_MAXRLVLS];
 
-	/* The precinct height exponents. */
-	uint_fast8_t prcheightexpns[JPC_MAXRLVLS];
+        /* The precinct height exponents. */
+        uint_fast8_t prcheightexpns[JPC_MAXRLVLS];
 
 } jpc_dec_ccp_t;
 
@@ -240,29 +240,29 @@ typedef struct {
 
 typedef struct {
 
-	/* How were these coding parameters set? */
-	int flags;
+        /* How were these coding parameters set? */
+        int flags;
 
-	/* Progression change list. */
-	jpc_pchglist_t *pchglist;
+        /* Progression change list. */
+        jpc_pchglist_t *pchglist;
 
-	/* Progression order. */
-	uint_fast8_t prgord;
+        /* Progression order. */
+        uint_fast8_t prgord;
 
-	/* The number of layers. */
-	uint_fast16_t numlyrs;
+        /* The number of layers. */
+        uint_fast16_t numlyrs;
 
-	/* The MCT ID. */
-	uint_fast8_t mctid;
+        /* The MCT ID. */
+        uint_fast8_t mctid;
 
-	/* The coding style parameters (e.g., SOP, EPH). */
-	uint_fast8_t csty;
+        /* The coding style parameters (e.g., SOP, EPH). */
+        uint_fast8_t csty;
 
-	/* The number of components. */
-	uint_fast16_t numcomps;
+        /* The number of components. */
+        uint_fast16_t numcomps;
 
-	/* The per-component coding parameters. */
-	jpc_dec_ccp_t *ccps;
+        /* The per-component coding parameters. */
+        jpc_dec_ccp_t *ccps;
 
 } jpc_dec_cp_t;
 
@@ -274,38 +274,38 @@ typedef struct {
 
 typedef struct jpc_dec_seg_s {
 
-	/* The next segment in the list. */
-	struct jpc_dec_seg_s *next;
+        /* The next segment in the list. */
+        struct jpc_dec_seg_s *next;
 
-	/* The previous segment in the list. */
-	struct jpc_dec_seg_s *prev;
+        /* The previous segment in the list. */
+        struct jpc_dec_seg_s *prev;
 
-	/* The starting pass number for this segment. */
-	int passno;
+        /* The starting pass number for this segment. */
+        int passno;
 
-	/* The number of passes in this segment. */
-	int numpasses;
+        /* The number of passes in this segment. */
+        int numpasses;
 
-	/* The maximum number of passes in this segment. */
-	int maxpasses;
+        /* The maximum number of passes in this segment. */
+        int maxpasses;
 
-	/* The type of data in this segment (i.e., MQ or raw). */
-	int type;
+        /* The type of data in this segment (i.e., MQ or raw). */
+        int type;
 
-	/* A stream containing the data for this segment. */
-	jas_stream_t *stream;
+        /* A stream containing the data for this segment. */
+        jas_stream_t *stream;
 
-	/* The number of bytes destined for this segment from the packet
-	  currently being decoded. */
-	int cnt;
+        /* The number of bytes destined for this segment from the packet
+          currently being decoded. */
+        int cnt;
 
-	/* A flag indicating if this segment has been terminated. */
-	int complete;
+        /* A flag indicating if this segment has been terminated. */
+        int complete;
 
-	/* The layer number to which this segment belongs. */
-	/* If the segment spans multiple layers, then the largest layer number
-	  spanned by the segment is used. */
-	int lyrno;
+        /* The layer number to which this segment belongs. */
+        /* If the segment spans multiple layers, then the largest layer number
+          spanned by the segment is used. */
+        int lyrno;
 
 } jpc_dec_seg_t;
 
@@ -313,11 +313,11 @@ typedef struct jpc_dec_seg_s {
 
 typedef struct {
 
-	/* The first entry in the list. */
-	jpc_dec_seg_t *head;
+        /* The first entry in the list. */
+        jpc_dec_seg_t *head;
 
-	/* The last entry in the list. */
-	jpc_dec_seg_t *tail;
+        /* The last entry in the list. */
+        jpc_dec_seg_t *tail;
 
 } jpc_dec_seglist_t;
 
@@ -325,35 +325,35 @@ typedef struct {
 
 typedef struct {
 
-	/* The number of passes. */
-	int numpasses;
+        /* The number of passes. */
+        int numpasses;
 
-	/* A list of segments that still need to be decoded. */
-	jpc_dec_seglist_t segs;
+        /* A list of segments that still need to be decoded. */
+        jpc_dec_seglist_t segs;
 
-	/* The first incomplete/partial segment. */
-	jpc_dec_seg_t *curseg;
+        /* The first incomplete/partial segment. */
+        jpc_dec_seg_t *curseg;
 
-	/* The number of leading insignificant bit planes for this code block. */
-	int numimsbs;
+        /* The number of leading insignificant bit planes for this code block. */
+        int numimsbs;
 
-	/* The number of bits used to encode pass data lengths. */
-	int numlenbits;
+        /* The number of bits used to encode pass data lengths. */
+        int numlenbits;
 
-	/* The first pass number containing data for this code block. */
-	int firstpassno;
+        /* The first pass number containing data for this code block. */
+        int firstpassno;
 
-	/* The MQ decoder. */
-	jpc_mqdec_t *mqdec;
+        /* The MQ decoder. */
+        jpc_mqdec_t *mqdec;
 
-	/* The raw bit stream decoder. */
-	jpc_bitstream_t *nulldec;
+        /* The raw bit stream decoder. */
+        jpc_bitstream_t *nulldec;
 
-	/* The per-sample state information for this code block. */
-	jas_matrix_t *flags;
+        /* The per-sample state information for this code block. */
+        jas_matrix_t *flags;
 
-	/* The sample data associated with this code block. */
-	jas_matrix_t *data;
+        /* The sample data associated with this code block. */
+        jas_matrix_t *data;
 
 } jpc_dec_cblk_t;
 
@@ -361,39 +361,39 @@ typedef struct {
 
 typedef struct {
 
-	/* The x-coordinate of the top-left corner of the precinct. */
-	uint_fast32_t xstart;
+        /* The x-coordinate of the top-left corner of the precinct. */
+        uint_fast32_t xstart;
 
-	/* The y-coordinate of the top-left corner of the precinct. */
-	uint_fast32_t ystart;
+        /* The y-coordinate of the top-left corner of the precinct. */
+        uint_fast32_t ystart;
 
-	/* The x-coordinate of the bottom-right corner of the precinct
-	  (plus one). */
-	uint_fast32_t xend;
+        /* The x-coordinate of the bottom-right corner of the precinct
+          (plus one). */
+        uint_fast32_t xend;
 
-	/* The y-coordinate of the bottom-right corner of the precinct
-	  (plus one). */
-	uint_fast32_t yend;
+        /* The y-coordinate of the bottom-right corner of the precinct
+          (plus one). */
+        uint_fast32_t yend;
 
-	/* The number of code blocks spanning this precinct in the horizontal
-	  direction. */
-	int numhcblks;
+        /* The number of code blocks spanning this precinct in the horizontal
+          direction. */
+        int numhcblks;
 
-	/* The number of code blocks spanning this precinct in the vertical
-	  direction. */
-	int numvcblks;
+        /* The number of code blocks spanning this precinct in the vertical
+          direction. */
+        int numvcblks;
 
-	/* The total number of code blocks in this precinct. */
-	int numcblks;
+        /* The total number of code blocks in this precinct. */
+        int numcblks;
 
-	/* The per code block information. */
-	jpc_dec_cblk_t *cblks;
+        /* The per code block information. */
+        jpc_dec_cblk_t *cblks;
 
-	/* The inclusion tag tree. */
-	jpc_tagtree_t *incltagtree;
+        /* The inclusion tag tree. */
+        jpc_tagtree_t *incltagtree;
 
-	/* The insignificant MSBs tag tree. */
-	jpc_tagtree_t *numimsbstagtree;
+        /* The insignificant MSBs tag tree. */
+        jpc_tagtree_t *numimsbstagtree;
 
 } jpc_dec_prc_t;
 
@@ -401,29 +401,29 @@ typedef struct {
 
 typedef struct {
 
-	/* The per-code-block-group state information. */
-	jpc_dec_prc_t *prcs;
+        /* The per-code-block-group state information. */
+        jpc_dec_prc_t *prcs;
 
-	/* The sample data associated with this band. */
-	jas_matrix_t *data;
+        /* The sample data associated with this band. */
+        jas_matrix_t *data;
 
-	/* The orientation of this band (i.e., LL, LH, HL, or HH). */
-	int orient;
+        /* The orientation of this band (i.e., LL, LH, HL, or HH). */
+        int orient;
 
-	/* The encoded quantizer step size. */
-	int stepsize;
+        /* The encoded quantizer step size. */
+        int stepsize;
 
-	/* The absolute quantizer step size. */
-	jpc_fix_t absstepsize;
+        /* The absolute quantizer step size. */
+        jpc_fix_t absstepsize;
 
-	/* The number of bit planes for this band. */
-	int numbps;
+        /* The number of bit planes for this band. */
+        int numbps;
 
-	/* The analysis gain associated with this band. */
-	int analgain;
+        /* The analysis gain associated with this band. */
+        int analgain;
 
-	/* The ROI shift value for this band. */
-	int roishift;
+        /* The ROI shift value for this band. */
+        int roishift;
 
 } jpc_dec_band_t;
 
@@ -431,60 +431,60 @@ typedef struct {
 
 typedef struct {
 
-	/* The number of bands associated with this resolution level. */
-	int numbands;
+        /* The number of bands associated with this resolution level. */
+        int numbands;
 
-	/* The per-band information. */
-	jpc_dec_band_t *bands;
+        /* The per-band information. */
+        jpc_dec_band_t *bands;
 
-	/* The x-coordinate of the top-left corner of the tile-component
-	  at this resolution. */
-	uint_fast32_t xstart;
+        /* The x-coordinate of the top-left corner of the tile-component
+          at this resolution. */
+        uint_fast32_t xstart;
 
-	/* The y-coordinate of the top-left corner of the tile-component
-	  at this resolution. */
-	uint_fast32_t ystart;
+        /* The y-coordinate of the top-left corner of the tile-component
+          at this resolution. */
+        uint_fast32_t ystart;
 
-	/* The x-coordinate of the bottom-right corner of the tile-component
-	  at this resolution (plus one). */
-	uint_fast32_t xend;
+        /* The x-coordinate of the bottom-right corner of the tile-component
+          at this resolution (plus one). */
+        uint_fast32_t xend;
 
-	/* The y-coordinate of the bottom-right corner of the tile-component
-	  at this resolution (plus one). */
-	uint_fast32_t yend;
+        /* The y-coordinate of the bottom-right corner of the tile-component
+          at this resolution (plus one). */
+        uint_fast32_t yend;
 
-	/* The exponent value for the nominal precinct width measured
-	  relative to the associated LL band. */
-	int prcwidthexpn;
+        /* 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 exponent value for the nominal precinct height measured
+          relative to the associated LL band. */
+        int prcheightexpn;
 
-	/* The number of precincts in the horizontal direction. */
-	int numhprcs;
+        /* The number of precincts in the horizontal direction. */
+        int numhprcs;
 
-	/* The number of precincts in the vertical direction. */
-	int numvprcs;
+        /* The number of precincts in the vertical direction. */
+        int numvprcs;
 
-	/* The total number of precincts. */
-	int numprcs;
+        /* The total number of precincts. */
+        int 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). */
-	int cbgwidthexpn;
+        /* 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). */
+        int 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). */
-	int cbgheightexpn;
+        /* 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). */
+        int cbgheightexpn;
 
-	/* The exponent value for the code block width. */
-	uint_fast16_t cblkwidthexpn;
+        /* 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 exponent value for the code block height. */
+        uint_fast16_t cblkheightexpn;
 
 } jpc_dec_rlvl_t;
 
@@ -492,33 +492,33 @@ typedef struct {
 
 typedef struct {
 
-	/* The x-coordinate of the top-left corner of the tile-component
-	  in the coordinate system of the tile-component. */
-	uint_fast32_t xstart;
+        /* The x-coordinate of the top-left corner of the tile-component
+          in the coordinate system of the tile-component. */
+        uint_fast32_t xstart;
 
-	/* The y-coordinate of the top-left corner of the tile-component
-	  in the coordinate system of the tile-component. */
-	uint_fast32_t ystart;
+        /* The y-coordinate of the top-left corner of the tile-component
+          in the coordinate system of the tile-component. */
+        uint_fast32_t ystart;
 
-	/* The x-coordinate of the bottom-right corner of the tile-component
-	  in the coordinate system of the tile-component (plus one). */
-	uint_fast32_t xend;
+        /* The x-coordinate of the bottom-right corner of the tile-component
+          in the coordinate system of the tile-component (plus one). */
+        uint_fast32_t xend;
 
-	/* The y-coordinate of the bottom-right corner of the tile-component
-	  in the coordinate system of the tile-component (plus one). */
-	uint_fast32_t yend;
+        /* The y-coordinate of the bottom-right corner of the tile-component
+          in the coordinate system of the tile-component (plus one). */
+        uint_fast32_t yend;
 
-	/* The component data for the current tile. */
-	jas_matrix_t *data;
+        /* The component data for the current tile. */
+        jas_matrix_t *data;
 
-	/* The number of resolution levels. */
-	uint_fast16_t numrlvls;
+        /* The number of resolution levels. */
+        uint_fast16_t numrlvls;
 
-	/* The per resolution level information. */
-	jpc_dec_rlvl_t *rlvls;
+        /* The per resolution level information. */
+        jpc_dec_rlvl_t *rlvls;
 
-	/* The TSFB. */
-	jpc_tsfb_t *tsfb;
+        /* The TSFB. */
+        jpc_tsfb_t *tsfb;
 
 } jpc_dec_tcomp_t;
 
@@ -526,60 +526,60 @@ typedef struct {
  * Tile states.
  */
 
-#define	JPC_TILE_INIT	0
-#define	JPC_TILE_ACTIVE	1
-#define	JPC_TILE_ACTIVELAST	2
-#define	JPC_TILE_DONE	3
+#define JPC_TILE_INIT   0
+#define JPC_TILE_ACTIVE 1
+#define JPC_TILE_ACTIVELAST     2
+#define JPC_TILE_DONE   3
 
 /* Decoder per-tile state information. */
 
 typedef struct {
 
-	/* The processing state for this tile. */
-	int state;
+        /* The processing state for this tile. */
+        int state;
 
-	/* The x-coordinate of the top-left corner of the tile on the reference
-	  grid. */
-	uint_fast32_t xstart;
+        /* The x-coordinate of the top-left corner of the tile on the reference
+          grid. */
+        uint_fast32_t xstart;
 
-	/* The y-coordinate of the top-left corner of the tile on the reference
-	  grid. */
-	uint_fast32_t ystart;
+        /* The y-coordinate of the top-left corner of the tile on the reference
+          grid. */
+        uint_fast32_t ystart;
 
-	/* The x-coordinate of the bottom-right corner of the tile on the
-	  reference grid (plus one). */
-	uint_fast32_t xend;
+        /* The x-coordinate of the bottom-right corner of the tile on the
+          reference grid (plus one). */
+        uint_fast32_t xend;
 
-	/* The y-coordinate of the bottom-right corner of the tile on the
-	  reference grid (plus one). */
-	uint_fast32_t yend;
+        /* The y-coordinate of the bottom-right corner of the tile on the
+          reference grid (plus one). */
+        uint_fast32_t yend;
 
-	/* The packed packet header data for this tile. */
-	jpc_ppxstab_t *pptstab;
+        /* The packed packet header data for this tile. */
+        jpc_ppxstab_t *pptstab;
 
-	/* A stream containing the packed packet header data for this tile. */
-	jas_stream_t *pkthdrstream;
+        /* A stream containing the packed packet header data for this tile. */
+        jas_stream_t *pkthdrstream;
 
-	/* The current position within the packed packet header stream. */
-	long pkthdrstreampos;
+        /* The current position within the packed packet header stream. */
+        long pkthdrstreampos;
 
-	/* The coding parameters for this tile. */
-	jpc_dec_cp_t *cp;
+        /* The coding parameters for this tile. */
+        jpc_dec_cp_t *cp;
 
-	/* The per tile-component information. */
-	jpc_dec_tcomp_t *tcomps;
+        /* The per tile-component information. */
+        jpc_dec_tcomp_t *tcomps;
 
-	/* The next expected tile-part number. */
-	int partno;
+        /* The next expected tile-part number. */
+        int partno;
 
-	/* The number of tile-parts. */
-	int numparts;
+        /* The number of tile-parts. */
+        int numparts;
 
-	/* The coding mode. */
-	int realmode;
+        /* The coding mode. */
+        int realmode;
 
-	/* The packet iterator for this tile. */
-	jpc_pi_t *pi;
+        /* The packet iterator for this tile. */
+        jpc_pi_t *pi;
 
 } jpc_dec_tile_t;
 
@@ -587,29 +587,29 @@ typedef struct {
 
 typedef struct {
 
-	/* The horizontal sampling period. */
-	uint_fast32_t hstep;
+        /* The horizontal sampling period. */
+        uint_fast32_t hstep;
 
-	/* The vertical sampling period. */
-	uint_fast32_t vstep;
+        /* The vertical sampling period. */
+        uint_fast32_t vstep;
 
-	/* The number of samples in the horizontal direction. */
-	uint_fast32_t width;
+        /* The number of samples in the horizontal direction. */
+        uint_fast32_t width;
 
-	/* The number of samples in the vertical direction. */
-	uint_fast32_t height;
+        /* The number of samples in the vertical direction. */
+        uint_fast32_t height;
 
-	/* The precision of the sample data. */
-	uint_fast16_t prec;
+        /* The precision of the sample data. */
+        uint_fast16_t prec;
 
-	/* The signedness of the sample data. */
-	bool sgnd;
+        /* The signedness of the sample data. */
+        bool sgnd;
 
-	/* The sample alignment horizontal offset. */
-	uint_fast32_t hsubstep;
-	
-	/* The sample alignment vertical offset. */
-	uint_fast32_t vsubstep;
+        /* The sample alignment horizontal offset. */
+        uint_fast32_t hsubstep;
+       
+        /* The sample alignment vertical offset. */
+        uint_fast32_t vsubstep;
 
 } jpc_dec_cmpt_t;
 
@@ -617,96 +617,96 @@ typedef struct {
 
 typedef struct {
 
-	/* The decoded image. */
-	jas_image_t *image;
+        /* The decoded image. */
+        jas_image_t *image;
 
-	/* The x-coordinate of the top-left corner of the image area on
-	  the reference grid. */
-	uint_fast32_t xstart;
+        /* The x-coordinate of the top-left corner of the image area on
+          the reference grid. */
+        uint_fast32_t xstart;
 
-	/* The y-coordinate of the top-left corner of the image area on
-	  the reference grid. */
-	uint_fast32_t ystart;
+        /* The y-coordinate of the top-left corner of the image area on
+          the reference grid. */
+        uint_fast32_t ystart;
 
-	/* The x-coordinate of the bottom-right corner of the image area on
-	  the reference grid (plus one). */
-	uint_fast32_t xend;
+        /* The x-coordinate of the bottom-right corner of the image area on
+          the reference grid (plus one). */
+        uint_fast32_t xend;
 
-	/* The y-coordinate of the bottom-right corner of the image area on
-	  the reference grid (plus one). */
-	uint_fast32_t yend;
+        /* The y-coordinate of the bottom-right corner of the image area on
+          the reference grid (plus one). */
+        uint_fast32_t yend;
 
-	/* The nominal tile width in units of the image reference grid. */
-	uint_fast32_t tilewidth;
+        /* The nominal tile 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 nominal tile height in units of the image reference grid. */
+        uint_fast32_t tileheight;
 
-	/* The horizontal offset from the origin of the reference grid to the
-	  left side of the first tile. */
-	uint_fast32_t tilexoff;
+        /* The horizontal offset from the origin of the reference grid to the
+          left side of the first tile. */
+        uint_fast32_t tilexoff;
 
-	/* The vertical offset from the origin of the reference grid to the
-	  top side of the first tile. */
-	uint_fast32_t tileyoff;
+        /* The vertical offset from the origin of the reference grid to the
+          top side of the first tile. */
+        uint_fast32_t tileyoff;
 
-	/* The number of tiles spanning the image area in the vertical
-	  direction. */
-	int numhtiles;
+        /* The number of tiles spanning the image area in the vertical
+          direction. */
+        int numhtiles;
 
-	/* The number of tiles spanning the image area in the horizontal
-	  direction. */
-	int numvtiles;
+        /* The number of tiles spanning the image area in the horizontal
+          direction. */
+        int numvtiles;
 
-	/* The total number of tiles. */
-	int numtiles;
+        /* The total number of tiles. */
+        int numtiles;
 
-	/* The per-tile information. */
-	jpc_dec_tile_t *tiles;
+        /* The per-tile information. */
+        jpc_dec_tile_t *tiles;
 
-	/* The tile currently being processed. */
-	jpc_dec_tile_t *curtile;
+        /* The tile currently being processed. */
+        jpc_dec_tile_t *curtile;
 
-	/* The number of components. */
-	int numcomps;
+        /* The number of components. */
+        int numcomps;
 
-	/* The stream containing the input JPEG-2000 code stream data. */
-	jas_stream_t *in;
+        /* The stream containing the input JPEG-2000 code stream data. */
+        jas_stream_t *in;
 
-	/* The default coding parameters for all tiles. */
-	jpc_dec_cp_t *cp;
+        /* The default coding parameters for all tiles. */
+        jpc_dec_cp_t *cp;
 
-	/* The maximum number of layers that may be decoded. */
-	int maxlyrs;
+        /* The maximum number of layers that may be decoded. */
+        int maxlyrs;
 
-	/* The maximum number of packets that may be decoded. */
-	int maxpkts;
+        /* The maximum number of packets that may be decoded. */
+        int maxpkts;
 
-	/* The number of packets decoded so far in the processing of the entire
-	  code stream. */
-	int numpkts;
+        /* The number of packets decoded so far in the processing of the entire
+          code stream. */
+        int numpkts;
 
-	/* The next expected PPM marker segment sequence number. */
-	int ppmseqno;
+        /* The next expected PPM marker segment sequence number. */
+        int ppmseqno;
 
-	/* The current state for code stream processing. */
-	int state;
+        /* The current state for code stream processing. */
+        int state;
 
-	/* The per-component information. */
-	jpc_dec_cmpt_t *cmpts;
+        /* The per-component information. */
+        jpc_dec_cmpt_t *cmpts;
 
-	/* The information from PPM marker segments. */
-	jpc_ppxstab_t *ppmstab;
+        /* The information from PPM marker segments. */
+        jpc_ppxstab_t *ppmstab;
 
-	/* A list of streams containing packet header data from PPM marker
-	  segments. */
-	jpc_streamlist_t *pkthdrstreams;
+        /* A list of streams containing packet header data from PPM marker
+          segments. */
+        jpc_streamlist_t *pkthdrstreams;
 
-	/* The expected ending offset for a tile-part. */
-	long curtileendoff;
+        /* The expected ending offset for a tile-part. */
+        long curtileendoff;
 
-	/* This is required by the tier-2 decoder. */
-	jpc_cstate_t *cstate;
+        /* This is required by the tier-2 decoder. */
+        jpc_cstate_t *cstate;
 
 } jpc_dec_t;
 
@@ -714,14 +714,14 @@ typedef struct {
 
 typedef struct {
 
-	/* The debug level for the decoder. */
-	int debug;
+        /* The debug level for the decoder. */
+        int debug;
 
-	/* The maximum number of layers to decode. */
-	int maxlyrs;
+        /* The maximum number of layers to decode. */
+        int maxlyrs;
 
-	/* The maximum number of packets to decode. */
-	int maxpkts;
+        /* The maximum number of packets to decode. */
+        int maxpkts;
 
 } jpc_dec_importopts_t;
 
diff --git a/converter/other/jpeg2000/libjasper/jpc/jpc_enc.c b/converter/other/jpeg2000/libjasper/jpc/jpc_enc.c
index 9db41ca2..eb2020bf 100644
--- a/converter/other/jpeg2000/libjasper/jpc/jpc_enc.c
+++ b/converter/other/jpeg2000/libjasper/jpc/jpc_enc.c
@@ -11,7 +11,6 @@
 #include "jasper/jas_string.h"
 #include "jasper/jas_malloc.h"
 #include "jasper/jas_image.h"
-#include "jasper/jas_fix.h"
 #include "jasper/jas_tvp.h"
 #include "jasper/jas_version.h"
 #include "jasper/jas_math.h"
@@ -69,7 +68,6 @@ static void prc_destroy(jpc_enc_prc_t *prcs);
 static jpc_enc_cblk_t *cblk_create(jpc_enc_cblk_t *cblk, jpc_enc_cp_t *cp,
   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);
 
@@ -78,17 +76,8 @@ void jpc_enc_dump(jpc_enc_t *enc);
 \*****************************************************************************/
 
 void quantize(jas_matrix_t *data, jpc_fix_t stepsize);
-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);
 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 setins(int numvalues, jpc_flt_t *values, jpc_flt_t value);
-static jpc_enc_cp_t *cp_create(char *optstr, jas_image_t *image);
-void jpc_enc_cp_destroy(jpc_enc_cp_t *cp);
 
 
 
@@ -143,7 +132,6 @@ typedef enum {
     OPT_NUMGBITS,
     OPT_RATE,
     OPT_ILYRRATES,
-    OPT_JP2OVERHEAD
 } optid_t;
 
 jas_taginfo_t encopts[] = {
@@ -173,7 +161,6 @@ jas_taginfo_t encopts[] = {
     {OPT_NUMGBITS, "numgbits"},
     {OPT_RATE, "rate"},
     {OPT_ILYRRATES, "ilyrrates"},
-    {OPT_JP2OVERHEAD, "_jp2overhead"},
     {-1, 0}
 };
 
@@ -230,72 +217,46 @@ trace(const char * const fmt, ...) {
 
 
 
-int
-jpc_encode(jas_image_t *image, jas_stream_t *out, char *optstr) {
-
-    jpc_enc_t *enc;
-    jpc_enc_cp_t *cp;
-
-    enc = 0;
-    cp = 0;
-
-    jpc_initluts();
-
-    if (!(cp = cp_create(optstr, image))) {
-        fprintf(stderr, "invalid JP encoder options\n");
-        goto error;
-    }
-
-    if (!(enc = jpc_enc_create(cp, out, image))) {
-        goto error;
-    }
-    cp = 0;
+/*****************************************************************************\
+* Option parsing code.
+\*****************************************************************************/
 
-    /* Encode the main header. */
-    if (jpc_enc_encodemainhdr(enc)) {
-        goto error;
-    }
+static void
+ratestrtosize(const char *    const s,
+              uint_fast32_t   const rawsize,
+              uint_fast32_t * const sizeP) {
 
-    /* Encode the main body.  This constitutes most of the encoding work. */
-    if (jpc_enc_encodemainbody(enc)) {
-        goto error;
-    }
+    if (strchr(s, 'B')) {
+        *sizeP = atoi(s);
+    } else {
+        jpc_flt_t const f = atof(s);
 
-    /* Write EOC marker segment. */
-    if (!(enc->mrk = jpc_ms_create(JPC_MS_EOC))) {
-        goto error;
-    }
-    if (jpc_putms(enc->out, enc->cstate, enc->mrk)) {
-        fprintf(stderr, "cannot write EOI marker\n");
-        goto error;
+        if (f < 0) {
+            *sizeP = 0;
+        } else if (f > 1.0) {
+            *sizeP = rawsize + 1;
+        } else {
+            *sizeP = f * rawsize;
+        }
     }
-    jpc_ms_destroy(enc->mrk);
-    enc->mrk = 0;
+}
 
-    if (jas_stream_flush(enc->out)) {
-        goto error;
-    }
 
-    jpc_enc_destroy(enc);
 
-    return 0;
+static void
+cp_destroy(jpc_enc_cp_t *cp) {
 
-error:
-    if (cp) {
-        jpc_enc_cp_destroy(cp);
-    }
-    if (enc) {
-        jpc_enc_destroy(enc);
+    if (cp->ccps) {
+        if (cp->tcp.ilyrrates) {
+            jas_free(cp->tcp.ilyrrates);
+        }
+        jas_free(cp->ccps);
     }
-    return -1;
+    jas_free(cp);
 }
 
 
 
-/*****************************************************************************\
-* Option parsing code.
-\*****************************************************************************/
-
 static jpc_enc_cp_t *
 cp_create(char *optstr, jas_image_t *image) {
 
@@ -314,7 +275,6 @@ cp_create(char *optstr, jas_image_t *image) {
     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;
@@ -332,7 +292,6 @@ cp_create(char *optstr, jas_image_t *image) {
     prcwidthexpn = 15;
     prcheightexpn = 15;
     enablemct = true;
-    jp2overhead = 0;
 
     cp->ccps = 0;
     cp->debug = 0;
@@ -380,6 +339,10 @@ cp_create(char *optstr, jas_image_t *image) {
 
     cp->rawsize = jas_image_rawsize(image);
     cp->totalsize = UINT_FAST32_MAX;
+        /* Set default value, the special value that means size is unlimited
+           (so lossless coding is called for).  To be overridden if user
+           specified
+        */
 
     tcp = &cp->tcp;
     tcp->csty = 0;
@@ -492,12 +455,8 @@ cp_create(char *optstr, jas_image_t *image) {
             cp->tccp.numgbits = atoi(jas_tvparser_getval(tvp));
             break;
         case OPT_RATE:
-            if (ratestrtosize(jas_tvparser_getval(tvp), cp->rawsize,
-              &cp->totalsize)) {
-                fprintf(stderr,
-                  "ignoring bad rate specifier %s\n",
-                  jas_tvparser_getval(tvp));
-            }
+            ratestrtosize(jas_tvparser_getval(tvp), cp->rawsize,
+                          &cp->totalsize);
             break;
         case OPT_ILYRRATES:
             if (jpc_atoaf(jas_tvparser_getval(tvp), &numilyrrates,
@@ -505,13 +464,10 @@ cp_create(char *optstr, jas_image_t *image) {
                 fprintf(stderr,
                         "warning: invalid intermediate layer rates specifier "
                         "ignored (%s)\n",
-                  jas_tvparser_getval(tvp));
+                        jas_tvparser_getval(tvp));
             }
             break;
 
-        case OPT_JP2OVERHEAD:
-            jp2overhead = atoi(jas_tvparser_getval(tvp));
-            break;
         default:
             fprintf(stderr, "warning: ignoring invalid option %s\n",
              jas_tvparser_gettag(tvp));
@@ -522,11 +478,6 @@ cp_create(char *optstr, jas_image_t *image) {
     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 {
@@ -697,20 +648,28 @@ cp_create(char *optstr, jas_image_t *image) {
         /* The intermediate layers rates must increase monotonically. */
         for (lyrno = 0; lyrno + 2 < tcp->numlyrs; ++lyrno) {
             if (tcp->ilyrrates[lyrno] >= tcp->ilyrrates[lyrno + 1]) {
-                fprintf(stderr,
-                        "intermediate layer rates must increase "
-                        "monotonically\n");
+                pm_message("Compression rate for Layer %u (%f) "
+                           "is not greater than that for Layer %u (%f).  "
+                           "Rates must increase at every layer",
+                           (unsigned)(lyrno+1),
+                           jpc_fixtodbl(tcp->ilyrrates[lyrno + 1]),
+                           (unsigned)lyrno,
+                           jpc_fixtodbl(tcp->ilyrrates[lyrno]));
                 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) {
-                    fprintf(stderr,
-                            "warning: intermediate layer rates must be "
-                            "less than overall rate\n");
+                double const thisLyrRate = jpc_fixtodbl(tcp->ilyrrates[lyrno]);
+                double const completeRate =
+                    ((double) cp->totalsize) / cp->rawsize;
+                if (thisLyrRate > completeRate) {
+                    pm_message(
+                        "Compression rate for Layer %u is %f, "
+                        "which is greater than the rate for the complete "
+                        "image (%f)",
+                        (unsigned)lyrno, thisLyrRate, completeRate);
                     goto error;
                 }
             }
@@ -732,118 +691,17 @@ error:
         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) {
-
-    char *cp;
-    jpc_flt_t f;
-
-    /* Note: This function must not modify output size on failure. */
-    if ((cp = 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;
-
-    enc = 0;
-
-    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);
+        cp_destroy(cp);
     }
     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);
-    }
-
-    jas_free(enc);
-}
-
-
-
 static int
-jpc_enc_encodemainhdr(jpc_enc_t *enc) {
+encodemainhdr(jpc_enc_t *enc) {
+
+    uint_fast32_t const maintlrlen = 2;
 
     jpc_siz_t *siz;
     jpc_cod_t *cod;
@@ -961,7 +819,7 @@ jpc_enc_encodemainhdr(jpc_enc_t *enc) {
                   (analgain + 1)), bandinfo->synenergywt);
             } else {
                 absstepsize = jpc_inttofix(1);
-            }   
+            }
             cp->ccps[cmptno].stepsizes[bandno] =
               jpc_abstorelstepsize(absstepsize,
               cp->ccps[cmptno].prec + analgain);
@@ -1038,61 +896,32 @@ jpc_enc_encodemainhdr(jpc_enc_t *enc) {
         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;
-}
-
-
-
-int
-jpc_enc_encodetiledata(jpc_enc_t *enc) {
-
-    assert(enc->tmpstream);
-    if (jpc_enc_encpkts(enc, enc->tmpstream)) {
-        return -1;
-    }
-    return 0;
-}
-
-
-
-void
-quantize(jas_matrix_t *data, jpc_fix_t stepsize) {
+        uint_fast32_t const overhead = mainhdrlen + maintlrlen;
 
-    int i;
-    int j;
-    jpc_fix_t t;
-
-    if (stepsize == jpc_inttofix(1)) {
-        return;
-    }
-
-    for (i = 0; i < jas_matrix_numrows(data); ++i) {
-        for (j = 0; j < jas_matrix_numcols(data); ++j) {
-            t = jas_matrix_get(data, i, j);
+        if (overhead > enc->cp->totalsize) {
+            pm_message("Requested limit on image size of %u bytes "
+                       "is not possible because it is less than "
+                       "the image metadata size (%u bytes)",
+                       (unsigned)enc->cp->totalsize, (unsigned)overhead);
+            return -1;
+        }
+        enc->mainbodysize = enc->cp->totalsize - overhead;
+        /* This has never actually worked.  'totalsize' is supposed to be
+           the total all-in, so if you request total size 200, you should
+           get an output file 200 bytes or smaller; but we see 209 bytes.
+           Furthermore, at 194 bytes, we get a warning that an empty layer
+           is generated, which probably is actually an error.
 
-{
-    if (t < 0) {
-        t = jpc_fix_neg(jpc_fix_div(jpc_fix_neg(t), stepsize));
+           We should fix this some day.
+        */
     } else {
-        t = jpc_fix_div(t, stepsize);
+        enc->mainbodysize = UINT_FAST32_MAX;
     }
-}
 
-            jas_matrix_set(data, i, j, t);
-        }
-    }
+    return 0;
 }
 
 
@@ -1166,12 +995,12 @@ calcrdslopes(jpc_enc_cblk_t *cblk) {
 
 static void
 traceLayerSizes(const uint_fast32_t * const lyrSizes,
-                unsigned int          const layerCt) {
+                uint_fast32_t         const layerCt) {
 
     if (jas_getdbglevel() > 0) {
-        unsigned int i;
+        uint_fast32_t i;
         for (i = 0; i < layerCt; ++i) {
-            fprintf(stderr, "Layer %u size = ", i);
+            fprintf(stderr, "Layer %u size = ", (unsigned)i);
 
             if (lyrSizes[i] == UINT_FAST32_MAX)
                 fprintf(stderr, "Unlimited");
@@ -1189,48 +1018,28 @@ computeLayerSizes(jpc_enc_t *      const encP,
                   jpc_enc_tile_t * const tileP,
                   jpc_enc_cp_t *   const cpP,
                   double           const rho,
-                  long             const tilehdrlen,
-                  const char **    const errorP) {
+                  long             const tilehdrlen) {
 
     /* Note that in allowed sizes, UINT_FAST32_MAX is a special value meaning
        "unlimited".
     */
 
-    unsigned int const lastLyrno = tileP->numlyrs - 1;
+    uint_fast32_t const lastLyrno = tileP->numlyrs - 1;
 
-    unsigned int lyrno;
+    uint_fast32_t lyrno;
 
     assert(tileP->numlyrs > 0);
 
     for (lyrno = 0; lyrno < lastLyrno; ++lyrno) {
-        tileP->lyrsizes[lyrno] = tileP->rawsize * jpc_fixtodbl(
-            cpP->tcp.ilyrrates[lyrno]);
+        tileP->lyrsizes[lyrno] =
+            MAX(tileP->rawsize *
+                jpc_fixtodbl(cpP->tcp.ilyrrates[lyrno]),
+                tilehdrlen + 1) - tilehdrlen;
     }
 
     tileP->lyrsizes[lastLyrno] =
-        (cpP->totalsize != UINT_FAST32_MAX) ?
-        (rho * encP->mainbodysize) : UINT_FAST32_MAX;
-
-
-    /* Subtract 'tilehdrlen' from every layer. */
-
-    for (lyrno = 0; lyrno < tileP->numlyrs; ++lyrno) {
-        if (tileP->lyrsizes[lyrno] != UINT_FAST32_MAX) {
-            if (tilehdrlen <= tileP->lyrsizes[lyrno]) {
-                tileP->lyrsizes[lyrno] -= tilehdrlen;
-            } else {
-                tileP->lyrsizes[lyrno] = 0;
-            }
-        }
-    }
-
-    if (tileP->lyrsizes[lastLyrno] < 1)
-        pm_asprintf(errorP, "Cannot make image that small (%u bytes).  "
-                    "Even with pixels compressed as far as possible, metadata "
-                    "would exceed the limit",
-                    (unsigned)cpP->totalsize);
-    else
-        *errorP = NULL;
+        (cpP->totalsize == UINT_FAST32_MAX) ?
+        UINT_FAST32_MAX : (rho * encP->mainbodysize);
 
     traceLayerSizes(tileP->lyrsizes, tileP->numlyrs);
 }
@@ -1313,8 +1122,8 @@ trace_layeringinfo(jpc_enc_t * const encP) {
 
 static void
 validateCumlensIncreases(const uint_fast32_t * const cumlens,
-                         unsigned int          const numlyrs) {
-    unsigned int lyrno;
+                         uint_fast32_t          const numlyrs) {
+    uint_fast32_t lyrno;
 
     for (lyrno = 1; lyrno < numlyrs - 1; ++lyrno) {
         if (cumlens[lyrno - 1] > cumlens[lyrno]) {
@@ -1404,7 +1213,7 @@ findMinMaxRDSlopeValues(jpc_enc_tile_t * const tileP,
 static void
 performTier2CodingOneLayer(jpc_enc_t *      const encP,
                            jpc_enc_tile_t * const tileP,
-                           unsigned int     const lyrno,
+                           uint_fast32_t     const lyrno,
                            jas_stream_t *   const outP,
                            const char **    const errorP) {
 /*----------------------------------------------------------------------------
@@ -1444,9 +1253,9 @@ performTier2CodingOneLayer(jpc_enc_t *      const encP,
 static void
 assignHighSlopePassesToLayer(jpc_enc_t *      const encP,
                              jpc_enc_tile_t * const tileP,
-                             unsigned int     const lyrno,
-                             bool             const haveThresh,
-                             jpc_flt_t        const thresh) {
+                             uint_fast32_t     const lyrno,
+                             bool              const haveThresh,
+                             jpc_flt_t         const thresh) {
 /*----------------------------------------------------------------------------
   Assign all passes with R-D slopes greater than or equal to 'thresh' to layer
   'lyrno' and the rest to no layer.
@@ -1505,8 +1314,7 @@ assignHighSlopePassesToLayer(jpc_enc_t *      const encP,
                                         for (; passP != endpassesP; ++passP) {
                                             passP->lyrno = -1;
                                         }
-                                    
-                                    }   
+                                    }
                                 }
                             }
                         }
@@ -1522,7 +1330,7 @@ assignHighSlopePassesToLayer(jpc_enc_t *      const encP,
 static void
 doLayer(jpc_enc_t *      const encP,
         jpc_enc_tile_t * const tileP,
-        unsigned int     const lyrno,
+        uint_fast32_t    const lyrno,
         uint_fast32_t    const allowedSize,
         jpc_flt_t        const mnrdslope,
         jpc_flt_t        const mxrdslope,
@@ -1550,7 +1358,7 @@ doLayer(jpc_enc_t *      const encP,
         long pos;
         jpc_flt_t lo;
         jpc_flt_t hi;
-        unsigned int numiters;
+        uint_fast32_t numiters;
 
         lo = mnrdslope;  /* initial value */
         hi = mxrdslope;  /* initial value */
@@ -1559,52 +1367,46 @@ doLayer(jpc_enc_t *      const encP,
         goodThresh = 0;     /* initial value */
 
         do {
-            if (allowedSize == UINT_FAST32_MAX) {
-                /* There's no rate constraint (This can be true of the last
-                   layer, e.g. for lossless coding). */
-                goodThresh = -1;
-                haveGoodThresh = true;
-            } else {
-                jpc_flt_t const thresh = (lo + hi) / 2;
-
-                int rc;
-                long oldpos;
-
-                /* Save the tier 2 coding state. */
-                jpc_save_t2state(encP);
-                oldpos = jas_stream_tell(outP);
-                assert(oldpos >= 0);
-
-                assignHighSlopePassesToLayer(encP, tileP, lyrno, true, thresh);
-
-                performTier2CodingOneLayer(encP, tileP, lyrno, outP, errorP);
-
-                if (!*errorP) {
-                    pos = jas_stream_tell(outP);
-
-                    /* Check the rate constraint. */
-                    assert(pos >= 0);
-                    if (pos > allowedSize) {
-                        /* The rate is too high. */
-                        lo = thresh;
-                    } else if (pos <= allowedSize) {
-                        /* The rate is low enough, so try higher. */
-                        hi = thresh;
-                        if (!haveGoodThresh || thresh < goodThresh) {
-                            goodThresh = thresh;
-                            haveGoodThresh = true;
-                        }
+            jpc_flt_t const thresh = (lo + hi) / 2;
+
+            int rc;
+            long oldpos;
+
+            /* Save the tier 2 coding state. */
+            jpc_save_t2state(encP);
+            oldpos = jas_stream_tell(outP);
+            assert(oldpos >= 0);
+
+            assignHighSlopePassesToLayer(encP, tileP, lyrno, true, thresh);
+
+            performTier2CodingOneLayer(encP, tileP, lyrno, outP, errorP);
+
+            if (!*errorP) {
+                pos = jas_stream_tell(outP);
+
+                /* Check the rate constraint. */
+                assert(pos >= 0);
+                if (pos > allowedSize) {
+                    /* The rate is too high. */
+                    lo = thresh;
+                } else if (pos <= allowedSize) {
+                    /* The rate is low enough, so try higher. */
+                    hi = thresh;
+                    if (!haveGoodThresh || thresh < goodThresh) {
+                        goodThresh = thresh;
+                        haveGoodThresh = true;
                     }
                 }
-                /* Restore the tier 2 coding state. */
-                jpc_restore_t2state(encP);
-                rc = jas_stream_seek(outP, oldpos, SEEK_SET);
-                if (rc < 0)
-                    abort();
-
-                trace("iter %u: allowedlen=%08ld actuallen=%08ld thresh=%f",
-                      numiters, allowedSize, pos, thresh);
             }
+            /* Restore the tier 2 coding state. */
+            jpc_restore_t2state(encP);
+            rc = jas_stream_seek(outP, oldpos, SEEK_SET);
+            if (rc < 0)
+                abort();
+
+            trace("iter %u: allowedlen=%08ld actuallen=%08ld thresh=%f",
+                  numiters, allowedSize, pos, thresh);
+
             ++numiters;
         } while (lo < hi - 1e-3 && numiters < 32 && !*errorP);
     }
@@ -1625,10 +1427,10 @@ doLayer(jpc_enc_t *      const encP,
 
 
 static void
-performTier2Coding(jpc_enc_t *     const encP,
-                   unsigned int    const numlyrs,
-                   uint_fast32_t * const cumlens,
-                   const char **   const errorP) {
+performTier2Coding(jpc_enc_t *      const encP,
+                   uint_fast32_t    const numlyrs,
+                   uint_fast32_t *  const cumlens,
+                   const char **    const errorP) {
 /*----------------------------------------------------------------------------
    Encode in 'numlyrs' layers, such that at each layer L, the size is
    cumlens[L].
@@ -1636,7 +1438,7 @@ performTier2Coding(jpc_enc_t *     const encP,
     jpc_enc_tile_t * const tileP = encP->curtile;
 
     jas_stream_t * outP;
-    unsigned int lyrno;
+    uint_fast32_t lyrno;
     jpc_flt_t mnrdslope;
     jpc_flt_t mxrdslope;
 
@@ -1669,6 +1471,562 @@ performTier2Coding(jpc_enc_t *     const encP,
 
 
 
+
+
+static void
+encodeTileBody(jpc_enc_t *   const encoderP,
+               long          const tilehdrlen,
+               const char ** const errorP) {
+/*----------------------------------------------------------------------------
+   Encode the body of encoder *encoderP's current tile, writing the encoded
+   result to the encoder's output stream.
+
+   Assume the tile header is already in that stream, and its length is
+   'tilehdrlen'.
+-----------------------------------------------------------------------------*/
+    jpc_enc_tile_t * const tileP = encoderP->curtile;
+    jpc_enc_cp_t *   const cp    = encoderP->cp;
+
+    int rc;
+
+    rc = jpc_enc_enccblks(encoderP);
+    if (rc != 0)
+        pm_asprintf(errorP, "jpc_enc_enccblks() failed");
+    else {
+        double const rho =
+            (double) (tileP->brx - tileP->tlx) * (tileP->bry - tileP->tly) /
+            ((cp->refgrdwidth - cp->imgareatlx) * (cp->refgrdheight -
+                                                   cp->imgareatly));
+        const char * error;
+
+        tileP->rawsize = cp->rawsize * rho;
+
+        computeLayerSizes(encoderP, tileP, cp, rho, tilehdrlen);
+
+        performTier2Coding(encoderP, tileP->numlyrs, tileP->lyrsizes, &error);
+
+        if (error) {
+            pm_asprintf(errorP, "Tier 2 coding failed.  %s", error);
+            pm_strfree(error);
+        } else {
+            int rc;
+
+            rc = jpc_enc_encpkts(encoderP, encoderP->tmpstream);
+            if (rc != 0)
+                pm_asprintf(errorP, "jpc_enc_encpkts() failed\n");
+            else
+                *errorP = NULL;
+        }
+    }
+}
+
+
+
+static void
+quantizeBand(jpc_enc_band_t * const bandP,
+             jpc_enc_tile_t * const tileP,
+             jpc_enc_cp_t *   const cp,
+             int              const prec,
+             int              const tccp_numgbits,
+             int *            const numgbitsP) {
+
+    if (bandP->data) {
+        int actualnumbps;
+        uint_fast32_t y;
+        jpc_fix_t mxmag;
+
+        for (y = 0, actualnumbps = 0, mxmag = 0;
+             y < jas_matrix_numrows(bandP->data);
+             ++y) {
+            uint_fast32_t x;
+
+            for (x = 0; x < jas_matrix_numcols(bandP->data); ++x)
+                mxmag = MAX(mxmag, abs(jas_matrix_get(bandP->data, y, x)));
+        }
+        if (tileP->intmode)
+            actualnumbps = jpc_firstone(mxmag) + 1;
+        else
+            actualnumbps = jpc_firstone(mxmag) + 1 - JPC_FIX_FRACBITS;
+
+        *numgbitsP = actualnumbps - (prec - 1 + bandP->analgain);
+
+        if (!tileP->intmode) {
+            bandP->absstepsize =
+                jpc_fix_div(
+                    jpc_inttofix(1 << (bandP->analgain + 1)),
+                    bandP->synweight);
+        } else {
+            bandP->absstepsize = jpc_inttofix(1);
+        }
+        bandP->stepsize = jpc_abstorelstepsize(
+            bandP->absstepsize, prec + bandP->analgain);
+        /* I couldn't figure out what the calculation with tccp_numgbits and
+           stepsize does (or even what a step size is), but there is an
+           assertion elsewhere than the number here is at least at large as
+           the 'numbps' value for every code block, which means
+           'actualnumbps'.  In practice, we saw that not be true, so we added
+           the code to make 'actualnumbps' the floor here in hopes that would
+           fix the problem.  But with the change, the image that caused the
+           assertion failure produces incorrect output.  22.11.07
+        */
+        bandP->numbps =
+            MAX(actualnumbps,
+                tccp_numgbits + JPC_QCX_GETEXPN(bandP->stepsize) - 1);
+
+        if (!tileP->intmode && bandP->data)
+            quantize(bandP->data, bandP->absstepsize);
+    } else
+        *numgbitsP = 0;
+}
+
+
+
+static int
+encodemainbody(jpc_enc_t *enc) {
+
+    int tileno;
+    int i;
+    jpc_sot_t *sot;
+    int rlvlno;
+    jpc_qcc_t *qcc;
+    jpc_cod_t *cod;
+    int adjust;
+    int j;
+    int absbandno;
+    long tilehdrlen;
+    long tilelen;
+    jpc_enc_tile_t *tile;
+    jpc_enc_cp_t *cp;
+    int samestepsizes;
+    jpc_enc_ccp_t *ccps;
+    jpc_enc_tccp_t *tccp;
+    int mingbits; /* Minimum number of guard bits needed */
+    const char * error;
+
+    cp = enc->cp;
+
+    for (tileno = 0; tileno < cp->numtiles; ++tileno) {
+        uint_fast16_t cmptno;
+
+        enc->curtile = jpc_enc_tile_create(enc->cp, enc->image, tileno);
+        if (!enc->curtile)
+            abort();
+
+        tile = enc->curtile;
+
+        if (jas_getdbglevel() >= 10) {
+            jpc_enc_dump(enc);
+        }
+
+        for (cmptno = 0; cmptno < tile->numtcmpts; ++cmptno) {
+
+            jpc_enc_tcmpt_t * const comp = &tile->tcmpts[cmptno];
+
+            if (!cp->ccps[cmptno].sgnd) {
+                adjust = 1 << (cp->ccps[cmptno].prec - 1);
+                for (i = 0; i < jas_matrix_numrows(comp->data); ++i) {
+                    for (j = 0; j < jas_matrix_numcols(comp->data); ++j) {
+                        *jas_matrix_getref(comp->data, i, j) -= adjust;
+                    }
+                }
+            }
+        }
+
+        if (!tile->intmode) {
+            uint_fast16_t cmptno;
+            for (cmptno = 0; cmptno < tile->numtcmpts; ++cmptno) {
+                jpc_enc_tcmpt_t * const comp = &tile->tcmpts[cmptno];
+                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 (i = 0; i < jas_image_numcmpts(enc->image); ++i) {
+            jpc_enc_tcmpt_t * const comp = &tile->tcmpts[i];
+            jpc_tsfb_analyze(comp->tsfb,
+                             ((comp->qmfbid == JPC_COX_RFT) ?
+                              JPC_TSFB_RITIMODE : 0), comp->data);
+
+        }
+
+        for (cmptno = 0; cmptno < tile->numtcmpts; ++cmptno) {
+
+            jpc_enc_tcmpt_t * const comp = &tile->tcmpts[cmptno];
+
+            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; rlvlno < comp->numrlvls; ++rlvlno) {
+                jpc_enc_rlvl_t * const lvl = &comp->rlvls[rlvlno];
+
+                unsigned int bandno;
+
+                if (!lvl->bands) {
+                    absbandno += rlvlno ? 3 : 1;
+                    continue;
+                }
+                for (bandno = 0; bandno < lvl->numbands; ++bandno) {
+                    jpc_enc_band_t * const band = &lvl->bands[bandno];
+
+                    int numgbits;
+
+                    quantizeBand(band, tile, cp,
+                                 cp->ccps[cmptno].prec,
+                                 cp->tccp.numgbits,
+                                 &numgbits);
+
+                    mingbits = MAX(mingbits, numgbits);
+
+                    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 (mingbits > cp->tccp.numgbits) {
+            fprintf(stderr, "error: too few guard bits (need at least %d)\n",
+                    mingbits);
+            return -1;
+        }
+
+        enc->tmpstream = jas_stream_memopen(0, 0);
+        if (!enc->tmpstream) {
+            fprintf(stderr, "cannot open tmp file\n");
+            return -1;
+        }
+
+        /* Write the tile header. */
+        enc->mrk = jpc_ms_create(JPC_MS_SOT);
+        if (!enc->mrk)
+            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)) {
+            fprintf(stderr, "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) {
+            jpc_enc_tcmpt_t * const comp = &tile->tcmpts[cmptno];
+            jpc_enc_tcmpt_t * const comp0 = &tile->tcmpts[0];
+
+            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 */
+                cod = &enc->mrk->parms.cod;
+                cod->compparms.csty = 0;
+                cod->compparms.numdlvls = comp0->numrlvls - 1;
+                cod->prg = tile->prg;
+                cod->numlyrs = tile->numlyrs;
+                cod->compparms.cblkwidthval =
+                    JPC_COX_CBLKSIZEEXPN(comp0->cblkwidthexpn);
+                cod->compparms.cblkheightval =
+                    JPC_COX_CBLKSIZEEXPN(comp0->cblkheightexpn);
+                cod->compparms.cblksty = comp0->cblksty;
+                cod->compparms.qmfbid = comp0->qmfbid;
+                cod->mctrans = (tile->mctid != JPC_MCT_NONE);
+                for (i = 0; i < comp0->numrlvls; ++i) {
+                    cod->compparms.rlvls[i].parwidthval =
+                        comp0->rlvls[i].prcwidthexpn;
+                    cod->compparms.rlvls[i].parheightval =
+                        comp0->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; cmptno < cp->numcmpts; ++cmptno) {
+            jpc_enc_tcmpt_t * const comp = &tile->tcmpts[cmptno];
+
+            ccps = &cp->ccps[cmptno];
+            if (ccps->numstepsizes == comp->numstepsizes) {
+                unsigned int bandno;
+                samestepsizes = 1;
+                for (bandno = 0; bandno < 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)) {
+            fprintf(stderr, "cannot write SOD marker\n");
+            return -1;
+        }
+        jpc_ms_destroy(enc->mrk);
+        enc->mrk = 0;
+        tilehdrlen = jas_stream_getrwcount(enc->tmpstream);
+
+/************************************************************************/
+/************************************************************************/
+/************************************************************************/
+
+        encodeTileBody(enc, tilehdrlen, &error);
+            /* Encodes current tile; writes to output file */
+
+        if (error) {
+            fprintf(stderr, "Failed to encode body of tile %u.  %s\n",
+                    tileno, error);
+            pm_strfree(error);
+            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_encode(jas_image_t *image, jas_stream_t *out, char *optstr) {
+
+    jpc_enc_t *enc;
+    jpc_enc_cp_t *cp;
+
+    enc = 0;
+    cp = 0;
+
+    jpc_initluts();
+
+    if (!(cp = cp_create(optstr, image))) {
+        fprintf(stderr, "invalid JP encoder options\n");
+        goto error;
+    }
+
+    if (!(enc = jpc_enc_create(cp, out, image))) {
+        goto error;
+    }
+    cp = 0;
+
+    /* Encode the main header. */
+    if (encodemainhdr(enc)) {
+        goto error;
+    }
+
+    /* Encode the main body.  This constitutes most of the encoding work. */
+    if (encodemainbody(enc)) {
+        goto error;
+    }
+
+    /* Write EOC marker segment. */
+    if (!(enc->mrk = jpc_ms_create(JPC_MS_EOC))) {
+        goto error;
+    }
+    if (jpc_putms(enc->out, enc->cstate, enc->mrk)) {
+        fprintf(stderr, "cannot write EOI marker\n");
+        goto error;
+    }
+    jpc_ms_destroy(enc->mrk);
+    enc->mrk = 0;
+
+    if (jas_stream_flush(enc->out)) {
+        goto error;
+    }
+
+    jpc_enc_destroy(enc);
+
+    return 0;
+
+error:
+    if (cp) {
+        cp_destroy(cp);
+    }
+    if (enc) {
+        jpc_enc_destroy(enc);
+    }
+    return -1;
+}
+
+
+
+/*****************************************************************************\
+* 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;
+
+    enc = 0;
+
+    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) {
+        cp_destroy(enc->cp);
+    }
+    if (enc->cstate) {
+        jpc_cstate_destroy(enc->cstate);
+    }
+    if (enc->tmpstream) {
+        jas_stream_close(enc->tmpstream);
+    }
+
+    jas_free(enc);
+}
+
+
+
+void
+quantize(jas_matrix_t *data, jpc_fix_t stepsize) {
+
+    int i;
+    int j;
+    jpc_fix_t t;
+
+    if (stepsize == jpc_inttofix(1)) {
+        return;
+    }
+
+    for (i = 0; i < jas_matrix_numrows(data); ++i) {
+        for (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);
+        }
+    }
+}
+
+
+
 /*****************************************************************************\
 * Tile constructors and destructors.
 \*****************************************************************************/
@@ -2227,7 +2585,7 @@ prc_create(jpc_enc_prc_t *prc, jpc_enc_cp_t *cp, jpc_enc_band_t *band) {
         }
 
         prc->cblks = jas_malloc(prc->numcblks * sizeof(jpc_enc_cblk_t));
-        
+
         if (!prc->cblks)
             goto error;
         for (cblkno = 0, cblk = prc->cblks;
@@ -2445,9 +2803,9 @@ jpc_enc_dump(jpc_enc_t *enc) {
                      prcno < rlvl->numprcs;
                      ++prcno, ++prc) {
                     fprintf(stderr, "        prc %5d %5d %5d %5d (%5d %5d)\n",
-                            (int)prc->tlx, (int)prc->tly, 
+                            (int)prc->tlx, (int)prc->tly,
                             (int)prc->brx, (int)prc->bry,
-                            (int)(prc->brx - prc->tlx), 
+                            (int)(prc->brx - prc->tlx),
                             (int)(prc->bry - prc->tly));
                     if (!prc->cblks) {
                         continue;
@@ -2468,352 +2826,6 @@ jpc_enc_dump(jpc_enc_t *enc) {
 
 
 
-static int
-jpc_enc_encodemainbody(jpc_enc_t *enc) {
-
-    int tileno;
-    int i;
-    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;
-    int rlvlno;
-    jpc_qcc_t *qcc;
-    jpc_cod_t *cod;
-    int adjust;
-    int j;
-    int absbandno;
-    long tilehdrlen;
-    long tilelen;
-    jpc_enc_tile_t *tile;
-    jpc_enc_cp_t *cp;
-    double rho;
-    uint_fast16_t cmptno;
-    int samestepsizes;
-    jpc_enc_ccp_t *ccps;
-    jpc_enc_tccp_t *tccp;
-    int bandno;
-    uint_fast32_t x;
-    uint_fast32_t y;
-    int mingbits;
-    int actualnumbps;
-    jpc_fix_t mxmag;
-    jpc_fix_t mag;
-    int numgbits;
-    const char * error;
-
-    cp = enc->cp;
-
-    for (tileno = 0; tileno < cp->numtiles; ++tileno) {
-        enc->curtile = jpc_enc_tile_create(enc->cp, enc->image, tileno);
-        if (!enc->curtile)
-            abort();
-
-        tile = enc->curtile;
-
-        if (jas_getdbglevel() >= 10) {
-            jpc_enc_dump(enc);
-        }
-
-        endcomps = &tile->tcmpts[tile->numtcmpts];
-        for (cmptno = 0, comp = tile->tcmpts;
-             cmptno < tile->numtcmpts;
-             ++cmptno, ++comp) {
-            if (!cp->ccps[cmptno].sgnd) {
-                adjust = 1 << (cp->ccps[cmptno].prec - 1);
-                for (i = 0; i < jas_matrix_numrows(comp->data); ++i) {
-                    for (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 (i = 0; i < jas_image_numcmpts(enc->image); ++i) {
-            comp = &tile->tcmpts[i];
-            jpc_tsfb_analyze(comp->tsfb,
-                             ((comp->qmfbid == JPC_COX_RFT) ?
-                              JPC_TSFB_RITIMODE : 0), 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;
-                    }
-                    actualnumbps = 0;
-                    mxmag = 0;
-                    for (y = 0; y < jas_matrix_numrows(band->data); ++y) {
-                        for (x = 0; x < jas_matrix_numcols(band->data); ++x) {
-                            mag = abs(jas_matrix_get(band->data, y, x));
-                            if (mag > mxmag) {
-                                mxmag = mag;
-                            }
-                        }
-                    }
-                    if (tile->intmode) {
-                        actualnumbps =
-                            jpc_firstone(mxmag) + 1;
-                    } else {
-                        actualnumbps =
-                            jpc_firstone(mxmag) + 1 - JPC_FIX_FRACBITS;
-                    }
-                    numgbits = actualnumbps - (cp->ccps[cmptno].prec - 1 +
-                                               band->analgain);
-                    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);
-                    }
-                    band->stepsize = jpc_abstorelstepsize(
-                        band->absstepsize, cp->ccps[cmptno].prec +
-                        band->analgain);
-                    band->numbps = cp->tccp.numgbits +
-                        JPC_QCX_GETEXPN(band->stepsize) - 1;
-
-                    if ((!tile->intmode) && band->data) {
-                        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 (mingbits > cp->tccp.numgbits) {
-            fprintf(stderr, "error: too few guard bits (need at least %d)\n",
-                    mingbits);
-            return -1;
-        }
-
-        enc->tmpstream = jas_stream_memopen(0, 0);
-        if (!enc->tmpstream) {
-            fprintf(stderr, "cannot open tmp file\n");
-            return -1;
-        }
-
-        /* Write the tile header. */
-        enc->mrk = jpc_ms_create(JPC_MS_SOT);
-        if (!enc->mrk)
-            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)) {
-            fprintf(stderr, "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 (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 (ccps->numstepsizes == comp->numstepsizes) {
-                samestepsizes = 1;
-                for (bandno = 0; bandno < 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)) {
-            fprintf(stderr, "cannot write SOD marker\n");
-            return -1;
-        }
-        jpc_ms_destroy(enc->mrk);
-        enc->mrk = 0;
-        tilehdrlen = jas_stream_getrwcount(enc->tmpstream);
-
-/************************************************************************/
-/************************************************************************/
-/************************************************************************/
-
-        if (jpc_enc_enccblks(enc)) {
-            abort();
-            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;
-
-        computeLayerSizes(enc, tile, cp, rho, tilehdrlen, &error);
-        
-        if (!error) {
-            int rc;
-            performTier2Coding(enc, tile->numlyrs, tile->lyrsizes, &error);
-
-            rc =  jpc_enc_encodetiledata(enc);
-            if (rc != 0)
-                pm_asprintf(&error, "jpc_enc_encodetiledata() failed\n");
-        }
-
-        if (error) {
-            fprintf(stderr, "%s\n", error);
-            pm_strfree(error);
-            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;
-}
-
-
-
 /*
  * Copyright (c) 1999-2000 Image Power, Inc. and the University of
  *   British Columbia.
@@ -2822,14 +2834,14 @@ jpc_enc_encodemainbody(jpc_enc_t *enc) {
  */
 
 /* __START_OF_JASPER_LICENSE__
- * 
+ *
  * JasPer Software License
- * 
+ *
  * IMAGE POWER JPEG-2000 PUBLIC LICENSE
  * ************************************
- * 
+ *
  * GRANT:
- * 
+ *
  * Permission is hereby granted, free of charge, to any person (the "User")
  * obtaining a copy of this software and associated documentation, to deal
  * in the JasPer Software without restriction, including without limitation
@@ -2837,22 +2849,22 @@ jpc_enc_encodemainbody(jpc_enc_t *enc) {
  * and/or sell copies of the JasPer Software (in source and binary forms),
  * and to permit persons to whom the JasPer Software is furnished to do so,
  * provided further that the License Conditions below are met.
- * 
+ *
  * License Conditions
  * ******************
- * 
+ *
  * A.  Redistributions of source code must retain the above copyright notice,
  * and this list of conditions, and the following disclaimer.
- * 
+ *
  * B.  Redistributions in binary form must reproduce the above copyright
  * notice, and this list of conditions, and the following disclaimer in
  * the documentation and/or other materials provided with the distribution.
- * 
+ *
  * C.  Neither the name of Image Power, Inc. nor any other contributor
  * (including, but not limited to, the University of British Columbia and
  * Michael David Adams) may be used to endorse or promote products derived
  * from this software without specific prior written permission.
- * 
+ *
  * D.  User agrees that it shall not commence any action against Image Power,
  * Inc., the University of British Columbia, Michael David Adams, or any
  * other contributors (collectively "Licensors") for infringement of any
@@ -2872,17 +2884,17 @@ jpc_enc_encodemainbody(jpc_enc_t *enc) {
  * trade dress, or service mark rights); and (v) divisions, continuations,
  * renewals, reissues and extensions of the foregoing (as and to the extent
  * applicable) now existing, hereafter filed, issued or acquired.
- * 
+ *
  * E.  If User commences an infringement action against any Licensor(s) then
  * such Licensor(s) shall have the right to terminate User's license and
  * all sublicenses that have been granted hereunder by User to other parties.
- * 
+ *
  * F.  This software is for use only in hardware or software products that
  * are compliant with ISO/IEC 15444-1 (i.e., JPEG-2000 Part 1).  No license
  * or right to this Software is granted for products that do not comply
  * with ISO/IEC 15444-1.  The JPEG-2000 Part 1 standard can be purchased
  * from the ISO.
- * 
+ *
  * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS LICENSE.
  * NO USE OF THE JASPER SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER
  * THIS DISCLAIMER.  THE JASPER SOFTWARE IS PROVIDED BY THE LICENSORS AND
@@ -2922,7 +2934,7 @@ jpc_enc_encodemainbody(jpc_enc_t *enc) {
  * TECHNOLOGY OR PRODUCTS FOR HIGH RISK ACTIVITIES AND WILL ENSURE THAT ITS
  * CUSTOMERS AND END-USERS OF ITS PRODUCTS ARE PROVIDED WITH A COPY OF THE
  * NOTICE SPECIFIED IN THIS SECTION.
- * 
+ *
  * __END_OF_JASPER_LICENSE__
  */
 
diff --git a/converter/other/jpeg2000/libjasper/jpc/jpc_enc.h b/converter/other/jpeg2000/libjasper/jpc/jpc_enc.h
index 86a8e59c..1e3887aa 100644
--- a/converter/other/jpeg2000/libjasper/jpc/jpc_enc.h
+++ b/converter/other/jpeg2000/libjasper/jpc/jpc_enc.h
@@ -6,14 +6,14 @@
  */
 
 /* __START_OF_JASPER_LICENSE__
- * 
+ *
  * JasPer Software License
- * 
+ *
  * IMAGE POWER JPEG-2000 PUBLIC LICENSE
  * ************************************
- * 
+ *
  * GRANT:
- * 
+ *
  * Permission is hereby granted, free of charge, to any person (the "User")
  * obtaining a copy of this software and associated documentation, to deal
  * in the JasPer Software without restriction, including without limitation
@@ -21,22 +21,22 @@
  * and/or sell copies of the JasPer Software (in source and binary forms),
  * and to permit persons to whom the JasPer Software is furnished to do so,
  * provided further that the License Conditions below are met.
- * 
+ *
  * License Conditions
  * ******************
- * 
+ *
  * A.  Redistributions of source code must retain the above copyright notice,
  * and this list of conditions, and the following disclaimer.
- * 
+ *
  * B.  Redistributions in binary form must reproduce the above copyright
  * notice, and this list of conditions, and the following disclaimer in
  * the documentation and/or other materials provided with the distribution.
- * 
+ *
  * C.  Neither the name of Image Power, Inc. nor any other contributor
  * (including, but not limited to, the University of British Columbia and
  * Michael David Adams) may be used to endorse or promote products derived
  * from this software without specific prior written permission.
- * 
+ *
  * D.  User agrees that it shall not commence any action against Image Power,
  * Inc., the University of British Columbia, Michael David Adams, or any
  * other contributors (collectively "Licensors") for infringement of any
@@ -56,17 +56,17 @@
  * trade dress, or service mark rights); and (v) divisions, continuations,
  * renewals, reissues and extensions of the foregoing (as and to the extent
  * applicable) now existing, hereafter filed, issued or acquired.
- * 
+ *
  * E.  If User commences an infringement action against any Licensor(s) then
  * such Licensor(s) shall have the right to terminate User's license and
  * all sublicenses that have been granted hereunder by User to other parties.
- * 
+ *
  * F.  This software is for use only in hardware or software products that
  * are compliant with ISO/IEC 15444-1 (i.e., JPEG-2000 Part 1).  No license
  * or right to this Software is granted for products that do not comply
  * with ISO/IEC 15444-1.  The JPEG-2000 Part 1 standard can be purchased
  * from the ISO.
- * 
+ *
  * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS LICENSE.
  * NO USE OF THE JASPER SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER
  * THIS DISCLAIMER.  THE JASPER SOFTWARE IS PROVIDED BY THE LICENSORS AND
@@ -106,7 +106,7 @@
  * TECHNOLOGY OR PRODUCTS FOR HIGH RISK ACTIVITIES AND WILL ENSURE THAT ITS
  * CUSTOMERS AND END-USERS OF ITS PRODUCTS ARE PROVIDED WITH A COPY OF THE
  * NOTICE SPECIFIED IN THIS SECTION.
- * 
+ *
  * __END_OF_JASPER_LICENSE__
  */
 
@@ -136,10 +136,10 @@
 \******************************************************************************/
 
 /* The number of bits used in various lookup tables. */
-#define	JPC_NUMEXTRABITS	JPC_NMSEDEC_FRACBITS
+#define JPC_NUMEXTRABITS        JPC_NMSEDEC_FRACBITS
 
 /* An invalid R-D slope value. */
-#define	JPC_BADRDSLOPE	(-1)
+#define JPC_BADRDSLOPE  (-1)
 
 /******************************************************************************\
 * Coding parameters types.
@@ -149,29 +149,29 @@
 
 typedef struct {
 
-	/* The horizontal sampling period. */
-	uint_fast8_t sampgrdstepx;
+        /* The horizontal sampling period. */
+        uint_fast8_t sampgrdstepx;
 
-	/* The vertical sampling period. */
-	uint_fast8_t sampgrdstepy;
+        /* The vertical sampling period. */
+        uint_fast8_t sampgrdstepy;
 
-	/* The sample alignment horizontal offset. */
-	uint_fast8_t sampgrdsubstepx;
+        /* The sample alignment horizontal offset. */
+        uint_fast8_t sampgrdsubstepx;
 
-	/* The sample alignment vertical offset. */
-	uint_fast8_t sampgrdsubstepy;
+        /* The sample alignment vertical offset. */
+        uint_fast8_t sampgrdsubstepy;
 
-	/* The precision of the samples. */
-	uint_fast8_t prec;
+        /* The precision of the samples. */
+        uint_fast8_t prec;
 
-	/* The signedness of the samples. */
-	bool sgnd;
+        /* The signedness of the samples. */
+        bool sgnd;
 
-	/* The number of step sizes. */
-	uint_fast16_t numstepsizes;
+        /* The number of step sizes. */
+        uint_fast16_t numstepsizes;
 
-	/* The quantizer step sizes. */
-	uint_fast16_t stepsizes[JPC_MAXBANDS];
+        /* The quantizer step sizes. */
+        uint_fast16_t stepsizes[JPC_MAXBANDS];
 
 } jpc_enc_ccp_t;
 
@@ -179,24 +179,24 @@ typedef struct {
 
 typedef struct {
 
-	/* The coding mode. */
-	bool intmode;
+        /* The coding mode. */
+        bool intmode;
 
-	/* The coding style (i.e., SOP, EPH). */
-	uint_fast8_t csty;
+        /* The coding style (i.e., SOP, EPH). */
+        uint_fast8_t csty;
 
-	/* The progression order. */
-	uint_fast8_t prg;
+        /* The progression order. */
+        uint_fast8_t prg;
 
-	/* The multicomponent transform. */
-	uint_fast8_t mctid;
+        /* The multicomponent transform. */
+        uint_fast8_t mctid;
 
-	/* The number of layers. */
-	uint_fast16_t numlyrs;
+        /* The number of layers. */
+        uint_fast16_t numlyrs;
 
-	/* The normalized bit rates associated with the various
-	  intermediate layers. */
-	jpc_fix_t *ilyrrates;
+        /* The normalized bit rates associated with the various
+          intermediate layers. */
+        jpc_fix_t *ilyrrates;
 
 } jpc_enc_tcp_t;
 
@@ -204,33 +204,33 @@ typedef struct {
 
 typedef struct {
 
-	/* The coding style (i.e., explicit precinct sizes). */
-	uint_fast8_t csty;
+        /* The coding style (i.e., explicit precinct sizes). */
+        uint_fast8_t csty;
 
-	/* The maximum number of resolution levels allowed. */
-	uint_fast8_t maxrlvls;
+        /* 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 width. */
+        uint_fast16_t cblkwidthexpn;
 
-	/* The exponent for the nominal code block height. */
-	uint_fast16_t cblkheightexpn;
+        /* 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 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 QMFB. */
+        uint_fast8_t qmfbid;
 
-	/* The precinct width values. */
-	uint_fast16_t prcwidthexpns[JPC_MAXRLVLS];
+        /* The precinct width values. */
+        uint_fast16_t prcwidthexpns[JPC_MAXRLVLS];
 
-	/* The precinct height values. */
-	uint_fast16_t prcheightexpns[JPC_MAXRLVLS];
+        /* The precinct height values. */
+        uint_fast16_t prcheightexpns[JPC_MAXRLVLS];
 
-	/* The number of guard bits. */
-	uint_fast8_t numgbits;
+        /* The number of guard bits. */
+        uint_fast8_t numgbits;
 
 } jpc_enc_tccp_t;
 
@@ -238,67 +238,67 @@ typedef struct {
 
 typedef struct {
 
-	/* The debug level. */
-	int debug;
+        /* 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 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 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 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 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 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 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 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 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 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 spanning the image area in the vertical
+          direction. */
+        uint_fast32_t numvtiles;
 
-	/* The number of tiles. */
-	uint_fast32_t numtiles;
+        /* The number of tiles. */
+        uint_fast32_t numtiles;
 
-	/* The number of components. */
-	uint_fast16_t numcmpts;
+        /* The number of components. */
+        uint_fast16_t numcmpts;
 
-	/* The per-component coding parameters. */
-	jpc_enc_ccp_t *ccps;
+        /* The per-component coding parameters. */
+        jpc_enc_ccp_t *ccps;
 
-	/* The per-tile coding parameters. */
-	jpc_enc_tcp_t tcp;
+        /* The per-tile coding parameters. */
+        jpc_enc_tcp_t tcp;
 
-	/* The per-tile-component coding parameters. */
-	jpc_enc_tccp_t tccp;
+        /* The per-tile-component coding parameters. */
+        jpc_enc_tccp_t tccp;
 
-	/* The target code stream length in bytes. */
-	uint_fast32_t totalsize;
+        /* 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;
+        /* The raw (i.e., uncompressed) size of the image in bytes. */
+        uint_fast32_t rawsize;
 
 } jpc_enc_cp_t;
 
@@ -310,35 +310,35 @@ typedef struct {
 
 typedef struct {
 
-	/* The starting offset for this pass. */
-	int start;
+        /* The starting offset for this pass. */
+        int start;
 
-	/* The ending offset for this pass. */
-	int end;
+        /* The ending offset for this pass. */
+        int end;
 
-	/* The type of data in this pass (i.e., MQ or raw). */
-	int type;
+        /* The type of data in this pass (i.e., MQ or raw). */
+        int type;
 
-	/* Flag indicating that this pass is terminated. */
-	int term;
+        /* Flag indicating that this pass is terminated. */
+        int term;
 
-	/* The entropy coder state after coding this pass. */
-	jpc_mqencstate_t mqencstate;
+        /* The entropy coder state after coding this pass. */
+        jpc_mqencstate_t mqencstate;
 
-	/* The layer to which this pass has been assigned. */
-	int lyrno;
+        /* The layer to which this pass has been assigned. */
+        int lyrno;
 
-	/* The R-D slope for this pass. */
-	jpc_flt_t rdslope;
+        /* The R-D slope for this pass. */
+        jpc_flt_t rdslope;
 
-	/* The weighted MSE reduction associated with this pass. */
-	jpc_flt_t wmsedec;
+        /* The weighted MSE reduction associated with this pass. */
+        jpc_flt_t wmsedec;
 
-	/* The cumulative weighted MSE reduction. */
-	jpc_flt_t cumwmsedec;
+        /* The cumulative weighted MSE reduction. */
+        jpc_flt_t cumwmsedec;
 
-	/* The normalized MSE reduction. */
-	long nmsedec;
+        /* The normalized MSE reduction. */
+        long nmsedec;
 
 } jpc_enc_pass_t;
 
@@ -346,53 +346,53 @@ typedef struct {
 
 typedef struct {
 
-	/* The number of passes. */
-	int numpasses;
+        /* The number of passes. */
+        int numpasses;
 
-	/* The per-pass information. */
-	jpc_enc_pass_t *passes;
+        /* The per-pass information. */
+        jpc_enc_pass_t *passes;
 
-	/* The number of passes encoded so far. */
-	int numencpasses;
+        /* The number of passes encoded so far. */
+        int numencpasses;
 
-	/* The number of insignificant MSBs. */
-	int numimsbs;
+        /* The number of insignificant MSBs. */
+        int numimsbs;
 
-	/* The number of bits used to encode pass data lengths. */
-	int numlenbits;
+        /* The number of bits used to encode pass data lengths. */
+        int numlenbits;
 
-	/* The byte stream for this code block. */
-	jas_stream_t *stream;
+        /* The byte stream for this code block. */
+        jas_stream_t *stream;
 
-	/* The entropy encoder. */
-	jpc_mqenc_t *mqenc;
+        /* The entropy encoder. */
+        jpc_mqenc_t *mqenc;
 
-	/* The data for this code block. */
-	jas_matrix_t *data;
+        /* The data for this code block. */
+        jas_matrix_t *data;
 
-	/* The state for this code block. */
-	jas_matrix_t *flags;
+        /* The state for this code block. */
+        jas_matrix_t *flags;
 
-	/* The number of bit planes required for this code block. */
-	int numbps;
+        /* The number of bit planes required for this code block. */
+        int numbps;
 
-	/* The next pass to be encoded. */
-	jpc_enc_pass_t *curpass;
+        /* 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 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 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 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;
+        /* The saved number of encoded passes. */
+        /* This is used by the rate control code. */
+        int savednumencpasses;
 
 } jpc_enc_cblk_t;
 
@@ -400,50 +400,50 @@ typedef struct {
 
 typedef struct jpc_enc_prc_s {
 
-	/* The x-coordinate of the top-left corner of the precinct. */
-	uint_fast32_t tlx;
+        /* 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 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 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 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 horizontal
+        direction. */
+        int numhcblks;
 
-	/* The number of code blocks spanning the precinct in the vertical
-	direction. */
-	int numvcblks;
+        /* The number of code blocks spanning the precinct in the vertical
+        direction. */
+        int numvcblks;
 
-	/* The total number of code blocks. */
-	int numcblks;
+        /* The total number of code blocks. */
+        int numcblks;
 
-	/* The per-code-block information. */
-	jpc_enc_cblk_t *cblks;
+        /* The per-code-block information. */
+        jpc_enc_cblk_t *cblks;
 
-	/* The inclusion tag tree. */
-	jpc_tagtree_t *incltree;
+        /* The inclusion tag tree. */
+        jpc_tagtree_t *incltree;
 
-	/* The insignifcant MSBs tag tree. */
-	jpc_tagtree_t *nlibtree;
+        /* The insignifcant MSBs tag tree. */
+        jpc_tagtree_t *nlibtree;
 
-	/* The per-band information. */
-	struct jpc_enc_band_s *band;
+        /* 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 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;
+        /* The saved leading-insignificant-bit-planes tag tree. */
+        /* This is used by rate control. */
+        jpc_tagtree_t *savnlibtree;
 
 } jpc_enc_prc_t;
 
@@ -451,33 +451,33 @@ typedef struct jpc_enc_prc_s {
 
 typedef struct jpc_enc_band_s {
 
-	/* The per precinct information. */
-	jpc_enc_prc_t *prcs;
+        /* The per precinct information. */
+        jpc_enc_prc_t *prcs;
 
-	/* The coefficient data for this band. */
-	jas_matrix_t *data;
+        /* The coefficient data for this band. */
+        jas_matrix_t *data;
 
-	/* The orientation of this band (i.e., LL, LH, HL, or HH). */
-	int orient;
+        /* The orientation of this band (i.e., LL, LH, HL, or HH). */
+        int orient;
 
-	/* The number of bit planes associated with this band. */
-	int numbps;
+        /* The number of bit planes associated with this band. */
+        int numbps;
 
-	/* The quantizer step size. */
-	jpc_fix_t absstepsize;
+        /* The quantizer step size. */
+        jpc_fix_t absstepsize;
 
-	/* The encoded quantizer step size. */
-	int stepsize;
+        /* 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 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 analysis gain for this band. */
+        int analgain;
 
-	/* The per-resolution-level information. */
-	struct jpc_enc_rlvl_s *rlvl;
+        /* The per-resolution-level information. */
+        struct jpc_enc_rlvl_s *rlvl;
 
 } jpc_enc_band_t;
 
@@ -485,65 +485,65 @@ typedef struct jpc_enc_band_s {
 
 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 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 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 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 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 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 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
+          horizontal direction. */
+        int numhprcs;
 
-	/* The number of precincts spanning the resolution level in the
-	  vertical direction. */
-	int numvprcs;
+        /* The number of precincts spanning the resolution level in the
+          vertical direction. */
+        int numvprcs;
 
-	/* The total number of precincts. */
-	int numprcs;
+        /* The total number of precincts. */
+        int 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). */
-	int cbgwidthexpn;
+        /* 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). */
+        int 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). */
-	int cbgheightexpn;
+        /* 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). */
+        int cbgheightexpn;
 
-	/* The exponent value for the code block width. */
-	uint_fast16_t cblkwidthexpn;
+        /* 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 exponent value for the code block height. */
+        uint_fast16_t cblkheightexpn;
 
-	/* The number of bands associated with this resolution level. */
-	int numbands;
+        /* The number of bands associated with this resolution level. */
+        int numbands;
 
-	/* The per-band information. */
-	jpc_enc_band_t *bands;
+        /* The per-band information. */
+        jpc_enc_band_t *bands;
 
-	/* The parent tile-component. */
-	struct jpc_enc_tcmpt_s *tcmpt;
+        /* The parent tile-component. */
+        struct jpc_enc_tcmpt_s *tcmpt;
 
 } jpc_enc_rlvl_t;
 
@@ -551,53 +551,53 @@ typedef struct jpc_enc_rlvl_s {
 
 typedef struct jpc_enc_tcmpt_s {
 
-	/* The number of resolution levels. */
-	uint_fast16_t numrlvls;
+        /* The number of resolution levels. */
+        uint_fast16_t numrlvls;
 
-	/* The per-resolution-level information. */
-	jpc_enc_rlvl_t *rlvls;
+        /* The per-resolution-level information. */
+        jpc_enc_rlvl_t *rlvls;
 
-	/* The tile-component data. */
-	jas_matrix_t *data;
+        /* The tile-component data. */
+        jas_matrix_t *data;
 
-	/* The QMFB. */
-	int qmfbid;
+        /* The QMFB. */
+        int qmfbid;
 
-	/* The number of bands. */
-	int numbands;
+        /* The number of bands. */
+        int numbands;
 
-	/* The TSFB. */
-	jpc_tsfb_t *tsfb;
+        /* The TSFB. */
+        jpc_tsfb_t *tsfb;
 
-	/* The synthesis energy weight (for the MCT). */
-	jpc_fix_t synweight;
+        /* The synthesis energy weight (for the MCT). */
+        jpc_fix_t synweight;
 
-	/* The precinct width exponents. */
-	int prcwidthexpns[JPC_MAXRLVLS];
+        /* The precinct width exponents. */
+        int prcwidthexpns[JPC_MAXRLVLS];
 
-	/* The precinct height exponents. */
-	int prcheightexpns[JPC_MAXRLVLS];
+        /* The precinct height exponents. */
+        int prcheightexpns[JPC_MAXRLVLS];
 
-	/* The code block width exponent. */
-	int cblkwidthexpn;
+        /* The code block width exponent. */
+        int cblkwidthexpn;
 
-	/* The code block height exponent. */
-	int cblkheightexpn;
+        /* The code block height exponent. */
+        int cblkheightexpn;
 
-	/* Coding style (i.e., explicit precinct sizes). */
-	int csty;
+        /* Coding style (i.e., explicit precinct sizes). */
+        int csty;
 
-	/* Code block style. */
-	int cblksty;
+        /* Code block style. */
+        int cblksty;
 
-	/* The number of quantizer step sizes. */
-	uint_fast16_t numstepsizes;
+        /* The number of quantizer step sizes. */
+        uint_fast16_t numstepsizes;
 
-	/* The encoded quantizer step sizes. */
-	uint_fast16_t stepsizes[JPC_MAXBANDS];
+        /* The encoded quantizer step sizes. */
+        uint_fast16_t stepsizes[JPC_MAXBANDS];
 
-	/* The parent tile. */
-	struct jpc_enc_tile_s *tile;
+        /* The parent tile. */
+        struct jpc_enc_tile_s *tile;
 
 } jpc_enc_tcmpt_t;
 
@@ -605,55 +605,55 @@ typedef struct jpc_enc_tcmpt_s {
 
 typedef struct jpc_enc_tile_s {
 
-	/* The tile number. */
-	uint_fast32_t tileno;
+        /* 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 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 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 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 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 coding style. */
+        uint_fast8_t csty;
 
-	/* The progression order. */
-	uint_fast8_t prg;
+        /* The progression order. */
+        uint_fast8_t prg;
 
-	/* The number of layers. */
-	uint_fast16_t numlyrs;
+        /* The number of layers. */
+        uint_fast16_t numlyrs;
 
-	/* The MCT to employ (if any). */
-	uint_fast8_t mctid;
+        /* 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 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 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 bytes to allocate to the various layers. */
+        uint_fast32_t *lyrsizes;
 
-	/* The number of tile-components. */
-	int numtcmpts;
+        /* The number of tile-components. */
+        int numtcmpts;
 
-	/* The per tile-component information. */
-	jpc_enc_tcmpt_t *tcmpts;
+        /* The per tile-component information. */
+        jpc_enc_tcmpt_t *tcmpts;
 
-	/* The raw (i.e., uncompressed) size of this tile. */
-	uint_fast32_t rawsize;
+        /* The raw (i.e., uncompressed) size of this tile. */
+        uint_fast32_t rawsize;
 
 } jpc_enc_tile_t;
 
@@ -661,34 +661,34 @@ typedef struct jpc_enc_tile_s {
 
 typedef struct jpc_enc_s {
 
-	/* The image being encoded. */
-	jas_image_t *image;
+        /* The image being encoded. */
+        jas_image_t *image;
 
-	/* The output stream. */
-	jas_stream_t *out;
+        /* The output stream. */
+        jas_stream_t *out;
 
-	/* The coding parameters. */
-	jpc_enc_cp_t *cp;
+        /* The coding parameters. */
+        jpc_enc_cp_t *cp;
 
-	/* The tile currently being processed. */
-	jpc_enc_tile_t *curtile;
+        /* The tile currently being processed. */
+        jpc_enc_tile_t *curtile;
 
-	/* The code stream state. */
-	jpc_cstate_t *cstate;
+        /* The code stream state. */
+        jpc_cstate_t *cstate;
 
-	/* The number of bytes output so far. */
-	uint_fast32_t len;
+        /* 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 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 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;
+        /* The stream used to temporarily hold tile-part data. */
+        jas_stream_t *tmpstream;
 
 } jpc_enc_t;
 
diff --git a/converter/other/jpeg2000/libjasper/jpc/jpc_fix.h b/converter/other/jpeg2000/libjasper/jpc/jpc_fix.h
index 5ff0c9f8..2083cdc6 100644
--- a/converter/other/jpeg2000/libjasper/jpc/jpc_fix.h
+++ b/converter/other/jpeg2000/libjasper/jpc/jpc_fix.h
@@ -6,14 +6,14 @@
  */
 
 /* __START_OF_JASPER_LICENSE__
- * 
+ *
  * JasPer Software License
- * 
+ *
  * IMAGE POWER JPEG-2000 PUBLIC LICENSE
  * ************************************
- * 
+ *
  * GRANT:
- * 
+ *
  * Permission is hereby granted, free of charge, to any person (the "User")
  * obtaining a copy of this software and associated documentation, to deal
  * in the JasPer Software without restriction, including without limitation
@@ -21,22 +21,22 @@
  * and/or sell copies of the JasPer Software (in source and binary forms),
  * and to permit persons to whom the JasPer Software is furnished to do so,
  * provided further that the License Conditions below are met.
- * 
+ *
  * License Conditions
  * ******************
- * 
+ *
  * A.  Redistributions of source code must retain the above copyright notice,
  * and this list of conditions, and the following disclaimer.
- * 
+ *
  * B.  Redistributions in binary form must reproduce the above copyright
  * notice, and this list of conditions, and the following disclaimer in
  * the documentation and/or other materials provided with the distribution.
- * 
+ *
  * C.  Neither the name of Image Power, Inc. nor any other contributor
  * (including, but not limited to, the University of British Columbia and
  * Michael David Adams) may be used to endorse or promote products derived
  * from this software without specific prior written permission.
- * 
+ *
  * D.  User agrees that it shall not commence any action against Image Power,
  * Inc., the University of British Columbia, Michael David Adams, or any
  * other contributors (collectively "Licensors") for infringement of any
@@ -56,17 +56,17 @@
  * trade dress, or service mark rights); and (v) divisions, continuations,
  * renewals, reissues and extensions of the foregoing (as and to the extent
  * applicable) now existing, hereafter filed, issued or acquired.
- * 
+ *
  * E.  If User commences an infringement action against any Licensor(s) then
  * such Licensor(s) shall have the right to terminate User's license and
  * all sublicenses that have been granted hereunder by User to other parties.
- * 
+ *
  * F.  This software is for use only in hardware or software products that
  * are compliant with ISO/IEC 15444-1 (i.e., JPEG-2000 Part 1).  No license
  * or right to this Software is granted for products that do not comply
  * with ISO/IEC 15444-1.  The JPEG-2000 Part 1 standard can be purchased
  * from the ISO.
- * 
+ *
  * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS LICENSE.
  * NO USE OF THE JASPER SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER
  * THIS DISCLAIMER.  THE JASPER SOFTWARE IS PROVIDED BY THE LICENSORS AND
@@ -106,7 +106,7 @@
  * TECHNOLOGY OR PRODUCTS FOR HIGH RISK ACTIVITIES AND WILL ENSURE THAT ITS
  * CUSTOMERS AND END-USERS OF ITS PRODUCTS ARE PROVIDED WITH A COPY OF THE
  * NOTICE SPECIFIED IN THIS SECTION.
- * 
+ *
  * __END_OF_JASPER_LICENSE__
  */
 
@@ -141,7 +141,7 @@ typedef int_fast32_t jpc_fix_t;
 typedef int_fast64_t jpc_fix_big_t;
 
 /* The number of bits used for the fractional part of a fixed-point number. */
-#define JPC_FIX_FRACBITS	13
+#define JPC_FIX_FRACBITS        13
 
 /******************************************************************************\
 * Instantiations of the generic fixed-point number macros for the
@@ -150,44 +150,44 @@ typedef int_fast64_t jpc_fix_big_t;
 * corresponding macros in the jasper/jas_fix.h header file.
 \******************************************************************************/
 
-#define	JPC_FIX_ZERO	JAS_FIX_ZERO(jpc_fix_t, JPC_FIX_FRACBITS)
-#define	JPC_FIX_ONE		JAS_FIX_ONE(jpc_fix_t, JPC_FIX_FRACBITS)
-#define	JPC_FIX_HALF	JAS_FIX_HALF(jpc_fix_t, JPC_FIX_FRACBITS)
-
-#define jpc_inttofix(x)	JAS_INTTOFIX(jpc_fix_t, JPC_FIX_FRACBITS, x)
-#define jpc_fixtoint(x)	JAS_FIXTOINT(jpc_fix_t, JPC_FIX_FRACBITS, x)
-#define jpc_fixtodbl(x)	JAS_FIXTODBL(jpc_fix_t, JPC_FIX_FRACBITS, x)
-#define jpc_dbltofix(x)	JAS_DBLTOFIX(jpc_fix_t, JPC_FIX_FRACBITS, x)
-
-#define	jpc_fix_add(x, y)	JAS_FIX_ADD(jpc_fix_t, JPC_FIX_FRACBITS, x, y)
-#define	jpc_fix_sub(x, y)	JAS_FIX_SUB(jpc_fix_t, JPC_FIX_FRACBITS, x, y)
-#define	jpc_fix_mul(x, y) \
-	JAS_FIX_MUL(jpc_fix_t, JPC_FIX_FRACBITS, jpc_fix_big_t, x, y)
-#define	jpc_fix_mulbyint(x, y) \
-	JAS_FIX_MULBYINT(jpc_fix_t, JPC_FIX_FRACBITS, x, y)
-#define	jpc_fix_div(x, y) \
-	JAS_FIX_DIV(jpc_fix_t, JPC_FIX_FRACBITS, jpc_fix_big_t, x, y)
-#define	jpc_fix_neg(x)		JAS_FIX_NEG(jpc_fix_t, JPC_FIX_FRACBITS, x)
-#define	jpc_fix_asl(x, n)	JAS_FIX_ASL(jpc_fix_t, JPC_FIX_FRACBITS, x, n)
-#define	jpc_fix_asr(x, n)	JAS_FIX_ASR(jpc_fix_t, JPC_FIX_FRACBITS, x, n)
-
-#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)
-
-#define	jpc_fix_abs(x)		JAS_FIX_ABS(jpc_fix_t, JPC_FIX_FRACBITS, x)
-#define	jpc_fix_isint(x)	JAS_FIX_ISINT(jpc_fix_t, JPC_FIX_FRACBITS, x)
-#define jpc_fix_sgn(x)		JAS_FIX_SGN(jpc_fix_t, JPC_FIX_FRACBITS, x)
-#define	jpc_fix_round(x)	JAS_FIX_ROUND(jpc_fix_t, JPC_FIX_FRACBITS, x)
-#define	jpc_fix_floor(x)	JAS_FIX_FLOOR(jpc_fix_t, JPC_FIX_FRACBITS, x)
-#define jpc_fix_trunc(x)	JAS_FIX_TRUNC(jpc_fix_t, JPC_FIX_FRACBITS, x)
+#define JPC_FIX_ZERO    JAS_FIX_ZERO(jpc_fix_t, JPC_FIX_FRACBITS)
+#define JPC_FIX_ONE             JAS_FIX_ONE(jpc_fix_t, JPC_FIX_FRACBITS)
+#define JPC_FIX_HALF    JAS_FIX_HALF(jpc_fix_t, JPC_FIX_FRACBITS)
+
+#define jpc_inttofix(x) JAS_INTTOFIX(jpc_fix_t, JPC_FIX_FRACBITS, x)
+#define jpc_fixtoint(x) JAS_FIXTOINT(jpc_fix_t, JPC_FIX_FRACBITS, x)
+#define jpc_fixtodbl(x) JAS_FIXTODBL(jpc_fix_t, JPC_FIX_FRACBITS, x)
+#define jpc_dbltofix(x) JAS_DBLTOFIX(jpc_fix_t, JPC_FIX_FRACBITS, x)
+
+#define jpc_fix_add(x, y)       JAS_FIX_ADD(jpc_fix_t, JPC_FIX_FRACBITS, x, y)
+#define jpc_fix_sub(x, y)       JAS_FIX_SUB(jpc_fix_t, JPC_FIX_FRACBITS, x, y)
+#define jpc_fix_mul(x, y) \
+        JAS_FIX_MUL(jpc_fix_t, JPC_FIX_FRACBITS, jpc_fix_big_t, x, y)
+#define jpc_fix_mulbyint(x, y) \
+        JAS_FIX_MULBYINT(jpc_fix_t, JPC_FIX_FRACBITS, x, y)
+#define jpc_fix_div(x, y) \
+        JAS_FIX_DIV(jpc_fix_t, JPC_FIX_FRACBITS, jpc_fix_big_t, x, y)
+#define jpc_fix_neg(x)          JAS_FIX_NEG(jpc_fix_t, JPC_FIX_FRACBITS, x)
+#define jpc_fix_asl(x, n)       JAS_FIX_ASL(jpc_fix_t, JPC_FIX_FRACBITS, x, n)
+#define jpc_fix_asr(x, n)       JAS_FIX_ASR(jpc_fix_t, JPC_FIX_FRACBITS, x, n)
+
+#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)
+
+#define jpc_fix_abs(x)          JAS_FIX_ABS(jpc_fix_t, JPC_FIX_FRACBITS, x)
+#define jpc_fix_isint(x)        JAS_FIX_ISINT(jpc_fix_t, JPC_FIX_FRACBITS, x)
+#define jpc_fix_sgn(x)          JAS_FIX_SGN(jpc_fix_t, JPC_FIX_FRACBITS, x)
+#define jpc_fix_round(x)        JAS_FIX_ROUND(jpc_fix_t, JPC_FIX_FRACBITS, x)
+#define jpc_fix_floor(x)        JAS_FIX_FLOOR(jpc_fix_t, JPC_FIX_FRACBITS, x)
+#define jpc_fix_trunc(x)        JAS_FIX_TRUNC(jpc_fix_t, JPC_FIX_FRACBITS, x)
 
 /******************************************************************************\
 * Extra macros for convenience.
 \******************************************************************************/
 
 /* Compute the sum of three fixed-point numbers. */
-#define jpc_fix_add3(x, y, z)	jpc_fix_add(jpc_fix_add(x, y), z)
+#define jpc_fix_add3(x, y, z)   jpc_fix_add(jpc_fix_add(x, y), z)
 
 #endif
diff --git a/converter/other/jpeg2000/libjasper/jpc/jpc_flt.h b/converter/other/jpeg2000/libjasper/jpc/jpc_flt.h
index 088eb00c..dc1950e3 100644
--- a/converter/other/jpeg2000/libjasper/jpc/jpc_flt.h
+++ b/converter/other/jpeg2000/libjasper/jpc/jpc_flt.h
@@ -6,14 +6,14 @@
  */
 
 /* __START_OF_JASPER_LICENSE__
- * 
+ *
  * JasPer Software License
- * 
+ *
  * IMAGE POWER JPEG-2000 PUBLIC LICENSE
  * ************************************
- * 
+ *
  * GRANT:
- * 
+ *
  * Permission is hereby granted, free of charge, to any person (the "User")
  * obtaining a copy of this software and associated documentation, to deal
  * in the JasPer Software without restriction, including without limitation
@@ -21,22 +21,22 @@
  * and/or sell copies of the JasPer Software (in source and binary forms),
  * and to permit persons to whom the JasPer Software is furnished to do so,
  * provided further that the License Conditions below are met.
- * 
+ *
  * License Conditions
  * ******************
- * 
+ *
  * A.  Redistributions of source code must retain the above copyright notice,
  * and this list of conditions, and the following disclaimer.
- * 
+ *
  * B.  Redistributions in binary form must reproduce the above copyright
  * notice, and this list of conditions, and the following disclaimer in
  * the documentation and/or other materials provided with the distribution.
- * 
+ *
  * C.  Neither the name of Image Power, Inc. nor any other contributor
  * (including, but not limited to, the University of British Columbia and
  * Michael David Adams) may be used to endorse or promote products derived
  * from this software without specific prior written permission.
- * 
+ *
  * D.  User agrees that it shall not commence any action against Image Power,
  * Inc., the University of British Columbia, Michael David Adams, or any
  * other contributors (collectively "Licensors") for infringement of any
@@ -56,17 +56,17 @@
  * trade dress, or service mark rights); and (v) divisions, continuations,
  * renewals, reissues and extensions of the foregoing (as and to the extent
  * applicable) now existing, hereafter filed, issued or acquired.
- * 
+ *
  * E.  If User commences an infringement action against any Licensor(s) then
  * such Licensor(s) shall have the right to terminate User's license and
  * all sublicenses that have been granted hereunder by User to other parties.
- * 
+ *
  * F.  This software is for use only in hardware or software products that
  * are compliant with ISO/IEC 15444-1 (i.e., JPEG-2000 Part 1).  No license
  * or right to this Software is granted for products that do not comply
  * with ISO/IEC 15444-1.  The JPEG-2000 Part 1 standard can be purchased
  * from the ISO.
- * 
+ *
  * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS LICENSE.
  * NO USE OF THE JASPER SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER
  * THIS DISCLAIMER.  THE JASPER SOFTWARE IS PROVIDED BY THE LICENSORS AND
@@ -106,7 +106,7 @@
  * TECHNOLOGY OR PRODUCTS FOR HIGH RISK ACTIVITIES AND WILL ENSURE THAT ITS
  * CUSTOMERS AND END-USERS OF ITS PRODUCTS ARE PROVIDED WITH A COPY OF THE
  * NOTICE SPECIFIED IN THIS SECTION.
- * 
+ *
  * __END_OF_JASPER_LICENSE__
  */
 
diff --git a/converter/other/jpeg2000/libjasper/jpc/jpc_math.c b/converter/other/jpeg2000/libjasper/jpc/jpc_math.c
index 01e3611e..420e0857 100644
--- a/converter/other/jpeg2000/libjasper/jpc/jpc_math.c
+++ b/converter/other/jpeg2000/libjasper/jpc/jpc_math.c
@@ -14,18 +14,18 @@
 int
 jpc_floorlog2(int_fast32_t const arg) {
 
-	int y;
+        int y;
     int x;
 
-	assert(arg > 0);
+        assert(arg > 0);
 
-	y = 0;
+        y = 0;
     x = arg;
-	while (x > 1) {
-		x >>= 1;
-		++y;
-	}
-	return y;
+        while (x > 1) {
+                x >>= 1;
+                ++y;
+        }
+        return y;
 }
 
 
@@ -34,12 +34,12 @@ jpc_floorlog2(int_fast32_t const arg) {
   jpc_floorlog2() and jpc_firstone() do the same thing.
   The only difference is how input 0 is handled.
 
-n                  : 0 1  2  3  4  5  6  7  8  9 10 11 12 13 14 15 16 17 18 19 
-ceil(log2(n))      : x 0  1  2  2  3  3  3  3  4  4  4  4  4  4  4  4  5  5  5 
-floor(log2(n))     : x 0  1  1  2  2  2  2  3  3  3  3  3  3  3  3  4  4  4  4 
-31-__builtin_clz(n): x 0  1  1  2  2  2  2  3  3  3  3  3  3  3  3  4  4  4  4 
-jpc_floorlog2(n)   : x 0  1  1  2  2  2  2  3  3  3  3  3  3  3  3  4  4  4  4 
-jpc_firstone(n)    :-1 0  1  1  2  2  2  2  3  3  3  3  3  3  3  3  4  4  4  4 
+n                  : 0 1  2  3  4  5  6  7  8  9 10 11 12 13 14 15 16 17 18 19
+ceil(log2(n))      : x 0  1  2  2  3  3  3  3  4  4  4  4  4  4  4  4  5  5  5
+floor(log2(n))     : x 0  1  1  2  2  2  2  3  3  3  3  3  3  3  3  4  4  4  4
+31-__builtin_clz(n): x 0  1  1  2  2  2  2  3  3  3  3  3  3  3  3  4  4  4  4
+jpc_floorlog2(n)   : x 0  1  1  2  2  2  2  3  3  3  3  3  3  3  3  4  4  4  4
+jpc_firstone(n)    :-1 0  1  1  2  2  2  2  3  3  3  3  3  3  3  3  4  4  4  4
 
 */
 
@@ -47,22 +47,24 @@ jpc_firstone(n)    :-1 0  1  1  2  2  2  2  3  3  3  3  3  3  3  3  4  4  4  4
 
 int
 jpc_firstone(int_fast32_t const arg) {
-/*---------------------------------------------------------------------------- 
+/*----------------------------------------------------------------------------
   Calculate the bit position of the first leading one in a nonnegative
   integer.
+
+  LSB is bit position 0.  Iff there are no ones, return -1.
 -----------------------------------------------------------------------------*/
-	int n;
+        int n;
     int x;
 
-	assert(arg >= 0);
+        assert(arg >= 0);
 
-	n = -1;
+        n = -1;
     x = arg;
-	while (x > 0) {
-		x >>= 1;
-		++n;
-	}
-	return n;
+        while (x > 0) {
+                x >>= 1;
+                ++n;
+        }
+        return n;
 }
 
 
@@ -75,14 +77,14 @@ jpc_firstone(int_fast32_t const arg) {
  */
 
 /* __START_OF_JASPER_LICENSE__
- * 
+ *
  * JasPer Software License
- * 
+ *
  * IMAGE POWER JPEG-2000 PUBLIC LICENSE
  * ************************************
- * 
+ *
  * GRANT:
- * 
+ *
  * Permission is hereby granted, free of charge, to any person (the "User")
  * obtaining a copy of this software and associated documentation, to deal
  * in the JasPer Software without restriction, including without limitation
@@ -90,22 +92,22 @@ jpc_firstone(int_fast32_t const arg) {
  * and/or sell copies of the JasPer Software (in source and binary forms),
  * and to permit persons to whom the JasPer Software is furnished to do so,
  * provided further that the License Conditions below are met.
- * 
+ *
  * License Conditions
  * ******************
- * 
+ *
  * A.  Redistributions of source code must retain the above copyright notice,
  * and this list of conditions, and the following disclaimer.
- * 
+ *
  * B.  Redistributions in binary form must reproduce the above copyright
  * notice, and this list of conditions, and the following disclaimer in
  * the documentation and/or other materials provided with the distribution.
- * 
+ *
  * C.  Neither the name of Image Power, Inc. nor any other contributor
  * (including, but not limited to, the University of British Columbia and
  * Michael David Adams) may be used to endorse or promote products derived
  * from this software without specific prior written permission.
- * 
+ *
  * D.  User agrees that it shall not commence any action against Image Power,
  * Inc., the University of British Columbia, Michael David Adams, or any
  * other contributors (collectively "Licensors") for infringement of any
@@ -125,17 +127,17 @@ jpc_firstone(int_fast32_t const arg) {
  * trade dress, or service mark rights); and (v) divisions, continuations,
  * renewals, reissues and extensions of the foregoing (as and to the extent
  * applicable) now existing, hereafter filed, issued or acquired.
- * 
+ *
  * E.  If User commences an infringement action against any Licensor(s) then
  * such Licensor(s) shall have the right to terminate User's license and
  * all sublicenses that have been granted hereunder by User to other parties.
- * 
+ *
  * F.  This software is for use only in hardware or software products that
  * are compliant with ISO/IEC 15444-1 (i.e., JPEG-2000 Part 1).  No license
  * or right to this Software is granted for products that do not comply
  * with ISO/IEC 15444-1.  The JPEG-2000 Part 1 standard can be purchased
  * from the ISO.
- * 
+ *
  * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS LICENSE.
  * NO USE OF THE JASPER SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER
  * THIS DISCLAIMER.  THE JASPER SOFTWARE IS PROVIDED BY THE LICENSORS AND
@@ -175,6 +177,6 @@ jpc_firstone(int_fast32_t const arg) {
  * TECHNOLOGY OR PRODUCTS FOR HIGH RISK ACTIVITIES AND WILL ENSURE THAT ITS
  * CUSTOMERS AND END-USERS OF ITS PRODUCTS ARE PROVIDED WITH A COPY OF THE
  * NOTICE SPECIFIED IN THIS SECTION.
- * 
+ *
  * __END_OF_JASPER_LICENSE__
  */
diff --git a/converter/other/jpeg2000/libjasper/jpc/jpc_math.h b/converter/other/jpeg2000/libjasper/jpc/jpc_math.h
index cd24c6a6..e08db334 100644
--- a/converter/other/jpeg2000/libjasper/jpc/jpc_math.h
+++ b/converter/other/jpeg2000/libjasper/jpc/jpc_math.h
@@ -4,14 +4,14 @@
  */
 
 /* __START_OF_JASPER_LICENSE__
- * 
+ *
  * JasPer Software License
- * 
+ *
  * IMAGE POWER JPEG-2000 PUBLIC LICENSE
  * ************************************
- * 
+ *
  * GRANT:
- * 
+ *
  * Permission is hereby granted, free of charge, to any person (the "User")
  * obtaining a copy of this software and associated documentation, to deal
  * in the JasPer Software without restriction, including without limitation
@@ -19,22 +19,22 @@
  * and/or sell copies of the JasPer Software (in source and binary forms),
  * and to permit persons to whom the JasPer Software is furnished to do so,
  * provided further that the License Conditions below are met.
- * 
+ *
  * License Conditions
  * ******************
- * 
+ *
  * A.  Redistributions of source code must retain the above copyright notice,
  * and this list of conditions, and the following disclaimer.
- * 
+ *
  * B.  Redistributions in binary form must reproduce the above copyright
  * notice, and this list of conditions, and the following disclaimer in
  * the documentation and/or other materials provided with the distribution.
- * 
+ *
  * C.  Neither the name of Image Power, Inc. nor any other contributor
  * (including, but not limited to, the University of British Columbia and
  * Michael David Adams) may be used to endorse or promote products derived
  * from this software without specific prior written permission.
- * 
+ *
  * D.  User agrees that it shall not commence any action against Image Power,
  * Inc., the University of British Columbia, Michael David Adams, or any
  * other contributors (collectively "Licensors") for infringement of any
@@ -54,17 +54,17 @@
  * trade dress, or service mark rights); and (v) divisions, continuations,
  * renewals, reissues and extensions of the foregoing (as and to the extent
  * applicable) now existing, hereafter filed, issued or acquired.
- * 
+ *
  * E.  If User commences an infringement action against any Licensor(s) then
  * such Licensor(s) shall have the right to terminate User's license and
  * all sublicenses that have been granted hereunder by User to other parties.
- * 
+ *
  * F.  This software is for use only in hardware or software products that
  * are compliant with ISO/IEC 15444-1 (i.e., JPEG-2000 Part 1).  No license
  * or right to this Software is granted for products that do not comply
  * with ISO/IEC 15444-1.  The JPEG-2000 Part 1 standard can be purchased
  * from the ISO.
- * 
+ *
  * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS LICENSE.
  * NO USE OF THE JASPER SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER
  * THIS DISCLAIMER.  THE JASPER SOFTWARE IS PROVIDED BY THE LICENSORS AND
@@ -104,12 +104,12 @@
  * TECHNOLOGY OR PRODUCTS FOR HIGH RISK ACTIVITIES AND WILL ENSURE THAT ITS
  * CUSTOMERS AND END-USERS OF ITS PRODUCTS ARE PROVIDED WITH A COPY OF THE
  * NOTICE SPECIFIED IN THIS SECTION.
- * 
+ *
  * __END_OF_JASPER_LICENSE__
  */
 
-#ifndef	JPC_MATH_H
-#define	JPC_MATH_H
+#ifndef JPC_MATH_H
+#define JPC_MATH_H
 
 /******************************************************************************\
 * Includes
@@ -123,23 +123,23 @@
 \******************************************************************************/
 
 /* Compute the floor of the quotient of two integers. */
-#define	JPC_FLOORDIV(x, y)	(assert(x >= 0 && y > 0), (x) / (y))
+#define JPC_FLOORDIV(x, y)      (assert(x >= 0 && y > 0), (x) / (y))
 
 /* Compute the ceiling of the quotient of two integers. */
-#define	JPC_CEILDIV(x, y)	(assert(x >= 0 && y > 0), ((x) + (y) - 1) / (y))
+#define JPC_CEILDIV(x, y)       (assert(x >= 0 && y > 0), ((x) + (y) - 1) / (y))
 
 /* Compute the floor of (x / 2^y). */
-#define	JPC_FLOORDIVPOW2(x, y) \
-	(assert(x >= 0 && y > 0), (x) >> (y))
+#define JPC_FLOORDIVPOW2(x, y) \
+        (assert(x >= 0 && y > 0), (x) >> (y))
 
 /* Compute the ceiling of (x / 2^y). */
-#define	JPC_CEILDIVPOW2(x, y) \
-	(assert(x >= 0 && y >= 0), ((x) + (1 << (y)) - 1) >> (y))
+#define JPC_CEILDIVPOW2(x, y) \
+        (assert(x >= 0 && y >= 0), ((x) + (1 << (y)) - 1) >> (y))
 /* JPC_CEILDIVPOW2U is for unsigned arguments (JPC_CEILDIVPOW2 would generate
    compiler warnings because of its superfluous >= 0 check)
 */
-#define	JPC_CEILDIVPOW2U(x, y) \
-	(((x) + (1 << (y)) - 1) >> (y))
+#define JPC_CEILDIVPOW2U(x, y) \
+        (((x) + (1 << (y)) - 1) >> (y))
 
 /******************************************************************************\
 * Functions.
diff --git a/converter/other/jpeg2000/libjasper/jpc/jpc_mct.c b/converter/other/jpeg2000/libjasper/jpc/jpc_mct.c
index 7c16c3e5..2d7ea47c 100644
--- a/converter/other/jpeg2000/libjasper/jpc/jpc_mct.c
+++ b/converter/other/jpeg2000/libjasper/jpc/jpc_mct.c
@@ -6,14 +6,14 @@
  */
 
 /* __START_OF_JASPER_LICENSE__
- * 
+ *
  * JasPer Software License
- * 
+ *
  * IMAGE POWER JPEG-2000 PUBLIC LICENSE
  * ************************************
- * 
+ *
  * GRANT:
- * 
+ *
  * Permission is hereby granted, free of charge, to any person (the "User")
  * obtaining a copy of this software and associated documentation, to deal
  * in the JasPer Software without restriction, including without limitation
@@ -21,22 +21,22 @@
  * and/or sell copies of the JasPer Software (in source and binary forms),
  * and to permit persons to whom the JasPer Software is furnished to do so,
  * provided further that the License Conditions below are met.
- * 
+ *
  * License Conditions
  * ******************
- * 
+ *
  * A.  Redistributions of source code must retain the above copyright notice,
  * and this list of conditions, and the following disclaimer.
- * 
+ *
  * B.  Redistributions in binary form must reproduce the above copyright
  * notice, and this list of conditions, and the following disclaimer in
  * the documentation and/or other materials provided with the distribution.
- * 
+ *
  * C.  Neither the name of Image Power, Inc. nor any other contributor
  * (including, but not limited to, the University of British Columbia and
  * Michael David Adams) may be used to endorse or promote products derived
  * from this software without specific prior written permission.
- * 
+ *
  * D.  User agrees that it shall not commence any action against Image Power,
  * Inc., the University of British Columbia, Michael David Adams, or any
  * other contributors (collectively "Licensors") for infringement of any
@@ -56,17 +56,17 @@
  * trade dress, or service mark rights); and (v) divisions, continuations,
  * renewals, reissues and extensions of the foregoing (as and to the extent
  * applicable) now existing, hereafter filed, issued or acquired.
- * 
+ *
  * E.  If User commences an infringement action against any Licensor(s) then
  * such Licensor(s) shall have the right to terminate User's license and
  * all sublicenses that have been granted hereunder by User to other parties.
- * 
+ *
  * F.  This software is for use only in hardware or software products that
  * are compliant with ISO/IEC 15444-1 (i.e., JPEG-2000 Part 1).  No license
  * or right to this Software is granted for products that do not comply
  * with ISO/IEC 15444-1.  The JPEG-2000 Part 1 standard can be purchased
  * from the ISO.
- * 
+ *
  * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS LICENSE.
  * NO USE OF THE JASPER SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER
  * THIS DISCLAIMER.  THE JASPER SOFTWARE IS PROVIDED BY THE LICENSORS AND
@@ -106,7 +106,7 @@
  * TECHNOLOGY OR PRODUCTS FOR HIGH RISK ACTIVITIES AND WILL ENSURE THAT ITS
  * CUSTOMERS AND END-USERS OF ITS PRODUCTS ARE PROVIDED WITH A COPY OF THE
  * NOTICE SPECIFIED IN THIS SECTION.
- * 
+ *
  * __END_OF_JASPER_LICENSE__
  */
 
@@ -135,203 +135,203 @@
 
 void jpc_rct(jas_matrix_t *c0, jas_matrix_t *c1, jas_matrix_t *c2)
 {
-	int numrows;
-	int numcols;
-	int i;
-	int j;
-	jpc_fix_t *c0p;
-	jpc_fix_t *c1p;
-	jpc_fix_t *c2p;
+        int numrows;
+        int numcols;
+        int i;
+        int j;
+        jpc_fix_t *c0p;
+        jpc_fix_t *c1p;
+        jpc_fix_t *c2p;
 
-	numrows = jas_matrix_numrows(c0);
-	numcols = jas_matrix_numcols(c0);
+        numrows = jas_matrix_numrows(c0);
+        numcols = jas_matrix_numcols(c0);
 
-	/* All three matrices must have the same dimensions. */
-	assert(jas_matrix_numrows(c1) == numrows && jas_matrix_numcols(c1) == numcols
-	  && jas_matrix_numrows(c2) == numrows && jas_matrix_numcols(c2) == numcols);
+        /* All three matrices must have the same dimensions. */
+        assert(jas_matrix_numrows(c1) == numrows && jas_matrix_numcols(c1) == numcols
+          && jas_matrix_numrows(c2) == numrows && jas_matrix_numcols(c2) == numcols);
 
-	for (i = 0; i < numrows; i++) {
-		c0p = jas_matrix_getref(c0, i, 0);
-		c1p = jas_matrix_getref(c1, i, 0);
-		c2p = jas_matrix_getref(c2, i, 0);
-		for (j = numcols; j > 0; --j) {
-			int r;
-			int g;
-			int b;
-			int y;
-			int u;
-			int v;
-			r = *c0p;
-			g = *c1p;
-			b = *c2p;
-			y = (r + (g << 1) + b) >> 2;
-			u = b - g;
-			v = r - g;
-			*c0p++ = y;
-			*c1p++ = u;
-			*c2p++ = v;
-		}
-	}
+        for (i = 0; i < numrows; i++) {
+                c0p = jas_matrix_getref(c0, i, 0);
+                c1p = jas_matrix_getref(c1, i, 0);
+                c2p = jas_matrix_getref(c2, i, 0);
+                for (j = numcols; j > 0; --j) {
+                        int r;
+                        int g;
+                        int b;
+                        int y;
+                        int u;
+                        int v;
+                        r = *c0p;
+                        g = *c1p;
+                        b = *c2p;
+                        y = (r + (g << 1) + b) >> 2;
+                        u = b - g;
+                        v = r - g;
+                        *c0p++ = y;
+                        *c1p++ = u;
+                        *c2p++ = v;
+                }
+        }
 }
 
 /* Compute the inverse RCT. */
 
 void jpc_irct(jas_matrix_t *c0, jas_matrix_t *c1, jas_matrix_t *c2)
 {
-	int numrows;
-	int numcols;
-	int i;
-	int j;
-	jpc_fix_t *c0p;
-	jpc_fix_t *c1p;
-	jpc_fix_t *c2p;
+        int numrows;
+        int numcols;
+        int i;
+        int j;
+        jpc_fix_t *c0p;
+        jpc_fix_t *c1p;
+        jpc_fix_t *c2p;
 
-	numrows = jas_matrix_numrows(c0);
-	numcols = jas_matrix_numcols(c0);
+        numrows = jas_matrix_numrows(c0);
+        numcols = jas_matrix_numcols(c0);
 
-	/* All three matrices must have the same dimensions. */
-	assert(jas_matrix_numrows(c1) == numrows && jas_matrix_numcols(c1) == numcols
-	  && jas_matrix_numrows(c2) == numrows && jas_matrix_numcols(c2) == numcols);
+        /* All three matrices must have the same dimensions. */
+        assert(jas_matrix_numrows(c1) == numrows && jas_matrix_numcols(c1) == numcols
+          && jas_matrix_numrows(c2) == numrows && jas_matrix_numcols(c2) == numcols);
 
-	for (i = 0; i < numrows; i++) {
-		c0p = jas_matrix_getref(c0, i, 0);
-		c1p = jas_matrix_getref(c1, i, 0);
-		c2p = jas_matrix_getref(c2, i, 0);
-		for (j = numcols; j > 0; --j) {
-			int r;
-			int g;
-			int b;
-			int y;
-			int u;
-			int v;
-			y = *c0p;
-			u = *c1p;
-			v = *c2p;
-			g = y - ((u + v) >> 2);
-			r = v + g;
-			b = u + g;
-			*c0p++ = r;
-			*c1p++ = g;
-			*c2p++ = b;
-		}
-	}
+        for (i = 0; i < numrows; i++) {
+                c0p = jas_matrix_getref(c0, i, 0);
+                c1p = jas_matrix_getref(c1, i, 0);
+                c2p = jas_matrix_getref(c2, i, 0);
+                for (j = numcols; j > 0; --j) {
+                        int r;
+                        int g;
+                        int b;
+                        int y;
+                        int u;
+                        int v;
+                        y = *c0p;
+                        u = *c1p;
+                        v = *c2p;
+                        g = y - ((u + v) >> 2);
+                        r = v + g;
+                        b = u + g;
+                        *c0p++ = r;
+                        *c1p++ = g;
+                        *c2p++ = b;
+                }
+        }
 }
 
 void jpc_ict(jas_matrix_t *c0, jas_matrix_t *c1, jas_matrix_t *c2)
 {
-	int numrows;
-	int numcols;
-	int i;
-	int j;
-	jpc_fix_t r;
-	jpc_fix_t g;
-	jpc_fix_t b;
-	jpc_fix_t y;
-	jpc_fix_t u;
-	jpc_fix_t v;
-	jpc_fix_t *c0p;
-	jpc_fix_t *c1p;
-	jpc_fix_t *c2p;
+        int numrows;
+        int numcols;
+        int i;
+        int j;
+        jpc_fix_t r;
+        jpc_fix_t g;
+        jpc_fix_t b;
+        jpc_fix_t y;
+        jpc_fix_t u;
+        jpc_fix_t v;
+        jpc_fix_t *c0p;
+        jpc_fix_t *c1p;
+        jpc_fix_t *c2p;
 
-	numrows = jas_matrix_numrows(c0);
-	assert(jas_matrix_numrows(c1) == numrows && jas_matrix_numrows(c2) == numrows);
-	numcols = jas_matrix_numcols(c0);
-	assert(jas_matrix_numcols(c1) == numcols && jas_matrix_numcols(c2) == numcols);
-	for (i = 0; i < numrows; ++i) {
-		c0p = jas_matrix_getref(c0, i, 0);
-		c1p = jas_matrix_getref(c1, i, 0);
-		c2p = jas_matrix_getref(c2, i, 0);
-		for (j = numcols; j > 0; --j) {
-			r = *c0p;
-			g = *c1p;
-			b = *c2p;
-			y = jpc_fix_add3(jpc_fix_mul(jpc_dbltofix(0.299), r), jpc_fix_mul(jpc_dbltofix(0.587), g),
-			  jpc_fix_mul(jpc_dbltofix(0.114), b));
-			u = jpc_fix_add3(jpc_fix_mul(jpc_dbltofix(-0.16875), r), jpc_fix_mul(jpc_dbltofix(-0.33126), g),
-			  jpc_fix_mul(jpc_dbltofix(0.5), b));
-			v = jpc_fix_add3(jpc_fix_mul(jpc_dbltofix(0.5), r), jpc_fix_mul(jpc_dbltofix(-0.41869), g),
-			  jpc_fix_mul(jpc_dbltofix(-0.08131), b));
-			*c0p++ = y;
-			*c1p++ = u;
-			*c2p++ = v;
-		}
-	}
+        numrows = jas_matrix_numrows(c0);
+        assert(jas_matrix_numrows(c1) == numrows && jas_matrix_numrows(c2) == numrows);
+        numcols = jas_matrix_numcols(c0);
+        assert(jas_matrix_numcols(c1) == numcols && jas_matrix_numcols(c2) == numcols);
+        for (i = 0; i < numrows; ++i) {
+                c0p = jas_matrix_getref(c0, i, 0);
+                c1p = jas_matrix_getref(c1, i, 0);
+                c2p = jas_matrix_getref(c2, i, 0);
+                for (j = numcols; j > 0; --j) {
+                        r = *c0p;
+                        g = *c1p;
+                        b = *c2p;
+                        y = jpc_fix_add3(jpc_fix_mul(jpc_dbltofix(0.299), r), jpc_fix_mul(jpc_dbltofix(0.587), g),
+                          jpc_fix_mul(jpc_dbltofix(0.114), b));
+                        u = jpc_fix_add3(jpc_fix_mul(jpc_dbltofix(-0.16875), r), jpc_fix_mul(jpc_dbltofix(-0.33126), g),
+                          jpc_fix_mul(jpc_dbltofix(0.5), b));
+                        v = jpc_fix_add3(jpc_fix_mul(jpc_dbltofix(0.5), r), jpc_fix_mul(jpc_dbltofix(-0.41869), g),
+                          jpc_fix_mul(jpc_dbltofix(-0.08131), b));
+                        *c0p++ = y;
+                        *c1p++ = u;
+                        *c2p++ = v;
+                }
+        }
 }
 
 void jpc_iict(jas_matrix_t *c0, jas_matrix_t *c1, jas_matrix_t *c2)
 {
-	int numrows;
-	int numcols;
-	int i;
-	int j;
-	jpc_fix_t r;
-	jpc_fix_t g;
-	jpc_fix_t b;
-	jpc_fix_t y;
-	jpc_fix_t u;
-	jpc_fix_t v;
-	jpc_fix_t *c0p;
-	jpc_fix_t *c1p;
-	jpc_fix_t *c2p;
+        int numrows;
+        int numcols;
+        int i;
+        int j;
+        jpc_fix_t r;
+        jpc_fix_t g;
+        jpc_fix_t b;
+        jpc_fix_t y;
+        jpc_fix_t u;
+        jpc_fix_t v;
+        jpc_fix_t *c0p;
+        jpc_fix_t *c1p;
+        jpc_fix_t *c2p;
 
-	numrows = jas_matrix_numrows(c0);
-	assert(jas_matrix_numrows(c1) == numrows && jas_matrix_numrows(c2) == numrows);
-	numcols = jas_matrix_numcols(c0);
-	assert(jas_matrix_numcols(c1) == numcols && jas_matrix_numcols(c2) == numcols);
-	for (i = 0; i < numrows; ++i) {
-		c0p = jas_matrix_getref(c0, i, 0);
-		c1p = jas_matrix_getref(c1, i, 0);
-		c2p = jas_matrix_getref(c2, i, 0);
-		for (j = numcols; j > 0; --j) {
-			y = *c0p;
-			u = *c1p;
-			v = *c2p;
-			r = jpc_fix_add(y, jpc_fix_mul(jpc_dbltofix(1.402), v));
-			g = jpc_fix_add3(y, jpc_fix_mul(jpc_dbltofix(-0.34413), u),
-			  jpc_fix_mul(jpc_dbltofix(-0.71414), v));
-			b = jpc_fix_add(y, jpc_fix_mul(jpc_dbltofix(1.772), u));
-			*c0p++ = r;
-			*c1p++ = g;
-			*c2p++ = b;
-		}
-	}
+        numrows = jas_matrix_numrows(c0);
+        assert(jas_matrix_numrows(c1) == numrows && jas_matrix_numrows(c2) == numrows);
+        numcols = jas_matrix_numcols(c0);
+        assert(jas_matrix_numcols(c1) == numcols && jas_matrix_numcols(c2) == numcols);
+        for (i = 0; i < numrows; ++i) {
+                c0p = jas_matrix_getref(c0, i, 0);
+                c1p = jas_matrix_getref(c1, i, 0);
+                c2p = jas_matrix_getref(c2, i, 0);
+                for (j = numcols; j > 0; --j) {
+                        y = *c0p;
+                        u = *c1p;
+                        v = *c2p;
+                        r = jpc_fix_add(y, jpc_fix_mul(jpc_dbltofix(1.402), v));
+                        g = jpc_fix_add3(y, jpc_fix_mul(jpc_dbltofix(-0.34413), u),
+                          jpc_fix_mul(jpc_dbltofix(-0.71414), v));
+                        b = jpc_fix_add(y, jpc_fix_mul(jpc_dbltofix(1.772), u));
+                        *c0p++ = r;
+                        *c1p++ = g;
+                        *c2p++ = b;
+                }
+        }
 }
 
 jpc_fix_t jpc_mct_getsynweight(int mctid, int cmptno)
 {
-	jpc_fix_t synweight;
+        jpc_fix_t synweight;
 
-	switch (mctid) {
-	case JPC_MCT_RCT:
-		switch (cmptno) {
-		case 0:
-			synweight = jpc_dbltofix(sqrt(3.0));
-			break;
-		case 1:
-			synweight = jpc_dbltofix(sqrt(0.6875));
-			break;
-		case 2:
-			synweight = jpc_dbltofix(sqrt(0.6875));
-			break;
-		}
-		break;
-	case JPC_MCT_ICT:
-		switch (cmptno) {
-		case 0:
-			synweight = jpc_dbltofix(sqrt(3.0000));
-			break;
-		case 1:
-			synweight = jpc_dbltofix(sqrt(3.2584));
-			break;
-		case 2:
-			synweight = jpc_dbltofix(sqrt(2.4755));
-			break;
-		}
-		break;
-	default:
-		synweight = JPC_FIX_ONE;
-		break;
-	}
+        switch (mctid) {
+        case JPC_MCT_RCT:
+                switch (cmptno) {
+                case 0:
+                        synweight = jpc_dbltofix(sqrt(3.0));
+                        break;
+                case 1:
+                        synweight = jpc_dbltofix(sqrt(0.6875));
+                        break;
+                case 2:
+                        synweight = jpc_dbltofix(sqrt(0.6875));
+                        break;
+                }
+                break;
+        case JPC_MCT_ICT:
+                switch (cmptno) {
+                case 0:
+                        synweight = jpc_dbltofix(sqrt(3.0000));
+                        break;
+                case 1:
+                        synweight = jpc_dbltofix(sqrt(3.2584));
+                        break;
+                case 2:
+                        synweight = jpc_dbltofix(sqrt(2.4755));
+                        break;
+                }
+                break;
+        default:
+                synweight = JPC_FIX_ONE;
+                break;
+        }
 
-	return synweight;
+        return synweight;
 }
diff --git a/converter/other/jpeg2000/libjasper/jpc/jpc_mct.h b/converter/other/jpeg2000/libjasper/jpc/jpc_mct.h
index d03d6ce1..bb424900 100644
--- a/converter/other/jpeg2000/libjasper/jpc/jpc_mct.h
+++ b/converter/other/jpeg2000/libjasper/jpc/jpc_mct.h
@@ -6,14 +6,14 @@
  */
 
 /* __START_OF_JASPER_LICENSE__
- * 
+ *
  * JasPer Software License
- * 
+ *
  * IMAGE POWER JPEG-2000 PUBLIC LICENSE
  * ************************************
- * 
+ *
  * GRANT:
- * 
+ *
  * Permission is hereby granted, free of charge, to any person (the "User")
  * obtaining a copy of this software and associated documentation, to deal
  * in the JasPer Software without restriction, including without limitation
@@ -21,22 +21,22 @@
  * and/or sell copies of the JasPer Software (in source and binary forms),
  * and to permit persons to whom the JasPer Software is furnished to do so,
  * provided further that the License Conditions below are met.
- * 
+ *
  * License Conditions
  * ******************
- * 
+ *
  * A.  Redistributions of source code must retain the above copyright notice,
  * and this list of conditions, and the following disclaimer.
- * 
+ *
  * B.  Redistributions in binary form must reproduce the above copyright
  * notice, and this list of conditions, and the following disclaimer in
  * the documentation and/or other materials provided with the distribution.
- * 
+ *
  * C.  Neither the name of Image Power, Inc. nor any other contributor
  * (including, but not limited to, the University of British Columbia and
  * Michael David Adams) may be used to endorse or promote products derived
  * from this software without specific prior written permission.
- * 
+ *
  * D.  User agrees that it shall not commence any action against Image Power,
  * Inc., the University of British Columbia, Michael David Adams, or any
  * other contributors (collectively "Licensors") for infringement of any
@@ -56,17 +56,17 @@
  * trade dress, or service mark rights); and (v) divisions, continuations,
  * renewals, reissues and extensions of the foregoing (as and to the extent
  * applicable) now existing, hereafter filed, issued or acquired.
- * 
+ *
  * E.  If User commences an infringement action against any Licensor(s) then
  * such Licensor(s) shall have the right to terminate User's license and
  * all sublicenses that have been granted hereunder by User to other parties.
- * 
+ *
  * F.  This software is for use only in hardware or software products that
  * are compliant with ISO/IEC 15444-1 (i.e., JPEG-2000 Part 1).  No license
  * or right to this Software is granted for products that do not comply
  * with ISO/IEC 15444-1.  The JPEG-2000 Part 1 standard can be purchased
  * from the ISO.
- * 
+ *
  * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS LICENSE.
  * NO USE OF THE JASPER SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER
  * THIS DISCLAIMER.  THE JASPER SOFTWARE IS PROVIDED BY THE LICENSORS AND
@@ -106,7 +106,7 @@
  * TECHNOLOGY OR PRODUCTS FOR HIGH RISK ACTIVITIES AND WILL ENSURE THAT ITS
  * CUSTOMERS AND END-USERS OF ITS PRODUCTS ARE PROVIDED WITH A COPY OF THE
  * NOTICE SPECIFIED IN THIS SECTION.
- * 
+ *
  * __END_OF_JASPER_LICENSE__
  */
 
@@ -134,9 +134,9 @@
  * Multicomponent transform IDs.
  */
 
-#define JPC_MCT_NONE	0
-#define JPC_MCT_ICT		1
-#define JPC_MCT_RCT		2
+#define JPC_MCT_NONE    0
+#define JPC_MCT_ICT             1
+#define JPC_MCT_RCT             2
 
 /******************************************************************************\
 * Functions.
diff --git a/converter/other/jpeg2000/libjasper/jpc/jpc_mqcod.c b/converter/other/jpeg2000/libjasper/jpc/jpc_mqcod.c
index 535eaa2d..e19f94ad 100644
--- a/converter/other/jpeg2000/libjasper/jpc/jpc_mqcod.c
+++ b/converter/other/jpeg2000/libjasper/jpc/jpc_mqcod.c
@@ -6,14 +6,14 @@
  */
 
 /* __START_OF_JASPER_LICENSE__
- * 
+ *
  * JasPer Software License
- * 
+ *
  * IMAGE POWER JPEG-2000 PUBLIC LICENSE
  * ************************************
- * 
+ *
  * GRANT:
- * 
+ *
  * Permission is hereby granted, free of charge, to any person (the "User")
  * obtaining a copy of this software and associated documentation, to deal
  * in the JasPer Software without restriction, including without limitation
@@ -21,22 +21,22 @@
  * and/or sell copies of the JasPer Software (in source and binary forms),
  * and to permit persons to whom the JasPer Software is furnished to do so,
  * provided further that the License Conditions below are met.
- * 
+ *
  * License Conditions
  * ******************
- * 
+ *
  * A.  Redistributions of source code must retain the above copyright notice,
  * and this list of conditions, and the following disclaimer.
- * 
+ *
  * B.  Redistributions in binary form must reproduce the above copyright
  * notice, and this list of conditions, and the following disclaimer in
  * the documentation and/or other materials provided with the distribution.
- * 
+ *
  * C.  Neither the name of Image Power, Inc. nor any other contributor
  * (including, but not limited to, the University of British Columbia and
  * Michael David Adams) may be used to endorse or promote products derived
  * from this software without specific prior written permission.
- * 
+ *
  * D.  User agrees that it shall not commence any action against Image Power,
  * Inc., the University of British Columbia, Michael David Adams, or any
  * other contributors (collectively "Licensors") for infringement of any
@@ -56,17 +56,17 @@
  * trade dress, or service mark rights); and (v) divisions, continuations,
  * renewals, reissues and extensions of the foregoing (as and to the extent
  * applicable) now existing, hereafter filed, issued or acquired.
- * 
+ *
  * E.  If User commences an infringement action against any Licensor(s) then
  * such Licensor(s) shall have the right to terminate User's license and
  * all sublicenses that have been granted hereunder by User to other parties.
- * 
+ *
  * F.  This software is for use only in hardware or software products that
  * are compliant with ISO/IEC 15444-1 (i.e., JPEG-2000 Part 1).  No license
  * or right to this Software is granted for products that do not comply
  * with ISO/IEC 15444-1.  The JPEG-2000 Part 1 standard can be purchased
  * from the ISO.
- * 
+ *
  * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS LICENSE.
  * NO USE OF THE JASPER SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER
  * THIS DISCLAIMER.  THE JASPER SOFTWARE IS PROVIDED BY THE LICENSORS AND
@@ -106,7 +106,7 @@
  * TECHNOLOGY OR PRODUCTS FOR HIGH RISK ACTIVITIES AND WILL ENSURE THAT ITS
  * CUSTOMERS AND END-USERS OF ITS PRODUCTS ARE PROVIDED WITH A COPY OF THE
  * NOTICE SPECIFIED IN THIS SECTION.
- * 
+ *
  * __END_OF_JASPER_LICENSE__
  */
 
@@ -131,98 +131,98 @@
 /* MQ coder per-state information. */
 
 jpc_mqstate_t jpc_mqstates[47 * 2] = {
-	{0x5601, 0, &jpc_mqstates[ 2], &jpc_mqstates[ 3]},
-	{0x5601, 1, &jpc_mqstates[ 3], &jpc_mqstates[ 2]},
-	{0x3401, 0, &jpc_mqstates[ 4], &jpc_mqstates[12]},
-	{0x3401, 1, &jpc_mqstates[ 5], &jpc_mqstates[13]},
-	{0x1801, 0, &jpc_mqstates[ 6], &jpc_mqstates[18]},
-	{0x1801, 1, &jpc_mqstates[ 7], &jpc_mqstates[19]},
-	{0x0ac1, 0, &jpc_mqstates[ 8], &jpc_mqstates[24]},
-	{0x0ac1, 1, &jpc_mqstates[ 9], &jpc_mqstates[25]},
-	{0x0521, 0, &jpc_mqstates[10], &jpc_mqstates[58]},
-	{0x0521, 1, &jpc_mqstates[11], &jpc_mqstates[59]},
-	{0x0221, 0, &jpc_mqstates[76], &jpc_mqstates[66]},
-	{0x0221, 1, &jpc_mqstates[77], &jpc_mqstates[67]},
-	{0x5601, 0, &jpc_mqstates[14], &jpc_mqstates[13]},
-	{0x5601, 1, &jpc_mqstates[15], &jpc_mqstates[12]},
-	{0x5401, 0, &jpc_mqstates[16], &jpc_mqstates[28]},
-	{0x5401, 1, &jpc_mqstates[17], &jpc_mqstates[29]},
-	{0x4801, 0, &jpc_mqstates[18], &jpc_mqstates[28]},
-	{0x4801, 1, &jpc_mqstates[19], &jpc_mqstates[29]},
-	{0x3801, 0, &jpc_mqstates[20], &jpc_mqstates[28]},
-	{0x3801, 1, &jpc_mqstates[21], &jpc_mqstates[29]},
-	{0x3001, 0, &jpc_mqstates[22], &jpc_mqstates[34]},
-	{0x3001, 1, &jpc_mqstates[23], &jpc_mqstates[35]},
-	{0x2401, 0, &jpc_mqstates[24], &jpc_mqstates[36]},
-	{0x2401, 1, &jpc_mqstates[25], &jpc_mqstates[37]},
-	{0x1c01, 0, &jpc_mqstates[26], &jpc_mqstates[40]},
-	{0x1c01, 1, &jpc_mqstates[27], &jpc_mqstates[41]},
-	{0x1601, 0, &jpc_mqstates[58], &jpc_mqstates[42]},
-	{0x1601, 1, &jpc_mqstates[59], &jpc_mqstates[43]},
-	{0x5601, 0, &jpc_mqstates[30], &jpc_mqstates[29]},
-	{0x5601, 1, &jpc_mqstates[31], &jpc_mqstates[28]},
-	{0x5401, 0, &jpc_mqstates[32], &jpc_mqstates[28]},
-	{0x5401, 1, &jpc_mqstates[33], &jpc_mqstates[29]},
-	{0x5101, 0, &jpc_mqstates[34], &jpc_mqstates[30]},
-	{0x5101, 1, &jpc_mqstates[35], &jpc_mqstates[31]},
-	{0x4801, 0, &jpc_mqstates[36], &jpc_mqstates[32]},
-	{0x4801, 1, &jpc_mqstates[37], &jpc_mqstates[33]},
-	{0x3801, 0, &jpc_mqstates[38], &jpc_mqstates[34]},
-	{0x3801, 1, &jpc_mqstates[39], &jpc_mqstates[35]},
-	{0x3401, 0, &jpc_mqstates[40], &jpc_mqstates[36]},
-	{0x3401, 1, &jpc_mqstates[41], &jpc_mqstates[37]},
-	{0x3001, 0, &jpc_mqstates[42], &jpc_mqstates[38]},
-	{0x3001, 1, &jpc_mqstates[43], &jpc_mqstates[39]},
-	{0x2801, 0, &jpc_mqstates[44], &jpc_mqstates[38]},
-	{0x2801, 1, &jpc_mqstates[45], &jpc_mqstates[39]},
-	{0x2401, 0, &jpc_mqstates[46], &jpc_mqstates[40]},
-	{0x2401, 1, &jpc_mqstates[47], &jpc_mqstates[41]},
-	{0x2201, 0, &jpc_mqstates[48], &jpc_mqstates[42]},
-	{0x2201, 1, &jpc_mqstates[49], &jpc_mqstates[43]},
-	{0x1c01, 0, &jpc_mqstates[50], &jpc_mqstates[44]},
-	{0x1c01, 1, &jpc_mqstates[51], &jpc_mqstates[45]},
-	{0x1801, 0, &jpc_mqstates[52], &jpc_mqstates[46]},
-	{0x1801, 1, &jpc_mqstates[53], &jpc_mqstates[47]},
-	{0x1601, 0, &jpc_mqstates[54], &jpc_mqstates[48]},
-	{0x1601, 1, &jpc_mqstates[55], &jpc_mqstates[49]},
-	{0x1401, 0, &jpc_mqstates[56], &jpc_mqstates[50]},
-	{0x1401, 1, &jpc_mqstates[57], &jpc_mqstates[51]},
-	{0x1201, 0, &jpc_mqstates[58], &jpc_mqstates[52]},
-	{0x1201, 1, &jpc_mqstates[59], &jpc_mqstates[53]},
-	{0x1101, 0, &jpc_mqstates[60], &jpc_mqstates[54]},
-	{0x1101, 1, &jpc_mqstates[61], &jpc_mqstates[55]},
-	{0x0ac1, 0, &jpc_mqstates[62], &jpc_mqstates[56]},
-	{0x0ac1, 1, &jpc_mqstates[63], &jpc_mqstates[57]},
-	{0x09c1, 0, &jpc_mqstates[64], &jpc_mqstates[58]},
-	{0x09c1, 1, &jpc_mqstates[65], &jpc_mqstates[59]},
-	{0x08a1, 0, &jpc_mqstates[66], &jpc_mqstates[60]},
-	{0x08a1, 1, &jpc_mqstates[67], &jpc_mqstates[61]},
-	{0x0521, 0, &jpc_mqstates[68], &jpc_mqstates[62]},
-	{0x0521, 1, &jpc_mqstates[69], &jpc_mqstates[63]},
-	{0x0441, 0, &jpc_mqstates[70], &jpc_mqstates[64]},
-	{0x0441, 1, &jpc_mqstates[71], &jpc_mqstates[65]},
-	{0x02a1, 0, &jpc_mqstates[72], &jpc_mqstates[66]},
-	{0x02a1, 1, &jpc_mqstates[73], &jpc_mqstates[67]},
-	{0x0221, 0, &jpc_mqstates[74], &jpc_mqstates[68]},
-	{0x0221, 1, &jpc_mqstates[75], &jpc_mqstates[69]},
-	{0x0141, 0, &jpc_mqstates[76], &jpc_mqstates[70]},
-	{0x0141, 1, &jpc_mqstates[77], &jpc_mqstates[71]},
-	{0x0111, 0, &jpc_mqstates[78], &jpc_mqstates[72]},
-	{0x0111, 1, &jpc_mqstates[79], &jpc_mqstates[73]},
-	{0x0085, 0, &jpc_mqstates[80], &jpc_mqstates[74]},
-	{0x0085, 1, &jpc_mqstates[81], &jpc_mqstates[75]},
-	{0x0049, 0, &jpc_mqstates[82], &jpc_mqstates[76]},
-	{0x0049, 1, &jpc_mqstates[83], &jpc_mqstates[77]},
-	{0x0025, 0, &jpc_mqstates[84], &jpc_mqstates[78]},
-	{0x0025, 1, &jpc_mqstates[85], &jpc_mqstates[79]},
-	{0x0015, 0, &jpc_mqstates[86], &jpc_mqstates[80]},
-	{0x0015, 1, &jpc_mqstates[87], &jpc_mqstates[81]},
-	{0x0009, 0, &jpc_mqstates[88], &jpc_mqstates[82]},
-	{0x0009, 1, &jpc_mqstates[89], &jpc_mqstates[83]},
-	{0x0005, 0, &jpc_mqstates[90], &jpc_mqstates[84]},
-	{0x0005, 1, &jpc_mqstates[91], &jpc_mqstates[85]},
-	{0x0001, 0, &jpc_mqstates[90], &jpc_mqstates[86]},
-	{0x0001, 1, &jpc_mqstates[91], &jpc_mqstates[87]},
-	{0x5601, 0, &jpc_mqstates[92], &jpc_mqstates[92]},
-	{0x5601, 1, &jpc_mqstates[93], &jpc_mqstates[93]},
+        {0x5601, 0, &jpc_mqstates[ 2], &jpc_mqstates[ 3]},
+        {0x5601, 1, &jpc_mqstates[ 3], &jpc_mqstates[ 2]},
+        {0x3401, 0, &jpc_mqstates[ 4], &jpc_mqstates[12]},
+        {0x3401, 1, &jpc_mqstates[ 5], &jpc_mqstates[13]},
+        {0x1801, 0, &jpc_mqstates[ 6], &jpc_mqstates[18]},
+        {0x1801, 1, &jpc_mqstates[ 7], &jpc_mqstates[19]},
+        {0x0ac1, 0, &jpc_mqstates[ 8], &jpc_mqstates[24]},
+        {0x0ac1, 1, &jpc_mqstates[ 9], &jpc_mqstates[25]},
+        {0x0521, 0, &jpc_mqstates[10], &jpc_mqstates[58]},
+        {0x0521, 1, &jpc_mqstates[11], &jpc_mqstates[59]},
+        {0x0221, 0, &jpc_mqstates[76], &jpc_mqstates[66]},
+        {0x0221, 1, &jpc_mqstates[77], &jpc_mqstates[67]},
+        {0x5601, 0, &jpc_mqstates[14], &jpc_mqstates[13]},
+        {0x5601, 1, &jpc_mqstates[15], &jpc_mqstates[12]},
+        {0x5401, 0, &jpc_mqstates[16], &jpc_mqstates[28]},
+        {0x5401, 1, &jpc_mqstates[17], &jpc_mqstates[29]},
+        {0x4801, 0, &jpc_mqstates[18], &jpc_mqstates[28]},
+        {0x4801, 1, &jpc_mqstates[19], &jpc_mqstates[29]},
+        {0x3801, 0, &jpc_mqstates[20], &jpc_mqstates[28]},
+        {0x3801, 1, &jpc_mqstates[21], &jpc_mqstates[29]},
+        {0x3001, 0, &jpc_mqstates[22], &jpc_mqstates[34]},
+        {0x3001, 1, &jpc_mqstates[23], &jpc_mqstates[35]},
+        {0x2401, 0, &jpc_mqstates[24], &jpc_mqstates[36]},
+        {0x2401, 1, &jpc_mqstates[25], &jpc_mqstates[37]},
+        {0x1c01, 0, &jpc_mqstates[26], &jpc_mqstates[40]},
+        {0x1c01, 1, &jpc_mqstates[27], &jpc_mqstates[41]},
+        {0x1601, 0, &jpc_mqstates[58], &jpc_mqstates[42]},
+        {0x1601, 1, &jpc_mqstates[59], &jpc_mqstates[43]},
+        {0x5601, 0, &jpc_mqstates[30], &jpc_mqstates[29]},
+        {0x5601, 1, &jpc_mqstates[31], &jpc_mqstates[28]},
+        {0x5401, 0, &jpc_mqstates[32], &jpc_mqstates[28]},
+        {0x5401, 1, &jpc_mqstates[33], &jpc_mqstates[29]},
+        {0x5101, 0, &jpc_mqstates[34], &jpc_mqstates[30]},
+        {0x5101, 1, &jpc_mqstates[35], &jpc_mqstates[31]},
+        {0x4801, 0, &jpc_mqstates[36], &jpc_mqstates[32]},
+        {0x4801, 1, &jpc_mqstates[37], &jpc_mqstates[33]},
+        {0x3801, 0, &jpc_mqstates[38], &jpc_mqstates[34]},
+        {0x3801, 1, &jpc_mqstates[39], &jpc_mqstates[35]},
+        {0x3401, 0, &jpc_mqstates[40], &jpc_mqstates[36]},
+        {0x3401, 1, &jpc_mqstates[41], &jpc_mqstates[37]},
+        {0x3001, 0, &jpc_mqstates[42], &jpc_mqstates[38]},
+        {0x3001, 1, &jpc_mqstates[43], &jpc_mqstates[39]},
+        {0x2801, 0, &jpc_mqstates[44], &jpc_mqstates[38]},
+        {0x2801, 1, &jpc_mqstates[45], &jpc_mqstates[39]},
+        {0x2401, 0, &jpc_mqstates[46], &jpc_mqstates[40]},
+        {0x2401, 1, &jpc_mqstates[47], &jpc_mqstates[41]},
+        {0x2201, 0, &jpc_mqstates[48], &jpc_mqstates[42]},
+        {0x2201, 1, &jpc_mqstates[49], &jpc_mqstates[43]},
+        {0x1c01, 0, &jpc_mqstates[50], &jpc_mqstates[44]},
+        {0x1c01, 1, &jpc_mqstates[51], &jpc_mqstates[45]},
+        {0x1801, 0, &jpc_mqstates[52], &jpc_mqstates[46]},
+        {0x1801, 1, &jpc_mqstates[53], &jpc_mqstates[47]},
+        {0x1601, 0, &jpc_mqstates[54], &jpc_mqstates[48]},
+        {0x1601, 1, &jpc_mqstates[55], &jpc_mqstates[49]},
+        {0x1401, 0, &jpc_mqstates[56], &jpc_mqstates[50]},
+        {0x1401, 1, &jpc_mqstates[57], &jpc_mqstates[51]},
+        {0x1201, 0, &jpc_mqstates[58], &jpc_mqstates[52]},
+        {0x1201, 1, &jpc_mqstates[59], &jpc_mqstates[53]},
+        {0x1101, 0, &jpc_mqstates[60], &jpc_mqstates[54]},
+        {0x1101, 1, &jpc_mqstates[61], &jpc_mqstates[55]},
+        {0x0ac1, 0, &jpc_mqstates[62], &jpc_mqstates[56]},
+        {0x0ac1, 1, &jpc_mqstates[63], &jpc_mqstates[57]},
+        {0x09c1, 0, &jpc_mqstates[64], &jpc_mqstates[58]},
+        {0x09c1, 1, &jpc_mqstates[65], &jpc_mqstates[59]},
+        {0x08a1, 0, &jpc_mqstates[66], &jpc_mqstates[60]},
+        {0x08a1, 1, &jpc_mqstates[67], &jpc_mqstates[61]},
+        {0x0521, 0, &jpc_mqstates[68], &jpc_mqstates[62]},
+        {0x0521, 1, &jpc_mqstates[69], &jpc_mqstates[63]},
+        {0x0441, 0, &jpc_mqstates[70], &jpc_mqstates[64]},
+        {0x0441, 1, &jpc_mqstates[71], &jpc_mqstates[65]},
+        {0x02a1, 0, &jpc_mqstates[72], &jpc_mqstates[66]},
+        {0x02a1, 1, &jpc_mqstates[73], &jpc_mqstates[67]},
+        {0x0221, 0, &jpc_mqstates[74], &jpc_mqstates[68]},
+        {0x0221, 1, &jpc_mqstates[75], &jpc_mqstates[69]},
+        {0x0141, 0, &jpc_mqstates[76], &jpc_mqstates[70]},
+        {0x0141, 1, &jpc_mqstates[77], &jpc_mqstates[71]},
+        {0x0111, 0, &jpc_mqstates[78], &jpc_mqstates[72]},
+        {0x0111, 1, &jpc_mqstates[79], &jpc_mqstates[73]},
+        {0x0085, 0, &jpc_mqstates[80], &jpc_mqstates[74]},
+        {0x0085, 1, &jpc_mqstates[81], &jpc_mqstates[75]},
+        {0x0049, 0, &jpc_mqstates[82], &jpc_mqstates[76]},
+        {0x0049, 1, &jpc_mqstates[83], &jpc_mqstates[77]},
+        {0x0025, 0, &jpc_mqstates[84], &jpc_mqstates[78]},
+        {0x0025, 1, &jpc_mqstates[85], &jpc_mqstates[79]},
+        {0x0015, 0, &jpc_mqstates[86], &jpc_mqstates[80]},
+        {0x0015, 1, &jpc_mqstates[87], &jpc_mqstates[81]},
+        {0x0009, 0, &jpc_mqstates[88], &jpc_mqstates[82]},
+        {0x0009, 1, &jpc_mqstates[89], &jpc_mqstates[83]},
+        {0x0005, 0, &jpc_mqstates[90], &jpc_mqstates[84]},
+        {0x0005, 1, &jpc_mqstates[91], &jpc_mqstates[85]},
+        {0x0001, 0, &jpc_mqstates[90], &jpc_mqstates[86]},
+        {0x0001, 1, &jpc_mqstates[91], &jpc_mqstates[87]},
+        {0x5601, 0, &jpc_mqstates[92], &jpc_mqstates[92]},
+        {0x5601, 1, &jpc_mqstates[93], &jpc_mqstates[93]},
 };
diff --git a/converter/other/jpeg2000/libjasper/jpc/jpc_mqcod.h b/converter/other/jpeg2000/libjasper/jpc/jpc_mqcod.h
index 5f99e021..f32fc7fc 100644
--- a/converter/other/jpeg2000/libjasper/jpc/jpc_mqcod.h
+++ b/converter/other/jpeg2000/libjasper/jpc/jpc_mqcod.h
@@ -6,14 +6,14 @@
  */
 
 /* __START_OF_JASPER_LICENSE__
- * 
+ *
  * JasPer Software License
- * 
+ *
  * IMAGE POWER JPEG-2000 PUBLIC LICENSE
  * ************************************
- * 
+ *
  * GRANT:
- * 
+ *
  * Permission is hereby granted, free of charge, to any person (the "User")
  * obtaining a copy of this software and associated documentation, to deal
  * in the JasPer Software without restriction, including without limitation
@@ -21,22 +21,22 @@
  * and/or sell copies of the JasPer Software (in source and binary forms),
  * and to permit persons to whom the JasPer Software is furnished to do so,
  * provided further that the License Conditions below are met.
- * 
+ *
  * License Conditions
  * ******************
- * 
+ *
  * A.  Redistributions of source code must retain the above copyright notice,
  * and this list of conditions, and the following disclaimer.
- * 
+ *
  * B.  Redistributions in binary form must reproduce the above copyright
  * notice, and this list of conditions, and the following disclaimer in
  * the documentation and/or other materials provided with the distribution.
- * 
+ *
  * C.  Neither the name of Image Power, Inc. nor any other contributor
  * (including, but not limited to, the University of British Columbia and
  * Michael David Adams) may be used to endorse or promote products derived
  * from this software without specific prior written permission.
- * 
+ *
  * D.  User agrees that it shall not commence any action against Image Power,
  * Inc., the University of British Columbia, Michael David Adams, or any
  * other contributors (collectively "Licensors") for infringement of any
@@ -56,17 +56,17 @@
  * trade dress, or service mark rights); and (v) divisions, continuations,
  * renewals, reissues and extensions of the foregoing (as and to the extent
  * applicable) now existing, hereafter filed, issued or acquired.
- * 
+ *
  * E.  If User commences an infringement action against any Licensor(s) then
  * such Licensor(s) shall have the right to terminate User's license and
  * all sublicenses that have been granted hereunder by User to other parties.
- * 
+ *
  * F.  This software is for use only in hardware or software products that
  * are compliant with ISO/IEC 15444-1 (i.e., JPEG-2000 Part 1).  No license
  * or right to this Software is granted for products that do not comply
  * with ISO/IEC 15444-1.  The JPEG-2000 Part 1 standard can be purchased
  * from the ISO.
- * 
+ *
  * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS LICENSE.
  * NO USE OF THE JASPER SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER
  * THIS DISCLAIMER.  THE JASPER SOFTWARE IS PROVIDED BY THE LICENSORS AND
@@ -106,7 +106,7 @@
  * TECHNOLOGY OR PRODUCTS FOR HIGH RISK ACTIVITIES AND WILL ENSURE THAT ITS
  * CUSTOMERS AND END-USERS OF ITS PRODUCTS ARE PROVIDED WITH A COPY OF THE
  * NOTICE SPECIFIED IN THIS SECTION.
- * 
+ *
  * __END_OF_JASPER_LICENSE__
  */
 
@@ -136,11 +136,11 @@
 
 typedef struct {
 
-	/* The most probable symbol (MPS). */
-	bool mps;
+        /* The most probable symbol (MPS). */
+        bool mps;
 
-	/* The state index. */
-	int_fast16_t ind;
+        /* The state index. */
+        int_fast16_t ind;
 
 } jpc_mqctx_t;
 
@@ -150,17 +150,17 @@ typedef struct {
 
 typedef struct jpc_mqstate_s {
 
-	/* The Qe value. */
-	uint_fast16_t qeval;
+        /* The Qe value. */
+        uint_fast16_t qeval;
 
-	/* The MPS. */
-	uint_fast16_t mps;
+        /* The MPS. */
+        uint_fast16_t mps;
 
-	/* The NMPS state. */
-	struct jpc_mqstate_s *nmps;
+        /* The NMPS state. */
+        struct jpc_mqstate_s *nmps;
 
-	/* The NLPS state. */
-	struct jpc_mqstate_s *nlps;
+        /* The NLPS state. */
+        struct jpc_mqstate_s *nlps;
 
 } jpc_mqstate_t;
 
diff --git a/converter/other/jpeg2000/libjasper/jpc/jpc_mqdec.c b/converter/other/jpeg2000/libjasper/jpc/jpc_mqdec.c
index f58a1c7d..2d419522 100644
--- a/converter/other/jpeg2000/libjasper/jpc/jpc_mqdec.c
+++ b/converter/other/jpeg2000/libjasper/jpc/jpc_mqdec.c
@@ -6,14 +6,14 @@
  */
 
 /* __START_OF_JASPER_LICENSE__
- * 
+ *
  * JasPer Software License
- * 
+ *
  * IMAGE POWER JPEG-2000 PUBLIC LICENSE
  * ************************************
- * 
+ *
  * GRANT:
- * 
+ *
  * Permission is hereby granted, free of charge, to any person (the "User")
  * obtaining a copy of this software and associated documentation, to deal
  * in the JasPer Software without restriction, including without limitation
@@ -21,22 +21,22 @@
  * and/or sell copies of the JasPer Software (in source and binary forms),
  * and to permit persons to whom the JasPer Software is furnished to do so,
  * provided further that the License Conditions below are met.
- * 
+ *
  * License Conditions
  * ******************
- * 
+ *
  * A.  Redistributions of source code must retain the above copyright notice,
  * and this list of conditions, and the following disclaimer.
- * 
+ *
  * B.  Redistributions in binary form must reproduce the above copyright
  * notice, and this list of conditions, and the following disclaimer in
  * the documentation and/or other materials provided with the distribution.
- * 
+ *
  * C.  Neither the name of Image Power, Inc. nor any other contributor
  * (including, but not limited to, the University of British Columbia and
  * Michael David Adams) may be used to endorse or promote products derived
  * from this software without specific prior written permission.
- * 
+ *
  * D.  User agrees that it shall not commence any action against Image Power,
  * Inc., the University of British Columbia, Michael David Adams, or any
  * other contributors (collectively "Licensors") for infringement of any
@@ -56,17 +56,17 @@
  * trade dress, or service mark rights); and (v) divisions, continuations,
  * renewals, reissues and extensions of the foregoing (as and to the extent
  * applicable) now existing, hereafter filed, issued or acquired.
- * 
+ *
  * E.  If User commences an infringement action against any Licensor(s) then
  * such Licensor(s) shall have the right to terminate User's license and
  * all sublicenses that have been granted hereunder by User to other parties.
- * 
+ *
  * F.  This software is for use only in hardware or software products that
  * are compliant with ISO/IEC 15444-1 (i.e., JPEG-2000 Part 1).  No license
  * or right to this Software is granted for products that do not comply
  * with ISO/IEC 15444-1.  The JPEG-2000 Part 1 standard can be purchased
  * from the ISO.
- * 
+ *
  * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS LICENSE.
  * NO USE OF THE JASPER SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER
  * THIS DISCLAIMER.  THE JASPER SOFTWARE IS PROVIDED BY THE LICENSORS AND
@@ -106,7 +106,7 @@
  * TECHNOLOGY OR PRODUCTS FOR HIGH RISK ACTIVITIES AND WILL ENSURE THAT ITS
  * CUSTOMERS AND END-USERS OF ITS PRODUCTS ARE PROVIDED WITH A COPY OF THE
  * NOTICE SPECIFIED IN THIS SECTION.
- * 
+ *
  * __END_OF_JASPER_LICENSE__
  */
 
@@ -136,10 +136,10 @@
 \******************************************************************************/
 
 #if defined(DEBUG)
-#define	MQDEC_CALL(n, x) \
-	((jas_getdbglevel() >= (n)) ? ((void)(x)) : ((void)0))
+#define MQDEC_CALL(n, x) \
+        ((jas_getdbglevel() >= (n)) ? ((void)(x)) : ((void)0))
 #else
-#define	MQDEC_CALL(n, x)
+#define MQDEC_CALL(n, x)
 #endif
 
 /******************************************************************************\
@@ -155,49 +155,49 @@ static void jpc_mqdec_bytein(jpc_mqdec_t *mqdec);
 /* Create a MQ decoder. */
 jpc_mqdec_t *jpc_mqdec_create(int maxctxs, jas_stream_t *in)
 {
-	jpc_mqdec_t *mqdec;
-
-	/* There must be at least one context. */
-	assert(maxctxs > 0);
-
-	/* Allocate memory for the MQ decoder. */
-	if (!(mqdec = jas_malloc(sizeof(jpc_mqdec_t)))) {
-		goto error;
-	}
-	mqdec->in = in;
-	mqdec->maxctxs = maxctxs;
-	/* Allocate memory for the per-context state information. */
-	if (!(mqdec->ctxs = jas_malloc(mqdec->maxctxs * sizeof(jpc_mqstate_t *)))) {
-		goto error;
-	}
-	/* Set the current context to the first context. */
-	mqdec->curctx = mqdec->ctxs;
-
-	/* If an input stream has been associated with the MQ decoder,
-	  initialize the decoder state from the stream. */
-	if (mqdec->in) {
-		jpc_mqdec_init(mqdec);
-	}
-	/* Initialize the per-context state information. */
-	jpc_mqdec_setctxs(mqdec, 0, 0);
-
-	return mqdec;
+        jpc_mqdec_t *mqdec;
+
+        /* There must be at least one context. */
+        assert(maxctxs > 0);
+
+        /* Allocate memory for the MQ decoder. */
+        if (!(mqdec = jas_malloc(sizeof(jpc_mqdec_t)))) {
+                goto error;
+        }
+        mqdec->in = in;
+        mqdec->maxctxs = maxctxs;
+        /* Allocate memory for the per-context state information. */
+        if (!(mqdec->ctxs = jas_malloc(mqdec->maxctxs * sizeof(jpc_mqstate_t *)))) {
+                goto error;
+        }
+        /* Set the current context to the first context. */
+        mqdec->curctx = mqdec->ctxs;
+
+        /* If an input stream has been associated with the MQ decoder,
+          initialize the decoder state from the stream. */
+        if (mqdec->in) {
+                jpc_mqdec_init(mqdec);
+        }
+        /* Initialize the per-context state information. */
+        jpc_mqdec_setctxs(mqdec, 0, 0);
+
+        return mqdec;
 
 error:
-	/* Oops...  Something has gone wrong. */
-	if (mqdec) {
-		jpc_mqdec_destroy(mqdec);
-	}
-	return 0;
+        /* Oops...  Something has gone wrong. */
+        if (mqdec) {
+                jpc_mqdec_destroy(mqdec);
+        }
+        return 0;
 }
 
 /* Destroy a MQ decoder. */
 void jpc_mqdec_destroy(jpc_mqdec_t *mqdec)
 {
-	if (mqdec->ctxs) {
-		jas_free(mqdec->ctxs);
-	}
-	jas_free(mqdec);
+        if (mqdec->ctxs) {
+                jas_free(mqdec->ctxs);
+        }
+        jas_free(mqdec);
 }
 
 /******************************************************************************\
@@ -208,59 +208,59 @@ void jpc_mqdec_destroy(jpc_mqdec_t *mqdec)
 
 void jpc_mqdec_init(jpc_mqdec_t *mqdec)
 {
-	int c;
-
-	mqdec->eof = 0;
-	mqdec->creg = 0;
-	/* Get the next byte from the input stream. */
-	if ((c = jas_stream_getc(mqdec->in)) == EOF) {
-		/* We have encountered an I/O error or EOF. */
-		c = 0xff;
-		mqdec->eof = 1;
-	}
-	mqdec->inbuffer = c;
-	mqdec->creg += mqdec->inbuffer << 16;
-	jpc_mqdec_bytein(mqdec);
-	mqdec->creg <<= 7;
-	mqdec->ctreg -= 7;
-	mqdec->areg = 0x8000;
+        int c;
+
+        mqdec->eof = 0;
+        mqdec->creg = 0;
+        /* Get the next byte from the input stream. */
+        if ((c = jas_stream_getc(mqdec->in)) == EOF) {
+                /* We have encountered an I/O error or EOF. */
+                c = 0xff;
+                mqdec->eof = 1;
+        }
+        mqdec->inbuffer = c;
+        mqdec->creg += mqdec->inbuffer << 16;
+        jpc_mqdec_bytein(mqdec);
+        mqdec->creg <<= 7;
+        mqdec->ctreg -= 7;
+        mqdec->areg = 0x8000;
 }
 
 /* Set the input stream for a MQ decoder. */
 
 void jpc_mqdec_setinput(jpc_mqdec_t *mqdec, jas_stream_t *in)
 {
-	mqdec->in = in;
+        mqdec->in = in;
 }
 
 /* Initialize one or more contexts. */
 
 void jpc_mqdec_setctxs(jpc_mqdec_t *mqdec, int numctxs, jpc_mqctx_t *ctxs)
 {
-	jpc_mqstate_t **ctx;
-	int n;
-
-	ctx = mqdec->ctxs;
-	n = JAS_MIN(mqdec->maxctxs, numctxs);
-	while (--n >= 0) {
-		*ctx = &jpc_mqstates[2 * ctxs->ind + ctxs->mps];
-		++ctx;
-		++ctxs;
-	}
-	n = mqdec->maxctxs - numctxs;
-	while (--n >= 0) {
-		*ctx = &jpc_mqstates[0];
-		++ctx;
-	}
+        jpc_mqstate_t **ctx;
+        int n;
+
+        ctx = mqdec->ctxs;
+        n = JAS_MIN(mqdec->maxctxs, numctxs);
+        while (--n >= 0) {
+                *ctx = &jpc_mqstates[2 * ctxs->ind + ctxs->mps];
+                ++ctx;
+                ++ctxs;
+        }
+        n = mqdec->maxctxs - numctxs;
+        while (--n >= 0) {
+                *ctx = &jpc_mqstates[0];
+                ++ctx;
+        }
 }
 
 /* Initialize a context. */
 
 void jpc_mqdec_setctx(jpc_mqdec_t *mqdec, int ctxno, jpc_mqctx_t *ctx)
 {
-	jpc_mqstate_t **ctxi;
-	ctxi = &mqdec->ctxs[ctxno];
-	*ctxi = &jpc_mqstates[2 * ctx->ind + ctx->mps];
+        jpc_mqstate_t **ctxi;
+        ctxi = &mqdec->ctxs[ctxno];
+        *ctxi = &jpc_mqstates[2 * ctx->ind + ctx->mps];
 }
 
 /******************************************************************************\
@@ -271,36 +271,36 @@ void jpc_mqdec_setctx(jpc_mqdec_t *mqdec, int ctxno, jpc_mqctx_t *ctx)
 
 int jpc_mqdec_getbit_func(register jpc_mqdec_t *mqdec)
 {
-	int bit;
-	JAS_DBGLOG(100, ("jpc_mqdec_getbit_func(%p)\n", mqdec));
-	MQDEC_CALL(100, jpc_mqdec_dump(mqdec, stderr));
-	bit = jpc_mqdec_getbit_macro(mqdec);
-	MQDEC_CALL(100, jpc_mqdec_dump(mqdec, stderr));
-	JAS_DBGLOG(100, ("ctx = %d, decoded %d\n", mqdec->curctx -
-	  mqdec->ctxs, bit));
-	return bit;
+        int bit;
+        JAS_DBGLOG(100, ("jpc_mqdec_getbit_func(%p)\n", mqdec));
+        MQDEC_CALL(100, jpc_mqdec_dump(mqdec, stderr));
+        bit = jpc_mqdec_getbit_macro(mqdec);
+        MQDEC_CALL(100, jpc_mqdec_dump(mqdec, stderr));
+        JAS_DBGLOG(100, ("ctx = %d, decoded %d\n", mqdec->curctx -
+          mqdec->ctxs, bit));
+        return bit;
 }
 
 /* Apply MPS_EXCHANGE algorithm (with RENORMD). */
 int jpc_mqdec_mpsexchrenormd(register jpc_mqdec_t *mqdec)
 {
-	int ret;
-	register jpc_mqstate_t *state = *mqdec->curctx;
-	jpc_mqdec_mpsexchange(mqdec->areg, state->qeval, mqdec->curctx, ret);
-	jpc_mqdec_renormd(mqdec->areg, mqdec->creg, mqdec->ctreg, mqdec->in,
-	  mqdec->eof, mqdec->inbuffer);
-	return ret;
+        int ret;
+        register jpc_mqstate_t *state = *mqdec->curctx;
+        jpc_mqdec_mpsexchange(mqdec->areg, state->qeval, mqdec->curctx, ret);
+        jpc_mqdec_renormd(mqdec->areg, mqdec->creg, mqdec->ctreg, mqdec->in,
+          mqdec->eof, mqdec->inbuffer);
+        return ret;
 }
 
 /* Apply LPS_EXCHANGE algorithm (with RENORMD). */
 int jpc_mqdec_lpsexchrenormd(register jpc_mqdec_t *mqdec)
 {
-	int ret;
-	register jpc_mqstate_t *state = *mqdec->curctx;
-	jpc_mqdec_lpsexchange(mqdec->areg, state->qeval, mqdec->curctx, ret);
-	jpc_mqdec_renormd(mqdec->areg, mqdec->creg, mqdec->ctreg, mqdec->in,
-	  mqdec->eof, mqdec->inbuffer);
-	return ret;
+        int ret;
+        register jpc_mqstate_t *state = *mqdec->curctx;
+        jpc_mqdec_lpsexchange(mqdec->areg, state->qeval, mqdec->curctx, ret);
+        jpc_mqdec_renormd(mqdec->areg, mqdec->creg, mqdec->ctreg, mqdec->in,
+          mqdec->eof, mqdec->inbuffer);
+        return ret;
 }
 
 /******************************************************************************\
@@ -310,30 +310,30 @@ int jpc_mqdec_lpsexchrenormd(register jpc_mqdec_t *mqdec)
 /* Apply the BYTEIN algorithm. */
 static void jpc_mqdec_bytein(jpc_mqdec_t *mqdec)
 {
-	int c;
-	unsigned char prevbuf;
-
-	if (!mqdec->eof) {
-		if ((c = jas_stream_getc(mqdec->in)) == EOF) {
-			mqdec->eof = 1;
-			c = 0xff;
-		}
-		prevbuf = mqdec->inbuffer;
-		mqdec->inbuffer = c;
-		if (prevbuf == 0xff) {
-			if (c > 0x8f) {
-				mqdec->creg += 0xff00;
-				mqdec->ctreg = 8;
-			} else {
-				mqdec->creg += c << 9;
-				mqdec->ctreg = 7;
-			}
-		} else {
-			mqdec->creg += c << 8;
-			mqdec->ctreg = 8;
-		}
-	} else {
-		mqdec->creg += 0xff00;
-		mqdec->ctreg = 8;
-	}
+        int c;
+        unsigned char prevbuf;
+
+        if (!mqdec->eof) {
+                if ((c = jas_stream_getc(mqdec->in)) == EOF) {
+                        mqdec->eof = 1;
+                        c = 0xff;
+                }
+                prevbuf = mqdec->inbuffer;
+                mqdec->inbuffer = c;
+                if (prevbuf == 0xff) {
+                        if (c > 0x8f) {
+                                mqdec->creg += 0xff00;
+                                mqdec->ctreg = 8;
+                        } else {
+                                mqdec->creg += c << 9;
+                                mqdec->ctreg = 7;
+                        }
+                } else {
+                        mqdec->creg += c << 8;
+                        mqdec->ctreg = 8;
+                }
+        } else {
+                mqdec->creg += 0xff00;
+                mqdec->ctreg = 8;
+        }
 }
diff --git a/converter/other/jpeg2000/libjasper/jpc/jpc_mqdec.h b/converter/other/jpeg2000/libjasper/jpc/jpc_mqdec.h
index 30185506..b207c92b 100644
--- a/converter/other/jpeg2000/libjasper/jpc/jpc_mqdec.h
+++ b/converter/other/jpeg2000/libjasper/jpc/jpc_mqdec.h
@@ -6,14 +6,14 @@
  */
 
 /* __START_OF_JASPER_LICENSE__
- * 
+ *
  * JasPer Software License
- * 
+ *
  * IMAGE POWER JPEG-2000 PUBLIC LICENSE
  * ************************************
- * 
+ *
  * GRANT:
- * 
+ *
  * Permission is hereby granted, free of charge, to any person (the "User")
  * obtaining a copy of this software and associated documentation, to deal
  * in the JasPer Software without restriction, including without limitation
@@ -21,22 +21,22 @@
  * and/or sell copies of the JasPer Software (in source and binary forms),
  * and to permit persons to whom the JasPer Software is furnished to do so,
  * provided further that the License Conditions below are met.
- * 
+ *
  * License Conditions
  * ******************
- * 
+ *
  * A.  Redistributions of source code must retain the above copyright notice,
  * and this list of conditions, and the following disclaimer.
- * 
+ *
  * B.  Redistributions in binary form must reproduce the above copyright
  * notice, and this list of conditions, and the following disclaimer in
  * the documentation and/or other materials provided with the distribution.
- * 
+ *
  * C.  Neither the name of Image Power, Inc. nor any other contributor
  * (including, but not limited to, the University of British Columbia and
  * Michael David Adams) may be used to endorse or promote products derived
  * from this software without specific prior written permission.
- * 
+ *
  * D.  User agrees that it shall not commence any action against Image Power,
  * Inc., the University of British Columbia, Michael David Adams, or any
  * other contributors (collectively "Licensors") for infringement of any
@@ -56,17 +56,17 @@
  * trade dress, or service mark rights); and (v) divisions, continuations,
  * renewals, reissues and extensions of the foregoing (as and to the extent
  * applicable) now existing, hereafter filed, issued or acquired.
- * 
+ *
  * E.  If User commences an infringement action against any Licensor(s) then
  * such Licensor(s) shall have the right to terminate User's license and
  * all sublicenses that have been granted hereunder by User to other parties.
- * 
+ *
  * F.  This software is for use only in hardware or software products that
  * are compliant with ISO/IEC 15444-1 (i.e., JPEG-2000 Part 1).  No license
  * or right to this Software is granted for products that do not comply
  * with ISO/IEC 15444-1.  The JPEG-2000 Part 1 standard can be purchased
  * from the ISO.
- * 
+ *
  * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS LICENSE.
  * NO USE OF THE JASPER SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER
  * THIS DISCLAIMER.  THE JASPER SOFTWARE IS PROVIDED BY THE LICENSORS AND
@@ -106,7 +106,7 @@
  * TECHNOLOGY OR PRODUCTS FOR HIGH RISK ACTIVITIES AND WILL ENSURE THAT ITS
  * CUSTOMERS AND END-USERS OF ITS PRODUCTS ARE PROVIDED WITH A COPY OF THE
  * NOTICE SPECIFIED IN THIS SECTION.
- * 
+ *
  * __END_OF_JASPER_LICENSE__
  */
 
@@ -136,32 +136,32 @@
 
 typedef struct {
 
-	/* The C register. */
-	uint_fast32_t creg;
+        /* The C register. */
+        uint_fast32_t creg;
 
-	/* The A register. */
-	uint_fast32_t areg;
+        /* The A register. */
+        uint_fast32_t areg;
 
-	/* The CT register. */
-	uint_fast32_t ctreg;
+        /* The CT register. */
+        uint_fast32_t ctreg;
 
-	/* The current context. */
-	jpc_mqstate_t **curctx;
+        /* The current context. */
+        jpc_mqstate_t **curctx;
 
-	/* The per-context information. */
-	jpc_mqstate_t **ctxs;
+        /* The per-context information. */
+        jpc_mqstate_t **ctxs;
 
-	/* The maximum number of contexts. */
-	int maxctxs;
+        /* The maximum number of contexts. */
+        int maxctxs;
 
-	/* The stream from which to read data. */
-	jas_stream_t *in;
+        /* The stream from which to read data. */
+        jas_stream_t *in;
 
-	/* The last character read. */
-	unsigned char inbuffer;
+        /* The last character read. */
+        unsigned char inbuffer;
 
-	/* The EOF indicator. */
-	int eof;
+        /* The EOF indicator. */
+        int eof;
 
 } jpc_mqdec_t;
 
@@ -190,8 +190,8 @@ void jpc_mqdec_init(jpc_mqdec_t *dec);
 \******************************************************************************/
 
 /* Set the current context for a MQ decoder. */
-#define	jpc_mqdec_setcurctx(dec, ctxno) \
-	((mqdec)->curctx = &(mqdec)->ctxs[ctxno]);
+#define jpc_mqdec_setcurctx(dec, ctxno) \
+        ((mqdec)->curctx = &(mqdec)->ctxs[ctxno]);
 
 /* Set the state information for a particular context of a MQ decoder. */
 void jpc_mqdec_setctx(jpc_mqdec_t *dec, int ctxno, jpc_mqctx_t *ctx);
@@ -205,20 +205,20 @@ void jpc_mqdec_setctxs(jpc_mqdec_t *dec, int numctxs, jpc_mqctx_t *ctxs);
 
 /* Decode a symbol. */
 #if !defined(DEBUG)
-#define	jpc_mqdec_getbit(dec) \
-	jpc_mqdec_getbit_macro(dec)
+#define jpc_mqdec_getbit(dec) \
+        jpc_mqdec_getbit_macro(dec)
 #else
-#define	jpc_mqdec_getbit(dec) \
-	jpc_mqdec_getbit_func(dec)
+#define jpc_mqdec_getbit(dec) \
+        jpc_mqdec_getbit_func(dec)
 #endif
 
 /* Decode a symbol (assuming an unskewed probability distribution). */
 #if !defined(DEBUG)
-#define	jpc_mqdec_getbitnoskew(dec) \
-	jpc_mqdec_getbit_macro(dec)
+#define jpc_mqdec_getbitnoskew(dec) \
+        jpc_mqdec_getbit_macro(dec)
 #else
-#define	jpc_mqdec_getbitnoskew(dec) \
-	jpc_mqdec_getbit_func(dec)
+#define jpc_mqdec_getbitnoskew(dec) \
+        jpc_mqdec_getbit_func(dec)
 #endif
 
 /******************************************************************************\
@@ -234,83 +234,83 @@ void mqdec_dump(jpc_mqdec_t *dec, FILE *out);
 * GIVEN BELOW.
 \******************************************************************************/
 
-#define	jpc_mqdec_getbit_macro(dec) \
-	((((dec)->areg -= (*(dec)->curctx)->qeval), \
-	  (dec)->creg >> 16 >= (*(dec)->curctx)->qeval) ? \
-	  ((((dec)->creg -= (*(dec)->curctx)->qeval << 16), \
-	  (dec)->areg & 0x8000) ?  (*(dec)->curctx)->mps : \
-	  jpc_mqdec_mpsexchrenormd(dec)) : \
-	  jpc_mqdec_lpsexchrenormd(dec))
+#define jpc_mqdec_getbit_macro(dec) \
+        ((((dec)->areg -= (*(dec)->curctx)->qeval), \
+          (dec)->creg >> 16 >= (*(dec)->curctx)->qeval) ? \
+          ((((dec)->creg -= (*(dec)->curctx)->qeval << 16), \
+          (dec)->areg & 0x8000) ?  (*(dec)->curctx)->mps : \
+          jpc_mqdec_mpsexchrenormd(dec)) : \
+          jpc_mqdec_lpsexchrenormd(dec))
 
-#define	jpc_mqdec_mpsexchange(areg, delta, curctx, bit) \
+#define jpc_mqdec_mpsexchange(areg, delta, curctx, bit) \
 { \
-	if ((areg) < (delta)) { \
-		register jpc_mqstate_t *state = *(curctx); \
-		/* LPS decoded. */ \
-		(bit) = state->mps ^ 1; \
-		*(curctx) = state->nlps; \
-	} else { \
-		register jpc_mqstate_t *state = *(curctx); \
-		/* MPS decoded. */ \
-		(bit) = state->mps; \
-		*(curctx) = state->nmps; \
-	} \
+        if ((areg) < (delta)) { \
+                register jpc_mqstate_t *state = *(curctx); \
+                /* LPS decoded. */ \
+                (bit) = state->mps ^ 1; \
+                *(curctx) = state->nlps; \
+        } else { \
+                register jpc_mqstate_t *state = *(curctx); \
+                /* MPS decoded. */ \
+                (bit) = state->mps; \
+                *(curctx) = state->nmps; \
+        } \
 }
 
-#define	jpc_mqdec_lpsexchange(areg, delta, curctx, bit) \
+#define jpc_mqdec_lpsexchange(areg, delta, curctx, bit) \
 { \
-	if ((areg) >= (delta)) { \
-		register jpc_mqstate_t *state = *(curctx); \
-		(areg) = (delta); \
-		(bit) = state->mps ^ 1; \
-		*(curctx) = state->nlps; \
-	} else { \
-		register jpc_mqstate_t *state = *(curctx); \
-		(areg) = (delta); \
-		(bit) = state->mps; \
-		*(curctx) = state->nmps; \
-	} \
+        if ((areg) >= (delta)) { \
+                register jpc_mqstate_t *state = *(curctx); \
+                (areg) = (delta); \
+                (bit) = state->mps ^ 1; \
+                *(curctx) = state->nlps; \
+        } else { \
+                register jpc_mqstate_t *state = *(curctx); \
+                (areg) = (delta); \
+                (bit) = state->mps; \
+                *(curctx) = state->nmps; \
+        } \
 }
 
-#define	jpc_mqdec_renormd(areg, creg, ctreg, in, eof, inbuf) \
+#define jpc_mqdec_renormd(areg, creg, ctreg, in, eof, inbuf) \
 { \
-	do { \
-		if (!(ctreg)) { \
-			jpc_mqdec_bytein2(creg, ctreg, in, eof, inbuf); \
-		} \
-		(areg) <<= 1; \
-		(creg) <<= 1; \
-		--(ctreg); \
-	} while (!((areg) & 0x8000)); \
+        do { \
+                if (!(ctreg)) { \
+                        jpc_mqdec_bytein2(creg, ctreg, in, eof, inbuf); \
+                } \
+                (areg) <<= 1; \
+                (creg) <<= 1; \
+                --(ctreg); \
+        } while (!((areg) & 0x8000)); \
 }
 
-#define	jpc_mqdec_bytein2(creg, ctreg, in, eof, inbuf) \
+#define jpc_mqdec_bytein2(creg, ctreg, in, eof, inbuf) \
 { \
-	int c; \
-	unsigned char prevbuf; \
-	if (!(eof)) { \
-		if ((c = jas_stream_getc(in)) == EOF) { \
-			(eof) = 1; \
-			c = 0xff; \
-		} \
-		prevbuf = (inbuf); \
-		(inbuf) = c; \
-		if (prevbuf == 0xff) { \
-			if (c > 0x8f) { \
-				(creg) += 0xff00; \
-				(ctreg) = 8; \
-			} else { \
-				(creg) += c << 9; \
-				(ctreg) = 7; \
-			} \
-		} else { \
-			(creg) += c << 8; \
-			(ctreg) = 8; \
-		} \
-	} else { \
-		(creg) += 0xff00; \
-		(ctreg) = 8; \
-	} \
+        int c; \
+        unsigned char prevbuf; \
+        if (!(eof)) { \
+                if ((c = jas_stream_getc(in)) == EOF) { \
+                        (eof) = 1; \
+                        c = 0xff; \
+                } \
+                prevbuf = (inbuf); \
+                (inbuf) = c; \
+                if (prevbuf == 0xff) { \
+                        if (c > 0x8f) { \
+                                (creg) += 0xff00; \
+                                (ctreg) = 8; \
+                        } else { \
+                                (creg) += c << 9; \
+                                (ctreg) = 7; \
+                        } \
+                } else { \
+                        (creg) += c << 8; \
+                        (ctreg) = 8; \
+                } \
+        } else { \
+                (creg) += 0xff00; \
+                (ctreg) = 8; \
+        } \
 }
 
 int jpc_mqdec_getbit_func(jpc_mqdec_t *dec);
diff --git a/converter/other/jpeg2000/libjasper/jpc/jpc_mqenc.h b/converter/other/jpeg2000/libjasper/jpc/jpc_mqenc.h
index 1421ae4d..4a1be355 100644
--- a/converter/other/jpeg2000/libjasper/jpc/jpc_mqenc.h
+++ b/converter/other/jpeg2000/libjasper/jpc/jpc_mqenc.h
@@ -6,14 +6,14 @@
  */
 
 /* __START_OF_JASPER_LICENSE__
- * 
+ *
  * JasPer Software License
- * 
+ *
  * IMAGE POWER JPEG-2000 PUBLIC LICENSE
  * ************************************
- * 
+ *
  * GRANT:
- * 
+ *
  * Permission is hereby granted, free of charge, to any person (the "User")
  * obtaining a copy of this software and associated documentation, to deal
  * in the JasPer Software without restriction, including without limitation
@@ -21,22 +21,22 @@
  * and/or sell copies of the JasPer Software (in source and binary forms),
  * and to permit persons to whom the JasPer Software is furnished to do so,
  * provided further that the License Conditions below are met.
- * 
+ *
  * License Conditions
  * ******************
- * 
+ *
  * A.  Redistributions of source code must retain the above copyright notice,
  * and this list of conditions, and the following disclaimer.
- * 
+ *
  * B.  Redistributions in binary form must reproduce the above copyright
  * notice, and this list of conditions, and the following disclaimer in
  * the documentation and/or other materials provided with the distribution.
- * 
+ *
  * C.  Neither the name of Image Power, Inc. nor any other contributor
  * (including, but not limited to, the University of British Columbia and
  * Michael David Adams) may be used to endorse or promote products derived
  * from this software without specific prior written permission.
- * 
+ *
  * D.  User agrees that it shall not commence any action against Image Power,
  * Inc., the University of British Columbia, Michael David Adams, or any
  * other contributors (collectively "Licensors") for infringement of any
@@ -56,17 +56,17 @@
  * trade dress, or service mark rights); and (v) divisions, continuations,
  * renewals, reissues and extensions of the foregoing (as and to the extent
  * applicable) now existing, hereafter filed, issued or acquired.
- * 
+ *
  * E.  If User commences an infringement action against any Licensor(s) then
  * such Licensor(s) shall have the right to terminate User's license and
  * all sublicenses that have been granted hereunder by User to other parties.
- * 
+ *
  * F.  This software is for use only in hardware or software products that
  * are compliant with ISO/IEC 15444-1 (i.e., JPEG-2000 Part 1).  No license
  * or right to this Software is granted for products that do not comply
  * with ISO/IEC 15444-1.  The JPEG-2000 Part 1 standard can be purchased
  * from the ISO.
- * 
+ *
  * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS LICENSE.
  * NO USE OF THE JASPER SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER
  * THIS DISCLAIMER.  THE JASPER SOFTWARE IS PROVIDED BY THE LICENSORS AND
@@ -106,7 +106,7 @@
  * TECHNOLOGY OR PRODUCTS FOR HIGH RISK ACTIVITIES AND WILL ENSURE THAT ITS
  * CUSTOMERS AND END-USERS OF ITS PRODUCTS ARE PROVIDED WITH A COPY OF THE
  * NOTICE SPECIFIED IN THIS SECTION.
- * 
+ *
  * __END_OF_JASPER_LICENSE__
  */
 
@@ -136,8 +136,8 @@
  * Termination modes.
  */
 
-#define	JPC_MQENC_DEFTERM	0	/* default termination */
-#define	JPC_MQENC_PTERM		1	/* predictable termination */
+#define JPC_MQENC_DEFTERM       0       /* default termination */
+#define JPC_MQENC_PTERM         1       /* predictable termination */
 
 /******************************************************************************\
 * Types.
@@ -147,53 +147,53 @@
 
 typedef struct {
 
-	/* The C register. */
-	uint_fast32_t creg;
+        /* The C register. */
+        uint_fast32_t creg;
 
-	/* The A register. */
-	uint_fast32_t areg;
+        /* The A register. */
+        uint_fast32_t areg;
 
-	/* The CT register. */
-	uint_fast32_t ctreg;
+        /* The CT register. */
+        uint_fast32_t ctreg;
 
-	/* The maximum number of contexts. */
-	int maxctxs;
+        /* The maximum number of contexts. */
+        int maxctxs;
 
-	/* The per-context information. */
-	jpc_mqstate_t **ctxs;
+        /* The per-context information. */
+        jpc_mqstate_t **ctxs;
 
-	/* The current context. */
-	jpc_mqstate_t **curctx;
+        /* The current context. */
+        jpc_mqstate_t **curctx;
 
-	/* The stream for encoder output. */
-	jas_stream_t *out;
+        /* The stream for encoder output. */
+        jas_stream_t *out;
 
-	/* The byte buffer (i.e., the B variable in the standard). */
-	int_fast16_t outbuf;
+        /* The byte buffer (i.e., the B variable in the standard). */
+        int_fast16_t outbuf;
 
-	/* The last byte output. */
-	int_fast16_t lastbyte;
+        /* The last byte output. */
+        int_fast16_t lastbyte;
 
-	/* The error indicator. */
-	int err;
-	
+        /* The error indicator. */
+        int err;
+       
 } jpc_mqenc_t;
 
 /* MQ arithmetic encoder state information. */
 
 typedef struct {
 
-	/* The A register. */
-	unsigned areg;
+        /* The A register. */
+        unsigned areg;
 
-	/* The C register. */
-	unsigned creg;
+        /* The C register. */
+        unsigned creg;
 
-	/* The CT register. */
-	unsigned ctreg;
+        /* The CT register. */
+        unsigned ctreg;
 
-	/* The last byte output by the encoder. */
-	int lastbyte;
+        /* The last byte output by the encoder. */
+        int lastbyte;
 
 } jpc_mqencstate_t;
 
@@ -219,7 +219,7 @@ void jpc_mqenc_init(jpc_mqenc_t *enc);
 \******************************************************************************/
 
 /* Set the current context. */
-#define	jpc_mqenc_setcurctx(enc, ctxno) \
+#define jpc_mqenc_setcurctx(enc, ctxno) \
         ((enc)->curctx = &(enc)->ctxs[ctxno]);
 
 /* Set the state information for a particular context. */
@@ -233,8 +233,8 @@ void jpc_mqenc_setctxs(jpc_mqenc_t *enc, int numctxs, jpc_mqctx_t *ctxs);
 \******************************************************************************/
 
 /* Get the error state of a MQ encoder. */
-#define	jpc_mqenc_error(enc) \
-	((enc)->err)
+#define jpc_mqenc_error(enc) \
+        ((enc)->err)
 
 /* Get the current encoder state. */
 void jpc_mqenc_getstate(jpc_mqenc_t *enc, jpc_mqencstate_t *state);
@@ -248,9 +248,9 @@ int jpc_mqenc_flush(jpc_mqenc_t *enc, int termmode);
 
 /* Encode a bit. */
 #if !defined(DEBUG)
-#define	jpc_mqenc_putbit(enc, bit)	jpc_mqenc_putbit_macro(enc, bit)
+#define jpc_mqenc_putbit(enc, bit)      jpc_mqenc_putbit_macro(enc, bit)
 #else
-#define	jpc_mqenc_putbit(enc, bit)	jpc_mqenc_putbit_func(enc, bit)
+#define jpc_mqenc_putbit(enc, bit)      jpc_mqenc_putbit_func(enc, bit)
 #endif
 
 /******************************************************************************\
@@ -265,12 +265,12 @@ int jpc_mqenc_dump(jpc_mqenc_t *mqenc, FILE *out);
 
 /* Note: This macro is included only to satisfy the needs of
   the mqenc_putbit macro. */
-#define	jpc_mqenc_putbit_macro(enc, bit) \
-	(((*((enc)->curctx))->mps == (bit)) ? \
-	  (((enc)->areg -= (*(enc)->curctx)->qeval), \
-	  ((!((enc)->areg & 0x8000)) ? (jpc_mqenc_codemps2(enc)) : \
-	  ((enc)->creg += (*(enc)->curctx)->qeval))) : \
-	  jpc_mqenc_codelps(enc))
+#define jpc_mqenc_putbit_macro(enc, bit) \
+        (((*((enc)->curctx))->mps == (bit)) ? \
+          (((enc)->areg -= (*(enc)->curctx)->qeval), \
+          ((!((enc)->areg & 0x8000)) ? (jpc_mqenc_codemps2(enc)) : \
+          ((enc)->creg += (*(enc)->curctx)->qeval))) : \
+          jpc_mqenc_codelps(enc))
 
 /* Note: These function prototypes are included only to satisfy the
   needs of the mqenc_putbit_macro macro.  Do not call any of these
diff --git a/converter/other/jpeg2000/libjasper/jpc/jpc_qmfb.c b/converter/other/jpeg2000/libjasper/jpc/jpc_qmfb.c
index 80bc5aa5..c2a87e19 100644
--- a/converter/other/jpeg2000/libjasper/jpc/jpc_qmfb.c
+++ b/converter/other/jpeg2000/libjasper/jpc/jpc_qmfb.c
@@ -6,14 +6,14 @@
  */
 
 /* __START_OF_JASPER_LICENSE__
- * 
+ *
  * JasPer Software License
- * 
+ *
  * IMAGE POWER JPEG-2000 PUBLIC LICENSE
  * ************************************
- * 
+ *
  * GRANT:
- * 
+ *
  * Permission is hereby granted, free of charge, to any person (the "User")
  * obtaining a copy of this software and associated documentation, to deal
  * in the JasPer Software without restriction, including without limitation
@@ -21,22 +21,22 @@
  * and/or sell copies of the JasPer Software (in source and binary forms),
  * and to permit persons to whom the JasPer Software is furnished to do so,
  * provided further that the License Conditions below are met.
- * 
+ *
  * License Conditions
  * ******************
- * 
+ *
  * A.  Redistributions of source code must retain the above copyright notice,
  * and this list of conditions, and the following disclaimer.
- * 
+ *
  * B.  Redistributions in binary form must reproduce the above copyright
  * notice, and this list of conditions, and the following disclaimer in
  * the documentation and/or other materials provided with the distribution.
- * 
+ *
  * C.  Neither the name of Image Power, Inc. nor any other contributor
  * (including, but not limited to, the University of British Columbia and
  * Michael David Adams) may be used to endorse or promote products derived
  * from this software without specific prior written permission.
- * 
+ *
  * D.  User agrees that it shall not commence any action against Image Power,
  * Inc., the University of British Columbia, Michael David Adams, or any
  * other contributors (collectively "Licensors") for infringement of any
@@ -56,17 +56,17 @@
  * trade dress, or service mark rights); and (v) divisions, continuations,
  * renewals, reissues and extensions of the foregoing (as and to the extent
  * applicable) now existing, hereafter filed, issued or acquired.
- * 
+ *
  * E.  If User commences an infringement action against any Licensor(s) then
  * such Licensor(s) shall have the right to terminate User's license and
  * all sublicenses that have been granted hereunder by User to other parties.
- * 
+ *
  * F.  This software is for use only in hardware or software products that
  * are compliant with ISO/IEC 15444-1 (i.e., JPEG-2000 Part 1).  No license
  * or right to this Software is granted for products that do not comply
  * with ISO/IEC 15444-1.  The JPEG-2000 Part 1 standard can be purchased
  * from the ISO.
- * 
+ *
  * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS LICENSE.
  * NO USE OF THE JASPER SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER
  * THIS DISCLAIMER.  THE JASPER SOFTWARE IS PROVIDED BY THE LICENSORS AND
@@ -106,7 +106,7 @@
  * TECHNOLOGY OR PRODUCTS FOR HIGH RISK ACTIVITIES AND WILL ENSURE THAT ITS
  * CUSTOMERS AND END-USERS OF ITS PRODUCTS ARE PROVIDED WITH A COPY OF THE
  * NOTICE SPECIFIED IN THIS SECTION.
- * 
+ *
  * __END_OF_JASPER_LICENSE__
  */
 
@@ -122,7 +122,6 @@
 
 #include <assert.h>
 
-#include "jasper/jas_fix.h"
 #include "jasper/jas_malloc.h"
 #include "jasper/jas_math.h"
 
@@ -153,19 +152,19 @@ static void jpc_ns_synthesize(jpc_qmfb1d_t *qmfb, int flags, jas_seq2d_t *x);
 \******************************************************************************/
 
 jpc_qmfb1dops_t jpc_ft_ops = {
-	jpc_ft_getnumchans,
-	jpc_ft_getanalfilters,
-	jpc_ft_getsynfilters,
-	jpc_ft_analyze,
-	jpc_ft_synthesize
+        jpc_ft_getnumchans,
+        jpc_ft_getanalfilters,
+        jpc_ft_getsynfilters,
+        jpc_ft_analyze,
+        jpc_ft_synthesize
 };
 
 jpc_qmfb1dops_t jpc_ns_ops = {
-	jpc_ns_getnumchans,
-	jpc_ns_getanalfilters,
-	jpc_ns_getsynfilters,
-	jpc_ns_analyze,
-	jpc_ns_synthesize
+        jpc_ns_getnumchans,
+        jpc_ns_getanalfilters,
+        jpc_ns_getsynfilters,
+        jpc_ns_analyze,
+        jpc_ns_synthesize
 };
 
 /******************************************************************************\
@@ -176,12 +175,12 @@ static void jpc_qmfb1d_setup(jpc_fix_t *startptr, int startind, int endind,
   int intrastep, jpc_fix_t **lstartptr, int *lstartind, int *lendind,
   jpc_fix_t **hstartptr, int *hstartind, int *hendind)
 {
-	*lstartind = JPC_CEILDIVPOW2(startind, 1);
-	*lendind = JPC_CEILDIVPOW2(endind, 1);
-	*hstartind = JPC_FLOORDIVPOW2(startind, 1);
-	*hendind = JPC_FLOORDIVPOW2(endind, 1);
-	*lstartptr = startptr;
-	*hstartptr = &startptr[(*lendind - *lstartind) * intrastep];
+        *lstartind = JPC_CEILDIVPOW2(startind, 1);
+        *lendind = JPC_CEILDIVPOW2(endind, 1);
+        *hstartind = JPC_FLOORDIVPOW2(startind, 1);
+        *hendind = JPC_FLOORDIVPOW2(endind, 1);
+        *lstartptr = startptr;
+        *hstartptr = &startptr[(*lendind - *lstartind) * intrastep];
 }
 
 static void jpc_qmfb1d_split(jpc_fix_t *startptr, int startind, int endind,
@@ -189,204 +188,204 @@ static void jpc_qmfb1d_split(jpc_fix_t *startptr, int startind, int endind,
   jpc_fix_t *hstartptr, int hstartind, int hendind)
 {
 #define QMFB_SPLITBUFSIZE 4096
-	jpc_fix_t splitbuf[QMFB_SPLITBUFSIZE];
-	jpc_fix_t *buf = splitbuf;
-	int llen;
-	int hlen;
-	int twostep;
-	jpc_fix_t *tmpptr;
-	register jpc_fix_t *ptr;
-	register jpc_fix_t *hptr;
-	register jpc_fix_t *lptr;
-	register int n;
-	int state;
-
-	twostep = step << 1;
-	llen = lendind - lstartind;
-	hlen = hendind - hstartind;
-
-	if (hstartind < lstartind) {
-		/* The first sample in the input signal is to appear
-		  in the highpass subband signal. */
-		/* Copy the appropriate samples into the lowpass subband
-		  signal, saving any samples destined for the highpass subband
-		  signal as they are overwritten. */
-		tmpptr = buf;
-		ptr = &startptr[step];
-		lptr = lstartptr;
-		n = llen;
-		state = 1;
-		while (n-- > 0) {
-			if (state) {
-				*tmpptr = *lptr;
-				++tmpptr;
-			}
-			*lptr = *ptr;
-			ptr += twostep;
-			lptr += step;
-			state ^= 1;
-		}
-		/* Copy the appropriate samples into the highpass subband
-		  signal. */
-		/* Handle the nonoverwritten samples. */
-		hptr = &hstartptr[(hlen - 1) * step];
-		ptr = &startptr[(((llen + hlen - 1) >> 1) << 1) * step];
-		n = hlen - (tmpptr - buf);
-		while (n-- > 0) {
-			*hptr = *ptr;
-			hptr -= step;
-			ptr -= twostep;
-		}
-		/* Handle the overwritten samples. */
-		n = tmpptr - buf;
-		while (n-- > 0) {
-			--tmpptr;
-			*hptr = *tmpptr;
-			hptr -= step;
-		}
-	} else {
-		/* The first sample in the input signal is to appear
-		  in the lowpass subband signal. */
-		/* Copy the appropriate samples into the lowpass subband
-		  signal, saving any samples for the highpass subband
-		  signal as they are overwritten. */
-		state = 0;
-		ptr = startptr;
-		lptr = lstartptr;
-		tmpptr = buf;
-		n = llen;
-		while (n-- > 0) {
-			if (state) {
-				*tmpptr = *lptr;
-				++tmpptr;
-			}
-			*lptr = *ptr;
-			ptr += twostep;
-			lptr += step;
-			state ^= 1;
-		}
-		/* Copy the appropriate samples into the highpass subband
-		  signal. */
-		/* Handle the nonoverwritten samples. */
-		ptr = &startptr[((((llen + hlen) >> 1) << 1) - 1) * step];
-		hptr = &hstartptr[(hlen - 1) * step];
-		n = hlen - (tmpptr - buf);
-		while (n-- > 0) {
-			*hptr = *ptr;
-			ptr -= twostep;
-			hptr -= step;
-		}
-		/* Handle the overwritten samples. */
-		n = tmpptr - buf;
-		while (n-- > 0) {
-			--tmpptr;
-			*hptr = *tmpptr;
-			hptr -= step;
-		}
-	}
+        jpc_fix_t splitbuf[QMFB_SPLITBUFSIZE];
+        jpc_fix_t *buf = splitbuf;
+        int llen;
+        int hlen;
+        int twostep;
+        jpc_fix_t *tmpptr;
+        register jpc_fix_t *ptr;
+        register jpc_fix_t *hptr;
+        register jpc_fix_t *lptr;
+        register int n;
+        int state;
+
+        twostep = step << 1;
+        llen = lendind - lstartind;
+        hlen = hendind - hstartind;
+
+        if (hstartind < lstartind) {
+                /* The first sample in the input signal is to appear
+                  in the highpass subband signal. */
+                /* Copy the appropriate samples into the lowpass subband
+                  signal, saving any samples destined for the highpass subband
+                  signal as they are overwritten. */
+                tmpptr = buf;
+                ptr = &startptr[step];
+                lptr = lstartptr;
+                n = llen;
+                state = 1;
+                while (n-- > 0) {
+                        if (state) {
+                                *tmpptr = *lptr;
+                                ++tmpptr;
+                        }
+                        *lptr = *ptr;
+                        ptr += twostep;
+                        lptr += step;
+                        state ^= 1;
+                }
+                /* Copy the appropriate samples into the highpass subband
+                  signal. */
+                /* Handle the nonoverwritten samples. */
+                hptr = &hstartptr[(hlen - 1) * step];
+                ptr = &startptr[(((llen + hlen - 1) >> 1) << 1) * step];
+                n = hlen - (tmpptr - buf);
+                while (n-- > 0) {
+                        *hptr = *ptr;
+                        hptr -= step;
+                        ptr -= twostep;
+                }
+                /* Handle the overwritten samples. */
+                n = tmpptr - buf;
+                while (n-- > 0) {
+                        --tmpptr;
+                        *hptr = *tmpptr;
+                        hptr -= step;
+                }
+        } else {
+                /* The first sample in the input signal is to appear
+                  in the lowpass subband signal. */
+                /* Copy the appropriate samples into the lowpass subband
+                  signal, saving any samples for the highpass subband
+                  signal as they are overwritten. */
+                state = 0;
+                ptr = startptr;
+                lptr = lstartptr;
+                tmpptr = buf;
+                n = llen;
+                while (n-- > 0) {
+                        if (state) {
+                                *tmpptr = *lptr;
+                                ++tmpptr;
+                        }
+                        *lptr = *ptr;
+                        ptr += twostep;
+                        lptr += step;
+                        state ^= 1;
+                }
+                /* Copy the appropriate samples into the highpass subband
+                  signal. */
+                /* Handle the nonoverwritten samples. */
+                ptr = &startptr[((((llen + hlen) >> 1) << 1) - 1) * step];
+                hptr = &hstartptr[(hlen - 1) * step];
+                n = hlen - (tmpptr - buf);
+                while (n-- > 0) {
+                        *hptr = *ptr;
+                        ptr -= twostep;
+                        hptr -= step;
+                }
+                /* Handle the overwritten samples. */
+                n = tmpptr - buf;
+                while (n-- > 0) {
+                        --tmpptr;
+                        *hptr = *tmpptr;
+                        hptr -= step;
+                }
+        }
 }
 
 static void jpc_qmfb1d_join(jpc_fix_t *startptr, int startind, int endind,
   register int step, jpc_fix_t *lstartptr, int lstartind, int lendind,
   jpc_fix_t *hstartptr, int hstartind, int hendind)
 {
-#define	QMFB_JOINBUFSIZE	4096
-	jpc_fix_t joinbuf[QMFB_JOINBUFSIZE];
-	jpc_fix_t *buf = joinbuf;
-	int llen;
-	int hlen;
-	int twostep;
-	jpc_fix_t *tmpptr;
-	register jpc_fix_t *ptr;
-	register jpc_fix_t *hptr;
-	register jpc_fix_t *lptr;
-	register int n;
-	int state;
-
-	twostep = step << 1;
-	llen = lendind - lstartind;
-	hlen = hendind - hstartind;
-
-	if (hstartind < lstartind) {
-		/* The first sample in the highpass subband signal is to
-		  appear first in the output signal. */
-		/* Copy the appropriate samples into the first phase of the
-		  output signal. */
-		tmpptr = buf;
-		hptr = hstartptr;
-		ptr = startptr;
-		n = (llen + 1) >> 1;
-		while (n-- > 0) {
-			*tmpptr = *ptr;
-			*ptr = *hptr;
-			++tmpptr;
-			ptr += twostep;
-			hptr += step;
-		}
-		n = hlen - ((llen + 1) >> 1);
-		while (n-- > 0) {
-			*ptr = *hptr;
-			ptr += twostep;
-			hptr += step;
-		}
-		/* Copy the appropriate samples into the second phase of
-		  the output signal. */
-		ptr -= (lendind > hendind) ? (step) : (step + twostep);
-		state = !((llen - 1) & 1);
-		lptr = &lstartptr[(llen - 1) * step];
-		n = llen;
-		while (n-- > 0) {
-			if (state) {
-				--tmpptr;
-				*ptr = *tmpptr;
-			} else {
-				*ptr = *lptr;
-			}
-			lptr -= step;
-			ptr -= twostep;
-			state ^= 1;
-		}
-	} else {
-		/* The first sample in the lowpass subband signal is to
-		  appear first in the output signal. */
-		/* Copy the appropriate samples into the first phase of the
-		  output signal (corresponding to even indexed samples). */
-		lptr = &lstartptr[(llen - 1) * step];
-		ptr = &startptr[((llen - 1) << 1) * step];
-		n = llen >> 1;
-		tmpptr = buf;
-		while (n-- > 0) {
-			*tmpptr = *ptr;
-			*ptr = *lptr;
-			++tmpptr;
-			ptr -= twostep;
-			lptr -= step;
-		}
-		n = llen - (llen >> 1);
-		while (n-- > 0) {
-			*ptr = *lptr;
-			ptr -= twostep;
-			lptr -= step;
-		}
-		/* Copy the appropriate samples into the second phase of
-		  the output signal (corresponding to odd indexed
-		  samples). */
-		ptr = &startptr[step];
-		hptr = hstartptr;
-		state = !(llen & 1);
-		n = hlen;
-		while (n-- > 0) {
-			if (state) {
-				--tmpptr;
-				*ptr = *tmpptr;
-			} else {
-				*ptr = *hptr;
-			}
-			hptr += step;
-			ptr += twostep;
-			state ^= 1;
-		}
-	}
+#define QMFB_JOINBUFSIZE        4096
+        jpc_fix_t joinbuf[QMFB_JOINBUFSIZE];
+        jpc_fix_t *buf = joinbuf;
+        int llen;
+        int hlen;
+        int twostep;
+        jpc_fix_t *tmpptr;
+        register jpc_fix_t *ptr;
+        register jpc_fix_t *hptr;
+        register jpc_fix_t *lptr;
+        register int n;
+        int state;
+
+        twostep = step << 1;
+        llen = lendind - lstartind;
+        hlen = hendind - hstartind;
+
+        if (hstartind < lstartind) {
+                /* The first sample in the highpass subband signal is to
+                  appear first in the output signal. */
+                /* Copy the appropriate samples into the first phase of the
+                  output signal. */
+                tmpptr = buf;
+                hptr = hstartptr;
+                ptr = startptr;
+                n = (llen + 1) >> 1;
+                while (n-- > 0) {
+                        *tmpptr = *ptr;
+                        *ptr = *hptr;
+                        ++tmpptr;
+                        ptr += twostep;
+                        hptr += step;
+                }
+                n = hlen - ((llen + 1) >> 1);
+                while (n-- > 0) {
+                        *ptr = *hptr;
+                        ptr += twostep;
+                        hptr += step;
+                }
+                /* Copy the appropriate samples into the second phase of
+                  the output signal. */
+                ptr -= (lendind > hendind) ? (step) : (step + twostep);
+                state = !((llen - 1) & 1);
+                lptr = &lstartptr[(llen - 1) * step];
+                n = llen;
+                while (n-- > 0) {
+                        if (state) {
+                                --tmpptr;
+                                *ptr = *tmpptr;
+                        } else {
+                                *ptr = *lptr;
+                        }
+                        lptr -= step;
+                        ptr -= twostep;
+                        state ^= 1;
+                }
+        } else {
+                /* The first sample in the lowpass subband signal is to
+                  appear first in the output signal. */
+                /* Copy the appropriate samples into the first phase of the
+                  output signal (corresponding to even indexed samples). */
+                lptr = &lstartptr[(llen - 1) * step];
+                ptr = &startptr[((llen - 1) << 1) * step];
+                n = llen >> 1;
+                tmpptr = buf;
+                while (n-- > 0) {
+                        *tmpptr = *ptr;
+                        *ptr = *lptr;
+                        ++tmpptr;
+                        ptr -= twostep;
+                        lptr -= step;
+                }
+                n = llen - (llen >> 1);
+                while (n-- > 0) {
+                        *ptr = *lptr;
+                        ptr -= twostep;
+                        lptr -= step;
+                }
+                /* Copy the appropriate samples into the second phase of
+                  the output signal (corresponding to odd indexed
+                  samples). */
+                ptr = &startptr[step];
+                hptr = hstartptr;
+                state = !(llen & 1);
+                n = hlen;
+                while (n-- > 0) {
+                        if (state) {
+                                --tmpptr;
+                                *ptr = *tmpptr;
+                        } else {
+                                *ptr = *hptr;
+                        }
+                        hptr += step;
+                        ptr += twostep;
+                        state ^= 1;
+                }
+        }
 }
 
 /******************************************************************************\
@@ -395,310 +394,310 @@ static void jpc_qmfb1d_join(jpc_fix_t *startptr, int startind, int endind,
 
 static int jpc_ft_getnumchans(jpc_qmfb1d_t *qmfb)
 {
-	return 2;
+        return 2;
 }
 
 static int jpc_ft_getanalfilters(jpc_qmfb1d_t *qmfb, int len, jas_seq2d_t **filters)
 {
-	abort();
-	return -1;
+        abort();
+        return -1;
 }
 
 static int jpc_ft_getsynfilters(jpc_qmfb1d_t *qmfb, int len, jas_seq2d_t **filters)
 {
-	jas_seq_t *lf;
-	jas_seq_t *hf;
-
-	lf = 0;
-	hf = 0;
-
-	if (len > 1 || (!len)) {
-		if (!(lf = jas_seq_create(-1, 2))) {
-			goto error;
-		}
-		jas_seq_set(lf, -1, jpc_dbltofix(0.5));
-		jas_seq_set(lf, 0, jpc_dbltofix(1.0));
-		jas_seq_set(lf, 1, jpc_dbltofix(0.5));
-		if (!(hf = jas_seq_create(-1, 4))) {
-			goto error;
-		}
-		jas_seq_set(hf, -1, jpc_dbltofix(-0.125));
-		jas_seq_set(hf, 0, jpc_dbltofix(-0.25));
-		jas_seq_set(hf, 1, jpc_dbltofix(0.75));
-		jas_seq_set(hf, 2, jpc_dbltofix(-0.25));
-		jas_seq_set(hf, 3, jpc_dbltofix(-0.125));
-	} else if (len == 1) {
-		if (!(lf = jas_seq_create(0, 1))) {
-			goto error;
-		}
-		jas_seq_set(lf, 0, jpc_dbltofix(1.0));
-		if (!(hf = jas_seq_create(0, 1))) {
-			goto error;
-		}
-		jas_seq_set(hf, 0, jpc_dbltofix(2.0));
-	} else {
-		abort();
-	}
-
-	filters[0] = lf;
-	filters[1] = hf;
-
-	return 0;
+        jas_seq_t *lf;
+        jas_seq_t *hf;
+
+        lf = 0;
+        hf = 0;
+
+        if (len > 1 || (!len)) {
+                if (!(lf = jas_seq_create(-1, 2))) {
+                        goto error;
+                }
+                jas_seq_set(lf, -1, jpc_dbltofix(0.5));
+                jas_seq_set(lf, 0, jpc_dbltofix(1.0));
+                jas_seq_set(lf, 1, jpc_dbltofix(0.5));
+                if (!(hf = jas_seq_create(-1, 4))) {
+                        goto error;
+                }
+                jas_seq_set(hf, -1, jpc_dbltofix(-0.125));
+                jas_seq_set(hf, 0, jpc_dbltofix(-0.25));
+                jas_seq_set(hf, 1, jpc_dbltofix(0.75));
+                jas_seq_set(hf, 2, jpc_dbltofix(-0.25));
+                jas_seq_set(hf, 3, jpc_dbltofix(-0.125));
+        } else if (len == 1) {
+                if (!(lf = jas_seq_create(0, 1))) {
+                        goto error;
+                }
+                jas_seq_set(lf, 0, jpc_dbltofix(1.0));
+                if (!(hf = jas_seq_create(0, 1))) {
+                        goto error;
+                }
+                jas_seq_set(hf, 0, jpc_dbltofix(2.0));
+        } else {
+                abort();
+        }
+
+        filters[0] = lf;
+        filters[1] = hf;
+
+        return 0;
 
 error:
-	if (lf) {
-		jas_seq_destroy(lf);
-	}
-	if (hf) {
-		jas_seq_destroy(hf);
-	}
-	return -1;
+        if (lf) {
+                jas_seq_destroy(lf);
+        }
+        if (hf) {
+                jas_seq_destroy(hf);
+        }
+        return -1;
 }
 
-#define	NFT_LIFT0(lstartptr, lstartind, lendind, hstartptr, hstartind, hendind, step, pluseq) \
+#define NFT_LIFT0(lstartptr, lstartind, lendind, hstartptr, hstartind, hendind, step, pluseq) \
 { \
-	register jpc_fix_t *lptr = (lstartptr); \
-	register jpc_fix_t *hptr = (hstartptr); \
-	register int n = (hendind) - (hstartind); \
-	if ((hstartind) < (lstartind)) { \
-		pluseq(*hptr, *lptr); \
-		hptr += (step); \
-		--n; \
-	} \
-	if ((hendind) >= (lendind)) { \
-		--n; \
-	} \
-	while (n-- > 0) { \
-		pluseq(*hptr, jpc_fix_asr(jpc_fix_add(*lptr, lptr[(step)]), 1)); \
-		hptr += (step); \
-		lptr += (step); \
-	} \
-	if ((hendind) >= (lendind)) { \
-		pluseq(*hptr, *lptr); \
-	} \
+        register jpc_fix_t *lptr = (lstartptr); \
+        register jpc_fix_t *hptr = (hstartptr); \
+        register int n = (hendind) - (hstartind); \
+        if ((hstartind) < (lstartind)) { \
+                pluseq(*hptr, *lptr); \
+                hptr += (step); \
+                --n; \
+        } \
+        if ((hendind) >= (lendind)) { \
+                --n; \
+        } \
+        while (n-- > 0) { \
+                pluseq(*hptr, jpc_fix_asr(jpc_fix_add(*lptr, lptr[(step)]), 1)); \
+                hptr += (step); \
+                lptr += (step); \
+        } \
+        if ((hendind) >= (lendind)) { \
+                pluseq(*hptr, *lptr); \
+        } \
 }
 
-#define	NFT_LIFT1(lstartptr, lstartind, lendind, hstartptr, hstartind, hendind, step, pluseq) \
+#define NFT_LIFT1(lstartptr, lstartind, lendind, hstartptr, hstartind, hendind, step, pluseq) \
 { \
-	register jpc_fix_t *lptr = (lstartptr); \
-	register jpc_fix_t *hptr = (hstartptr); \
-	register int n = (lendind) - (lstartind); \
-	if ((hstartind) >= (lstartind)) { \
-		pluseq(*lptr, *hptr); \
-		lptr += (step); \
-		--n; \
-	} \
-	if ((lendind) > (hendind)) { \
-		--n; \
-	} \
-	while (n-- > 0) { \
-		pluseq(*lptr, jpc_fix_asr(jpc_fix_add(*hptr, hptr[(step)]), 2)); \
-		lptr += (step); \
-		hptr += (step); \
-	} \
-	if ((lendind) > (hendind)) { \
-		pluseq(*lptr, *hptr); \
-	} \
+        register jpc_fix_t *lptr = (lstartptr); \
+        register jpc_fix_t *hptr = (hstartptr); \
+        register int n = (lendind) - (lstartind); \
+        if ((hstartind) >= (lstartind)) { \
+                pluseq(*lptr, *hptr); \
+                lptr += (step); \
+                --n; \
+        } \
+        if ((lendind) > (hendind)) { \
+                --n; \
+        } \
+        while (n-- > 0) { \
+                pluseq(*lptr, jpc_fix_asr(jpc_fix_add(*hptr, hptr[(step)]), 2)); \
+                lptr += (step); \
+                hptr += (step); \
+        } \
+        if ((lendind) > (hendind)) { \
+                pluseq(*lptr, *hptr); \
+        } \
 }
 
-#define	RFT_LIFT0(lstartptr, lstartind, lendind, hstartptr, hstartind, hendind, step, pmeqop) \
+#define RFT_LIFT0(lstartptr, lstartind, lendind, hstartptr, hstartind, hendind, step, pmeqop) \
 { \
-	register jpc_fix_t *lptr = (lstartptr); \
-	register jpc_fix_t *hptr = (hstartptr); \
-	register int n = (hendind) - (hstartind); \
-	if ((hstartind) < (lstartind)) { \
-		*hptr pmeqop *lptr; \
-		hptr += (step); \
-		--n; \
-	} \
-	if ((hendind) >= (lendind)) { \
-		--n; \
-	} \
-	while (n-- > 0) { \
-		*hptr pmeqop (*lptr + lptr[(step)]) >> 1; \
-		hptr += (step); \
-		lptr += (step); \
-	} \
-	if ((hendind) >= (lendind)) { \
-		*hptr pmeqop *lptr; \
-	} \
+        register jpc_fix_t *lptr = (lstartptr); \
+        register jpc_fix_t *hptr = (hstartptr); \
+        register int n = (hendind) - (hstartind); \
+        if ((hstartind) < (lstartind)) { \
+                *hptr pmeqop *lptr; \
+                hptr += (step); \
+                --n; \
+        } \
+        if ((hendind) >= (lendind)) { \
+                --n; \
+        } \
+        while (n-- > 0) { \
+                *hptr pmeqop (*lptr + lptr[(step)]) >> 1; \
+                hptr += (step); \
+                lptr += (step); \
+        } \
+        if ((hendind) >= (lendind)) { \
+                *hptr pmeqop *lptr; \
+        } \
 }
 
-#define	RFT_LIFT1(lstartptr, lstartind, lendind, hstartptr, hstartind, hendind, step, pmeqop) \
+#define RFT_LIFT1(lstartptr, lstartind, lendind, hstartptr, hstartind, hendind, step, pmeqop) \
 { \
-	register jpc_fix_t *lptr = (lstartptr); \
-	register jpc_fix_t *hptr = (hstartptr); \
-	register int n = (lendind) - (lstartind); \
-	if ((hstartind) >= (lstartind)) { \
-		*lptr pmeqop ((*hptr << 1) + 2) >> 2; \
-		lptr += (step); \
-		--n; \
-	} \
-	if ((lendind) > (hendind)) { \
-		--n; \
-	} \
-	while (n-- > 0) { \
-		*lptr pmeqop ((*hptr + hptr[(step)]) + 2) >> 2; \
-		lptr += (step); \
-		hptr += (step); \
-	} \
-	if ((lendind) > (hendind)) { \
-		*lptr pmeqop ((*hptr << 1) + 2) >> 2; \
-	} \
+        register jpc_fix_t *lptr = (lstartptr); \
+        register jpc_fix_t *hptr = (hstartptr); \
+        register int n = (lendind) - (lstartind); \
+        if ((hstartind) >= (lstartind)) { \
+                *lptr pmeqop ((*hptr << 1) + 2) >> 2; \
+                lptr += (step); \
+                --n; \
+        } \
+        if ((lendind) > (hendind)) { \
+                --n; \
+        } \
+        while (n-- > 0) { \
+                *lptr pmeqop ((*hptr + hptr[(step)]) + 2) >> 2; \
+                lptr += (step); \
+                hptr += (step); \
+        } \
+        if ((lendind) > (hendind)) { \
+                *lptr pmeqop ((*hptr << 1) + 2) >> 2; \
+        } \
 }
 
 static void jpc_ft_analyze(jpc_qmfb1d_t *qmfb, int flags, jas_seq2d_t *x)
 {
-	jpc_fix_t *startptr;
-	int startind;
-	int endind;
-	jpc_fix_t *  lstartptr;
-	int   lstartind;
-	int   lendind;
-	jpc_fix_t *  hstartptr;
-	int   hstartind;
-	int   hendind;
-	int interstep;
-	int intrastep;
-	int numseq;
-
-	if (flags & JPC_QMFB1D_VERT) {
-		interstep = 1;
-		intrastep = jas_seq2d_rowstep(x);
-		numseq = jas_seq2d_width(x);
-		startind = jas_seq2d_ystart(x);
-		endind = jas_seq2d_yend(x);
-	} else {
-		interstep = jas_seq2d_rowstep(x);
-		intrastep = 1;
-		numseq = jas_seq2d_height(x);
-		startind = jas_seq2d_xstart(x);
-		endind = jas_seq2d_xend(x);
-	}
-
-	assert(startind < endind);
-
-	startptr = jas_seq2d_getref(x, jas_seq2d_xstart(x), jas_seq2d_ystart(x));
-	if (flags & JPC_QMFB1D_RITIMODE) {
-		while (numseq-- > 0) {
-			jpc_qmfb1d_setup(startptr, startind, endind, intrastep,
-			  &lstartptr, &lstartind, &lendind, &hstartptr,
-			  &hstartind, &hendind);
-			if (endind - startind > 1) {
-				jpc_qmfb1d_split(startptr, startind, endind,
-				  intrastep, lstartptr, lstartind, lendind,
-				  hstartptr, hstartind, hendind);
-				RFT_LIFT0(lstartptr, lstartind, lendind,
-				  hstartptr, hstartind, hendind, intrastep, -=);
-				RFT_LIFT1(lstartptr, lstartind, lendind,
-				  hstartptr, hstartind, hendind, intrastep, +=);
-			} else {
-				if (lstartind == lendind) {
-					*startptr <<= 1;
-				}
-			}
-			startptr += interstep;
-		}
-	} else {
-		while (numseq-- > 0) {
-			jpc_qmfb1d_setup(startptr, startind, endind, intrastep,
-			  &lstartptr, &lstartind, &lendind, &hstartptr,
-			  &hstartind, &hendind);
-			if (endind - startind > 1) {
-				jpc_qmfb1d_split(startptr, startind, endind,
-				  intrastep, lstartptr, lstartind, lendind,
-				  hstartptr, hstartind, hendind);
-				NFT_LIFT0(lstartptr, lstartind, lendind,
-				  hstartptr, hstartind, hendind, intrastep,
-				  jpc_fix_minuseq);
-				NFT_LIFT1(lstartptr, lstartind, lendind,
-				  hstartptr, hstartind, hendind, intrastep,
-				  jpc_fix_pluseq);
-			} else {
-				if (lstartind == lendind) {
-					*startptr = jpc_fix_asl(*startptr, 1);
-				}
-			}
-			startptr += interstep;
-		}
-	}
+        jpc_fix_t *startptr;
+        int startind;
+        int endind;
+        jpc_fix_t *  lstartptr;
+        int   lstartind;
+        int   lendind;
+        jpc_fix_t *  hstartptr;
+        int   hstartind;
+        int   hendind;
+        int interstep;
+        int intrastep;
+        int numseq;
+
+        if (flags & JPC_QMFB1D_VERT) {
+                interstep = 1;
+                intrastep = jas_seq2d_rowstep(x);
+                numseq = jas_seq2d_width(x);
+                startind = jas_seq2d_ystart(x);
+                endind = jas_seq2d_yend(x);
+        } else {
+                interstep = jas_seq2d_rowstep(x);
+                intrastep = 1;
+                numseq = jas_seq2d_height(x);
+                startind = jas_seq2d_xstart(x);
+                endind = jas_seq2d_xend(x);
+        }
+
+        assert(startind < endind);
+
+        startptr = jas_seq2d_getref(x, jas_seq2d_xstart(x), jas_seq2d_ystart(x));
+        if (flags & JPC_QMFB1D_RITIMODE) {
+                while (numseq-- > 0) {
+                        jpc_qmfb1d_setup(startptr, startind, endind, intrastep,
+                          &lstartptr, &lstartind, &lendind, &hstartptr,
+                          &hstartind, &hendind);
+                        if (endind - startind > 1) {
+                                jpc_qmfb1d_split(startptr, startind, endind,
+                                  intrastep, lstartptr, lstartind, lendind,
+                                  hstartptr, hstartind, hendind);
+                                RFT_LIFT0(lstartptr, lstartind, lendind,
+                                  hstartptr, hstartind, hendind, intrastep, -=);
+                                RFT_LIFT1(lstartptr, lstartind, lendind,
+                                  hstartptr, hstartind, hendind, intrastep, +=);
+                        } else {
+                                if (lstartind == lendind) {
+                                        *startptr <<= 1;
+                                }
+                        }
+                        startptr += interstep;
+                }
+        } else {
+                while (numseq-- > 0) {
+                        jpc_qmfb1d_setup(startptr, startind, endind, intrastep,
+                          &lstartptr, &lstartind, &lendind, &hstartptr,
+                          &hstartind, &hendind);
+                        if (endind - startind > 1) {
+                                jpc_qmfb1d_split(startptr, startind, endind,
+                                  intrastep, lstartptr, lstartind, lendind,
+                                  hstartptr, hstartind, hendind);
+                                NFT_LIFT0(lstartptr, lstartind, lendind,
+                                  hstartptr, hstartind, hendind, intrastep,
+                                  jpc_fix_minuseq);
+                                NFT_LIFT1(lstartptr, lstartind, lendind,
+                                  hstartptr, hstartind, hendind, intrastep,
+                                  jpc_fix_pluseq);
+                        } else {
+                                if (lstartind == lendind) {
+                                        *startptr = jpc_fix_asl(*startptr, 1);
+                                }
+                        }
+                        startptr += interstep;
+                }
+        }
 }
 
 static void jpc_ft_synthesize(jpc_qmfb1d_t *qmfb, int flags, jas_seq2d_t *x)
 {
-	jpc_fix_t *startptr;
-	int startind;
-	int endind;
-	jpc_fix_t *lstartptr;
-	int lstartind;
-	int lendind;
-	jpc_fix_t *hstartptr;
-	int hstartind;
-	int hendind;
-	int interstep;
-	int intrastep;
-	int numseq;
-
-	if (flags & JPC_QMFB1D_VERT) {
-		interstep = 1;
-		intrastep = jas_seq2d_rowstep(x);
-		numseq = jas_seq2d_width(x);
-		startind = jas_seq2d_ystart(x);
-		endind = jas_seq2d_yend(x);
-	} else {
-		interstep = jas_seq2d_rowstep(x);
-		intrastep = 1;
-		numseq = jas_seq2d_height(x);
-		startind = jas_seq2d_xstart(x);
-		endind = jas_seq2d_xend(x);
-	}
-
-	assert(startind < endind);
-
-	startptr = jas_seq2d_getref(x, jas_seq2d_xstart(x), jas_seq2d_ystart(x));
-	if (flags & JPC_QMFB1D_RITIMODE) {
-		while (numseq-- > 0) {
-			jpc_qmfb1d_setup(startptr, startind, endind, intrastep,
-			  &lstartptr, &lstartind, &lendind, &hstartptr,
-			  &hstartind, &hendind);
-			if (endind - startind > 1) {
-				RFT_LIFT1(lstartptr, lstartind, lendind,
-				  hstartptr, hstartind, hendind, intrastep, -=);
-				RFT_LIFT0(lstartptr, lstartind, lendind,
-				  hstartptr, hstartind, hendind, intrastep, +=);
-				jpc_qmfb1d_join(startptr, startind, endind,
-				  intrastep, lstartptr, lstartind, lendind,
-				  hstartptr, hstartind, hendind);
-			} else {
-				if (lstartind == lendind) {
-					*startptr >>= 1;
-				}
-			}
-			startptr += interstep;
-		}
-	} else {
-		while (numseq-- > 0) {
-			jpc_qmfb1d_setup(startptr, startind, endind, intrastep,
-			  &lstartptr, &lstartind, &lendind, &hstartptr,
-			  &hstartind, &hendind);
-			if (endind - startind > 1) {
-				NFT_LIFT1(lstartptr, lstartind, lendind,
-				  hstartptr, hstartind, hendind, intrastep,
-				  jpc_fix_minuseq);
-				NFT_LIFT0(lstartptr, lstartind, lendind,
-				  hstartptr, hstartind, hendind, intrastep,
-				  jpc_fix_pluseq);
-				jpc_qmfb1d_join(startptr, startind, endind,
-				  intrastep, lstartptr, lstartind, lendind,
-				  hstartptr, hstartind, hendind);
-			} else {
-				if (lstartind == lendind) {
-					*startptr = jpc_fix_asr(*startptr, 1);
-				}
-			}
-			startptr += interstep;
-		}
-	}
+        jpc_fix_t *startptr;
+        int startind;
+        int endind;
+        jpc_fix_t *lstartptr;
+        int lstartind;
+        int lendind;
+        jpc_fix_t *hstartptr;
+        int hstartind;
+        int hendind;
+        int interstep;
+        int intrastep;
+        int numseq;
+
+        if (flags & JPC_QMFB1D_VERT) {
+                interstep = 1;
+                intrastep = jas_seq2d_rowstep(x);
+                numseq = jas_seq2d_width(x);
+                startind = jas_seq2d_ystart(x);
+                endind = jas_seq2d_yend(x);
+        } else {
+                interstep = jas_seq2d_rowstep(x);
+                intrastep = 1;
+                numseq = jas_seq2d_height(x);
+                startind = jas_seq2d_xstart(x);
+                endind = jas_seq2d_xend(x);
+        }
+
+        assert(startind < endind);
+
+        startptr = jas_seq2d_getref(x, jas_seq2d_xstart(x), jas_seq2d_ystart(x));
+        if (flags & JPC_QMFB1D_RITIMODE) {
+                while (numseq-- > 0) {
+                        jpc_qmfb1d_setup(startptr, startind, endind, intrastep,
+                          &lstartptr, &lstartind, &lendind, &hstartptr,
+                          &hstartind, &hendind);
+                        if (endind - startind > 1) {
+                                RFT_LIFT1(lstartptr, lstartind, lendind,
+                                  hstartptr, hstartind, hendind, intrastep, -=);
+                                RFT_LIFT0(lstartptr, lstartind, lendind,
+                                  hstartptr, hstartind, hendind, intrastep, +=);
+                                jpc_qmfb1d_join(startptr, startind, endind,
+                                  intrastep, lstartptr, lstartind, lendind,
+                                  hstartptr, hstartind, hendind);
+                        } else {
+                                if (lstartind == lendind) {
+                                        *startptr >>= 1;
+                                }
+                        }
+                        startptr += interstep;
+                }
+        } else {
+                while (numseq-- > 0) {
+                        jpc_qmfb1d_setup(startptr, startind, endind, intrastep,
+                          &lstartptr, &lstartind, &lendind, &hstartptr,
+                          &hstartind, &hendind);
+                        if (endind - startind > 1) {
+                                NFT_LIFT1(lstartptr, lstartind, lendind,
+                                  hstartptr, hstartind, hendind, intrastep,
+                                  jpc_fix_minuseq);
+                                NFT_LIFT0(lstartptr, lstartind, lendind,
+                                  hstartptr, hstartind, hendind, intrastep,
+                                  jpc_fix_pluseq);
+                                jpc_qmfb1d_join(startptr, startind, endind,
+                                  intrastep, lstartptr, lstartind, lendind,
+                                  hstartptr, hstartind, hendind);
+                        } else {
+                                if (lstartind == lendind) {
+                                        *startptr = jpc_fix_asr(*startptr, 1);
+                                }
+                        }
+                        startptr += interstep;
+                }
+        }
 }
 
 /******************************************************************************\
@@ -707,276 +706,276 @@ static void jpc_ft_synthesize(jpc_qmfb1d_t *qmfb, int flags, jas_seq2d_t *x)
 
 static int jpc_ns_getnumchans(jpc_qmfb1d_t *qmfb)
 {
-	return 2;
+        return 2;
 }
 
 static int jpc_ns_getanalfilters(jpc_qmfb1d_t *qmfb, int len, jas_seq2d_t **filters)
 {
-	abort();
-	return -1;
+        abort();
+        return -1;
 }
 
 static int jpc_ns_getsynfilters(jpc_qmfb1d_t *qmfb, int len, jas_seq2d_t **filters)
 {
-	jas_seq_t *lf;
-	jas_seq_t *hf;
-
-	lf = 0;
-	hf = 0;
-
-	if (len > 1 || (!len)) {
-		if (!(lf = jas_seq_create(-3, 4))) {
-			goto error;
-		}
-		jas_seq_set(lf, -3, jpc_dbltofix(-0.09127176311424948));
-		jas_seq_set(lf, -2, jpc_dbltofix(-0.05754352622849957));
-		jas_seq_set(lf, -1, jpc_dbltofix(0.5912717631142470));
-		jas_seq_set(lf, 0, jpc_dbltofix(1.115087052456994));
-		jas_seq_set(lf, 1, jpc_dbltofix(0.5912717631142470));
-		jas_seq_set(lf, 2, jpc_dbltofix(-0.05754352622849957));
-		jas_seq_set(lf, 3, jpc_dbltofix(-0.09127176311424948));
-		if (!(hf = jas_seq_create(-3, 6))) {
-			goto error;
-		}
-		jas_seq_set(hf, -3, jpc_dbltofix(-0.02674875741080976 * 2.0));
-		jas_seq_set(hf, -2, jpc_dbltofix(-0.01686411844287495 * 2.0));
-		jas_seq_set(hf, -1, jpc_dbltofix(0.07822326652898785 * 2.0));
-		jas_seq_set(hf, 0, jpc_dbltofix(0.2668641184428723 * 2.0));
-		jas_seq_set(hf, 1, jpc_dbltofix(-0.6029490182363579 * 2.0));
-		jas_seq_set(hf, 2, jpc_dbltofix(0.2668641184428723 * 2.0));
-		jas_seq_set(hf, 3, jpc_dbltofix(0.07822326652898785 * 2.0));
-		jas_seq_set(hf, 4, jpc_dbltofix(-0.01686411844287495 * 2.0));
-		jas_seq_set(hf, 5, jpc_dbltofix(-0.02674875741080976 * 2.0));
-	} else if (len == 1) {
-		if (!(lf = jas_seq_create(0, 1))) {
-			goto error;
-		}
-		jas_seq_set(lf, 0, jpc_dbltofix(1.0));
-		if (!(hf = jas_seq_create(0, 1))) {
-			goto error;
-		}
-		jas_seq_set(hf, 0, jpc_dbltofix(2.0));
-	} else {
-		abort();
-	}
-
-	filters[0] = lf;
-	filters[1] = hf;
-
-	return 0;
+        jas_seq_t *lf;
+        jas_seq_t *hf;
+
+        lf = 0;
+        hf = 0;
+
+        if (len > 1 || (!len)) {
+                if (!(lf = jas_seq_create(-3, 4))) {
+                        goto error;
+                }
+                jas_seq_set(lf, -3, jpc_dbltofix(-0.09127176311424948));
+                jas_seq_set(lf, -2, jpc_dbltofix(-0.05754352622849957));
+                jas_seq_set(lf, -1, jpc_dbltofix(0.5912717631142470));
+                jas_seq_set(lf, 0, jpc_dbltofix(1.115087052456994));
+                jas_seq_set(lf, 1, jpc_dbltofix(0.5912717631142470));
+                jas_seq_set(lf, 2, jpc_dbltofix(-0.05754352622849957));
+                jas_seq_set(lf, 3, jpc_dbltofix(-0.09127176311424948));
+                if (!(hf = jas_seq_create(-3, 6))) {
+                        goto error;
+                }
+                jas_seq_set(hf, -3, jpc_dbltofix(-0.02674875741080976 * 2.0));
+                jas_seq_set(hf, -2, jpc_dbltofix(-0.01686411844287495 * 2.0));
+                jas_seq_set(hf, -1, jpc_dbltofix(0.07822326652898785 * 2.0));
+                jas_seq_set(hf, 0, jpc_dbltofix(0.2668641184428723 * 2.0));
+                jas_seq_set(hf, 1, jpc_dbltofix(-0.6029490182363579 * 2.0));
+                jas_seq_set(hf, 2, jpc_dbltofix(0.2668641184428723 * 2.0));
+                jas_seq_set(hf, 3, jpc_dbltofix(0.07822326652898785 * 2.0));
+                jas_seq_set(hf, 4, jpc_dbltofix(-0.01686411844287495 * 2.0));
+                jas_seq_set(hf, 5, jpc_dbltofix(-0.02674875741080976 * 2.0));
+        } else if (len == 1) {
+                if (!(lf = jas_seq_create(0, 1))) {
+                        goto error;
+                }
+                jas_seq_set(lf, 0, jpc_dbltofix(1.0));
+                if (!(hf = jas_seq_create(0, 1))) {
+                        goto error;
+                }
+                jas_seq_set(hf, 0, jpc_dbltofix(2.0));
+        } else {
+                abort();
+        }
+
+        filters[0] = lf;
+        filters[1] = hf;
+
+        return 0;
 
 error:
-	if (lf) {
-		jas_seq_destroy(lf);
-	}
-	if (hf) {
-		jas_seq_destroy(hf);
-	}
-	return -1;
+        if (lf) {
+                jas_seq_destroy(lf);
+        }
+        if (hf) {
+                jas_seq_destroy(hf);
+        }
+        return -1;
 }
 
-#define	NNS_LIFT0(lstartptr, lstartind, lendind, hstartptr, hstartind, hendind, step, alpha) \
+#define NNS_LIFT0(lstartptr, lstartind, lendind, hstartptr, hstartind, hendind, step, alpha) \
 { \
-	register jpc_fix_t *lptr = (lstartptr); \
-	register jpc_fix_t *hptr = (hstartptr); \
-	register int n = (hendind) - (hstartind); \
-	jpc_fix_t twoalpha = jpc_fix_mulbyint(alpha, 2); \
-	if ((hstartind) < (lstartind)) { \
-		jpc_fix_pluseq(*hptr, jpc_fix_mul(*lptr, (twoalpha))); \
-		hptr += (step); \
-		--n; \
-	} \
-	if ((hendind) >= (lendind)) { \
-		--n; \
-	} \
-	while (n-- > 0) { \
-		jpc_fix_pluseq(*hptr, jpc_fix_mul(jpc_fix_add(*lptr, lptr[(step)]), (alpha))); \
-		hptr += (step); \
-		lptr += (step); \
-	} \
-	if ((hendind) >= (lendind)) { \
-		jpc_fix_pluseq(*hptr, jpc_fix_mul(*lptr, (twoalpha))); \
-	} \
+        register jpc_fix_t *lptr = (lstartptr); \
+        register jpc_fix_t *hptr = (hstartptr); \
+        register int n = (hendind) - (hstartind); \
+        jpc_fix_t twoalpha = jpc_fix_mulbyint(alpha, 2); \
+        if ((hstartind) < (lstartind)) { \
+                jpc_fix_pluseq(*hptr, jpc_fix_mul(*lptr, (twoalpha))); \
+                hptr += (step); \
+                --n; \
+        } \
+        if ((hendind) >= (lendind)) { \
+                --n; \
+        } \
+        while (n-- > 0) { \
+                jpc_fix_pluseq(*hptr, jpc_fix_mul(jpc_fix_add(*lptr, lptr[(step)]), (alpha))); \
+                hptr += (step); \
+                lptr += (step); \
+        } \
+        if ((hendind) >= (lendind)) { \
+                jpc_fix_pluseq(*hptr, jpc_fix_mul(*lptr, (twoalpha))); \
+        } \
 }
 
-#define	NNS_LIFT1(lstartptr, lstartind, lendind, hstartptr, hstartind, hendind, step, alpha) \
+#define NNS_LIFT1(lstartptr, lstartind, lendind, hstartptr, hstartind, hendind, step, alpha) \
 { \
-	register jpc_fix_t *lptr = (lstartptr); \
-	register jpc_fix_t *hptr = (hstartptr); \
-	register int n = (lendind) - (lstartind); \
-	int twoalpha = jpc_fix_mulbyint(alpha, 2); \
-	if ((hstartind) >= (lstartind)) { \
-		jpc_fix_pluseq(*lptr, jpc_fix_mul(*hptr, (twoalpha))); \
-		lptr += (step); \
-		--n; \
-	} \
-	if ((lendind) > (hendind)) { \
-		--n; \
-	} \
-	while (n-- > 0) { \
-		jpc_fix_pluseq(*lptr, jpc_fix_mul(jpc_fix_add(*hptr, hptr[(step)]), (alpha))); \
-		lptr += (step); \
-		hptr += (step); \
-	} \
-	if ((lendind) > (hendind)) { \
-		jpc_fix_pluseq(*lptr, jpc_fix_mul(*hptr, (twoalpha))); \
-	} \
+        register jpc_fix_t *lptr = (lstartptr); \
+        register jpc_fix_t *hptr = (hstartptr); \
+        register int n = (lendind) - (lstartind); \
+        int twoalpha = jpc_fix_mulbyint(alpha, 2); \
+        if ((hstartind) >= (lstartind)) { \
+                jpc_fix_pluseq(*lptr, jpc_fix_mul(*hptr, (twoalpha))); \
+                lptr += (step); \
+                --n; \
+        } \
+        if ((lendind) > (hendind)) { \
+                --n; \
+        } \
+        while (n-- > 0) { \
+                jpc_fix_pluseq(*lptr, jpc_fix_mul(jpc_fix_add(*hptr, hptr[(step)]), (alpha))); \
+                lptr += (step); \
+                hptr += (step); \
+        } \
+        if ((lendind) > (hendind)) { \
+                jpc_fix_pluseq(*lptr, jpc_fix_mul(*hptr, (twoalpha))); \
+        } \
 }
 
-#define	NNS_SCALE(startptr, startind, endind, step, alpha) \
+#define NNS_SCALE(startptr, startind, endind, step, alpha) \
 { \
-	register jpc_fix_t *ptr = (startptr); \
-	register int n = (endind) - (startind); \
-	while (n-- > 0) { \
-		jpc_fix_muleq(*ptr, alpha); \
-		ptr += (step); \
-	} \
+        register jpc_fix_t *ptr = (startptr); \
+        register int n = (endind) - (startind); \
+        while (n-- > 0) { \
+                jpc_fix_muleq(*ptr, alpha); \
+                ptr += (step); \
+        } \
 }
 
 static void jpc_ns_analyze(jpc_qmfb1d_t *qmfb, int flags, jas_seq2d_t *x)
 {
-	jpc_fix_t *startptr;
-	int startind;
-	int endind;
-	jpc_fix_t *lstartptr;
-	int lstartind;
-	int lendind;
-	jpc_fix_t *hstartptr;
-	int hstartind;
-	int hendind;
-	int interstep;
-	int intrastep;
-	int numseq;
-
-	if (flags & JPC_QMFB1D_VERT) {
-		interstep = 1;
-		intrastep = jas_seq2d_rowstep(x);
-		numseq = jas_seq2d_width(x);
-		startind = jas_seq2d_ystart(x);
-		endind = jas_seq2d_yend(x);
-	} else {
-		interstep = jas_seq2d_rowstep(x);
-		intrastep = 1;
-		numseq = jas_seq2d_height(x);
-		startind = jas_seq2d_xstart(x);
-		endind = jas_seq2d_xend(x);
-	}
-
-	assert(startind < endind);
-
-	startptr = jas_seq2d_getref(x, jas_seq2d_xstart(x), jas_seq2d_ystart(x));
-	if (!(flags & JPC_QMFB1D_RITIMODE)) {
-		while (numseq-- > 0) {
-			jpc_qmfb1d_setup(startptr, startind, endind, intrastep,
-			  &lstartptr, &lstartind, &lendind, &hstartptr,
-			  &hstartind, &hendind);
-			if (endind - startind > 1) {
-				jpc_qmfb1d_split(startptr, startind, endind,
-				  intrastep, lstartptr, lstartind, lendind,
-				  hstartptr, hstartind, hendind);
-				NNS_LIFT0(lstartptr, lstartind, lendind,
-				  hstartptr, hstartind, hendind, intrastep,
-				  jpc_dbltofix(-1.586134342));
-				NNS_LIFT1(lstartptr, lstartind, lendind,
-				  hstartptr, hstartind, hendind, intrastep,
-				  jpc_dbltofix(-0.052980118));
-				NNS_LIFT0(lstartptr, lstartind, lendind,
-				  hstartptr, hstartind, hendind, intrastep,
-				  jpc_dbltofix(0.882911075));
-				NNS_LIFT1(lstartptr, lstartind, lendind,
-				  hstartptr, hstartind, hendind, intrastep,
-				  jpc_dbltofix(0.443506852));
-				NNS_SCALE(lstartptr, lstartind, lendind,
-				  intrastep, jpc_dbltofix(1.0/1.23017410558578));
-				NNS_SCALE(hstartptr, hstartind, hendind,
-				  intrastep, jpc_dbltofix(1.0/1.62578613134411));
-			} else {
+        jpc_fix_t *startptr;
+        int startind;
+        int endind;
+        jpc_fix_t *lstartptr;
+        int lstartind;
+        int lendind;
+        jpc_fix_t *hstartptr;
+        int hstartind;
+        int hendind;
+        int interstep;
+        int intrastep;
+        int numseq;
+
+        if (flags & JPC_QMFB1D_VERT) {
+                interstep = 1;
+                intrastep = jas_seq2d_rowstep(x);
+                numseq = jas_seq2d_width(x);
+                startind = jas_seq2d_ystart(x);
+                endind = jas_seq2d_yend(x);
+        } else {
+                interstep = jas_seq2d_rowstep(x);
+                intrastep = 1;
+                numseq = jas_seq2d_height(x);
+                startind = jas_seq2d_xstart(x);
+                endind = jas_seq2d_xend(x);
+        }
+
+        assert(startind < endind);
+
+        startptr = jas_seq2d_getref(x, jas_seq2d_xstart(x), jas_seq2d_ystart(x));
+        if (!(flags & JPC_QMFB1D_RITIMODE)) {
+                while (numseq-- > 0) {
+                        jpc_qmfb1d_setup(startptr, startind, endind, intrastep,
+                          &lstartptr, &lstartind, &lendind, &hstartptr,
+                          &hstartind, &hendind);
+                        if (endind - startind > 1) {
+                                jpc_qmfb1d_split(startptr, startind, endind,
+                                  intrastep, lstartptr, lstartind, lendind,
+                                  hstartptr, hstartind, hendind);
+                                NNS_LIFT0(lstartptr, lstartind, lendind,
+                                  hstartptr, hstartind, hendind, intrastep,
+                                  jpc_dbltofix(-1.586134342));
+                                NNS_LIFT1(lstartptr, lstartind, lendind,
+                                  hstartptr, hstartind, hendind, intrastep,
+                                  jpc_dbltofix(-0.052980118));
+                                NNS_LIFT0(lstartptr, lstartind, lendind,
+                                  hstartptr, hstartind, hendind, intrastep,
+                                  jpc_dbltofix(0.882911075));
+                                NNS_LIFT1(lstartptr, lstartind, lendind,
+                                  hstartptr, hstartind, hendind, intrastep,
+                                  jpc_dbltofix(0.443506852));
+                                NNS_SCALE(lstartptr, lstartind, lendind,
+                                  intrastep, jpc_dbltofix(1.0/1.23017410558578));
+                                NNS_SCALE(hstartptr, hstartind, hendind,
+                                  intrastep, jpc_dbltofix(1.0/1.62578613134411));
+                        } else {
 #if 0
-				if (lstartind == lendind) {
-					*startptr = jpc_fix_asl(*startptr, 1);
-				}
+                                if (lstartind == lendind) {
+                                        *startptr = jpc_fix_asl(*startptr, 1);
+                                }
 #endif
-			}
-			startptr += interstep;
-		}
-	} else {
-		/* The reversible integer-to-integer mode is not valid for this
-		  transform. */
-		abort();
-	}
+                        }
+                        startptr += interstep;
+                }
+        } else {
+                /* The reversible integer-to-integer mode is not valid for this
+                  transform. */
+                abort();
+        }
 }
 
 static void jpc_ns_synthesize(jpc_qmfb1d_t *qmfb, int flags, jas_seq2d_t *x)
 {
-	jpc_fix_t *startptr;
-	int startind;
-	int endind;
-	jpc_fix_t *lstartptr;
-	int lstartind;
-	int lendind;
-	jpc_fix_t *hstartptr;
-	int hstartind;
-	int hendind;
-	int interstep;
-	int intrastep;
-	int numseq;
-
-	if (flags & JPC_QMFB1D_VERT) {
-		interstep = 1;
-		intrastep = jas_seq2d_rowstep(x);
-		numseq = jas_seq2d_width(x);
-		startind = jas_seq2d_ystart(x);
-		endind = jas_seq2d_yend(x);
-	} else {
-		interstep = jas_seq2d_rowstep(x);
-		intrastep = 1;
-		numseq = jas_seq2d_height(x);
-		startind = jas_seq2d_xstart(x);
-		endind = jas_seq2d_xend(x);
-	}
-
-	assert(startind < endind);
-
-	startptr = jas_seq2d_getref(x, jas_seq2d_xstart(x), jas_seq2d_ystart(x));
-	if (!(flags & JPC_QMFB1D_RITIMODE)) {
-		while (numseq-- > 0) {
-			jpc_qmfb1d_setup(startptr, startind, endind, intrastep,
-			  &lstartptr, &lstartind, &lendind, &hstartptr,
-			  &hstartind, &hendind);
-			if (endind - startind > 1) {
-				NNS_SCALE(lstartptr, lstartind, lendind,
-				  intrastep, jpc_dbltofix(1.23017410558578));
-				NNS_SCALE(hstartptr, hstartind, hendind,
-				  intrastep, jpc_dbltofix(1.62578613134411));
-				NNS_LIFT1(lstartptr, lstartind, lendind,
-				  hstartptr, hstartind, hendind, intrastep,
-				  jpc_dbltofix(-0.443506852));
-				NNS_LIFT0(lstartptr, lstartind, lendind,
-				  hstartptr, hstartind, hendind, intrastep,
-				  jpc_dbltofix(-0.882911075));
-				NNS_LIFT1(lstartptr, lstartind, lendind,
-				  hstartptr, hstartind, hendind, intrastep,
-				  jpc_dbltofix(0.052980118));
-				NNS_LIFT0(lstartptr, lstartind, lendind,
-				  hstartptr, hstartind, hendind, intrastep,
-				  jpc_dbltofix(1.586134342));
-				jpc_qmfb1d_join(startptr, startind, endind,
-				  intrastep, lstartptr, lstartind, lendind,
-				  hstartptr, hstartind, hendind);
-			} else {
+        jpc_fix_t *startptr;
+        int startind;
+        int endind;
+        jpc_fix_t *lstartptr;
+        int lstartind;
+        int lendind;
+        jpc_fix_t *hstartptr;
+        int hstartind;
+        int hendind;
+        int interstep;
+        int intrastep;
+        int numseq;
+
+        if (flags & JPC_QMFB1D_VERT) {
+                interstep = 1;
+                intrastep = jas_seq2d_rowstep(x);
+                numseq = jas_seq2d_width(x);
+                startind = jas_seq2d_ystart(x);
+                endind = jas_seq2d_yend(x);
+        } else {
+                interstep = jas_seq2d_rowstep(x);
+                intrastep = 1;
+                numseq = jas_seq2d_height(x);
+                startind = jas_seq2d_xstart(x);
+                endind = jas_seq2d_xend(x);
+        }
+
+        assert(startind < endind);
+
+        startptr = jas_seq2d_getref(x, jas_seq2d_xstart(x), jas_seq2d_ystart(x));
+        if (!(flags & JPC_QMFB1D_RITIMODE)) {
+                while (numseq-- > 0) {
+                        jpc_qmfb1d_setup(startptr, startind, endind, intrastep,
+                          &lstartptr, &lstartind, &lendind, &hstartptr,
+                          &hstartind, &hendind);
+                        if (endind - startind > 1) {
+                                NNS_SCALE(lstartptr, lstartind, lendind,
+                                  intrastep, jpc_dbltofix(1.23017410558578));
+                                NNS_SCALE(hstartptr, hstartind, hendind,
+                                  intrastep, jpc_dbltofix(1.62578613134411));
+                                NNS_LIFT1(lstartptr, lstartind, lendind,
+                                  hstartptr, hstartind, hendind, intrastep,
+                                  jpc_dbltofix(-0.443506852));
+                                NNS_LIFT0(lstartptr, lstartind, lendind,
+                                  hstartptr, hstartind, hendind, intrastep,
+                                  jpc_dbltofix(-0.882911075));
+                                NNS_LIFT1(lstartptr, lstartind, lendind,
+                                  hstartptr, hstartind, hendind, intrastep,
+                                  jpc_dbltofix(0.052980118));
+                                NNS_LIFT0(lstartptr, lstartind, lendind,
+                                  hstartptr, hstartind, hendind, intrastep,
+                                  jpc_dbltofix(1.586134342));
+                                jpc_qmfb1d_join(startptr, startind, endind,
+                                  intrastep, lstartptr, lstartind, lendind,
+                                  hstartptr, hstartind, hendind);
+                        } else {
 #if 0
-				if (lstartind == lendind) {
-					*startptr = jpc_fix_asr(*startptr, 1);
-				}
+                                if (lstartind == lendind) {
+                                        *startptr = jpc_fix_asr(*startptr, 1);
+                                }
 #endif
-			}
-			startptr += interstep;
-		}
-	} else {
-		/* The reversible integer-to-integer mode is not valid
+                        }
+                        startptr += interstep;
+                }
+        } else {
+                /* The reversible integer-to-integer mode is not valid
            for this transform. */
-		abort();
-	}
+                abort();
+        }
 }
 
 /******************************************************************************\
@@ -985,49 +984,49 @@ static void jpc_ns_synthesize(jpc_qmfb1d_t *qmfb, int flags, jas_seq2d_t *x)
 
 jpc_qmfb1d_t *jpc_qmfb1d_make(int qmfbid)
 {
-	jpc_qmfb1d_t *qmfb;
-	if (!(qmfb = jpc_qmfb1d_create())) {
-		return 0;
-	}
-	switch (qmfbid) {
-	case JPC_QMFB1D_FT:
-		qmfb->ops = &jpc_ft_ops;
-		break;
-	case JPC_QMFB1D_NS:
-		qmfb->ops = &jpc_ns_ops;
-		break;
-	default:
-		jpc_qmfb1d_destroy(qmfb);
-		return 0;
-		break;
-	}
-	return qmfb;
+        jpc_qmfb1d_t *qmfb;
+        if (!(qmfb = jpc_qmfb1d_create())) {
+                return 0;
+        }
+        switch (qmfbid) {
+        case JPC_QMFB1D_FT:
+                qmfb->ops = &jpc_ft_ops;
+                break;
+        case JPC_QMFB1D_NS:
+                qmfb->ops = &jpc_ns_ops;
+                break;
+        default:
+                jpc_qmfb1d_destroy(qmfb);
+                return 0;
+                break;
+        }
+        return qmfb;
 }
 
 static jpc_qmfb1d_t *jpc_qmfb1d_create()
 {
-	jpc_qmfb1d_t *qmfb;
-	if (!(qmfb = jas_malloc(sizeof(jpc_qmfb1d_t)))) {
-		return 0;
-	}
-	qmfb->ops = 0;
-	return qmfb;
+        jpc_qmfb1d_t *qmfb;
+        if (!(qmfb = jas_malloc(sizeof(jpc_qmfb1d_t)))) {
+                return 0;
+        }
+        qmfb->ops = 0;
+        return qmfb;
 }
 
 jpc_qmfb1d_t *jpc_qmfb1d_copy(jpc_qmfb1d_t *qmfb)
 {
-	jpc_qmfb1d_t *newqmfb;
+        jpc_qmfb1d_t *newqmfb;
 
-	if (!(newqmfb = jpc_qmfb1d_create())) {
-		return 0;
-	}
-	newqmfb->ops = qmfb->ops;
-	return newqmfb;
+        if (!(newqmfb = jpc_qmfb1d_create())) {
+                return 0;
+        }
+        newqmfb->ops = qmfb->ops;
+        return newqmfb;
 }
 
 void jpc_qmfb1d_destroy(jpc_qmfb1d_t *qmfb)
 {
-	jas_free(qmfb);
+        jas_free(qmfb);
 }
 
 /******************************************************************************\
@@ -1038,27 +1037,27 @@ void jpc_qmfb1d_getbands(jpc_qmfb1d_t *qmfb, int flags, uint_fast32_t xstart,
   uint_fast32_t ystart, uint_fast32_t xend, uint_fast32_t yend, int maxbands,
   int *numbandsptr, jpc_qmfb1dband_t *bands)
 {
-	int start;
-	int end;
-	if (flags & JPC_QMFB1D_VERT) {
-		start = ystart;
-		end = yend;
-	} else {
-		start = xstart;
-		end = xend;
-	}
-	assert(jpc_qmfb1d_getnumchans(qmfb) == 2);
-	assert(start <= end);
-	bands[0].start = JPC_CEILDIVPOW2(start, 1);
-	bands[0].end = JPC_CEILDIVPOW2(end, 1);
-	bands[0].locstart = start;
-	bands[0].locend = start + bands[0].end - bands[0].start;
-	bands[1].start = JPC_FLOORDIVPOW2(start, 1);
-	bands[1].end = JPC_FLOORDIVPOW2(end, 1);
-	bands[1].locstart = bands[0].locend;
-	bands[1].locend = bands[1].locstart + bands[1].end - bands[1].start;
-	assert(bands[1].locend == end);
-	*numbandsptr = 2;
+        int start;
+        int end;
+        if (flags & JPC_QMFB1D_VERT) {
+                start = ystart;
+                end = yend;
+        } else {
+                start = xstart;
+                end = xend;
+        }
+        assert(jpc_qmfb1d_getnumchans(qmfb) == 2);
+        assert(start <= end);
+        bands[0].start = JPC_CEILDIVPOW2(start, 1);
+        bands[0].end = JPC_CEILDIVPOW2(end, 1);
+        bands[0].locstart = start;
+        bands[0].locend = start + bands[0].end - bands[0].start;
+        bands[1].start = JPC_FLOORDIVPOW2(start, 1);
+        bands[1].end = JPC_FLOORDIVPOW2(end, 1);
+        bands[1].locstart = bands[0].locend;
+        bands[1].locend = bands[1].locstart + bands[1].end - bands[1].start;
+        assert(bands[1].locend == end);
+        *numbandsptr = 2;
 }
 
 /******************************************************************************\
@@ -1067,25 +1066,25 @@ void jpc_qmfb1d_getbands(jpc_qmfb1d_t *qmfb, int flags, uint_fast32_t xstart,
 
 int jpc_qmfb1d_getnumchans(jpc_qmfb1d_t *qmfb)
 {
-	return (*qmfb->ops->getnumchans)(qmfb);
+        return (*qmfb->ops->getnumchans)(qmfb);
 }
 
 int jpc_qmfb1d_getanalfilters(jpc_qmfb1d_t *qmfb, int len, jas_seq2d_t **filters)
 {
-	return (*qmfb->ops->getanalfilters)(qmfb, len, filters);
+        return (*qmfb->ops->getanalfilters)(qmfb, len, filters);
 }
 
 int jpc_qmfb1d_getsynfilters(jpc_qmfb1d_t *qmfb, int len, jas_seq2d_t **filters)
 {
-	return (*qmfb->ops->getsynfilters)(qmfb, len, filters);
+        return (*qmfb->ops->getsynfilters)(qmfb, len, filters);
 }
 
 void jpc_qmfb1d_analyze(jpc_qmfb1d_t *qmfb, int flags, jas_seq2d_t *x)
 {
-	(*qmfb->ops->analyze)(qmfb, flags, x);
+        (*qmfb->ops->analyze)(qmfb, flags, x);
 }
 
 void jpc_qmfb1d_synthesize(jpc_qmfb1d_t *qmfb, int flags, jas_seq2d_t *x)
 {
-	(*qmfb->ops->synthesize)(qmfb, flags, x);
+        (*qmfb->ops->synthesize)(qmfb, flags, x);
 }
diff --git a/converter/other/jpeg2000/libjasper/jpc/jpc_qmfb.h b/converter/other/jpeg2000/libjasper/jpc/jpc_qmfb.h
index e10b6c13..fb46965b 100644
--- a/converter/other/jpeg2000/libjasper/jpc/jpc_qmfb.h
+++ b/converter/other/jpeg2000/libjasper/jpc/jpc_qmfb.h
@@ -6,14 +6,14 @@
  */
 
 /* __START_OF_JASPER_LICENSE__
- * 
+ *
  * JasPer Software License
- * 
+ *
  * IMAGE POWER JPEG-2000 PUBLIC LICENSE
  * ************************************
- * 
+ *
  * GRANT:
- * 
+ *
  * Permission is hereby granted, free of charge, to any person (the "User")
  * obtaining a copy of this software and associated documentation, to deal
  * in the JasPer Software without restriction, including without limitation
@@ -21,22 +21,22 @@
  * and/or sell copies of the JasPer Software (in source and binary forms),
  * and to permit persons to whom the JasPer Software is furnished to do so,
  * provided further that the License Conditions below are met.
- * 
+ *
  * License Conditions
  * ******************
- * 
+ *
  * A.  Redistributions of source code must retain the above copyright notice,
  * and this list of conditions, and the following disclaimer.
- * 
+ *
  * B.  Redistributions in binary form must reproduce the above copyright
  * notice, and this list of conditions, and the following disclaimer in
  * the documentation and/or other materials provided with the distribution.
- * 
+ *
  * C.  Neither the name of Image Power, Inc. nor any other contributor
  * (including, but not limited to, the University of British Columbia and
  * Michael David Adams) may be used to endorse or promote products derived
  * from this software without specific prior written permission.
- * 
+ *
  * D.  User agrees that it shall not commence any action against Image Power,
  * Inc., the University of British Columbia, Michael David Adams, or any
  * other contributors (collectively "Licensors") for infringement of any
@@ -56,17 +56,17 @@
  * trade dress, or service mark rights); and (v) divisions, continuations,
  * renewals, reissues and extensions of the foregoing (as and to the extent
  * applicable) now existing, hereafter filed, issued or acquired.
- * 
+ *
  * E.  If User commences an infringement action against any Licensor(s) then
  * such Licensor(s) shall have the right to terminate User's license and
  * all sublicenses that have been granted hereunder by User to other parties.
- * 
+ *
  * F.  This software is for use only in hardware or software products that
  * are compliant with ISO/IEC 15444-1 (i.e., JPEG-2000 Part 1).  No license
  * or right to this Software is granted for products that do not comply
  * with ISO/IEC 15444-1.  The JPEG-2000 Part 1 standard can be purchased
  * from the ISO.
- * 
+ *
  * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS LICENSE.
  * NO USE OF THE JASPER SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER
  * THIS DISCLAIMER.  THE JASPER SOFTWARE IS PROVIDED BY THE LICENSORS AND
@@ -106,7 +106,7 @@
  * TECHNOLOGY OR PRODUCTS FOR HIGH RISK ACTIVITIES AND WILL ENSURE THAT ITS
  * CUSTOMERS AND END-USERS OF ITS PRODUCTS ARE PROVIDED WITH A COPY OF THE
  * NOTICE SPECIFIED IN THIS SECTION.
- * 
+ *
  * __END_OF_JASPER_LICENSE__
  */
 
@@ -130,17 +130,17 @@
 \******************************************************************************/
 
 /* The maximum number of channels for a QMF bank. */
-#define	JPC_QMFB1D_MAXCHANS	2
+#define JPC_QMFB1D_MAXCHANS     2
 
 /* Select reversible integer-to-integer mode. */
-#define	JPC_QMFB1D_RITIMODE	1
+#define JPC_QMFB1D_RITIMODE     1
 
 /* Vertical filtering. */
-#define	JPC_QMFB1D_VERT	0x10000
+#define JPC_QMFB1D_VERT 0x10000
 
 /* QMFB IDs. */
-#define	JPC_QMFB1D_FT	1	/* 5/3 */
-#define	JPC_QMFB1D_NS	2	/* 9/7 */
+#define JPC_QMFB1D_FT   1       /* 5/3 */
+#define JPC_QMFB1D_NS   2       /* 9/7 */
 
 /******************************************************************************\
 * Types.
@@ -153,17 +153,17 @@ struct jpc_qmfb1dops_s;
 
 typedef struct {
 
-	/* The starting index for the band in the downsampled domain. */
-	int start;
+        /* The starting index for the band in the downsampled domain. */
+        int start;
 
-	/* The ending index for the band in the downsampled domain. */
-	int end;
+        /* The ending index for the band in the downsampled domain. */
+        int end;
 
-	/* The location of the start of the band. */
-	int locstart;
+        /* The location of the start of the band. */
+        int locstart;
 
-	/* The location of the end of the band. */
-	int locend;
+        /* The location of the end of the band. */
+        int locend;
 
 } jpc_qmfb1dband_t;
 
@@ -171,8 +171,8 @@ typedef struct {
 
 typedef struct {
 
-	/* The operations for this QMFB. */
-	struct jpc_qmfb1dops_s *ops;
+        /* The operations for this QMFB. */
+        struct jpc_qmfb1dops_s *ops;
 
 } jpc_qmfb1d_t;
 
@@ -180,20 +180,20 @@ typedef struct {
 
 typedef struct jpc_qmfb1dops_s {
 
-	/* The number of channels in the QMFB. */
-	int (*getnumchans)(jpc_qmfb1d_t *qmfb);
+        /* The number of channels in the QMFB. */
+        int (*getnumchans)(jpc_qmfb1d_t *qmfb);
 
-	/* Get the analysis filters for this QMFB. */
-	int (*getanalfilters)(jpc_qmfb1d_t *qmfb, int len, jas_seq2d_t **filters);
+        /* Get the analysis filters for this QMFB. */
+        int (*getanalfilters)(jpc_qmfb1d_t *qmfb, int len, jas_seq2d_t **filters);
 
-	/* Get the synthesis filters for this QMFB. */
-	int (*getsynfilters)(jpc_qmfb1d_t *qmfb, int len, jas_seq2d_t **filters);
+        /* Get the synthesis filters for this QMFB. */
+        int (*getsynfilters)(jpc_qmfb1d_t *qmfb, int len, jas_seq2d_t **filters);
 
-	/* Do analysis. */
-	void (*analyze)(jpc_qmfb1d_t *qmfb, int flags, jas_seq2d_t *x);
+        /* Do analysis. */
+        void (*analyze)(jpc_qmfb1d_t *qmfb, int flags, jas_seq2d_t *x);
 
-	/* Do synthesis. */
-	void (*synthesize)(jpc_qmfb1d_t *qmfb, int flags, jas_seq2d_t *x);
+        /* Do synthesis. */
+        void (*synthesize)(jpc_qmfb1d_t *qmfb, int flags, jas_seq2d_t *x);
 
 } jpc_qmfb1dops_t;
 
diff --git a/converter/other/jpeg2000/libjasper/jpc/jpc_t1cod.c b/converter/other/jpeg2000/libjasper/jpc/jpc_t1cod.c
index 650cb854..ed188154 100644
--- a/converter/other/jpeg2000/libjasper/jpc/jpc_t1cod.c
+++ b/converter/other/jpeg2000/libjasper/jpc/jpc_t1cod.c
@@ -6,14 +6,14 @@
  */
 
 /* __START_OF_JASPER_LICENSE__
- * 
+ *
  * JasPer Software License
- * 
+ *
  * IMAGE POWER JPEG-2000 PUBLIC LICENSE
  * ************************************
- * 
+ *
  * GRANT:
- * 
+ *
  * Permission is hereby granted, free of charge, to any person (the "User")
  * obtaining a copy of this software and associated documentation, to deal
  * in the JasPer Software without restriction, including without limitation
@@ -21,22 +21,22 @@
  * and/or sell copies of the JasPer Software (in source and binary forms),
  * and to permit persons to whom the JasPer Software is furnished to do so,
  * provided further that the License Conditions below are met.
- * 
+ *
  * License Conditions
  * ******************
- * 
+ *
  * A.  Redistributions of source code must retain the above copyright notice,
  * and this list of conditions, and the following disclaimer.
- * 
+ *
  * B.  Redistributions in binary form must reproduce the above copyright
  * notice, and this list of conditions, and the following disclaimer in
  * the documentation and/or other materials provided with the distribution.
- * 
+ *
  * C.  Neither the name of Image Power, Inc. nor any other contributor
  * (including, but not limited to, the University of British Columbia and
  * Michael David Adams) may be used to endorse or promote products derived
  * from this software without specific prior written permission.
- * 
+ *
  * D.  User agrees that it shall not commence any action against Image Power,
  * Inc., the University of British Columbia, Michael David Adams, or any
  * other contributors (collectively "Licensors") for infringement of any
@@ -56,17 +56,17 @@
  * trade dress, or service mark rights); and (v) divisions, continuations,
  * renewals, reissues and extensions of the foregoing (as and to the extent
  * applicable) now existing, hereafter filed, issued or acquired.
- * 
+ *
  * E.  If User commences an infringement action against any Licensor(s) then
  * such Licensor(s) shall have the right to terminate User's license and
  * all sublicenses that have been granted hereunder by User to other parties.
- * 
+ *
  * F.  This software is for use only in hardware or software products that
  * are compliant with ISO/IEC 15444-1 (i.e., JPEG-2000 Part 1).  No license
  * or right to this Software is granted for products that do not comply
  * with ISO/IEC 15444-1.  The JPEG-2000 Part 1 standard can be purchased
  * from the ISO.
- * 
+ *
  * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS LICENSE.
  * NO USE OF THE JASPER SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER
  * THIS DISCLAIMER.  THE JASPER SOFTWARE IS PROVIDED BY THE LICENSORS AND
@@ -106,7 +106,7 @@
  * TECHNOLOGY OR PRODUCTS FOR HIGH RISK ACTIVITIES AND WILL ENSURE THAT ITS
  * CUSTOMERS AND END-USERS OF ITS PRODUCTS ARE PROVIDED WITH A COPY OF THE
  * NOTICE SPECIFIED IN THIS SECTION.
- * 
+ *
  * __END_OF_JASPER_LICENSE__
  */
 
@@ -157,46 +157,46 @@ jpc_mqctx_t jpc_mqctxs[JPC_NUMCTXS];
 
 int JPC_PASSTYPE(int passno)
 {
-	int passtype;
-	switch (passno % 3) {
-	case 0:
-		passtype = JPC_CLNPASS;
-		break;
-	case 1:
-		passtype = JPC_SIGPASS;
-		break;
-	case 2:
-		passtype = JPC_REFPASS;
-		break;
-	default:
-		passtype = -1;
-		assert(0);
-		break;
-	}
-	return passtype;
+        int passtype;
+        switch (passno % 3) {
+        case 0:
+                passtype = JPC_CLNPASS;
+                break;
+        case 1:
+                passtype = JPC_SIGPASS;
+                break;
+        case 2:
+                passtype = JPC_REFPASS;
+                break;
+        default:
+                passtype = -1;
+                assert(0);
+                break;
+        }
+        return passtype;
 }
 
 int JPC_NOMINALGAIN(int qmfbid, int numlvls, int lvlno, int orient)
 {
 if (qmfbid == JPC_COX_INS) {
-	return 0;
+        return 0;
 }
-	assert(qmfbid == JPC_COX_RFT);
-	if (lvlno == 0) {
-		assert(orient == JPC_TSFB_LL);
-		return 0;
-	} else {
-		switch (orient) {
-		case JPC_TSFB_LH:
-		case JPC_TSFB_HL:
-			return 1;
-			break;
-		case JPC_TSFB_HH:
-			return 2;
-			break;
-		}
-	}
-	abort();
+        assert(qmfbid == JPC_COX_RFT);
+        if (lvlno == 0) {
+                assert(orient == JPC_TSFB_LL);
+                return 0;
+        } else {
+                switch (orient) {
+                case JPC_TSFB_LH:
+                case JPC_TSFB_HL:
+                        return 1;
+                        break;
+                case JPC_TSFB_HH:
+                        return 2;
+                        break;
+                }
+        }
+        abort();
 }
 
 /******************************************************************************\
@@ -205,66 +205,66 @@ if (qmfbid == JPC_COX_INS) {
 
 int JPC_SEGTYPE(int passno, int firstpassno, int bypass)
 {
-	int passtype;
-	if (bypass) {
-		passtype = JPC_PASSTYPE(passno);
-		if (passtype == JPC_CLNPASS) {
-			return JPC_SEG_MQ;
-		}
-		return ((passno < firstpassno + 10) ? JPC_SEG_MQ : JPC_SEG_RAW);
-	} else {
-		return JPC_SEG_MQ;
-	}
+        int passtype;
+        if (bypass) {
+                passtype = JPC_PASSTYPE(passno);
+                if (passtype == JPC_CLNPASS) {
+                        return JPC_SEG_MQ;
+                }
+                return ((passno < firstpassno + 10) ? JPC_SEG_MQ : JPC_SEG_RAW);
+        } else {
+                return JPC_SEG_MQ;
+        }
 }
 
 int JPC_SEGPASSCNT(int passno, int firstpassno, int numpasses, int bypass, int termall)
 {
-	int ret;
-	int passtype;
-
-	if (termall) {
-		ret = 1;
-	} else if (bypass) {
-		if (passno < firstpassno + 10) {
-			ret = 10 - (passno - firstpassno);
-		} else {
-			passtype = JPC_PASSTYPE(passno);
-			switch (passtype) {
-			case JPC_SIGPASS:
-				ret = 2;
-				break;
-			case JPC_REFPASS:
-				ret = 1;
-				break;
-			case JPC_CLNPASS:
-				ret = 1;
-				break;
-			default:
-				ret = -1;
-				assert(0);
-				break;
-			}
-		}
-	} else {
-		ret = JPC_PREC * 3 - 2;
-	}
-	ret = JAS_MIN(ret, numpasses - passno);
-	return ret;
+        int ret;
+        int passtype;
+
+        if (termall) {
+                ret = 1;
+        } else if (bypass) {
+                if (passno < firstpassno + 10) {
+                        ret = 10 - (passno - firstpassno);
+                } else {
+                        passtype = JPC_PASSTYPE(passno);
+                        switch (passtype) {
+                        case JPC_SIGPASS:
+                                ret = 2;
+                                break;
+                        case JPC_REFPASS:
+                                ret = 1;
+                                break;
+                        case JPC_CLNPASS:
+                                ret = 1;
+                                break;
+                        default:
+                                ret = -1;
+                                assert(0);
+                                break;
+                        }
+                }
+        } else {
+                ret = JPC_PREC * 3 - 2;
+        }
+        ret = JAS_MIN(ret, numpasses - passno);
+        return ret;
 }
 
 int JPC_ISTERMINATED(int passno, int firstpassno, int numpasses, int termall,
   int lazy)
 {
-	int ret;
-	int n;
-	if (passno - firstpassno == numpasses - 1) {
-		ret = 1;
-	} else {
-		n = JPC_SEGPASSCNT(passno, firstpassno, numpasses, lazy, termall);
-		ret = (n <= 1) ? 1 : 0;
-	}
-
-	return ret;
+        int ret;
+        int n;
+        if (passno - firstpassno == numpasses - 1) {
+                ret = 1;
+        } else {
+                n = JPC_SEGPASSCNT(passno, firstpassno, numpasses, lazy, termall);
+                ret = (n <= 1) ? 1 : 0;
+        }
+
+        return ret;
 }
 
 /******************************************************************************\
@@ -273,265 +273,265 @@ int JPC_ISTERMINATED(int passno, int firstpassno, int numpasses, int termall,
 
 static void jpc_initmqctxs(void)
 {
-	jpc_initctxs(jpc_mqctxs);
+        jpc_initctxs(jpc_mqctxs);
 }
 
 void jpc_initluts()
 {
-	int i;
-	int orient;
-	int refine;
-	float u;
-	float v;
-	float t;
+        int i;
+        int orient;
+        int refine;
+        float u;
+        float v;
+        float t;
 
 /* XXX - hack */
 jpc_initmqctxs();
 
-	for (orient = 0; orient < 4; ++orient) {
-		for (i = 0; i < 256; ++i) {
-			jpc_zcctxnolut[(orient << 8) | i] = jpc_getzcctxno(i, orient);
-		}
-	}
-
-	for (i = 0; i < 256; ++i) {
-		jpc_spblut[i] = jpc_getspb(i << 4);
-	}
-
-	for (i = 0; i < 256; ++i) {
-		jpc_scctxnolut[i] = jpc_getscctxno(i << 4);
-	}
-
-	for (refine = 0; refine < 2; ++refine) {
-		for (i = 0; i < 2048; ++i) {
-			jpc_magctxnolut[(refine << 11) + i] = jpc_getmagctxno((refine ? JPC_REFINE : 0) | i);
-		}
-	}
-
-	for (i = 0; i < (1 << JPC_NMSEDEC_BITS); ++i) {
-		t = i * jpc_pow2i(-JPC_NMSEDEC_FRACBITS);
-		u = t;
-		v = t - 1.5;
-		jpc_signmsedec[i] = jpc_dbltofix(floor((u * u - v * v) * jpc_pow2i(JPC_NMSEDEC_FRACBITS) + 0.5) / jpc_pow2i(JPC_NMSEDEC_FRACBITS));
+        for (orient = 0; orient < 4; ++orient) {
+                for (i = 0; i < 256; ++i) {
+                        jpc_zcctxnolut[(orient << 8) | i] = jpc_getzcctxno(i, orient);
+                }
+        }
+
+        for (i = 0; i < 256; ++i) {
+                jpc_spblut[i] = jpc_getspb(i << 4);
+        }
+
+        for (i = 0; i < 256; ++i) {
+                jpc_scctxnolut[i] = jpc_getscctxno(i << 4);
+        }
+
+        for (refine = 0; refine < 2; ++refine) {
+                for (i = 0; i < 2048; ++i) {
+                        jpc_magctxnolut[(refine << 11) + i] = jpc_getmagctxno((refine ? JPC_REFINE : 0) | i);
+                }
+        }
+
+        for (i = 0; i < (1 << JPC_NMSEDEC_BITS); ++i) {
+                t = i * jpc_pow2i(-JPC_NMSEDEC_FRACBITS);
+                u = t;
+                v = t - 1.5;
+                jpc_signmsedec[i] = jpc_dbltofix(floor((u * u - v * v) * jpc_pow2i(JPC_NMSEDEC_FRACBITS) + 0.5) / jpc_pow2i(JPC_NMSEDEC_FRACBITS));
 /* XXX - this calc is not correct */
-		jpc_signmsedec0[i] = jpc_dbltofix(floor((u * u) * jpc_pow2i(JPC_NMSEDEC_FRACBITS) + 0.5) / jpc_pow2i(JPC_NMSEDEC_FRACBITS));
-		u = t - 1.0;
-		if (i & (1 << (JPC_NMSEDEC_BITS - 1))) {
-			v = t - 1.5;
-		} else {
-			v = t - 0.5;
-		}
-		jpc_refnmsedec[i] = jpc_dbltofix(floor((u * u - v * v) * 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.0;
+                if (i & (1 << (JPC_NMSEDEC_BITS - 1))) {
+                        v = t - 1.5;
+                } else {
+                        v = t - 0.5;
+                }
+                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));
+        }
 }
 
 jpc_fix_t jpc_getsignmsedec_func(jpc_fix_t x, int bitpos)
 {
-	jpc_fix_t y;
-	assert(!(x & (~JAS_ONES(bitpos + 1))));
-	y = jpc_getsignmsedec_macro(x, bitpos);
-	return y;
+        jpc_fix_t y;
+        assert(!(x & (~JAS_ONES(bitpos + 1))));
+        y = jpc_getsignmsedec_macro(x, bitpos);
+        return y;
 }
 
 int jpc_getzcctxno(int f, int orient)
 {
-	int h;
-	int v;
-	int d;
-	int n;
-	int t;
-	int hv;
-
-	/* Avoid compiler warning. */
-	n = 0;
-
-	h = ((f & JPC_WSIG) != 0) + ((f & JPC_ESIG) != 0);
-	v = ((f & JPC_NSIG) != 0) + ((f & JPC_SSIG) != 0);
-	d = ((f & JPC_NWSIG) != 0) + ((f & JPC_NESIG) != 0) + ((f & JPC_SESIG) != 0) + ((f & JPC_SWSIG) != 0);
-	switch (orient) {
-	case JPC_TSFB_HL:
-		t = h;
-		h = v;
-		v = t;
-	case JPC_TSFB_LL:
-	case JPC_TSFB_LH:
-		if (!h) {
-			if (!v) {
-				if (!d) {
-					n = 0;
-				} else if (d == 1) {
-					n = 1;
-				} else {
-					n = 2;
-				}
-			} else if (v == 1) {
-				n = 3;
-			} else {
-				n = 4;
-			}
-		} else if (h == 1) {
-			if (!v) {
-				if (!d) {
-					n = 5;
-				} else {
-					n = 6;
-				}
-			} else {
-				n = 7;
-			}
-		} else {
-			n = 8;
-		}
-		break;
-	case JPC_TSFB_HH:
-		hv = h + v;
-		if (!d) {
-			if (!hv) {
-				n = 0;
-			} else if (hv == 1) {
-				n = 1;
-			} else {
-				n = 2;
-			}
-		} else if (d == 1) {
-			if (!hv) {
-				n = 3;
-			} else if (hv == 1) {
-				n = 4;
-			} else {
-				n = 5;
-			}
-		} else if (d == 2) {
-			if (!hv) {
-				n = 6;
-			} else {
-				n = 7;
-			}
-		} else {
-			n = 8;
-		}
-		break;
-	}
-	assert(n < JPC_NUMZCCTXS);
-	return JPC_ZCCTXNO + n;
+        int h;
+        int v;
+        int d;
+        int n;
+        int t;
+        int hv;
+
+        /* Avoid compiler warning. */
+        n = 0;
+
+        h = ((f & JPC_WSIG) != 0) + ((f & JPC_ESIG) != 0);
+        v = ((f & JPC_NSIG) != 0) + ((f & JPC_SSIG) != 0);
+        d = ((f & JPC_NWSIG) != 0) + ((f & JPC_NESIG) != 0) + ((f & JPC_SESIG) != 0) + ((f & JPC_SWSIG) != 0);
+        switch (orient) {
+        case JPC_TSFB_HL:
+                t = h;
+                h = v;
+                v = t;
+        case JPC_TSFB_LL:
+        case JPC_TSFB_LH:
+                if (!h) {
+                        if (!v) {
+                                if (!d) {
+                                        n = 0;
+                                } else if (d == 1) {
+                                        n = 1;
+                                } else {
+                                        n = 2;
+                                }
+                        } else if (v == 1) {
+                                n = 3;
+                        } else {
+                                n = 4;
+                        }
+                } else if (h == 1) {
+                        if (!v) {
+                                if (!d) {
+                                        n = 5;
+                                } else {
+                                        n = 6;
+                                }
+                        } else {
+                                n = 7;
+                        }
+                } else {
+                        n = 8;
+                }
+                break;
+        case JPC_TSFB_HH:
+                hv = h + v;
+                if (!d) {
+                        if (!hv) {
+                                n = 0;
+                        } else if (hv == 1) {
+                                n = 1;
+                        } else {
+                                n = 2;
+                        }
+                } else if (d == 1) {
+                        if (!hv) {
+                                n = 3;
+                        } else if (hv == 1) {
+                                n = 4;
+                        } else {
+                                n = 5;
+                        }
+                } else if (d == 2) {
+                        if (!hv) {
+                                n = 6;
+                        } else {
+                                n = 7;
+                        }
+                } else {
+                        n = 8;
+                }
+                break;
+        }
+        assert(n < JPC_NUMZCCTXS);
+        return JPC_ZCCTXNO + n;
 }
 
 int jpc_getspb(int f)
 {
-	int hc;
-	int vc;
-	int n;
-
-	hc = JAS_MIN(((f & (JPC_ESIG | JPC_ESGN)) == JPC_ESIG) + ((f & (JPC_WSIG | JPC_WSGN)) == JPC_WSIG), 1) -
-	  JAS_MIN(((f & (JPC_ESIG | JPC_ESGN)) == (JPC_ESIG | JPC_ESGN)) + ((f & (JPC_WSIG | JPC_WSGN)) == (JPC_WSIG | JPC_WSGN)), 1);
-	vc = JAS_MIN(((f & (JPC_NSIG | JPC_NSGN)) == JPC_NSIG) + ((f & (JPC_SSIG | JPC_SSGN)) == JPC_SSIG), 1) -
-	  JAS_MIN(((f & (JPC_NSIG | JPC_NSGN)) == (JPC_NSIG | JPC_NSGN)) + ((f & (JPC_SSIG | JPC_SSGN)) == (JPC_SSIG | JPC_SSGN)), 1);
-	if (!hc && !vc) {
-		n = 0;
-	} else {
-		n = (!(hc > 0 || (!hc && vc > 0)));
-	}
-	return n;
+        int hc;
+        int vc;
+        int n;
+
+        hc = JAS_MIN(((f & (JPC_ESIG | JPC_ESGN)) == JPC_ESIG) + ((f & (JPC_WSIG | JPC_WSGN)) == JPC_WSIG), 1) -
+          JAS_MIN(((f & (JPC_ESIG | JPC_ESGN)) == (JPC_ESIG | JPC_ESGN)) + ((f & (JPC_WSIG | JPC_WSGN)) == (JPC_WSIG | JPC_WSGN)), 1);
+        vc = JAS_MIN(((f & (JPC_NSIG | JPC_NSGN)) == JPC_NSIG) + ((f & (JPC_SSIG | JPC_SSGN)) == JPC_SSIG), 1) -
+          JAS_MIN(((f & (JPC_NSIG | JPC_NSGN)) == (JPC_NSIG | JPC_NSGN)) + ((f & (JPC_SSIG | JPC_SSGN)) == (JPC_SSIG | JPC_SSGN)), 1);
+        if (!hc && !vc) {
+                n = 0;
+        } else {
+                n = (!(hc > 0 || (!hc && vc > 0)));
+        }
+        return n;
 }
 
 int jpc_getscctxno(int f)
 {
-	int hc;
-	int vc;
-	int n;
-
-	/* Avoid compiler warning. */
-	n = 0;
-
-	hc = JAS_MIN(((f & (JPC_ESIG | JPC_ESGN)) == JPC_ESIG) + ((f & (JPC_WSIG | JPC_WSGN)) == JPC_WSIG),
-	  1) - JAS_MIN(((f & (JPC_ESIG | JPC_ESGN)) == (JPC_ESIG | JPC_ESGN)) +
-	  ((f & (JPC_WSIG | JPC_WSGN)) == (JPC_WSIG | JPC_WSGN)), 1);
-	vc = JAS_MIN(((f & (JPC_NSIG | JPC_NSGN)) == JPC_NSIG) + ((f & (JPC_SSIG | JPC_SSGN)) == JPC_SSIG),
-	  1) - JAS_MIN(((f & (JPC_NSIG | JPC_NSGN)) == (JPC_NSIG | JPC_NSGN)) +
-	  ((f & (JPC_SSIG | JPC_SSGN)) == (JPC_SSIG | JPC_SSGN)), 1);
-	assert(hc >= -1 && hc <= 1 && vc >= -1 && vc <= 1);
-	if (hc < 0) {
-		hc = -hc;
-		vc = -vc;
-	}
-	if (!hc) {
-		if (vc == -1) {
-			n = 1;
-		} else if (!vc) {
-			n = 0;
-		} else {
-			n = 1;
-		}
-	} else if (hc == 1) {
-		if (vc == -1) {
-			n = 2;
-		} else if (!vc) {
-			n = 3;
-		} else {
-			n = 4;
-		}
-	}
-	assert(n < JPC_NUMSCCTXS);
-	return JPC_SCCTXNO + n;
+        int hc;
+        int vc;
+        int n;
+
+        /* Avoid compiler warning. */
+        n = 0;
+
+        hc = JAS_MIN(((f & (JPC_ESIG | JPC_ESGN)) == JPC_ESIG) + ((f & (JPC_WSIG | JPC_WSGN)) == JPC_WSIG),
+          1) - JAS_MIN(((f & (JPC_ESIG | JPC_ESGN)) == (JPC_ESIG | JPC_ESGN)) +
+          ((f & (JPC_WSIG | JPC_WSGN)) == (JPC_WSIG | JPC_WSGN)), 1);
+        vc = JAS_MIN(((f & (JPC_NSIG | JPC_NSGN)) == JPC_NSIG) + ((f & (JPC_SSIG | JPC_SSGN)) == JPC_SSIG),
+          1) - JAS_MIN(((f & (JPC_NSIG | JPC_NSGN)) == (JPC_NSIG | JPC_NSGN)) +
+          ((f & (JPC_SSIG | JPC_SSGN)) == (JPC_SSIG | JPC_SSGN)), 1);
+        assert(hc >= -1 && hc <= 1 && vc >= -1 && vc <= 1);
+        if (hc < 0) {
+                hc = -hc;
+                vc = -vc;
+        }
+        if (!hc) {
+                if (vc == -1) {
+                        n = 1;
+                } else if (!vc) {
+                        n = 0;
+                } else {
+                        n = 1;
+                }
+        } else if (hc == 1) {
+                if (vc == -1) {
+                        n = 2;
+                } else if (!vc) {
+                        n = 3;
+                } else {
+                        n = 4;
+                }
+        }
+        assert(n < JPC_NUMSCCTXS);
+        return JPC_SCCTXNO + n;
 }
 
 int jpc_getmagctxno(int f)
 {
-	int n;
+        int n;
 
-	if (!(f & JPC_REFINE)) {
-		n = (f & (JPC_OTHSIGMSK)) ? 1 : 0;
-	} else {
-		n = 2;
-	}
+        if (!(f & JPC_REFINE)) {
+                n = (f & (JPC_OTHSIGMSK)) ? 1 : 0;
+        } else {
+                n = 2;
+        }
 
-	assert(n < JPC_NUMMAGCTXS);
-	return JPC_MAGCTXNO + n;
+        assert(n < JPC_NUMMAGCTXS);
+        return JPC_MAGCTXNO + n;
 }
 
 void jpc_initctxs(jpc_mqctx_t *ctxs)
 {
-	jpc_mqctx_t *ctx;
-	int i;
-
-	ctx = ctxs;
-	for (i = 0; i < JPC_NUMCTXS; ++i) {
-		ctx->mps = 0;
-		switch (i) {
-		case JPC_UCTXNO:
-			ctx->ind = 46;
-			break;
-		case JPC_ZCCTXNO:
-			ctx->ind = 4;
-			break;
-		case JPC_AGGCTXNO:
-			ctx->ind = 3;
-			break;
-		default:
-			ctx->ind = 0;
-			break;
-		}
-		++ctx;
-	}
+        jpc_mqctx_t *ctx;
+        int i;
+
+        ctx = ctxs;
+        for (i = 0; i < JPC_NUMCTXS; ++i) {
+                ctx->mps = 0;
+                switch (i) {
+                case JPC_UCTXNO:
+                        ctx->ind = 46;
+                        break;
+                case JPC_ZCCTXNO:
+                        ctx->ind = 4;
+                        break;
+                case JPC_AGGCTXNO:
+                        ctx->ind = 3;
+                        break;
+                default:
+                        ctx->ind = 0;
+                        break;
+                }
+                ++ctx;
+        }
 }
 
 /* Calculate the real quantity exp2(n), where x is an integer. */
 double jpc_pow2i(int n)
 {
-	double x;
-	double a;
-
-	x = 1.0;
-	if (n < 0) {
-		a = 0.5;
-		n = -n;
-	} else {
-		a = 2.0;
-	}
-	while (--n >= 0) {
-		x *= a;
-	}
-	return x;
+        double x;
+        double a;
+
+        x = 1.0;
+        if (n < 0) {
+                a = 0.5;
+                n = -n;
+        } else {
+                a = 2.0;
+        }
+        while (--n >= 0) {
+                x *= a;
+        }
+        return x;
 }
diff --git a/converter/other/jpeg2000/libjasper/jpc/jpc_t1cod.h b/converter/other/jpeg2000/libjasper/jpc/jpc_t1cod.h
index 3e061d20..771464ec 100644
--- a/converter/other/jpeg2000/libjasper/jpc/jpc_t1cod.h
+++ b/converter/other/jpeg2000/libjasper/jpc/jpc_t1cod.h
@@ -6,14 +6,14 @@
  */
 
 /* __START_OF_JASPER_LICENSE__
- * 
+ *
  * JasPer Software License
- * 
+ *
  * IMAGE POWER JPEG-2000 PUBLIC LICENSE
  * ************************************
- * 
+ *
  * GRANT:
- * 
+ *
  * Permission is hereby granted, free of charge, to any person (the "User")
  * obtaining a copy of this software and associated documentation, to deal
  * in the JasPer Software without restriction, including without limitation
@@ -21,22 +21,22 @@
  * and/or sell copies of the JasPer Software (in source and binary forms),
  * and to permit persons to whom the JasPer Software is furnished to do so,
  * provided further that the License Conditions below are met.
- * 
+ *
  * License Conditions
  * ******************
- * 
+ *
  * A.  Redistributions of source code must retain the above copyright notice,
  * and this list of conditions, and the following disclaimer.
- * 
+ *
  * B.  Redistributions in binary form must reproduce the above copyright
  * notice, and this list of conditions, and the following disclaimer in
  * the documentation and/or other materials provided with the distribution.
- * 
+ *
  * C.  Neither the name of Image Power, Inc. nor any other contributor
  * (including, but not limited to, the University of British Columbia and
  * Michael David Adams) may be used to endorse or promote products derived
  * from this software without specific prior written permission.
- * 
+ *
  * D.  User agrees that it shall not commence any action against Image Power,
  * Inc., the University of British Columbia, Michael David Adams, or any
  * other contributors (collectively "Licensors") for infringement of any
@@ -56,17 +56,17 @@
  * trade dress, or service mark rights); and (v) divisions, continuations,
  * renewals, reissues and extensions of the foregoing (as and to the extent
  * applicable) now existing, hereafter filed, issued or acquired.
- * 
+ *
  * E.  If User commences an infringement action against any Licensor(s) then
  * such Licensor(s) shall have the right to terminate User's license and
  * all sublicenses that have been granted hereunder by User to other parties.
- * 
+ *
  * F.  This software is for use only in hardware or software products that
  * are compliant with ISO/IEC 15444-1 (i.e., JPEG-2000 Part 1).  No license
  * or right to this Software is granted for products that do not comply
  * with ISO/IEC 15444-1.  The JPEG-2000 Part 1 standard can be purchased
  * from the ISO.
- * 
+ *
  * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS LICENSE.
  * NO USE OF THE JASPER SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER
  * THIS DISCLAIMER.  THE JASPER SOFTWARE IS PROVIDED BY THE LICENSORS AND
@@ -106,7 +106,7 @@
  * TECHNOLOGY OR PRODUCTS FOR HIGH RISK ACTIVITIES AND WILL ENSURE THAT ITS
  * CUSTOMERS AND END-USERS OF ITS PRODUCTS ARE PROVIDED WITH A COPY OF THE
  * NOTICE SPECIFIED IN THIS SECTION.
- * 
+ *
  * __END_OF_JASPER_LICENSE__
  */
 
@@ -132,95 +132,95 @@
 \******************************************************************************/
 
 /* The number of bits used to index into various lookup tables. */
-#define JPC_NMSEDEC_BITS	7
-#define JPC_NMSEDEC_FRACBITS	(JPC_NMSEDEC_BITS - 1)
+#define JPC_NMSEDEC_BITS        7
+#define JPC_NMSEDEC_FRACBITS    (JPC_NMSEDEC_BITS - 1)
 
 /*
  * Segment types.
  */
 
 /* Invalid. */
-#define JPC_SEG_INVALID	0
+#define JPC_SEG_INVALID 0
 /* MQ. */
-#define JPC_SEG_MQ		1
+#define JPC_SEG_MQ              1
 /* Raw. */
-#define JPC_SEG_RAW		2
+#define JPC_SEG_RAW             2
 
 /* The nominal word size. */
-#define	JPC_PREC	32
+#define JPC_PREC        32
 
 /* Tier-1 coding pass types. */
-#define	JPC_SIGPASS	0	/* significance */
-#define	JPC_REFPASS	1	/* refinement */
-#define	JPC_CLNPASS	2	/* cleanup */
+#define JPC_SIGPASS     0       /* significance */
+#define JPC_REFPASS     1       /* refinement */
+#define JPC_CLNPASS     2       /* cleanup */
 
 /*
  * Per-sample state information for tier-1 coding.
  */
 
 /* The northeast neighbour has been found to be significant. */
-#define	JPC_NESIG	0x0001
+#define JPC_NESIG       0x0001
 /* The southeast neighbour has been found to be significant. */
-#define	JPC_SESIG	0x0002
+#define JPC_SESIG       0x0002
 /* The southwest neighbour has been found to be significant. */
-#define	JPC_SWSIG	0x0004
+#define JPC_SWSIG       0x0004
 /* The northwest neighbour has been found to be significant. */
-#define	JPC_NWSIG	0x0008
+#define JPC_NWSIG       0x0008
 /* The north neighbour has been found to be significant. */
-#define	JPC_NSIG	0x0010
+#define JPC_NSIG        0x0010
 /* The east neighbour has been found to be significant. */
-#define	JPC_ESIG	0x0020
+#define JPC_ESIG        0x0020
 /* The south neighbour has been found to be significant. */
-#define	JPC_SSIG	0x0040
+#define JPC_SSIG        0x0040
 /* The west neighbour has been found to be significant. */
-#define	JPC_WSIG	0x0080
+#define JPC_WSIG        0x0080
 /* The significance mask for 8-connected neighbours. */
-#define	JPC_OTHSIGMSK \
-	(JPC_NSIG | JPC_NESIG | JPC_ESIG | JPC_SESIG | JPC_SSIG | JPC_SWSIG | JPC_WSIG | JPC_NWSIG)
+#define JPC_OTHSIGMSK \
+        (JPC_NSIG | JPC_NESIG | JPC_ESIG | JPC_SESIG | JPC_SSIG | JPC_SWSIG | JPC_WSIG | JPC_NWSIG)
 /* The significance mask for 4-connected neighbours. */
-#define	JPC_PRIMSIGMSK	(JPC_NSIG | JPC_ESIG | JPC_SSIG | JPC_WSIG)
+#define JPC_PRIMSIGMSK  (JPC_NSIG | JPC_ESIG | JPC_SSIG | JPC_WSIG)
 
 /* The north neighbour is negative in value. */
-#define	JPC_NSGN	0x0100
+#define JPC_NSGN        0x0100
 /* The east neighbour is negative in value. */
-#define	JPC_ESGN	0x0200
+#define JPC_ESGN        0x0200
 /* The south neighbour is negative in value. */
-#define	JPC_SSGN	0x0400
+#define JPC_SSGN        0x0400
 /* The west neighbour is negative in value. */
-#define	JPC_WSGN	0x0800
+#define JPC_WSGN        0x0800
 /* The sign mask for 4-connected neighbours. */
-#define	JPC_SGNMSK	(JPC_NSGN | JPC_ESGN | JPC_SSGN | JPC_WSGN)
+#define JPC_SGNMSK      (JPC_NSGN | JPC_ESGN | JPC_SSGN | JPC_WSGN)
 
 /* This sample has been found to be significant. */
-#define JPC_SIG		0x1000
+#define JPC_SIG         0x1000
 /* The sample has been refined. */
-#define	JPC_REFINE	0x2000
+#define JPC_REFINE      0x2000
 /* This sample has been processed during the significance pass. */
-#define	JPC_VISIT	0x4000
+#define JPC_VISIT       0x4000
 
 /* The number of aggregation contexts. */
-#define	JPC_NUMAGGCTXS	1
+#define JPC_NUMAGGCTXS  1
 /* The number of zero coding contexts. */
-#define	JPC_NUMZCCTXS	9
+#define JPC_NUMZCCTXS   9
 /* The number of magnitude contexts. */
-#define	JPC_NUMMAGCTXS	3
+#define JPC_NUMMAGCTXS  3
 /* The number of sign coding contexts. */
-#define	JPC_NUMSCCTXS	5
+#define JPC_NUMSCCTXS   5
 /* The number of uniform contexts. */
-#define	JPC_NUMUCTXS	1
+#define JPC_NUMUCTXS    1
 
 /* The context ID for the first aggregation context. */
-#define	JPC_AGGCTXNO	0
+#define JPC_AGGCTXNO    0
 /* The context ID for the first zero coding context. */
-#define	JPC_ZCCTXNO		(JPC_AGGCTXNO + JPC_NUMAGGCTXS)
+#define JPC_ZCCTXNO             (JPC_AGGCTXNO + JPC_NUMAGGCTXS)
 /* The context ID for the first magnitude context. */
-#define	JPC_MAGCTXNO	(JPC_ZCCTXNO + JPC_NUMZCCTXS)
+#define JPC_MAGCTXNO    (JPC_ZCCTXNO + JPC_NUMZCCTXS)
 /* The context ID for the first sign coding context. */
-#define	JPC_SCCTXNO		(JPC_MAGCTXNO + JPC_NUMMAGCTXS)
+#define JPC_SCCTXNO             (JPC_MAGCTXNO + JPC_NUMMAGCTXS)
 /* The context ID for the first uniform context. */
-#define	JPC_UCTXNO		(JPC_SCCTXNO + JPC_NUMSCCTXS)
+#define JPC_UCTXNO              (JPC_SCCTXNO + JPC_NUMSCCTXS)
 /* The total number of contexts. */
-#define	JPC_NUMCTXS		(JPC_UCTXNO + JPC_NUMUCTXS)
+#define JPC_NUMCTXS             (JPC_UCTXNO + JPC_NUMUCTXS)
 
 /******************************************************************************\
 * External data.
@@ -249,76 +249,76 @@ void jpc_initctxs(jpc_mqctx_t *ctxs);
 
 /* Get the zero coding context. */
 int jpc_getzcctxno(int f, int orient);
-#define	JPC_GETZCCTXNO(f, orient) \
-	(jpc_zcctxnolut[((orient) << 8) | ((f) & JPC_OTHSIGMSK)])
+#define JPC_GETZCCTXNO(f, orient) \
+        (jpc_zcctxnolut[((orient) << 8) | ((f) & JPC_OTHSIGMSK)])
 
 /* Get the sign prediction bit. */
 int jpc_getspb(int f);
-#define	JPC_GETSPB(f) \
-	(jpc_spblut[((f) & (JPC_PRIMSIGMSK | JPC_SGNMSK)) >> 4])
+#define JPC_GETSPB(f) \
+        (jpc_spblut[((f) & (JPC_PRIMSIGMSK | JPC_SGNMSK)) >> 4])
 
 /* Get the sign coding context. */
 int jpc_getscctxno(int f);
-#define	JPC_GETSCCTXNO(f) \
-	(jpc_scctxnolut[((f) & (JPC_PRIMSIGMSK | JPC_SGNMSK)) >> 4])
+#define JPC_GETSCCTXNO(f) \
+        (jpc_scctxnolut[((f) & (JPC_PRIMSIGMSK | JPC_SGNMSK)) >> 4])
 
 /* Get the magnitude context. */
 int jpc_getmagctxno(int f);
-#define	JPC_GETMAGCTXNO(f) \
-	(jpc_magctxnolut[((f) & JPC_OTHSIGMSK) | ((((f) & JPC_REFINE) != 0) << 11)])
+#define JPC_GETMAGCTXNO(f) \
+        (jpc_magctxnolut[((f) & JPC_OTHSIGMSK) | ((((f) & JPC_REFINE) != 0) << 11)])
 
 /* Get the normalized MSE reduction for significance passes. */
-#define	JPC_GETSIGNMSEDEC(x, bitpos)	jpc_getsignmsedec_macro(x, bitpos)
+#define JPC_GETSIGNMSEDEC(x, bitpos)    jpc_getsignmsedec_macro(x, bitpos)
 jpc_fix_t jpc_getsignmsedec_func(jpc_fix_t x, int bitpos);
-#define	jpc_getsignmsedec_macro(x, bitpos) \
-	((bitpos > JPC_NMSEDEC_FRACBITS) ? jpc_signmsedec[JPC_ASR(x, bitpos - JPC_NMSEDEC_FRACBITS) & JAS_ONES(JPC_NMSEDEC_BITS)] : \
-	  (jpc_signmsedec0[JPC_ASR(x, bitpos - JPC_NMSEDEC_FRACBITS) & JAS_ONES(JPC_NMSEDEC_BITS)]))
+#define jpc_getsignmsedec_macro(x, bitpos) \
+        ((bitpos > JPC_NMSEDEC_FRACBITS) ? jpc_signmsedec[JPC_ASR(x, bitpos - JPC_NMSEDEC_FRACBITS) & JAS_ONES(JPC_NMSEDEC_BITS)] : \
+          (jpc_signmsedec0[JPC_ASR(x, bitpos - JPC_NMSEDEC_FRACBITS) & JAS_ONES(JPC_NMSEDEC_BITS)]))
 
 /* Get the normalized MSE reduction for refinement passes. */
-#define	JPC_GETREFNMSEDEC(x, bitpos)	jpc_getrefnmsedec_macro(x, bitpos)
+#define JPC_GETREFNMSEDEC(x, bitpos)    jpc_getrefnmsedec_macro(x, bitpos)
 jpc_fix_t jpc_refsignmsedec_func(jpc_fix_t x, int bitpos);
-#define	jpc_getrefnmsedec_macro(x, bitpos) \
-	((bitpos > JPC_NMSEDEC_FRACBITS) ? jpc_refnmsedec[JPC_ASR(x, bitpos - JPC_NMSEDEC_FRACBITS) & JAS_ONES(JPC_NMSEDEC_BITS)] : \
-	  (jpc_refnmsedec0[JPC_ASR(x, bitpos - JPC_NMSEDEC_FRACBITS) & JAS_ONES(JPC_NMSEDEC_BITS)]))
+#define jpc_getrefnmsedec_macro(x, bitpos) \
+        ((bitpos > JPC_NMSEDEC_FRACBITS) ? jpc_refnmsedec[JPC_ASR(x, bitpos - JPC_NMSEDEC_FRACBITS) & JAS_ONES(JPC_NMSEDEC_BITS)] : \
+          (jpc_refnmsedec0[JPC_ASR(x, bitpos - JPC_NMSEDEC_FRACBITS) & JAS_ONES(JPC_NMSEDEC_BITS)]))
 
 /* Arithmetic shift right (with ability to shift left also). */
-#define	JPC_ASR(x, n) \
-	(((n) >= 0) ? ((x) >> (n)) : ((x) << (-(n))))
+#define JPC_ASR(x, n) \
+        (((n) >= 0) ? ((x) >> (n)) : ((x) << (-(n))))
 
 /* Update the per-sample state information. */
-#define	JPC_UPDATEFLAGS4(fp, rowstep, s, vcausalflag) \
+#define JPC_UPDATEFLAGS4(fp, rowstep, s, vcausalflag) \
 { \
-	register jpc_fix_t *np = (fp) - (rowstep); \
-	register jpc_fix_t *sp = (fp) + (rowstep); \
-	if ((vcausalflag)) { \
-		sp[-1] |= JPC_NESIG; \
-		sp[1] |= JPC_NWSIG; \
-		if (s) { \
-			*sp |= JPC_NSIG | JPC_NSGN; \
-			(fp)[-1] |= JPC_ESIG | JPC_ESGN; \
-			(fp)[1] |= JPC_WSIG | JPC_WSGN; \
-		} else { \
-			*sp |= JPC_NSIG; \
-			(fp)[-1] |= JPC_ESIG; \
-			(fp)[1] |= JPC_WSIG; \
-		} \
-	} else { \
-		np[-1] |= JPC_SESIG; \
-		np[1] |= JPC_SWSIG; \
-		sp[-1] |= JPC_NESIG; \
-		sp[1] |= JPC_NWSIG; \
-		if (s) { \
-			*np |= JPC_SSIG | JPC_SSGN; \
-			*sp |= JPC_NSIG | JPC_NSGN; \
-			(fp)[-1] |= JPC_ESIG | JPC_ESGN; \
-			(fp)[1] |= JPC_WSIG | JPC_WSGN; \
-		} else { \
-			*np |= JPC_SSIG; \
-			*sp |= JPC_NSIG; \
-			(fp)[-1] |= JPC_ESIG; \
-			(fp)[1] |= JPC_WSIG; \
-		} \
-	} \
+        register jpc_fix_t *np = (fp) - (rowstep); \
+        register jpc_fix_t *sp = (fp) + (rowstep); \
+        if ((vcausalflag)) { \
+                sp[-1] |= JPC_NESIG; \
+                sp[1] |= JPC_NWSIG; \
+                if (s) { \
+                        *sp |= JPC_NSIG | JPC_NSGN; \
+                        (fp)[-1] |= JPC_ESIG | JPC_ESGN; \
+                        (fp)[1] |= JPC_WSIG | JPC_WSGN; \
+                } else { \
+                        *sp |= JPC_NSIG; \
+                        (fp)[-1] |= JPC_ESIG; \
+                        (fp)[1] |= JPC_WSIG; \
+                } \
+        } else { \
+                np[-1] |= JPC_SESIG; \
+                np[1] |= JPC_SWSIG; \
+                sp[-1] |= JPC_NESIG; \
+                sp[1] |= JPC_NWSIG; \
+                if (s) { \
+                        *np |= JPC_SSIG | JPC_SSGN; \
+                        *sp |= JPC_NSIG | JPC_NSGN; \
+                        (fp)[-1] |= JPC_ESIG | JPC_ESGN; \
+                        (fp)[1] |= JPC_WSIG | JPC_WSGN; \
+                } else { \
+                        *np |= JPC_SSIG; \
+                        *sp |= JPC_NSIG; \
+                        (fp)[-1] |= JPC_ESIG; \
+                        (fp)[1] |= JPC_WSIG; \
+                } \
+        } \
 }
 
 /* Initialize the lookup tables used by the codec. */
diff --git a/converter/other/jpeg2000/libjasper/jpc/jpc_t1dec.c b/converter/other/jpeg2000/libjasper/jpc/jpc_t1dec.c
index b6c5e14f..dd6ae05a 100644
--- a/converter/other/jpeg2000/libjasper/jpc/jpc_t1dec.c
+++ b/converter/other/jpeg2000/libjasper/jpc/jpc_t1dec.c
@@ -6,14 +6,14 @@
  */
 
 /* __START_OF_JASPER_LICENSE__
- * 
+ *
  * JasPer Software License
- * 
+ *
  * IMAGE POWER JPEG-2000 PUBLIC LICENSE
  * ************************************
- * 
+ *
  * GRANT:
- * 
+ *
  * Permission is hereby granted, free of charge, to any person (the "User")
  * obtaining a copy of this software and associated documentation, to deal
  * in the JasPer Software without restriction, including without limitation
@@ -21,22 +21,22 @@
  * and/or sell copies of the JasPer Software (in source and binary forms),
  * and to permit persons to whom the JasPer Software is furnished to do so,
  * provided further that the License Conditions below are met.
- * 
+ *
  * License Conditions
  * ******************
- * 
+ *
  * A.  Redistributions of source code must retain the above copyright notice,
  * and this list of conditions, and the following disclaimer.
- * 
+ *
  * B.  Redistributions in binary form must reproduce the above copyright
  * notice, and this list of conditions, and the following disclaimer in
  * the documentation and/or other materials provided with the distribution.
- * 
+ *
  * C.  Neither the name of Image Power, Inc. nor any other contributor
  * (including, but not limited to, the University of British Columbia and
  * Michael David Adams) may be used to endorse or promote products derived
  * from this software without specific prior written permission.
- * 
+ *
  * D.  User agrees that it shall not commence any action against Image Power,
  * Inc., the University of British Columbia, Michael David Adams, or any
  * other contributors (collectively "Licensors") for infringement of any
@@ -56,17 +56,17 @@
  * trade dress, or service mark rights); and (v) divisions, continuations,
  * renewals, reissues and extensions of the foregoing (as and to the extent
  * applicable) now existing, hereafter filed, issued or acquired.
- * 
+ *
  * E.  If User commences an infringement action against any Licensor(s) then
  * such Licensor(s) shall have the right to terminate User's license and
  * all sublicenses that have been granted hereunder by User to other parties.
- * 
+ *
  * F.  This software is for use only in hardware or software products that
  * are compliant with ISO/IEC 15444-1 (i.e., JPEG-2000 Part 1).  No license
  * or right to this Software is granted for products that do not comply
  * with ISO/IEC 15444-1.  The JPEG-2000 Part 1 standard can be purchased
  * from the ISO.
- * 
+ *
  * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS LICENSE.
  * NO USE OF THE JASPER SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER
  * THIS DISCLAIMER.  THE JASPER SOFTWARE IS PROVIDED BY THE LICENSORS AND
@@ -106,7 +106,7 @@
  * TECHNOLOGY OR PRODUCTS FOR HIGH RISK ACTIVITIES AND WILL ENSURE THAT ITS
  * CUSTOMERS AND END-USERS OF ITS PRODUCTS ARE PROVIDED WITH A COPY OF THE
  * NOTICE SPECIFIED IN THIS SECTION.
- * 
+ *
  * __END_OF_JASPER_LICENSE__
  */
 
@@ -126,7 +126,6 @@
 
 #include "netpbm/nstring.h"
 
-#include "jasper/jas_fix.h"
 #include "jasper/jas_stream.h"
 #include "jasper/jas_math.h"
 
diff --git a/converter/other/jpeg2000/libjasper/jpc/jpc_t1dec.h b/converter/other/jpeg2000/libjasper/jpc/jpc_t1dec.h
index f8b3b342..35ff549a 100644
--- a/converter/other/jpeg2000/libjasper/jpc/jpc_t1dec.h
+++ b/converter/other/jpeg2000/libjasper/jpc/jpc_t1dec.h
@@ -6,14 +6,14 @@
  */
 
 /* __START_OF_JASPER_LICENSE__
- * 
+ *
  * JasPer Software License
- * 
+ *
  * IMAGE POWER JPEG-2000 PUBLIC LICENSE
  * ************************************
- * 
+ *
  * GRANT:
- * 
+ *
  * Permission is hereby granted, free of charge, to any person (the "User")
  * obtaining a copy of this software and associated documentation, to deal
  * in the JasPer Software without restriction, including without limitation
@@ -21,22 +21,22 @@
  * and/or sell copies of the JasPer Software (in source and binary forms),
  * and to permit persons to whom the JasPer Software is furnished to do so,
  * provided further that the License Conditions below are met.
- * 
+ *
  * License Conditions
  * ******************
- * 
+ *
  * A.  Redistributions of source code must retain the above copyright notice,
  * and this list of conditions, and the following disclaimer.
- * 
+ *
  * B.  Redistributions in binary form must reproduce the above copyright
  * notice, and this list of conditions, and the following disclaimer in
  * the documentation and/or other materials provided with the distribution.
- * 
+ *
  * C.  Neither the name of Image Power, Inc. nor any other contributor
  * (including, but not limited to, the University of British Columbia and
  * Michael David Adams) may be used to endorse or promote products derived
  * from this software without specific prior written permission.
- * 
+ *
  * D.  User agrees that it shall not commence any action against Image Power,
  * Inc., the University of British Columbia, Michael David Adams, or any
  * other contributors (collectively "Licensors") for infringement of any
@@ -56,17 +56,17 @@
  * trade dress, or service mark rights); and (v) divisions, continuations,
  * renewals, reissues and extensions of the foregoing (as and to the extent
  * applicable) now existing, hereafter filed, issued or acquired.
- * 
+ *
  * E.  If User commences an infringement action against any Licensor(s) then
  * such Licensor(s) shall have the right to terminate User's license and
  * all sublicenses that have been granted hereunder by User to other parties.
- * 
+ *
  * F.  This software is for use only in hardware or software products that
  * are compliant with ISO/IEC 15444-1 (i.e., JPEG-2000 Part 1).  No license
  * or right to this Software is granted for products that do not comply
  * with ISO/IEC 15444-1.  The JPEG-2000 Part 1 standard can be purchased
  * from the ISO.
- * 
+ *
  * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS LICENSE.
  * NO USE OF THE JASPER SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER
  * THIS DISCLAIMER.  THE JASPER SOFTWARE IS PROVIDED BY THE LICENSORS AND
@@ -106,7 +106,7 @@
  * TECHNOLOGY OR PRODUCTS FOR HIGH RISK ACTIVITIES AND WILL ENSURE THAT ITS
  * CUSTOMERS AND END-USERS OF ITS PRODUCTS ARE PROVIDED WITH A COPY OF THE
  * NOTICE SPECIFIED IN THIS SECTION.
- * 
+ *
  * __END_OF_JASPER_LICENSE__
  */
 
diff --git a/converter/other/jpeg2000/libjasper/jpc/jpc_t1enc.c b/converter/other/jpeg2000/libjasper/jpc/jpc_t1enc.c
index e1af0f61..367dd020 100644
--- a/converter/other/jpeg2000/libjasper/jpc/jpc_t1enc.c
+++ b/converter/other/jpeg2000/libjasper/jpc/jpc_t1enc.c
@@ -6,14 +6,14 @@
  */
 
 /* __START_OF_JASPER_LICENSE__
- * 
+ *
  * JasPer Software License
- * 
+ *
  * IMAGE POWER JPEG-2000 PUBLIC LICENSE
  * ************************************
- * 
+ *
  * GRANT:
- * 
+ *
  * Permission is hereby granted, free of charge, to any person (the "User")
  * obtaining a copy of this software and associated documentation, to deal
  * in the JasPer Software without restriction, including without limitation
@@ -21,22 +21,22 @@
  * and/or sell copies of the JasPer Software (in source and binary forms),
  * and to permit persons to whom the JasPer Software is furnished to do so,
  * provided further that the License Conditions below are met.
- * 
+ *
  * License Conditions
  * ******************
- * 
+ *
  * A.  Redistributions of source code must retain the above copyright notice,
  * and this list of conditions, and the following disclaimer.
- * 
+ *
  * B.  Redistributions in binary form must reproduce the above copyright
  * notice, and this list of conditions, and the following disclaimer in
  * the documentation and/or other materials provided with the distribution.
- * 
+ *
  * C.  Neither the name of Image Power, Inc. nor any other contributor
  * (including, but not limited to, the University of British Columbia and
  * Michael David Adams) may be used to endorse or promote products derived
  * from this software without specific prior written permission.
- * 
+ *
  * D.  User agrees that it shall not commence any action against Image Power,
  * Inc., the University of British Columbia, Michael David Adams, or any
  * other contributors (collectively "Licensors") for infringement of any
@@ -56,17 +56,17 @@
  * trade dress, or service mark rights); and (v) divisions, continuations,
  * renewals, reissues and extensions of the foregoing (as and to the extent
  * applicable) now existing, hereafter filed, issued or acquired.
- * 
+ *
  * E.  If User commences an infringement action against any Licensor(s) then
  * such Licensor(s) shall have the right to terminate User's license and
  * all sublicenses that have been granted hereunder by User to other parties.
- * 
+ *
  * F.  This software is for use only in hardware or software products that
  * are compliant with ISO/IEC 15444-1 (i.e., JPEG-2000 Part 1).  No license
  * or right to this Software is granted for products that do not comply
  * with ISO/IEC 15444-1.  The JPEG-2000 Part 1 standard can be purchased
  * from the ISO.
- * 
+ *
  * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS LICENSE.
  * NO USE OF THE JASPER SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER
  * THIS DISCLAIMER.  THE JASPER SOFTWARE IS PROVIDED BY THE LICENSORS AND
@@ -106,7 +106,7 @@
  * TECHNOLOGY OR PRODUCTS FOR HIGH RISK ACTIVITIES AND WILL ENSURE THAT ITS
  * CUSTOMERS AND END-USERS OF ITS PRODUCTS ARE PROVIDED WITH A COPY OF THE
  * NOTICE SPECIFIED IN THIS SECTION.
- * 
+ *
  * __END_OF_JASPER_LICENSE__
  */
 
@@ -124,7 +124,8 @@
 #include <stdlib.h>
 #include <assert.h>
 
-#include "jasper/jas_fix.h"
+#include "netpbm/nstring.h"
+
 #include "jasper/jas_malloc.h"
 #include "jasper/jas_math.h"
 
@@ -149,74 +150,108 @@ static int jpc_encrawsigpass(jpc_bitstream_t *out, int bitpos, int,
 static int jpc_encrawrefpass(jpc_bitstream_t *out, int bitpos, int,
   jas_matrix_t *flags, 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;
-    int i;
-    int j;
-    int mx;
-    int bmx;
-    int v;
-    jpc_enc_tile_t *tile;
-    uint_fast32_t prcno;
-    jpc_enc_prc_t *prc;
+static void
+encodeBlocksOfPrecinct(jpc_enc_prc_t *   const prcP,
+                       jpc_enc_band_t *  const bandP,
+                       jpc_enc_tcmpt_t * const tcmptP,
+                       jpc_enc_t *       const encoderP,
+                       const char **     const errorP) {
 
-    tile = enc->curtile;
+    if (prcP->cblks) {
+        int bmx;
+        uint_fast32_t cblkno;
 
-    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 (cblkno = 0, bmx = 0; cblkno < prcP->numcblks; ++ cblkno) {
+            jpc_enc_cblk_t * const cblkP = &prcP->cblks[cblkno];
+
+            int mx;
+            uint_fast32_t row;
+
+            for (row = 0, mx = 0;
+                 row < jas_matrix_numrows(cblkP->data);
+                 ++row) {
+
+                uint_fast32_t col;
+
+                for (col = 0; col < jas_matrix_numcols(cblkP->data); ++col) {
+                    int const v = abs(jas_matrix_get(cblkP->data, row, col));
+                    if (v > mx)
+                        mx = v;
                 }
-                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 (i = 0; i < jas_matrix_numrows(cblk->data); ++i) {
-                            for (j = 0; j < jas_matrix_numcols(cblk->data); ++j) {
-                                v = abs(jas_matrix_get(cblk->data, i, j));
-                                if (v > mx) {
-                                    mx = v;
-                                }
-                            }
-                        }
-                        if (mx > bmx) {
-                            bmx = mx;
-                        }
-                        cblk->numbps = JAS_MAX(jpc_firstone(mx) + 1 - JPC_NUMEXTRABITS, 0);
-                    }
+            }
+            if (mx > bmx)
+                bmx = mx;
 
-                    for (cblk = prc->cblks; cblk != endcblks; ++cblk) {
-                        cblk->numimsbs = band->numbps - cblk->numbps;
-                        assert(cblk->numimsbs >= 0);
-                    }
+            cblkP->numbps = MAX(jpc_firstone(mx) + 1 - JPC_NUMEXTRABITS, 0);
+        }
+
+        for (cblkno = 0; cblkno < prcP->numcblks; ++ cblkno)
+            assert(prcP->cblks[cblkno].numbps <= bandP->numbps);
+
+        for (cblkno = 0, *errorP = NULL;
+             cblkno < prcP->numcblks && !*errorP;
+             ++ cblkno) {
 
-                    for (cblk = prc->cblks; cblk != endcblks; ++cblk) {
-                        if (jpc_enc_enccblk(enc, cblk->stream, tcmpt, band, cblk)) {
-                            return -1;
+            jpc_enc_cblk_t * const cblkP = &prcP->cblks[cblkno];
+
+            int rc;
+
+            rc = jpc_enc_enccblk(encoderP,
+                                 cblkP->stream, tcmptP, bandP, cblkP);
+            if (rc != 0)
+                pm_asprintf(errorP, "Encoding failed on code block %u "
+                            "of %u", (unsigned)cblkno,
+                            (unsigned)prcP->numcblks);
+        }
+    } else
+        *errorP = NULL;
+}
+
+
+
+int
+jpc_enc_enccblks(jpc_enc_t * const encoderP) {
+/*----------------------------------------------------------------------------
+  Encode all of the code blocks associated with the current tile.
+-----------------------------------------------------------------------------*/
+    jpc_enc_tile_t * const tileP = encoderP->curtile;
+
+    uint_fast32_t cmptno;
+
+    for (cmptno = 0; cmptno < tileP->numtcmpts; ++cmptno) {
+        jpc_enc_tcmpt_t * const tcmptP = &tileP->tcmpts[cmptno];
+
+        unsigned int lvlno;
+        for (lvlno = 0; lvlno < tcmptP->numrlvls; ++ lvlno) {
+            jpc_enc_rlvl_t * const lvlP = &tcmptP->rlvls[lvlno];
+
+            if (lvlP->bands) {
+                uint_fast32_t bandno;
+
+                for (bandno = 0; bandno < lvlP->numbands; ++bandno) {
+                    jpc_enc_band_t * const bandP = &lvlP->bands[bandno];
+
+                    if (bandP->data) {
+                        uint_fast32_t prcno;
+
+                        for (prcno = 0; prcno < lvlP->numprcs; ++prcno) {
+
+                            const char * error;
+
+                            encodeBlocksOfPrecinct(&bandP->prcs[prcno],
+                                                   bandP,
+                                                   tcmptP,
+                                                   encoderP,
+                                                   &error);
+
+                            if (error) {
+                                pm_strfree(error);
+                                return -1;
+                            }
                         }
                     }
                 }
@@ -226,6 +261,8 @@ int jpc_enc_enccblks(jpc_enc_t *enc)
     return 0;
 }
 
+
+
 static int getthebyte(jas_stream_t *in, long off)
 {
     int c;
@@ -392,7 +429,7 @@ assert(jas_stream_tell(cblk->stream) == jas_stream_getrwcount(cblk->stream));
 #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) == 
+        assert(jas_stream_tell(cblk->stream) ==
                jas_stream_getrwcount(cblk->stream));
 #endif
 
diff --git a/converter/other/jpeg2000/libjasper/jpc/jpc_t1enc.h b/converter/other/jpeg2000/libjasper/jpc/jpc_t1enc.h
index 9ce5ed27..08b4811f 100644
--- a/converter/other/jpeg2000/libjasper/jpc/jpc_t1enc.h
+++ b/converter/other/jpeg2000/libjasper/jpc/jpc_t1enc.h
@@ -6,14 +6,14 @@
  */
 
 /* __START_OF_JASPER_LICENSE__
- * 
+ *
  * JasPer Software License
- * 
+ *
  * IMAGE POWER JPEG-2000 PUBLIC LICENSE
  * ************************************
- * 
+ *
  * GRANT:
- * 
+ *
  * Permission is hereby granted, free of charge, to any person (the "User")
  * obtaining a copy of this software and associated documentation, to deal
  * in the JasPer Software without restriction, including without limitation
@@ -21,22 +21,22 @@
  * and/or sell copies of the JasPer Software (in source and binary forms),
  * and to permit persons to whom the JasPer Software is furnished to do so,
  * provided further that the License Conditions below are met.
- * 
+ *
  * License Conditions
  * ******************
- * 
+ *
  * A.  Redistributions of source code must retain the above copyright notice,
  * and this list of conditions, and the following disclaimer.
- * 
+ *
  * B.  Redistributions in binary form must reproduce the above copyright
  * notice, and this list of conditions, and the following disclaimer in
  * the documentation and/or other materials provided with the distribution.
- * 
+ *
  * C.  Neither the name of Image Power, Inc. nor any other contributor
  * (including, but not limited to, the University of British Columbia and
  * Michael David Adams) may be used to endorse or promote products derived
  * from this software without specific prior written permission.
- * 
+ *
  * D.  User agrees that it shall not commence any action against Image Power,
  * Inc., the University of British Columbia, Michael David Adams, or any
  * other contributors (collectively "Licensors") for infringement of any
@@ -56,17 +56,17 @@
  * trade dress, or service mark rights); and (v) divisions, continuations,
  * renewals, reissues and extensions of the foregoing (as and to the extent
  * applicable) now existing, hereafter filed, issued or acquired.
- * 
+ *
  * E.  If User commences an infringement action against any Licensor(s) then
  * such Licensor(s) shall have the right to terminate User's license and
  * all sublicenses that have been granted hereunder by User to other parties.
- * 
+ *
  * F.  This software is for use only in hardware or software products that
  * are compliant with ISO/IEC 15444-1 (i.e., JPEG-2000 Part 1).  No license
  * or right to this Software is granted for products that do not comply
  * with ISO/IEC 15444-1.  The JPEG-2000 Part 1 standard can be purchased
  * from the ISO.
- * 
+ *
  * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS LICENSE.
  * NO USE OF THE JASPER SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER
  * THIS DISCLAIMER.  THE JASPER SOFTWARE IS PROVIDED BY THE LICENSORS AND
@@ -106,7 +106,7 @@
  * TECHNOLOGY OR PRODUCTS FOR HIGH RISK ACTIVITIES AND WILL ENSURE THAT ITS
  * CUSTOMERS AND END-USERS OF ITS PRODUCTS ARE PROVIDED WITH A COPY OF THE
  * NOTICE SPECIFIED IN THIS SECTION.
- * 
+ *
  * __END_OF_JASPER_LICENSE__
  */
 
diff --git a/converter/other/jpeg2000/libjasper/jpc/jpc_t2cod.c b/converter/other/jpeg2000/libjasper/jpc/jpc_t2cod.c
index a9ca0dc1..9a635285 100644
--- a/converter/other/jpeg2000/libjasper/jpc/jpc_t2cod.c
+++ b/converter/other/jpeg2000/libjasper/jpc/jpc_t2cod.c
@@ -6,14 +6,14 @@
  */
 
 /* __START_OF_JASPER_LICENSE__
- * 
+ *
  * JasPer Software License
- * 
+ *
  * IMAGE POWER JPEG-2000 PUBLIC LICENSE
  * ************************************
- * 
+ *
  * GRANT:
- * 
+ *
  * Permission is hereby granted, free of charge, to any person (the "User")
  * obtaining a copy of this software and associated documentation, to deal
  * in the JasPer Software without restriction, including without limitation
@@ -21,22 +21,22 @@
  * and/or sell copies of the JasPer Software (in source and binary forms),
  * and to permit persons to whom the JasPer Software is furnished to do so,
  * provided further that the License Conditions below are met.
- * 
+ *
  * License Conditions
  * ******************
- * 
+ *
  * A.  Redistributions of source code must retain the above copyright notice,
  * and this list of conditions, and the following disclaimer.
- * 
+ *
  * B.  Redistributions in binary form must reproduce the above copyright
  * notice, and this list of conditions, and the following disclaimer in
  * the documentation and/or other materials provided with the distribution.
- * 
+ *
  * C.  Neither the name of Image Power, Inc. nor any other contributor
  * (including, but not limited to, the University of British Columbia and
  * Michael David Adams) may be used to endorse or promote products derived
  * from this software without specific prior written permission.
- * 
+ *
  * D.  User agrees that it shall not commence any action against Image Power,
  * Inc., the University of British Columbia, Michael David Adams, or any
  * other contributors (collectively "Licensors") for infringement of any
@@ -56,17 +56,17 @@
  * trade dress, or service mark rights); and (v) divisions, continuations,
  * renewals, reissues and extensions of the foregoing (as and to the extent
  * applicable) now existing, hereafter filed, issued or acquired.
- * 
+ *
  * E.  If User commences an infringement action against any Licensor(s) then
  * such Licensor(s) shall have the right to terminate User's license and
  * all sublicenses that have been granted hereunder by User to other parties.
- * 
+ *
  * F.  This software is for use only in hardware or software products that
  * are compliant with ISO/IEC 15444-1 (i.e., JPEG-2000 Part 1).  No license
  * or right to this Software is granted for products that do not comply
  * with ISO/IEC 15444-1.  The JPEG-2000 Part 1 standard can be purchased
  * from the ISO.
- * 
+ *
  * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS LICENSE.
  * NO USE OF THE JASPER SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER
  * THIS DISCLAIMER.  THE JASPER SOFTWARE IS PROVIDED BY THE LICENSORS AND
@@ -106,7 +106,7 @@
  * TECHNOLOGY OR PRODUCTS FOR HIGH RISK ACTIVITIES AND WILL ENSURE THAT ITS
  * CUSTOMERS AND END-USERS OF ITS PRODUCTS ARE PROVIDED WITH A COPY OF THE
  * NOTICE SPECIFIED IN THIS SECTION.
- * 
+ *
  * __END_OF_JASPER_LICENSE__
  */
 
@@ -132,602 +132,602 @@ static int jpc_pi_nextcprl(jpc_pi_t *pi);
 
 int jpc_pi_next(jpc_pi_t *pi)
 {
-	jpc_pchg_t *pchg;
-	int ret;
-
-
-	for (;;) {
-
-		pi->valid = false;
-
-		if (!pi->pchg) {
-			++pi->pchgno;
-			pi->compno = 0;
-			pi->rlvlno = 0;
-			pi->prcno = 0;
-			pi->lyrno = 0;
-			pi->prgvolfirst = true;
-			if (pi->pchgno < jpc_pchglist_numpchgs(pi->pchglist)) {
-				pi->pchg = jpc_pchglist_get(pi->pchglist, pi->pchgno);
-			} else if (pi->pchgno == jpc_pchglist_numpchgs(pi->pchglist)) {
-				pi->pchg = &pi->defaultpchg;
-			} else {
-				return 1;
-			}
-		}
-
-		pchg = pi->pchg;
-		switch (pchg->prgord) {
-		case JPC_COD_LRCPPRG:
-			ret = jpc_pi_nextlrcp(pi);
-			break;
-		case JPC_COD_RLCPPRG:
-			ret = jpc_pi_nextrlcp(pi);
-			break;
-		case JPC_COD_RPCLPRG:
-			ret = jpc_pi_nextrpcl(pi);
-			break;
-		case JPC_COD_PCRLPRG:
-			ret = jpc_pi_nextpcrl(pi);
-			break;
-		case JPC_COD_CPRLPRG:
-			ret = jpc_pi_nextcprl(pi);
-			break;
-		default:
-			ret = -1;
-			break;
-		}
-		if (!ret) {
-			pi->valid = true;
-			++pi->pktno;
-			return 0;
-		}
-		pi->pchg = 0;
-	}
+        jpc_pchg_t *pchg;
+        int ret;
+
+
+        for (;;) {
+
+                pi->valid = false;
+
+                if (!pi->pchg) {
+                        ++pi->pchgno;
+                        pi->compno = 0;
+                        pi->rlvlno = 0;
+                        pi->prcno = 0;
+                        pi->lyrno = 0;
+                        pi->prgvolfirst = true;
+                        if (pi->pchgno < jpc_pchglist_numpchgs(pi->pchglist)) {
+                                pi->pchg = jpc_pchglist_get(pi->pchglist, pi->pchgno);
+                        } else if (pi->pchgno == jpc_pchglist_numpchgs(pi->pchglist)) {
+                                pi->pchg = &pi->defaultpchg;
+                        } else {
+                                return 1;
+                        }
+                }
+
+                pchg = pi->pchg;
+                switch (pchg->prgord) {
+                case JPC_COD_LRCPPRG:
+                        ret = jpc_pi_nextlrcp(pi);
+                        break;
+                case JPC_COD_RLCPPRG:
+                        ret = jpc_pi_nextrlcp(pi);
+                        break;
+                case JPC_COD_RPCLPRG:
+                        ret = jpc_pi_nextrpcl(pi);
+                        break;
+                case JPC_COD_PCRLPRG:
+                        ret = jpc_pi_nextpcrl(pi);
+                        break;
+                case JPC_COD_CPRLPRG:
+                        ret = jpc_pi_nextcprl(pi);
+                        break;
+                default:
+                        ret = -1;
+                        break;
+                }
+                if (!ret) {
+                        pi->valid = true;
+                        ++pi->pktno;
+                        return 0;
+                }
+                pi->pchg = 0;
+        }
 }
 
 static int jpc_pi_nextlrcp(register jpc_pi_t *pi)
 {
-	jpc_pchg_t *pchg;
-	int *prclyrno;
-
-	pchg = pi->pchg;
-	if (!pi->prgvolfirst) {
-		prclyrno = &pi->pirlvl->prclyrnos[pi->prcno];
-		goto skip;
-	} else {
-		pi->prgvolfirst = false;
-	}
-
-	for (pi->lyrno = 0; pi->lyrno < pi->numlyrs && pi->lyrno <
-	  pchg->lyrnoend; ++pi->lyrno) {
-		for (pi->rlvlno = pchg->rlvlnostart; pi->rlvlno < pi->maxrlvls &&
-		  pi->rlvlno < pchg->rlvlnoend; ++pi->rlvlno) {
-			for (pi->compno = pchg->compnostart, pi->picomp =
-			  &pi->picomps[pi->compno]; pi->compno < pi->numcomps
-			  && pi->compno < pchg->compnoend; ++pi->compno,
-			  ++pi->picomp) {
-				if (pi->rlvlno >= pi->picomp->numrlvls) {
-					continue;
-				}
-				pi->pirlvl = &pi->picomp->pirlvls[pi->rlvlno];
-				for (pi->prcno = 0, prclyrno =
-				  pi->pirlvl->prclyrnos; pi->prcno <
-				  pi->pirlvl->numprcs; ++pi->prcno,
-				  ++prclyrno) {
-					if (pi->lyrno >= *prclyrno) {
-						*prclyrno = pi->lyrno;
-						++(*prclyrno);
-						return 0;
-					}
+        jpc_pchg_t *pchg;
+        int *prclyrno;
+
+        pchg = pi->pchg;
+        if (!pi->prgvolfirst) {
+                prclyrno = &pi->pirlvl->prclyrnos[pi->prcno];
+                goto skip;
+        } else {
+                pi->prgvolfirst = false;
+        }
+
+        for (pi->lyrno = 0; pi->lyrno < pi->numlyrs && pi->lyrno <
+          pchg->lyrnoend; ++pi->lyrno) {
+                for (pi->rlvlno = pchg->rlvlnostart; pi->rlvlno < pi->maxrlvls &&
+                  pi->rlvlno < pchg->rlvlnoend; ++pi->rlvlno) {
+                        for (pi->compno = pchg->compnostart, pi->picomp =
+                          &pi->picomps[pi->compno]; pi->compno < pi->numcomps
+                          && pi->compno < pchg->compnoend; ++pi->compno,
+                          ++pi->picomp) {
+                                if (pi->rlvlno >= pi->picomp->numrlvls) {
+                                        continue;
+                                }
+                                pi->pirlvl = &pi->picomp->pirlvls[pi->rlvlno];
+                                for (pi->prcno = 0, prclyrno =
+                                  pi->pirlvl->prclyrnos; pi->prcno <
+                                  pi->pirlvl->numprcs; ++pi->prcno,
+                                  ++prclyrno) {
+                                        if (pi->lyrno >= *prclyrno) {
+                                                *prclyrno = pi->lyrno;
+                                                ++(*prclyrno);
+                                                return 0;
+                                        }
 skip:
-					;
-				}
-			}
-		}
-	}
-	return 1;
+                                        ;
+                                }
+                        }
+                }
+        }
+        return 1;
 }
 
 static int jpc_pi_nextrlcp(register jpc_pi_t *pi)
 {
-	jpc_pchg_t *pchg;
-	int *prclyrno;
-
-	pchg = pi->pchg;
-	if (!pi->prgvolfirst) {
-		assert(pi->prcno < pi->pirlvl->numprcs);
-		prclyrno = &pi->pirlvl->prclyrnos[pi->prcno];
-		goto skip;
-	} else {
-		pi->prgvolfirst = 0;
-	}
-
-	for (pi->rlvlno = pchg->rlvlnostart; pi->rlvlno < pi->maxrlvls &&
-	  pi->rlvlno < pchg->rlvlnoend; ++pi->rlvlno) {
-		for (pi->lyrno = 0; pi->lyrno < pi->numlyrs && pi->lyrno <
-		  pchg->lyrnoend; ++pi->lyrno) {
-			for (pi->compno = pchg->compnostart, pi->picomp =
-			  &pi->picomps[pi->compno]; pi->compno < pi->numcomps &&
-			  pi->compno < pchg->compnoend; ++pi->compno, ++pi->picomp) {
-				if (pi->rlvlno >= pi->picomp->numrlvls) {
-					continue;
-				}
-				pi->pirlvl = &pi->picomp->pirlvls[pi->rlvlno];
-				for (pi->prcno = 0, prclyrno = pi->pirlvl->prclyrnos;
-				  pi->prcno < pi->pirlvl->numprcs; ++pi->prcno, ++prclyrno) {
-					if (pi->lyrno >= *prclyrno) {
-						*prclyrno = pi->lyrno;
-						++(*prclyrno);
-						return 0;
-					}
+        jpc_pchg_t *pchg;
+        int *prclyrno;
+
+        pchg = pi->pchg;
+        if (!pi->prgvolfirst) {
+                assert(pi->prcno < pi->pirlvl->numprcs);
+                prclyrno = &pi->pirlvl->prclyrnos[pi->prcno];
+                goto skip;
+        } else {
+                pi->prgvolfirst = 0;
+        }
+
+        for (pi->rlvlno = pchg->rlvlnostart; pi->rlvlno < pi->maxrlvls &&
+          pi->rlvlno < pchg->rlvlnoend; ++pi->rlvlno) {
+                for (pi->lyrno = 0; pi->lyrno < pi->numlyrs && pi->lyrno <
+                  pchg->lyrnoend; ++pi->lyrno) {
+                        for (pi->compno = pchg->compnostart, pi->picomp =
+                          &pi->picomps[pi->compno]; pi->compno < pi->numcomps &&
+                          pi->compno < pchg->compnoend; ++pi->compno, ++pi->picomp) {
+                                if (pi->rlvlno >= pi->picomp->numrlvls) {
+                                        continue;
+                                }
+                                pi->pirlvl = &pi->picomp->pirlvls[pi->rlvlno];
+                                for (pi->prcno = 0, prclyrno = pi->pirlvl->prclyrnos;
+                                  pi->prcno < pi->pirlvl->numprcs; ++pi->prcno, ++prclyrno) {
+                                        if (pi->lyrno >= *prclyrno) {
+                                                *prclyrno = pi->lyrno;
+                                                ++(*prclyrno);
+                                                return 0;
+                                        }
 skip:
-					;
-				}
-			}
-		}
-	}
-	return 1;
+                                        ;
+                                }
+                        }
+                }
+        }
+        return 1;
 }
 
 static int jpc_pi_nextrpcl(register jpc_pi_t *pi)
 {
-	int rlvlno;
-	jpc_pirlvl_t *pirlvl;
-	jpc_pchg_t *pchg;
-	int prchind;
-	int prcvind;
-	int *prclyrno;
-	int compno;
-	jpc_picomp_t *picomp;
-	int xstep;
-	int ystep;
-	uint_fast32_t r;
-	uint_fast32_t rpx;
-	uint_fast32_t rpy;
-	uint_fast32_t trx0;
-	uint_fast32_t try0;
-
-	pchg = pi->pchg;
-	if (!pi->prgvolfirst) {
-		goto skip;
-	} else {
-		pi->xstep = 0;
-		pi->ystep = 0;
-		for (compno = 0, picomp = pi->picomps; compno < pi->numcomps;
-		  ++compno, ++picomp) {
-			for (rlvlno = 0, pirlvl = picomp->pirlvls; rlvlno <
-			  picomp->numrlvls; ++rlvlno, ++pirlvl) {
-				xstep = picomp->hsamp * (1 << (pirlvl->prcwidthexpn +
-				  picomp->numrlvls - rlvlno - 1));
-				ystep = picomp->vsamp * (1 << (pirlvl->prcheightexpn +
-				  picomp->numrlvls - rlvlno - 1));
-				pi->xstep = (!pi->xstep) ? xstep : JAS_MIN(pi->xstep, xstep);
-				pi->ystep = (!pi->ystep) ? ystep : JAS_MIN(pi->ystep, ystep);
-			}
-		}
-		pi->prgvolfirst = 0;
-	}
-
-	for (pi->rlvlno = pchg->rlvlnostart; pi->rlvlno < pchg->rlvlnoend &&
-	  pi->rlvlno < pi->maxrlvls; ++pi->rlvlno) {
-		for (pi->y = pi->ystart; pi->y < pi->yend; pi->y +=
-		  pi->ystep - (pi->y % pi->ystep)) {
-			for (pi->x = pi->xstart; pi->x < pi->xend; pi->x +=
-			  pi->xstep - (pi->x % pi->xstep)) {
-				for (pi->compno = pchg->compnostart,
-				  pi->picomp = &pi->picomps[pi->compno];
-				  pi->compno < pchg->compnoend && pi->compno <
-				  pi->numcomps; ++pi->compno, ++pi->picomp) {
-					if (pi->rlvlno >= pi->picomp->numrlvls) {
-						continue;
-					}
-					pi->pirlvl = &pi->picomp->pirlvls[pi->rlvlno];
-					if (pi->pirlvl->numprcs == 0) {
-						continue;
-					}
-					r = pi->picomp->numrlvls - 1 - pi->rlvlno;
-					rpx = r + pi->pirlvl->prcwidthexpn;
-					rpy = r + pi->pirlvl->prcheightexpn;
-					trx0 = JPC_CEILDIV(pi->xstart, pi->picomp->hsamp << r);
-					try0 = JPC_CEILDIV(pi->ystart, pi->picomp->vsamp << r);
-					if (((pi->x == pi->xstart && ((trx0 << r) % (1 << rpx)))
-					  || !(pi->x % (1 << rpx))) &&
-					  ((pi->y == pi->ystart && ((try0 << r) % (1 << rpy)))
-					  || !(pi->y % (1 << rpy)))) {
-						prchind = JPC_FLOORDIVPOW2(JPC_CEILDIV(pi->x, pi->picomp->hsamp
-						  << r), pi->pirlvl->prcwidthexpn) - JPC_FLOORDIVPOW2(trx0,
-						  pi->pirlvl->prcwidthexpn);
-						prcvind = JPC_FLOORDIVPOW2(JPC_CEILDIV(pi->y, pi->picomp->vsamp
-						  << r), pi->pirlvl->prcheightexpn) - JPC_FLOORDIVPOW2(try0,
-						  pi->pirlvl->prcheightexpn);
-						pi->prcno = prcvind * pi->pirlvl->numhprcs + prchind;
-
-						assert(pi->prcno < pi->pirlvl->numprcs);
-						for (pi->lyrno = 0; pi->lyrno <
-						  pi->numlyrs && pi->lyrno < pchg->lyrnoend; ++pi->lyrno) {
-							prclyrno = &pi->pirlvl->prclyrnos[pi->prcno];
-							if (pi->lyrno >= *prclyrno) {
-								++(*prclyrno);
-								return 0;
-							}
+        int rlvlno;
+        jpc_pirlvl_t *pirlvl;
+        jpc_pchg_t *pchg;
+        int prchind;
+        int prcvind;
+        int *prclyrno;
+        int compno;
+        jpc_picomp_t *picomp;
+        int xstep;
+        int ystep;
+        uint_fast32_t r;
+        uint_fast32_t rpx;
+        uint_fast32_t rpy;
+        uint_fast32_t trx0;
+        uint_fast32_t try0;
+
+        pchg = pi->pchg;
+        if (!pi->prgvolfirst) {
+                goto skip;
+        } else {
+                pi->xstep = 0;
+                pi->ystep = 0;
+                for (compno = 0, picomp = pi->picomps; compno < pi->numcomps;
+                  ++compno, ++picomp) {
+                        for (rlvlno = 0, pirlvl = picomp->pirlvls; rlvlno <
+                          picomp->numrlvls; ++rlvlno, ++pirlvl) {
+                                xstep = picomp->hsamp * (1 << (pirlvl->prcwidthexpn +
+                                  picomp->numrlvls - rlvlno - 1));
+                                ystep = picomp->vsamp * (1 << (pirlvl->prcheightexpn +
+                                  picomp->numrlvls - rlvlno - 1));
+                                pi->xstep = (!pi->xstep) ? xstep : JAS_MIN(pi->xstep, xstep);
+                                pi->ystep = (!pi->ystep) ? ystep : JAS_MIN(pi->ystep, ystep);
+                        }
+                }
+                pi->prgvolfirst = 0;
+        }
+
+        for (pi->rlvlno = pchg->rlvlnostart; pi->rlvlno < pchg->rlvlnoend &&
+          pi->rlvlno < pi->maxrlvls; ++pi->rlvlno) {
+                for (pi->y = pi->ystart; pi->y < pi->yend; pi->y +=
+                  pi->ystep - (pi->y % pi->ystep)) {
+                        for (pi->x = pi->xstart; pi->x < pi->xend; pi->x +=
+                          pi->xstep - (pi->x % pi->xstep)) {
+                                for (pi->compno = pchg->compnostart,
+                                  pi->picomp = &pi->picomps[pi->compno];
+                                  pi->compno < pchg->compnoend && pi->compno <
+                                  pi->numcomps; ++pi->compno, ++pi->picomp) {
+                                        if (pi->rlvlno >= pi->picomp->numrlvls) {
+                                                continue;
+                                        }
+                                        pi->pirlvl = &pi->picomp->pirlvls[pi->rlvlno];
+                                        if (pi->pirlvl->numprcs == 0) {
+                                                continue;
+                                        }
+                                        r = pi->picomp->numrlvls - 1 - pi->rlvlno;
+                                        rpx = r + pi->pirlvl->prcwidthexpn;
+                                        rpy = r + pi->pirlvl->prcheightexpn;
+                                        trx0 = JPC_CEILDIV(pi->xstart, pi->picomp->hsamp << r);
+                                        try0 = JPC_CEILDIV(pi->ystart, pi->picomp->vsamp << r);
+                                        if (((pi->x == pi->xstart && ((trx0 << r) % (1 << rpx)))
+                                          || !(pi->x % (1 << rpx))) &&
+                                          ((pi->y == pi->ystart && ((try0 << r) % (1 << rpy)))
+                                          || !(pi->y % (1 << rpy)))) {
+                                                prchind = JPC_FLOORDIVPOW2(JPC_CEILDIV(pi->x, pi->picomp->hsamp
+                                                  << r), pi->pirlvl->prcwidthexpn) - JPC_FLOORDIVPOW2(trx0,
+                                                  pi->pirlvl->prcwidthexpn);
+                                                prcvind = JPC_FLOORDIVPOW2(JPC_CEILDIV(pi->y, pi->picomp->vsamp
+                                                  << r), pi->pirlvl->prcheightexpn) - JPC_FLOORDIVPOW2(try0,
+                                                  pi->pirlvl->prcheightexpn);
+                                                pi->prcno = prcvind * pi->pirlvl->numhprcs + prchind;
+
+                                                assert(pi->prcno < pi->pirlvl->numprcs);
+                                                for (pi->lyrno = 0; pi->lyrno <
+                                                  pi->numlyrs && pi->lyrno < pchg->lyrnoend; ++pi->lyrno) {
+                                                        prclyrno = &pi->pirlvl->prclyrnos[pi->prcno];
+                                                        if (pi->lyrno >= *prclyrno) {
+                                                                ++(*prclyrno);
+                                                                return 0;
+                                                        }
 skip:
-							;
-						}
-					}
-				}
-			}
-		}
-	}
-	return 1;
+                                                        ;
+                                                }
+                                        }
+                                }
+                        }
+                }
+        }
+        return 1;
 }
 
 static int jpc_pi_nextpcrl(register jpc_pi_t *pi)
 {
-	int rlvlno;
-	jpc_pirlvl_t *pirlvl;
-	jpc_pchg_t *pchg;
-	int prchind;
-	int prcvind;
-	int *prclyrno;
-	int compno;
-	jpc_picomp_t *picomp;
-	int xstep;
-	int ystep;
-	uint_fast32_t trx0;
-	uint_fast32_t try0;
-	uint_fast32_t r;
-	uint_fast32_t rpx;
-	uint_fast32_t rpy;
-
-	pchg = pi->pchg;
-	if (!pi->prgvolfirst) {
-		goto skip;
-	} else {
-		pi->xstep = 0;
-		pi->ystep = 0;
-		for (compno = 0, picomp = pi->picomps; compno < pi->numcomps;
-		  ++compno, ++picomp) {
-			for (rlvlno = 0, pirlvl = picomp->pirlvls; rlvlno <
-			  picomp->numrlvls; ++rlvlno, ++pirlvl) {
-				xstep = picomp->hsamp * (1 <<
-				  (pirlvl->prcwidthexpn + picomp->numrlvls -
-				  rlvlno - 1));
-				ystep = picomp->vsamp * (1 <<
-				  (pirlvl->prcheightexpn + picomp->numrlvls -
-				  rlvlno - 1));
-				pi->xstep = (!pi->xstep) ? xstep :
-				  JAS_MIN(pi->xstep, xstep);
-				pi->ystep = (!pi->ystep) ? ystep :
-				  JAS_MIN(pi->ystep, ystep);
-			}
-		}
-		pi->prgvolfirst = 0;
-	}
-
-	for (pi->y = pi->ystart; pi->y < pi->yend; pi->y += pi->ystep -
-	  (pi->y % pi->ystep)) {
-		for (pi->x = pi->xstart; pi->x < pi->xend; pi->x += pi->xstep -
-		  (pi->x % pi->xstep)) {
-			for (pi->compno = pchg->compnostart, pi->picomp =
-			  &pi->picomps[pi->compno]; pi->compno < pi->numcomps
-			  && pi->compno < pchg->compnoend; ++pi->compno,
-			  ++pi->picomp) {
-				for (pi->rlvlno = pchg->rlvlnostart,
-				  pi->pirlvl = &pi->picomp->pirlvls[pi->rlvlno];
-				  pi->rlvlno < pi->picomp->numrlvls &&
-				  pi->rlvlno < pchg->rlvlnoend; ++pi->rlvlno,
-				  ++pi->pirlvl) {
-					if (pi->pirlvl->numprcs == 0) {
-						continue;
-					}
-					r = pi->picomp->numrlvls - 1 - pi->rlvlno;
-					trx0 = JPC_CEILDIV(pi->xstart, pi->picomp->hsamp << r);
-					try0 = JPC_CEILDIV(pi->ystart, pi->picomp->vsamp << r);
-					rpx = r + pi->pirlvl->prcwidthexpn;
-					rpy = r + pi->pirlvl->prcheightexpn;
-					if (((pi->x == pi->xstart && ((trx0 << r) % (1 << rpx))) ||
-					  !(pi->x % (pi->picomp->hsamp << rpx))) &&
-					  ((pi->y == pi->ystart && ((try0 << r) % (1 << rpy))) ||
-					  !(pi->y % (pi->picomp->vsamp << rpy)))) {
-						prchind = JPC_FLOORDIVPOW2(JPC_CEILDIV(pi->x, pi->picomp->hsamp
-						  << r), pi->pirlvl->prcwidthexpn) - JPC_FLOORDIVPOW2(trx0,
-						  pi->pirlvl->prcwidthexpn);
-						prcvind = JPC_FLOORDIVPOW2(JPC_CEILDIV(pi->y, pi->picomp->vsamp
-						  << r), pi->pirlvl->prcheightexpn) - JPC_FLOORDIVPOW2(try0,
-						  pi->pirlvl->prcheightexpn);
-						pi->prcno = prcvind * pi->pirlvl->numhprcs + prchind;
-						assert(pi->prcno < pi->pirlvl->numprcs);
-						for (pi->lyrno = 0; pi->lyrno < pi->numlyrs &&
-						  pi->lyrno < pchg->lyrnoend; ++pi->lyrno) {
-							prclyrno = &pi->pirlvl->prclyrnos[pi->prcno];
-							if (pi->lyrno >= *prclyrno) {
-								++(*prclyrno);
-								return 0;
-							}
+        int rlvlno;
+        jpc_pirlvl_t *pirlvl;
+        jpc_pchg_t *pchg;
+        int prchind;
+        int prcvind;
+        int *prclyrno;
+        int compno;
+        jpc_picomp_t *picomp;
+        int xstep;
+        int ystep;
+        uint_fast32_t trx0;
+        uint_fast32_t try0;
+        uint_fast32_t r;
+        uint_fast32_t rpx;
+        uint_fast32_t rpy;
+
+        pchg = pi->pchg;
+        if (!pi->prgvolfirst) {
+                goto skip;
+        } else {
+                pi->xstep = 0;
+                pi->ystep = 0;
+                for (compno = 0, picomp = pi->picomps; compno < pi->numcomps;
+                  ++compno, ++picomp) {
+                        for (rlvlno = 0, pirlvl = picomp->pirlvls; rlvlno <
+                          picomp->numrlvls; ++rlvlno, ++pirlvl) {
+                                xstep = picomp->hsamp * (1 <<
+                                  (pirlvl->prcwidthexpn + picomp->numrlvls -
+                                  rlvlno - 1));
+                                ystep = picomp->vsamp * (1 <<
+                                  (pirlvl->prcheightexpn + picomp->numrlvls -
+                                  rlvlno - 1));
+                                pi->xstep = (!pi->xstep) ? xstep :
+                                  JAS_MIN(pi->xstep, xstep);
+                                pi->ystep = (!pi->ystep) ? ystep :
+                                  JAS_MIN(pi->ystep, ystep);
+                        }
+                }
+                pi->prgvolfirst = 0;
+        }
+
+        for (pi->y = pi->ystart; pi->y < pi->yend; pi->y += pi->ystep -
+          (pi->y % pi->ystep)) {
+                for (pi->x = pi->xstart; pi->x < pi->xend; pi->x += pi->xstep -
+                  (pi->x % pi->xstep)) {
+                        for (pi->compno = pchg->compnostart, pi->picomp =
+                          &pi->picomps[pi->compno]; pi->compno < pi->numcomps
+                          && pi->compno < pchg->compnoend; ++pi->compno,
+                          ++pi->picomp) {
+                                for (pi->rlvlno = pchg->rlvlnostart,
+                                  pi->pirlvl = &pi->picomp->pirlvls[pi->rlvlno];
+                                  pi->rlvlno < pi->picomp->numrlvls &&
+                                  pi->rlvlno < pchg->rlvlnoend; ++pi->rlvlno,
+                                  ++pi->pirlvl) {
+                                        if (pi->pirlvl->numprcs == 0) {
+                                                continue;
+                                        }
+                                        r = pi->picomp->numrlvls - 1 - pi->rlvlno;
+                                        trx0 = JPC_CEILDIV(pi->xstart, pi->picomp->hsamp << r);
+                                        try0 = JPC_CEILDIV(pi->ystart, pi->picomp->vsamp << r);
+                                        rpx = r + pi->pirlvl->prcwidthexpn;
+                                        rpy = r + pi->pirlvl->prcheightexpn;
+                                        if (((pi->x == pi->xstart && ((trx0 << r) % (1 << rpx))) ||
+                                          !(pi->x % (pi->picomp->hsamp << rpx))) &&
+                                          ((pi->y == pi->ystart && ((try0 << r) % (1 << rpy))) ||
+                                          !(pi->y % (pi->picomp->vsamp << rpy)))) {
+                                                prchind = JPC_FLOORDIVPOW2(JPC_CEILDIV(pi->x, pi->picomp->hsamp
+                                                  << r), pi->pirlvl->prcwidthexpn) - JPC_FLOORDIVPOW2(trx0,
+                                                  pi->pirlvl->prcwidthexpn);
+                                                prcvind = JPC_FLOORDIVPOW2(JPC_CEILDIV(pi->y, pi->picomp->vsamp
+                                                  << r), pi->pirlvl->prcheightexpn) - JPC_FLOORDIVPOW2(try0,
+                                                  pi->pirlvl->prcheightexpn);
+                                                pi->prcno = prcvind * pi->pirlvl->numhprcs + prchind;
+                                                assert(pi->prcno < pi->pirlvl->numprcs);
+                                                for (pi->lyrno = 0; pi->lyrno < pi->numlyrs &&
+                                                  pi->lyrno < pchg->lyrnoend; ++pi->lyrno) {
+                                                        prclyrno = &pi->pirlvl->prclyrnos[pi->prcno];
+                                                        if (pi->lyrno >= *prclyrno) {
+                                                                ++(*prclyrno);
+                                                                return 0;
+                                                        }
 skip:
-							;
-						}
-					}
-				}
-			}
-		}
-	}
-	return 1;
+                                                        ;
+                                                }
+                                        }
+                                }
+                        }
+                }
+        }
+        return 1;
 }
 
 static int jpc_pi_nextcprl(register jpc_pi_t *pi)
 {
-	int rlvlno;
-	jpc_pirlvl_t *pirlvl;
-	jpc_pchg_t *pchg;
-	int prchind;
-	int prcvind;
-	int *prclyrno;
-	uint_fast32_t trx0;
-	uint_fast32_t try0;
-	uint_fast32_t r;
-	uint_fast32_t rpx;
-	uint_fast32_t rpy;
-
-	pchg = pi->pchg;
-	if (!pi->prgvolfirst) {
-		goto skip;
-	} else {
-		pi->prgvolfirst = 0;
-	}
-
-	for (pi->compno = pchg->compnostart, pi->picomp =
-	  &pi->picomps[pi->compno]; pi->compno < pchg->compnoend; ++pi->compno,
-	  ++pi->picomp) {
-		pirlvl = pi->picomp->pirlvls;
-		pi->xstep = pi->picomp->hsamp * (1 << (pirlvl->prcwidthexpn +
-		  pi->picomp->numrlvls - 1));
-		pi->ystep = pi->picomp->vsamp * (1 << (pirlvl->prcheightexpn +
-		  pi->picomp->numrlvls - 1));
-		for (rlvlno = 1, pirlvl = &pi->picomp->pirlvls[1];
-		  rlvlno < pi->picomp->numrlvls; ++rlvlno, ++pirlvl) {
-			pi->xstep = JAS_MIN(pi->xstep, pi->picomp->hsamp * (1 <<
-			  (pirlvl->prcwidthexpn + pi->picomp->numrlvls -
-			  rlvlno - 1)));
-			pi->ystep = JAS_MIN(pi->ystep, pi->picomp->vsamp * (1 <<
-			  (pirlvl->prcheightexpn + pi->picomp->numrlvls -
-			  rlvlno - 1)));
-		}
-		for (pi->y = pi->ystart; pi->y < pi->yend;
-		  pi->y += pi->ystep - (pi->y % pi->ystep)) {
-			for (pi->x = pi->xstart; pi->x < pi->xend;
-			  pi->x += pi->xstep - (pi->x % pi->xstep)) {
-				for (pi->rlvlno = pchg->rlvlnostart,
-				  pi->pirlvl = &pi->picomp->pirlvls[pi->rlvlno];
-				  pi->rlvlno < pi->picomp->numrlvls && pi->rlvlno <
-				  pchg->rlvlnoend; ++pi->rlvlno, ++pi->pirlvl) {
-					if (pi->pirlvl->numprcs == 0) {
-						continue;
-					}
-					r = pi->picomp->numrlvls - 1 - pi->rlvlno;
-					trx0 = JPC_CEILDIV(pi->xstart, pi->picomp->hsamp << r);
-					try0 = JPC_CEILDIV(pi->ystart, pi->picomp->vsamp << r);
-					rpx = r + pi->pirlvl->prcwidthexpn;
-					rpy = r + pi->pirlvl->prcheightexpn;
-					if (((pi->x == pi->xstart && ((trx0 << r) % (1 << rpx))) ||
-					  !(pi->x % (pi->picomp->hsamp << rpx))) &&
-					  ((pi->y == pi->ystart && ((try0 << r) % (1 << rpy))) ||
-					  !(pi->y % (pi->picomp->vsamp << rpy)))) {
-						prchind = JPC_FLOORDIVPOW2(JPC_CEILDIV(pi->x, pi->picomp->hsamp
-						  << r), pi->pirlvl->prcwidthexpn) - JPC_FLOORDIVPOW2(trx0,
-						  pi->pirlvl->prcwidthexpn);
-						prcvind = JPC_FLOORDIVPOW2(JPC_CEILDIV(pi->y, pi->picomp->vsamp
-						  << r), pi->pirlvl->prcheightexpn) - JPC_FLOORDIVPOW2(try0,
-						  pi->pirlvl->prcheightexpn);
-						pi->prcno = prcvind *
-						  pi->pirlvl->numhprcs +
-						  prchind;
-						assert(pi->prcno <
-						  pi->pirlvl->numprcs);
-						for (pi->lyrno = 0; pi->lyrno <
-						  pi->numlyrs && pi->lyrno < pchg->lyrnoend; ++pi->lyrno) {
-							prclyrno = &pi->pirlvl->prclyrnos[pi->prcno];
-							if (pi->lyrno >= *prclyrno) {
-								++(*prclyrno);
-								return 0;
-							}
+        int rlvlno;
+        jpc_pirlvl_t *pirlvl;
+        jpc_pchg_t *pchg;
+        int prchind;
+        int prcvind;
+        int *prclyrno;
+        uint_fast32_t trx0;
+        uint_fast32_t try0;
+        uint_fast32_t r;
+        uint_fast32_t rpx;
+        uint_fast32_t rpy;
+
+        pchg = pi->pchg;
+        if (!pi->prgvolfirst) {
+                goto skip;
+        } else {
+                pi->prgvolfirst = 0;
+        }
+
+        for (pi->compno = pchg->compnostart, pi->picomp =
+          &pi->picomps[pi->compno]; pi->compno < pchg->compnoend; ++pi->compno,
+          ++pi->picomp) {
+                pirlvl = pi->picomp->pirlvls;
+                pi->xstep = pi->picomp->hsamp * (1 << (pirlvl->prcwidthexpn +
+                  pi->picomp->numrlvls - 1));
+                pi->ystep = pi->picomp->vsamp * (1 << (pirlvl->prcheightexpn +
+                  pi->picomp->numrlvls - 1));
+                for (rlvlno = 1, pirlvl = &pi->picomp->pirlvls[1];
+                  rlvlno < pi->picomp->numrlvls; ++rlvlno, ++pirlvl) {
+                        pi->xstep = JAS_MIN(pi->xstep, pi->picomp->hsamp * (1 <<
+                          (pirlvl->prcwidthexpn + pi->picomp->numrlvls -
+                          rlvlno - 1)));
+                        pi->ystep = JAS_MIN(pi->ystep, pi->picomp->vsamp * (1 <<
+                          (pirlvl->prcheightexpn + pi->picomp->numrlvls -
+                          rlvlno - 1)));
+                }
+                for (pi->y = pi->ystart; pi->y < pi->yend;
+                  pi->y += pi->ystep - (pi->y % pi->ystep)) {
+                        for (pi->x = pi->xstart; pi->x < pi->xend;
+                          pi->x += pi->xstep - (pi->x % pi->xstep)) {
+                                for (pi->rlvlno = pchg->rlvlnostart,
+                                  pi->pirlvl = &pi->picomp->pirlvls[pi->rlvlno];
+                                  pi->rlvlno < pi->picomp->numrlvls && pi->rlvlno <
+                                  pchg->rlvlnoend; ++pi->rlvlno, ++pi->pirlvl) {
+                                        if (pi->pirlvl->numprcs == 0) {
+                                                continue;
+                                        }
+                                        r = pi->picomp->numrlvls - 1 - pi->rlvlno;
+                                        trx0 = JPC_CEILDIV(pi->xstart, pi->picomp->hsamp << r);
+                                        try0 = JPC_CEILDIV(pi->ystart, pi->picomp->vsamp << r);
+                                        rpx = r + pi->pirlvl->prcwidthexpn;
+                                        rpy = r + pi->pirlvl->prcheightexpn;
+                                        if (((pi->x == pi->xstart && ((trx0 << r) % (1 << rpx))) ||
+                                          !(pi->x % (pi->picomp->hsamp << rpx))) &&
+                                          ((pi->y == pi->ystart && ((try0 << r) % (1 << rpy))) ||
+                                          !(pi->y % (pi->picomp->vsamp << rpy)))) {
+                                                prchind = JPC_FLOORDIVPOW2(JPC_CEILDIV(pi->x, pi->picomp->hsamp
+                                                  << r), pi->pirlvl->prcwidthexpn) - JPC_FLOORDIVPOW2(trx0,
+                                                  pi->pirlvl->prcwidthexpn);
+                                                prcvind = JPC_FLOORDIVPOW2(JPC_CEILDIV(pi->y, pi->picomp->vsamp
+                                                  << r), pi->pirlvl->prcheightexpn) - JPC_FLOORDIVPOW2(try0,
+                                                  pi->pirlvl->prcheightexpn);
+                                                pi->prcno = prcvind *
+                                                  pi->pirlvl->numhprcs +
+                                                  prchind;
+                                                assert(pi->prcno <
+                                                  pi->pirlvl->numprcs);
+                                                for (pi->lyrno = 0; pi->lyrno <
+                                                  pi->numlyrs && pi->lyrno < pchg->lyrnoend; ++pi->lyrno) {
+                                                        prclyrno = &pi->pirlvl->prclyrnos[pi->prcno];
+                                                        if (pi->lyrno >= *prclyrno) {
+                                                                ++(*prclyrno);
+                                                                return 0;
+                                                        }
 skip:
-							;
-						}
-					}
-				}
-			}
-		}
-	}
-	return 1;
+                                                        ;
+                                                }
+                                        }
+                                }
+                        }
+                }
+        }
+        return 1;
 }
 
 static void pirlvl_destroy(jpc_pirlvl_t *rlvl)
 {
-	if (rlvl->prclyrnos) {
-		jas_free(rlvl->prclyrnos);
-	}
+        if (rlvl->prclyrnos) {
+                jas_free(rlvl->prclyrnos);
+        }
 }
 
 static void jpc_picomp_destroy(jpc_picomp_t *picomp)
 {
-	int 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);
-	}
+        int 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;
-	int compno;
-	if (pi->picomps) {
-		for (compno = 0, picomp = pi->picomps; compno < pi->numcomps;
-		  ++compno, ++picomp) {
-			jpc_picomp_destroy(picomp);
-		}
-		jas_free(pi->picomps);
-	}
-	if (pi->pchglist) {
-		jpc_pchglist_destroy(pi->pchglist);
-	}
-	jas_free(pi);
+        jpc_picomp_t *picomp;
+        int compno;
+        if (pi->picomps) {
+                for (compno = 0, picomp = pi->picomps; compno < pi->numcomps;
+                  ++compno, ++picomp) {
+                        jpc_picomp_destroy(picomp);
+                }
+                jas_free(pi->picomps);
+        }
+        if (pi->pchglist) {
+                jpc_pchglist_destroy(pi->pchglist);
+        }
+        jas_free(pi);
 }
 
 jpc_pi_t *jpc_pi_create0(void)
 {
-	jpc_pi_t *pi;
-	if (!(pi = jas_malloc(sizeof(jpc_pi_t)))) {
-		return 0;
-	}
-	pi->picomps = 0;
-	pi->pchgno = 0;
-	if (!(pi->pchglist = jpc_pchglist_create())) {
-		jas_free(pi);
-		return 0;
-	}
-	return pi;
+        jpc_pi_t *pi;
+        if (!(pi = jas_malloc(sizeof(jpc_pi_t)))) {
+                return 0;
+        }
+        pi->picomps = 0;
+        pi->pchgno = 0;
+        if (!(pi->pchglist = jpc_pchglist_create())) {
+                jas_free(pi);
+                return 0;
+        }
+        return pi;
 }
 
 int jpc_pi_addpchg(jpc_pi_t *pi, jpc_pocpchg_t *pchg)
 {
-	return jpc_pchglist_insert(pi->pchglist, -1, pchg);
+        return jpc_pchglist_insert(pi->pchglist, -1, pchg);
 }
 
 jpc_pchglist_t *jpc_pchglist_create(void)
 {
-	jpc_pchglist_t *pchglist;
-	if (!(pchglist = jas_malloc(sizeof(jpc_pchglist_t)))) {
-		return 0;
-	}
-	pchglist->numpchgs = 0;
-	pchglist->maxpchgs = 0;
-	pchglist->pchgs = 0;
-	return pchglist;
+        jpc_pchglist_t *pchglist;
+        if (!(pchglist = jas_malloc(sizeof(jpc_pchglist_t)))) {
+                return 0;
+        }
+        pchglist->numpchgs = 0;
+        pchglist->maxpchgs = 0;
+        pchglist->pchgs = 0;
+        return pchglist;
 }
 
 int jpc_pchglist_insert(jpc_pchglist_t *pchglist, int pchgno, jpc_pchg_t *pchg)
 {
-	int i;
-	int newmaxpchgs;
-	jpc_pchg_t **newpchgs;
-	if (pchgno < 0) {
-		pchgno = pchglist->numpchgs;
-	}
-	if (pchglist->numpchgs >= pchglist->maxpchgs) {
-		newmaxpchgs = pchglist->maxpchgs + 128;
-		if (!(newpchgs = jas_realloc(pchglist->pchgs, newmaxpchgs * sizeof(jpc_pchg_t *)))) {
-			return -1;
-		}
-		pchglist->maxpchgs = newmaxpchgs;
-		pchglist->pchgs = newpchgs;
-	}
-	for (i = pchglist->numpchgs; i > pchgno; --i) {
-		pchglist->pchgs[i] = pchglist->pchgs[i - 1];
-	}
-	pchglist->pchgs[pchgno] = pchg;
-	++pchglist->numpchgs;
-	return 0;
+        int i;
+        int newmaxpchgs;
+        jpc_pchg_t **newpchgs;
+        if (pchgno < 0) {
+                pchgno = pchglist->numpchgs;
+        }
+        if (pchglist->numpchgs >= pchglist->maxpchgs) {
+                newmaxpchgs = pchglist->maxpchgs + 128;
+                if (!(newpchgs = jas_realloc(pchglist->pchgs, newmaxpchgs * sizeof(jpc_pchg_t *)))) {
+                        return -1;
+                }
+                pchglist->maxpchgs = newmaxpchgs;
+                pchglist->pchgs = newpchgs;
+        }
+        for (i = pchglist->numpchgs; i > pchgno; --i) {
+                pchglist->pchgs[i] = pchglist->pchgs[i - 1];
+        }
+        pchglist->pchgs[pchgno] = pchg;
+        ++pchglist->numpchgs;
+        return 0;
 }
 
 jpc_pchg_t *jpc_pchglist_remove(jpc_pchglist_t *pchglist, int pchgno)
 {
-	int i;
-	jpc_pchg_t *pchg;
-	assert(pchgno < pchglist->numpchgs);
-	pchg = pchglist->pchgs[pchgno];
-	for (i = pchgno + 1; i < pchglist->numpchgs; ++i) {
-		pchglist->pchgs[i - 1] = pchglist->pchgs[i];
-	}
-	--pchglist->numpchgs;
-	return pchg;
+        int i;
+        jpc_pchg_t *pchg;
+        assert(pchgno < pchglist->numpchgs);
+        pchg = pchglist->pchgs[pchgno];
+        for (i = pchgno + 1; i < pchglist->numpchgs; ++i) {
+                pchglist->pchgs[i - 1] = pchglist->pchgs[i];
+        }
+        --pchglist->numpchgs;
+        return pchg;
 }
 
 jpc_pchg_t *jpc_pchg_copy(jpc_pchg_t *pchg)
 {
-	jpc_pchg_t *newpchg;
-	if (!(newpchg = jas_malloc(sizeof(jpc_pchg_t)))) {
-		return 0;
-	}
-	*newpchg = *pchg;
-	return newpchg;
+        jpc_pchg_t *newpchg;
+        if (!(newpchg = jas_malloc(sizeof(jpc_pchg_t)))) {
+                return 0;
+        }
+        *newpchg = *pchg;
+        return newpchg;
 }
 
 jpc_pchglist_t *jpc_pchglist_copy(jpc_pchglist_t *pchglist)
 {
-	jpc_pchglist_t *newpchglist;
-	jpc_pchg_t *newpchg;
-	int pchgno;
-	if (!(newpchglist = jpc_pchglist_create())) {
-		return 0;
-	}
-	for (pchgno = 0; pchgno < pchglist->numpchgs; ++pchgno) {
-		if (!(newpchg = jpc_pchg_copy(pchglist->pchgs[pchgno])) ||
-		  jpc_pchglist_insert(newpchglist, -1, newpchg)) {
-			jpc_pchglist_destroy(newpchglist);
-			return 0;
-		}
-	}
-	return newpchglist;
+        jpc_pchglist_t *newpchglist;
+        jpc_pchg_t *newpchg;
+        int pchgno;
+        if (!(newpchglist = jpc_pchglist_create())) {
+                return 0;
+        }
+        for (pchgno = 0; pchgno < pchglist->numpchgs; ++pchgno) {
+                if (!(newpchg = jpc_pchg_copy(pchglist->pchgs[pchgno])) ||
+                  jpc_pchglist_insert(newpchglist, -1, newpchg)) {
+                        jpc_pchglist_destroy(newpchglist);
+                        return 0;
+                }
+        }
+        return newpchglist;
 }
 
 void jpc_pchglist_destroy(jpc_pchglist_t *pchglist)
 {
-	int pchgno;
-	if (pchglist->pchgs) {
-		for (pchgno = 0; pchgno < pchglist->numpchgs; ++pchgno) {
-			jpc_pchg_destroy(pchglist->pchgs[pchgno]);
-		}
-		jas_free(pchglist->pchgs);
-	}
-	jas_free(pchglist);
+        int pchgno;
+        if (pchglist->pchgs) {
+                for (pchgno = 0; pchgno < pchglist->numpchgs; ++pchgno) {
+                        jpc_pchg_destroy(pchglist->pchgs[pchgno]);
+                }
+                jas_free(pchglist->pchgs);
+        }
+        jas_free(pchglist);
 }
 
 void jpc_pchg_destroy(jpc_pchg_t *pchg)
 {
-	jas_free(pchg);
+        jas_free(pchg);
 }
 
 jpc_pchg_t *jpc_pchglist_get(jpc_pchglist_t *pchglist, int pchgno)
 {
-	return pchglist->pchgs[pchgno];
+        return pchglist->pchgs[pchgno];
 }
 
 int jpc_pchglist_numpchgs(jpc_pchglist_t *pchglist)
 {
-	return pchglist->numpchgs;
+        return pchglist->numpchgs;
 }
 
 int jpc_pi_init(jpc_pi_t *pi)
 {
-	int compno;
-	int rlvlno;
-	int prcno;
-	jpc_picomp_t *picomp;
-	jpc_pirlvl_t *pirlvl;
-	int *prclyrno;
-
-	pi->prgvolfirst = 0;
-	pi->valid = 0;
-	pi->pktno = -1;
-	pi->pchgno = -1;
-	pi->pchg = 0;
-
-	for (compno = 0, picomp = pi->picomps; compno < pi->numcomps;
-	  ++compno, ++picomp) {
-		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 compno;
+        int rlvlno;
+        int prcno;
+        jpc_picomp_t *picomp;
+        jpc_pirlvl_t *pirlvl;
+        int *prclyrno;
+
+        pi->prgvolfirst = 0;
+        pi->valid = 0;
+        pi->pktno = -1;
+        pi->pchgno = -1;
+        pi->pchg = 0;
+
+        for (compno = 0, picomp = pi->picomps; compno < pi->numcomps;
+          ++compno, ++picomp) {
+                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;
 }
diff --git a/converter/other/jpeg2000/libjasper/jpc/jpc_t2cod.h b/converter/other/jpeg2000/libjasper/jpc/jpc_t2cod.h
index 82dafcce..8e9b6b15 100644
--- a/converter/other/jpeg2000/libjasper/jpc/jpc_t2cod.h
+++ b/converter/other/jpeg2000/libjasper/jpc/jpc_t2cod.h
@@ -6,14 +6,14 @@
  */
 
 /* __START_OF_JASPER_LICENSE__
- * 
+ *
  * JasPer Software License
- * 
+ *
  * IMAGE POWER JPEG-2000 PUBLIC LICENSE
  * ************************************
- * 
+ *
  * GRANT:
- * 
+ *
  * Permission is hereby granted, free of charge, to any person (the "User")
  * obtaining a copy of this software and associated documentation, to deal
  * in the JasPer Software without restriction, including without limitation
@@ -21,22 +21,22 @@
  * and/or sell copies of the JasPer Software (in source and binary forms),
  * and to permit persons to whom the JasPer Software is furnished to do so,
  * provided further that the License Conditions below are met.
- * 
+ *
  * License Conditions
  * ******************
- * 
+ *
  * A.  Redistributions of source code must retain the above copyright notice,
  * and this list of conditions, and the following disclaimer.
- * 
+ *
  * B.  Redistributions in binary form must reproduce the above copyright
  * notice, and this list of conditions, and the following disclaimer in
  * the documentation and/or other materials provided with the distribution.
- * 
+ *
  * C.  Neither the name of Image Power, Inc. nor any other contributor
  * (including, but not limited to, the University of British Columbia and
  * Michael David Adams) may be used to endorse or promote products derived
  * from this software without specific prior written permission.
- * 
+ *
  * D.  User agrees that it shall not commence any action against Image Power,
  * Inc., the University of British Columbia, Michael David Adams, or any
  * other contributors (collectively "Licensors") for infringement of any
@@ -56,17 +56,17 @@
  * trade dress, or service mark rights); and (v) divisions, continuations,
  * renewals, reissues and extensions of the foregoing (as and to the extent
  * applicable) now existing, hereafter filed, issued or acquired.
- * 
+ *
  * E.  If User commences an infringement action against any Licensor(s) then
  * such Licensor(s) shall have the right to terminate User's license and
  * all sublicenses that have been granted hereunder by User to other parties.
- * 
+ *
  * F.  This software is for use only in hardware or software products that
  * are compliant with ISO/IEC 15444-1 (i.e., JPEG-2000 Part 1).  No license
  * or right to this Software is granted for products that do not comply
  * with ISO/IEC 15444-1.  The JPEG-2000 Part 1 standard can be purchased
  * from the ISO.
- * 
+ *
  * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS LICENSE.
  * NO USE OF THE JASPER SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER
  * THIS DISCLAIMER.  THE JASPER SOFTWARE IS PROVIDED BY THE LICENSORS AND
@@ -106,7 +106,7 @@
  * TECHNOLOGY OR PRODUCTS FOR HIGH RISK ACTIVITIES AND WILL ENSURE THAT ITS
  * CUSTOMERS AND END-USERS OF ITS PRODUCTS ARE PROVIDED WITH A COPY OF THE
  * NOTICE SPECIFIED IN THIS SECTION.
- * 
+ *
  * __END_OF_JASPER_LICENSE__
  */
 
@@ -117,7 +117,7 @@
  */
 
 #ifndef JPC_T2COD_H
-#define	JPC_T2COD_H
+#define JPC_T2COD_H
 
 /******************************************************************************\
 * Includes.
@@ -133,15 +133,15 @@
 
 typedef struct {
 
-	/* The number of progression changes. */
-	int numpchgs;
+        /* The number of progression changes. */
+        int numpchgs;
 
-	/* The maximum number of progression changes that can be accommodated
-	  without growing the progression change array. */
-	int maxpchgs;
+        /* The maximum number of progression changes that can be accommodated
+          without growing the progression change array. */
+        int maxpchgs;
 
-	/* The progression changes. */
-	jpc_pchg_t **pchgs;
+        /* The progression changes. */
+        jpc_pchg_t **pchgs;
 
 } jpc_pchglist_t;
 
@@ -149,21 +149,21 @@ typedef struct {
 
 typedef struct {
 
-	/* The number of precincts. */
-	int numprcs;
+        /* The number of precincts. */
+        int numprcs;
 
-	/* The last layer processed for each precinct. */
-	int *prclyrnos;
+        /* The last layer processed for each precinct. */
+        int *prclyrnos;
 
-	/* The precinct width exponent. */
-	int prcwidthexpn;
+        /* The precinct width exponent. */
+        int prcwidthexpn;
 
-	/* The precinct height exponent. */
-	int prcheightexpn;
+        /* The precinct height exponent. */
+        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 horizontal
+          direction. */
+        int numhprcs;
 
 } jpc_pirlvl_t;
 
@@ -171,17 +171,17 @@ typedef struct {
 
 typedef struct {
 
-	/* The number of resolution levels. */
-	int numrlvls;
+        /* The number of resolution levels. */
+        int numrlvls;
 
-	/* The per-resolution-level information. */
-	jpc_pirlvl_t *pirlvls;
+        /* The per-resolution-level information. */
+        jpc_pirlvl_t *pirlvls;
 
-	/* The horizontal sampling period. */
-	int hsamp;
+        /* The horizontal sampling period. */
+        int hsamp;
 
-	/* The vertical sampling period. */
-	int vsamp;
+        /* The vertical sampling period. */
+        int vsamp;
 
 } jpc_picomp_t;
 
@@ -189,84 +189,84 @@ typedef struct {
 
 typedef struct {
 
-	/* The number of layers. */
-	int numlyrs;
+        /* The number of layers. */
+        int numlyrs;
 
-	/* The number of resolution levels. */
-	int maxrlvls;
+        /* The number of resolution levels. */
+        int maxrlvls;
 
-	/* The number of components. */
-	int numcomps;
+        /* The number of components. */
+        int numcomps;
 
-	/* The per-component information. */
-	jpc_picomp_t *picomps;
+        /* The per-component information. */
+        jpc_picomp_t *picomps;
 
-	/* The current component. */
-	jpc_picomp_t *picomp;
+        /* The current component. */
+        jpc_picomp_t *picomp;
 
-	/* The current resolution level. */
-	jpc_pirlvl_t *pirlvl;
+        /* The current resolution level. */
+        jpc_pirlvl_t *pirlvl;
 
-	/* The number of the current component. */
-	int compno;
+        /* The number of the current component. */
+        int compno;
 
-	/* The number of the current resolution level. */
-	int rlvlno;
+        /* The number of the current resolution level. */
+        int rlvlno;
 
-	/* The number of the current precinct. */
-	int prcno;
+        /* The number of the current precinct. */
+        int prcno;
 
-	/* The number of the current layer. */
-	int lyrno;
+        /* The number of the current layer. */
+        int lyrno;
 
-	/* The x-coordinate of the current position. */
-	int x;
+        /* The x-coordinate of the current position. */
+        int x;
 
-	/* The y-coordinate of the current position. */
-	int y;
+        /* The y-coordinate of the current position. */
+        int y;
 
-	/* The horizontal step size. */
-	int xstep;
+        /* The horizontal step size. */
+        int xstep;
 
-	/* The vertical step size. */
-	int ystep;
+        /* The vertical step size. */
+        int ystep;
 
-	/* The x-coordinate of the top-left corner of the tile on the reference
-	  grid. */
-	int xstart;
+        /* The x-coordinate of the top-left corner of the tile on the reference
+          grid. */
+        int xstart;
 
-	/* The y-coordinate of the top-left corner of the tile on the reference
-	  grid. */
-	int ystart;
+        /* The y-coordinate of the top-left corner of the tile on the reference
+          grid. */
+        int ystart;
 
-	/* The x-coordinate of the bottom-right corner of the tile on the
-	  reference grid (plus one). */
-	int xend;
+        /* The x-coordinate of the bottom-right corner of the tile on the
+          reference grid (plus one). */
+        int xend;
 
-	/* The y-coordinate of the bottom-right corner of the tile on the
-	  reference grid (plus one). */
-	int yend;
+        /* The y-coordinate of the bottom-right corner of the tile on the
+          reference grid (plus one). */
+        int yend;
 
-	/* The current progression change. */
-	jpc_pchg_t *pchg;
+        /* The current progression change. */
+        jpc_pchg_t *pchg;
 
-	/* The progression change list. */
-	jpc_pchglist_t *pchglist;
+        /* The progression change list. */
+        jpc_pchglist_t *pchglist;
 
-	/* The progression to use in the absence of explicit specification. */
-	jpc_pchg_t defaultpchg;
+        /* The progression to use in the absence of explicit specification. */
+        jpc_pchg_t defaultpchg;
 
-	/* The current progression change number. */
-	int pchgno;
+        /* The current progression change number. */
+        int pchgno;
 
-	/* Is this the first time in the current progression volume? */
-	bool prgvolfirst;
+        /* Is this the first time in the current progression volume? */
+        bool prgvolfirst;
 
-	/* Is the current iterator value valid? */
-	bool valid;
+        /* Is the current iterator value valid? */
+        bool valid;
 
-	/* The current packet number. */
-	int pktno;
+        /* The current packet number. */
+        int pktno;
 
 } jpc_pi_t;
 
@@ -293,22 +293,22 @@ int jpc_pi_begin(jpc_pi_t *pi);
 int jpc_pi_next(jpc_pi_t *pi);
 
 /* Get the index of the current packet. */
-#define	jpc_pi_getind(pi)	((pi)->pktno)
+#define jpc_pi_getind(pi)       ((pi)->pktno)
 
 /* Get the component number of the current packet. */
-#define jpc_pi_cmptno(pi)	(assert(pi->valid), (pi)->compno)
+#define jpc_pi_cmptno(pi)       (assert(pi->valid), (pi)->compno)
 
 /* Get the resolution level of the current packet. */
-#define jpc_pi_rlvlno(pi)	(assert(pi->valid), (pi)->rlvlno)
+#define jpc_pi_rlvlno(pi)       (assert(pi->valid), (pi)->rlvlno)
 
 /* Get the layer number of the current packet. */
-#define jpc_pi_lyrno(pi)	(assert(pi->valid), (pi)->lyrno)
+#define jpc_pi_lyrno(pi)        (assert(pi->valid), (pi)->lyrno)
 
 /* Get the precinct number of the current packet. */
-#define jpc_pi_prcno(pi)	(assert(pi->valid), (pi)->prcno)
+#define jpc_pi_prcno(pi)        (assert(pi->valid), (pi)->prcno)
 
 /* Get the progression order for the current packet. */
-#define jpc_pi_prg(pi)	(assert(pi->valid), (pi)->pchg->prgord)
+#define jpc_pi_prg(pi)  (assert(pi->valid), (pi)->pchg->prgord)
 
 /******************************************************************************\
 * Functions/macros for progression change lists.
diff --git a/converter/other/jpeg2000/libjasper/jpc/jpc_t2dec.c b/converter/other/jpeg2000/libjasper/jpc/jpc_t2dec.c
index 9aaaa55c..32e68db7 100644
--- a/converter/other/jpeg2000/libjasper/jpc/jpc_t2dec.c
+++ b/converter/other/jpeg2000/libjasper/jpc/jpc_t2dec.c
@@ -6,14 +6,14 @@
  */
 
 /* __START_OF_JASPER_LICENSE__
- * 
+ *
  * JasPer Software License
- * 
+ *
  * IMAGE POWER JPEG-2000 PUBLIC LICENSE
  * ************************************
- * 
+ *
  * GRANT:
- * 
+ *
  * Permission is hereby granted, free of charge, to any person (the "User")
  * obtaining a copy of this software and associated documentation, to deal
  * in the JasPer Software without restriction, including without limitation
@@ -21,22 +21,22 @@
  * and/or sell copies of the JasPer Software (in source and binary forms),
  * and to permit persons to whom the JasPer Software is furnished to do so,
  * provided further that the License Conditions below are met.
- * 
+ *
  * License Conditions
  * ******************
- * 
+ *
  * A.  Redistributions of source code must retain the above copyright notice,
  * and this list of conditions, and the following disclaimer.
- * 
+ *
  * B.  Redistributions in binary form must reproduce the above copyright
  * notice, and this list of conditions, and the following disclaimer in
  * the documentation and/or other materials provided with the distribution.
- * 
+ *
  * C.  Neither the name of Image Power, Inc. nor any other contributor
  * (including, but not limited to, the University of British Columbia and
  * Michael David Adams) may be used to endorse or promote products derived
  * from this software without specific prior written permission.
- * 
+ *
  * D.  User agrees that it shall not commence any action against Image Power,
  * Inc., the University of British Columbia, Michael David Adams, or any
  * other contributors (collectively "Licensors") for infringement of any
@@ -56,17 +56,17 @@
  * trade dress, or service mark rights); and (v) divisions, continuations,
  * renewals, reissues and extensions of the foregoing (as and to the extent
  * applicable) now existing, hereafter filed, issued or acquired.
- * 
+ *
  * E.  If User commences an infringement action against any Licensor(s) then
  * such Licensor(s) shall have the right to terminate User's license and
  * all sublicenses that have been granted hereunder by User to other parties.
- * 
+ *
  * F.  This software is for use only in hardware or software products that
  * are compliant with ISO/IEC 15444-1 (i.e., JPEG-2000 Part 1).  No license
  * or right to this Software is granted for products that do not comply
  * with ISO/IEC 15444-1.  The JPEG-2000 Part 1 standard can be purchased
  * from the ISO.
- * 
+ *
  * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS LICENSE.
  * NO USE OF THE JASPER SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER
  * THIS DISCLAIMER.  THE JASPER SOFTWARE IS PROVIDED BY THE LICENSORS AND
@@ -106,7 +106,7 @@
  * TECHNOLOGY OR PRODUCTS FOR HIGH RISK ACTIVITIES AND WILL ENSURE THAT ITS
  * CUSTOMERS AND END-USERS OF ITS PRODUCTS ARE PROVIDED WITH A COPY OF THE
  * NOTICE SPECIFIED IN THIS SECTION.
- * 
+ *
  * __END_OF_JASPER_LICENSE__
  */
 
@@ -125,7 +125,6 @@
 #include <assert.h>
 
 #include "jasper/jas_types.h"
-#include "jasper/jas_fix.h"
 #include "jasper/jas_malloc.h"
 #include "jasper/jas_math.h"
 #include "jasper/jas_stream.h"
@@ -155,305 +154,305 @@ static int jpc_dec_decodepkt(jpc_dec_t *dec, jas_stream_t *pkthdrstream, jas_str
 
 static int jpc_getcommacode(jpc_bitstream_t *in)
 {
-	int n;
-	int v;
-
-	n = 0;
-	for (;;) {
-		if ((v = jpc_bitstream_getbit(in)) < 0) {
-			return -1;
-		}
-		if (jpc_bitstream_eof(in)) {
-			return -1;
-		}
-		if (!v) {
-			break;
-		}
-		++n;
-	}
-
-	return n;
+        int n;
+        int v;
+
+        n = 0;
+        for (;;) {
+                if ((v = jpc_bitstream_getbit(in)) < 0) {
+                        return -1;
+                }
+                if (jpc_bitstream_eof(in)) {
+                        return -1;
+                }
+                if (!v) {
+                        break;
+                }
+                ++n;
+        }
+
+        return n;
 }
 
 static int jpc_getnumnewpasses(jpc_bitstream_t *in)
 {
-	int n;
-
-	if ((n = jpc_bitstream_getbit(in)) > 0) {
-		if ((n = jpc_bitstream_getbit(in)) > 0) {
-			if ((n = jpc_bitstream_getbits(in, 2)) == 3) {
-				if ((n = jpc_bitstream_getbits(in, 5)) == 31) {
-					if ((n = jpc_bitstream_getbits(in, 7)) >= 0) {
-						n += 36 + 1;
-					}
-				} else if (n >= 0) {
-					n += 5 + 1;
-				}
-			} else if (n >= 0) {
-				n += 2 + 1;
-			}
-		} else if (!n) {
-			n += 2;
-		}
-	} else if (!n) {
-		++n;
-	}
-
-	return n;
+        int n;
+
+        if ((n = jpc_bitstream_getbit(in)) > 0) {
+                if ((n = jpc_bitstream_getbit(in)) > 0) {
+                        if ((n = jpc_bitstream_getbits(in, 2)) == 3) {
+                                if ((n = jpc_bitstream_getbits(in, 5)) == 31) {
+                                        if ((n = jpc_bitstream_getbits(in, 7)) >= 0) {
+                                                n += 36 + 1;
+                                        }
+                                } else if (n >= 0) {
+                                        n += 5 + 1;
+                                }
+                        } else if (n >= 0) {
+                                n += 2 + 1;
+                        }
+                } else if (!n) {
+                        n += 2;
+                }
+        } else if (!n) {
+                ++n;
+        }
+
+        return n;
 }
 
 static int jpc_dec_decodepkt(jpc_dec_t *dec, jas_stream_t *pkthdrstream, jas_stream_t *in, int compno, int rlvlno,
   int prcno, int lyrno)
 {
-	jpc_bitstream_t *inb;
-	jpc_dec_tcomp_t *tcomp;
-	jpc_dec_rlvl_t *rlvl;
-	jpc_dec_band_t *band;
-	jpc_dec_cblk_t *cblk;
-	int n;
-	int m;
-	int i;
-	jpc_tagtreenode_t *leaf;
-	int included;
-	int ret;
-	int numnewpasses;
-	jpc_dec_seg_t *seg;
-	int len;
-	int present;
-	int savenumnewpasses;
-	int mycounter;
-	jpc_ms_t *ms;
-	jpc_dec_tile_t *tile;
-	jpc_dec_ccp_t *ccp;
-	jpc_dec_cp_t *cp;
-	int bandno;
-	jpc_dec_prc_t *prc;
-	int usedcblkcnt;
-	int cblkno;
-	uint_fast32_t bodylen;
-	bool discard;
-	int passno;
-	int maxpasses;
-	int hdrlen;
-	int hdroffstart;
-	int hdroffend;
-
-	discard = (lyrno >= dec->maxlyrs);
-
-	tile = dec->curtile;
-	cp = tile->cp;
-	ccp = &cp->ccps[compno];
-
-	/*
-	 * Decode the packet header.
-	 */
-
-	/* Decode the SOP marker segment if present. */
-	if (cp->csty & JPC_COD_SOP) {
-		if (jpc_dec_lookahead(in) == JPC_MS_SOP) {
-			if (!(ms = jpc_getms(in, dec->cstate))) {
-				return -1;
-			}
-			if (jpc_ms_gettype(ms) != JPC_MS_SOP) {
-				jpc_ms_destroy(ms);
-				fprintf(stderr, "missing SOP marker segment\n");
-				return -1;
-			}
-			jpc_ms_destroy(ms);
-		}
-	}
+        jpc_bitstream_t *inb;
+        jpc_dec_tcomp_t *tcomp;
+        jpc_dec_rlvl_t *rlvl;
+        jpc_dec_band_t *band;
+        jpc_dec_cblk_t *cblk;
+        int n;
+        int m;
+        int i;
+        jpc_tagtreenode_t *leaf;
+        int included;
+        int ret;
+        int numnewpasses;
+        jpc_dec_seg_t *seg;
+        int len;
+        int present;
+        int savenumnewpasses;
+        int mycounter;
+        jpc_ms_t *ms;
+        jpc_dec_tile_t *tile;
+        jpc_dec_ccp_t *ccp;
+        jpc_dec_cp_t *cp;
+        int bandno;
+        jpc_dec_prc_t *prc;
+        int usedcblkcnt;
+        int cblkno;
+        uint_fast32_t bodylen;
+        bool discard;
+        int passno;
+        int maxpasses;
+        int hdrlen;
+        int hdroffstart;
+        int hdroffend;
+
+        discard = (lyrno >= dec->maxlyrs);
+
+        tile = dec->curtile;
+        cp = tile->cp;
+        ccp = &cp->ccps[compno];
+
+        /*
+         * Decode the packet header.
+         */
+
+        /* Decode the SOP marker segment if present. */
+        if (cp->csty & JPC_COD_SOP) {
+                if (jpc_dec_lookahead(in) == JPC_MS_SOP) {
+                        if (!(ms = jpc_getms(in, dec->cstate))) {
+                                return -1;
+                        }
+                        if (jpc_ms_gettype(ms) != JPC_MS_SOP) {
+                                jpc_ms_destroy(ms);
+                                fprintf(stderr, "missing SOP marker segment\n");
+                                return -1;
+                        }
+                        jpc_ms_destroy(ms);
+                }
+        }
 
 hdroffstart = jas_stream_getrwcount(pkthdrstream);
 
-	if (!(inb = jpc_bitstream_sopen(pkthdrstream, "r"))) {
-		return -1;
-	}
-
-	if ((present = jpc_bitstream_getbit(inb)) < 0) {
-		return 1;
-	}
-	JAS_DBGLOG(10, ("\n", present));
-	JAS_DBGLOG(10, ("present=%d ", present));
-
-	/* Is the packet non-empty? */
-	if (present) {
-		/* The packet is non-empty. */
-		tcomp = &tile->tcomps[compno];
-		rlvl = &tcomp->rlvls[rlvlno];
-		bodylen = 0;
-		for (bandno = 0, band = rlvl->bands; bandno < rlvl->numbands;
-		  ++bandno, ++band) {
-			if (!band->data) {
-				continue;
-			}
-			prc = &band->prcs[prcno];
-			if (!prc->cblks) {
-				continue;
-			}
-			usedcblkcnt = 0;
-			for (cblkno = 0, cblk = prc->cblks; cblkno < prc->numcblks;
-			  ++cblkno, ++cblk) {
-				++usedcblkcnt;
-				if (!cblk->numpasses) {
-					leaf = jpc_tagtree_getleaf(prc->incltagtree, usedcblkcnt - 1);
-					if ((included = jpc_tagtree_decode(prc->incltagtree, leaf, lyrno + 1, inb)) < 0) {
-						return -1;
-					}
-				} else {
-					if ((included = jpc_bitstream_getbit(inb)) < 0) {
-						return -1;
-					}
-				}
-				JAS_DBGLOG(10, ("\n"));
-				JAS_DBGLOG(10, ("included=%d ", included));
-				if (!included) {
-					continue;
-				}
-				if (!cblk->numpasses) {
-					i = 1;
-					leaf = jpc_tagtree_getleaf(prc->numimsbstagtree, usedcblkcnt - 1);
-					for (;;) {
-						if ((ret = jpc_tagtree_decode(prc->numimsbstagtree, leaf, i, inb)) < 0) {
-							return -1;
-						}
-						if (ret) {
-							break;
-						}
-						++i;
-					}
-					cblk->numimsbs = i - 1;
-					cblk->firstpassno = cblk->numimsbs * 3;
-				}
-				if ((numnewpasses = jpc_getnumnewpasses(inb)) < 0) {
-					return -1;
-				}
-				JAS_DBGLOG(10, ("numnewpasses=%d ", numnewpasses));
-				seg = cblk->curseg;
-				savenumnewpasses = numnewpasses;
-				mycounter = 0;
-				if (numnewpasses > 0) {
-					if ((m = jpc_getcommacode(inb)) < 0) {
-						return -1;
-					}
-					cblk->numlenbits += m;
-					JAS_DBGLOG(10, ("increment=%d ", m));
-					while (numnewpasses > 0) {
-						passno = cblk->firstpassno + cblk->numpasses + mycounter;
-	/* XXX - the maxpasses is not set precisely but this doesn't matter... */
-						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())) {
-								return -1;
-							}
-							jpc_seglist_insert(&cblk->segs, cblk->segs.tail, seg);
-							if (!cblk->curseg) {
-								cblk->curseg = seg;
-							}
-							seg->passno = passno;
-							seg->type = JPC_SEGTYPE(seg->passno, cblk->firstpassno, (ccp->cblkctx & JPC_COX_LAZY) != 0);
-							seg->maxpasses = maxpasses;
-						}
-						n = JAS_MIN(numnewpasses, maxpasses);
-						mycounter += n;
-						numnewpasses -= n;
-						if ((len = jpc_bitstream_getbits(inb, cblk->numlenbits + jpc_floorlog2(n))) < 0) {
-							return -1;
-						}
-						JAS_DBGLOG(10, ("len=%d ", len));
-						if (!discard) {
-							seg->lyrno = lyrno;
-							seg->numpasses += n;
-							seg->cnt = len;
-							seg = seg->next;
-						}
-						bodylen += len;
-					}
-				}
-				cblk->numpasses += savenumnewpasses;
-			}
-		}
-
-		jpc_bitstream_inalign(inb, 0, 0);
-
-	} else {
-		if (jpc_bitstream_inalign(inb, 0x7f, 0)) {
-			fprintf(stderr, "alignment failed\n");
-			return -1;
-		}
-	}
-	jpc_bitstream_close(inb);
-
-	hdroffend = jas_stream_getrwcount(pkthdrstream);
-	hdrlen = hdroffend - hdroffstart;
-	if (jas_getdbglevel() >= 5) {
-		fprintf(stderr, "hdrlen=%lu bodylen=%lu \n", (unsigned long) hdrlen,
-		  (unsigned long) bodylen);
-	}
-
-	if (cp->csty & JPC_COD_EPH) {
-		if (jpc_dec_lookahead(pkthdrstream) == JPC_MS_EPH) {
-			if (!(ms = jpc_getms(pkthdrstream, dec->cstate))) {
-				fprintf(stderr, "cannot get (EPH) marker segment\n");
-				return -1;
-			}
-			if (jpc_ms_gettype(ms) != JPC_MS_EPH) {
-				jpc_ms_destroy(ms);
-				fprintf(stderr, "missing EPH marker segment\n");
-				return -1;
-			}
-			jpc_ms_destroy(ms);
-		}
-	}
-
-	/* decode the packet body. */
-
-	if (jas_getdbglevel() >= 1) {
-		fprintf(stderr, "packet body offset=%06ld\n", (long) jas_stream_getrwcount(in));
-	}
-
-	if (!discard) {
-		tcomp = &tile->tcomps[compno];
-		rlvl = &tcomp->rlvls[rlvlno];
-		for (bandno = 0, band = rlvl->bands; bandno < rlvl->numbands;
-		  ++bandno, ++band) {
-			if (!band->data) {
-				continue;
-			}
-			prc = &band->prcs[prcno];
-			if (!prc->cblks) {
-				continue;
-			}
-			for (cblkno = 0, cblk = prc->cblks; cblkno < prc->numcblks;
-			  ++cblkno, ++cblk) {
-				seg = cblk->curseg;
-				while (seg) {
-					if (!seg->stream) {
-						if (!(seg->stream = jas_stream_memopen(0, 0))) {
-							return -1;
-						}
-					}
+        if (!(inb = jpc_bitstream_sopen(pkthdrstream, "r"))) {
+                return -1;
+        }
+
+        if ((present = jpc_bitstream_getbit(inb)) < 0) {
+                return 1;
+        }
+        JAS_DBGLOG(10, ("\n", present));
+        JAS_DBGLOG(10, ("present=%d ", present));
+
+        /* Is the packet non-empty? */
+        if (present) {
+                /* The packet is non-empty. */
+                tcomp = &tile->tcomps[compno];
+                rlvl = &tcomp->rlvls[rlvlno];
+                bodylen = 0;
+                for (bandno = 0, band = rlvl->bands; bandno < rlvl->numbands;
+                  ++bandno, ++band) {
+                        if (!band->data) {
+                                continue;
+                        }
+                        prc = &band->prcs[prcno];
+                        if (!prc->cblks) {
+                                continue;
+                        }
+                        usedcblkcnt = 0;
+                        for (cblkno = 0, cblk = prc->cblks; cblkno < prc->numcblks;
+                          ++cblkno, ++cblk) {
+                                ++usedcblkcnt;
+                                if (!cblk->numpasses) {
+                                        leaf = jpc_tagtree_getleaf(prc->incltagtree, usedcblkcnt - 1);
+                                        if ((included = jpc_tagtree_decode(prc->incltagtree, leaf, lyrno + 1, inb)) < 0) {
+                                                return -1;
+                                        }
+                                } else {
+                                        if ((included = jpc_bitstream_getbit(inb)) < 0) {
+                                                return -1;
+                                        }
+                                }
+                                JAS_DBGLOG(10, ("\n"));
+                                JAS_DBGLOG(10, ("included=%d ", included));
+                                if (!included) {
+                                        continue;
+                                }
+                                if (!cblk->numpasses) {
+                                        i = 1;
+                                        leaf = jpc_tagtree_getleaf(prc->numimsbstagtree, usedcblkcnt - 1);
+                                        for (;;) {
+                                                if ((ret = jpc_tagtree_decode(prc->numimsbstagtree, leaf, i, inb)) < 0) {
+                                                        return -1;
+                                                }
+                                                if (ret) {
+                                                        break;
+                                                }
+                                                ++i;
+                                        }
+                                        cblk->numimsbs = i - 1;
+                                        cblk->firstpassno = cblk->numimsbs * 3;
+                                }
+                                if ((numnewpasses = jpc_getnumnewpasses(inb)) < 0) {
+                                        return -1;
+                                }
+                                JAS_DBGLOG(10, ("numnewpasses=%d ", numnewpasses));
+                                seg = cblk->curseg;
+                                savenumnewpasses = numnewpasses;
+                                mycounter = 0;
+                                if (numnewpasses > 0) {
+                                        if ((m = jpc_getcommacode(inb)) < 0) {
+                                                return -1;
+                                        }
+                                        cblk->numlenbits += m;
+                                        JAS_DBGLOG(10, ("increment=%d ", m));
+                                        while (numnewpasses > 0) {
+                                                passno = cblk->firstpassno + cblk->numpasses + mycounter;
+        /* XXX - the maxpasses is not set precisely but this doesn't matter... */
+                                                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())) {
+                                                                return -1;
+                                                        }
+                                                        jpc_seglist_insert(&cblk->segs, cblk->segs.tail, seg);
+                                                        if (!cblk->curseg) {
+                                                                cblk->curseg = seg;
+                                                        }
+                                                        seg->passno = passno;
+                                                        seg->type = JPC_SEGTYPE(seg->passno, cblk->firstpassno, (ccp->cblkctx & JPC_COX_LAZY) != 0);
+                                                        seg->maxpasses = maxpasses;
+                                                }
+                                                n = JAS_MIN(numnewpasses, maxpasses);
+                                                mycounter += n;
+                                                numnewpasses -= n;
+                                                if ((len = jpc_bitstream_getbits(inb, cblk->numlenbits + jpc_floorlog2(n))) < 0) {
+                                                        return -1;
+                                                }
+                                                JAS_DBGLOG(10, ("len=%d ", len));
+                                                if (!discard) {
+                                                        seg->lyrno = lyrno;
+                                                        seg->numpasses += n;
+                                                        seg->cnt = len;
+                                                        seg = seg->next;
+                                                }
+                                                bodylen += len;
+                                        }
+                                }
+                                cblk->numpasses += savenumnewpasses;
+                        }
+                }
+
+                jpc_bitstream_inalign(inb, 0, 0);
+
+        } else {
+                if (jpc_bitstream_inalign(inb, 0x7f, 0)) {
+                        fprintf(stderr, "alignment failed\n");
+                        return -1;
+                }
+        }
+        jpc_bitstream_close(inb);
+
+        hdroffend = jas_stream_getrwcount(pkthdrstream);
+        hdrlen = hdroffend - hdroffstart;
+        if (jas_getdbglevel() >= 5) {
+                fprintf(stderr, "hdrlen=%lu bodylen=%lu \n", (unsigned long) hdrlen,
+                  (unsigned long) bodylen);
+        }
+
+        if (cp->csty & JPC_COD_EPH) {
+                if (jpc_dec_lookahead(pkthdrstream) == JPC_MS_EPH) {
+                        if (!(ms = jpc_getms(pkthdrstream, dec->cstate))) {
+                                fprintf(stderr, "cannot get (EPH) marker segment\n");
+                                return -1;
+                        }
+                        if (jpc_ms_gettype(ms) != JPC_MS_EPH) {
+                                jpc_ms_destroy(ms);
+                                fprintf(stderr, "missing EPH marker segment\n");
+                                return -1;
+                        }
+                        jpc_ms_destroy(ms);
+                }
+        }
+
+        /* decode the packet body. */
+
+        if (jas_getdbglevel() >= 1) {
+                fprintf(stderr, "packet body offset=%06ld\n", (long) jas_stream_getrwcount(in));
+        }
+
+        if (!discard) {
+                tcomp = &tile->tcomps[compno];
+                rlvl = &tcomp->rlvls[rlvlno];
+                for (bandno = 0, band = rlvl->bands; bandno < rlvl->numbands;
+                  ++bandno, ++band) {
+                        if (!band->data) {
+                                continue;
+                        }
+                        prc = &band->prcs[prcno];
+                        if (!prc->cblks) {
+                                continue;
+                        }
+                        for (cblkno = 0, cblk = prc->cblks; cblkno < prc->numcblks;
+                          ++cblkno, ++cblk) {
+                                seg = cblk->curseg;
+                                while (seg) {
+                                        if (!seg->stream) {
+                                                if (!(seg->stream = jas_stream_memopen(0, 0))) {
+                                                        return -1;
+                                                }
+                                        }
 #if 0
 fprintf(stderr, "lyrno=%02d, compno=%02d, lvlno=%02d, prcno=%02d, bandno=%02d, cblkno=%02d, passno=%02d numpasses=%02d cnt=%d numbps=%d, numimsbs=%d\n", lyrno, compno, rlvlno, prcno, band - rlvl->bands, cblk - prc->cblks, seg->passno, seg->numpasses, seg->cnt, band->numbps, cblk->numimsbs);
 #endif
-					if (seg->cnt > 0) {
-						if (jpc_getdata(in, seg->stream, seg->cnt) < 0) {
-							return -1;
-						}
-						seg->cnt = 0;
-					}
-					if (seg->numpasses >= seg->maxpasses) {
-						cblk->curseg = seg->next;
-					}
-					seg = seg->next;
-				}
-			}
-		}
-	} else {
-		if (jas_stream_gobble(in, bodylen) != bodylen) {
-			return -1;
-		}
-	}
-	return 0;
+                                        if (seg->cnt > 0) {
+                                                if (jpc_getdata(in, seg->stream, seg->cnt) < 0) {
+                                                        return -1;
+                                                }
+                                                seg->cnt = 0;
+                                        }
+                                        if (seg->numpasses >= seg->maxpasses) {
+                                                cblk->curseg = seg->next;
+                                        }
+                                        seg = seg->next;
+                                }
+                        }
+                }
+        } else {
+                if (jas_stream_gobble(in, bodylen) != bodylen) {
+                        return -1;
+                }
+        }
+        return 0;
 }
 
 /********************************************************************************************/
@@ -461,166 +460,166 @@ fprintf(stderr, "lyrno=%02d, compno=%02d, lvlno=%02d, prcno=%02d, bandno=%02d, c
 
 int jpc_dec_decodepkts(jpc_dec_t *dec, jas_stream_t *pkthdrstream, jas_stream_t *in)
 {
-	jpc_dec_tile_t *tile;
-	jpc_pi_t *pi;
-	int ret;
+        jpc_dec_tile_t *tile;
+        jpc_pi_t *pi;
+        int ret;
 
-	tile = dec->curtile;
-	pi = tile->pi;
-	for (;;) {
+        tile = dec->curtile;
+        pi = tile->pi;
+        for (;;) {
 if (!tile->pkthdrstream || jas_stream_peekc(tile->pkthdrstream) == EOF) {
-		switch (jpc_dec_lookahead(in)) {
-		case JPC_MS_EOC:
-		case JPC_MS_SOT:
-			return 0;
-			break;
-		case JPC_MS_SOP:
-		case JPC_MS_EPH:
-		case 0:
-			break;
-		default:
-			return -1;
-			break;
-		}
+                switch (jpc_dec_lookahead(in)) {
+                case JPC_MS_EOC:
+                case JPC_MS_SOT:
+                        return 0;
+                        break;
+                case JPC_MS_SOP:
+                case JPC_MS_EPH:
+                case 0:
+                        break;
+                default:
+                        return -1;
+                        break;
+                }
 }
-		if ((ret = jpc_pi_next(pi))) {
-			return ret;
-		}
+                if ((ret = jpc_pi_next(pi))) {
+                        return ret;
+                }
 if (dec->maxpkts >= 0 && dec->numpkts >= dec->maxpkts) {
-	fprintf(stderr, "warning: stopping decode prematurely as requested\n");
-	return 0;
+        fprintf(stderr, "warning: stopping decode prematurely as requested\n");
+        return 0;
 }
-		if (jas_getdbglevel() >= 1) {
-			fprintf(stderr, "packet offset=%08ld prg=%d cmptno=%02d "
-			  "rlvlno=%02d prcno=%03d lyrno=%02d\n", (long)
-			  jas_stream_getrwcount(in), jpc_pi_prg(pi), jpc_pi_cmptno(pi),
-			  jpc_pi_rlvlno(pi), jpc_pi_prcno(pi), jpc_pi_lyrno(pi));
-		}
-		if (jpc_dec_decodepkt(dec, pkthdrstream, in, jpc_pi_cmptno(pi), jpc_pi_rlvlno(pi),
-		  jpc_pi_prcno(pi), jpc_pi_lyrno(pi))) {
-			return -1;
-		}
+                if (jas_getdbglevel() >= 1) {
+                        fprintf(stderr, "packet offset=%08ld prg=%d cmptno=%02d "
+                          "rlvlno=%02d prcno=%03d lyrno=%02d\n", (long)
+                          jas_stream_getrwcount(in), jpc_pi_prg(pi), jpc_pi_cmptno(pi),
+                          jpc_pi_rlvlno(pi), jpc_pi_prcno(pi), jpc_pi_lyrno(pi));
+                }
+                if (jpc_dec_decodepkt(dec, pkthdrstream, in, jpc_pi_cmptno(pi), jpc_pi_rlvlno(pi),
+                  jpc_pi_prcno(pi), jpc_pi_lyrno(pi))) {
+                        return -1;
+                }
 ++dec->numpkts;
-	}
+        }
 
-	return 0;
+        return 0;
 }
 
 jpc_pi_t *jpc_dec_pi_create(jpc_dec_t *dec, jpc_dec_tile_t *tile)
 {
-	jpc_pi_t *pi;
-	int compno;
-	jpc_picomp_t *picomp;
-	jpc_pirlvl_t *pirlvl;
-	jpc_dec_tcomp_t *tcomp;
-	int rlvlno;
-	jpc_dec_rlvl_t *rlvl;
-	int prcno;
-	int *prclyrno;
-	jpc_dec_cmpt_t *cmpt;
-
-	if (!(pi = jpc_pi_create0())) {
-		return 0;
-	}
-	pi->numcomps = dec->numcomps;
-	if (!(pi->picomps = jas_malloc(pi->numcomps * sizeof(jpc_picomp_t)))) {
-		jpc_pi_destroy(pi);
-		return 0;
-	}
-	for (compno = 0, picomp = pi->picomps; compno < pi->numcomps; ++compno,
-	  ++picomp) {
-		picomp->pirlvls = 0;
-	}
-
-	for (compno = 0, tcomp = tile->tcomps, picomp = pi->picomps;
-	  compno < pi->numcomps; ++compno, ++tcomp, ++picomp) {
-		picomp->numrlvls = tcomp->numrlvls;
-		if (!(picomp->pirlvls = jas_malloc(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) {
+        jpc_pi_t *pi;
+        int compno;
+        jpc_picomp_t *picomp;
+        jpc_pirlvl_t *pirlvl;
+        jpc_dec_tcomp_t *tcomp;
+        int rlvlno;
+        jpc_dec_rlvl_t *rlvl;
+        int prcno;
+        int *prclyrno;
+        jpc_dec_cmpt_t *cmpt;
+
+        if (!(pi = jpc_pi_create0())) {
+                return 0;
+        }
+        pi->numcomps = dec->numcomps;
+        if (!(pi->picomps = jas_malloc(pi->numcomps * sizeof(jpc_picomp_t)))) {
+                jpc_pi_destroy(pi);
+                return 0;
+        }
+        for (compno = 0, picomp = pi->picomps; compno < pi->numcomps; ++compno,
+          ++picomp) {
+                picomp->pirlvls = 0;
+        }
+
+        for (compno = 0, tcomp = tile->tcomps, picomp = pi->picomps;
+          compno < pi->numcomps; ++compno, ++tcomp, ++picomp) {
+                picomp->numrlvls = tcomp->numrlvls;
+                if (!(picomp->pirlvls = jas_malloc(picomp->numrlvls *
+                  sizeof(jpc_pirlvl_t)))) {
+                        jpc_pi_destroy(pi);
+                        return 0;
+                }
+                for (rlvlno = 0, pirlvl = picomp->pirlvls; rlvlno <
+                  picomp->numrlvls; ++rlvlno, ++pirlvl) {
+                        pirlvl->prclyrnos = 0;
+                }
+                for (rlvlno = 0, pirlvl = picomp->pirlvls, rlvl = tcomp->rlvls;
+                  rlvlno < picomp->numrlvls; ++rlvlno, ++pirlvl, ++rlvl) {
 /* XXX sizeof(long) should be sizeof different type */
-			pirlvl->numprcs = rlvl->numprcs;
-			if (!(pirlvl->prclyrnos = jas_malloc(pirlvl->numprcs *
-			  sizeof(long)))) {
-				jpc_pi_destroy(pi);
-				return 0;
-			}
-		}
-	}
-
-	pi->maxrlvls = 0;
-	for (compno = 0, tcomp = tile->tcomps, picomp = pi->picomps, cmpt =
-	  dec->cmpts; compno < pi->numcomps; ++compno, ++tcomp, ++picomp,
-	  ++cmpt) {
-		picomp->hsamp = cmpt->hstep;
-		picomp->vsamp = cmpt->vstep;
-		for (rlvlno = 0, pirlvl = picomp->pirlvls, rlvl = tcomp->rlvls;
-		  rlvlno < picomp->numrlvls; ++rlvlno, ++pirlvl, ++rlvl) {
-			pirlvl->prcwidthexpn = rlvl->prcwidthexpn;
-			pirlvl->prcheightexpn = rlvl->prcheightexpn;
-			for (prcno = 0, prclyrno = pirlvl->prclyrnos;
-			  prcno < pirlvl->numprcs; ++prcno, ++prclyrno) {
-				*prclyrno = 0;
-			}
-			pirlvl->numhprcs = rlvl->numhprcs;
-		}
-		if (pi->maxrlvls < tcomp->numrlvls) {
-			pi->maxrlvls = tcomp->numrlvls;
-		}
-	}
-
-	pi->numlyrs = tile->cp->numlyrs;
-	pi->xstart = tile->xstart;
-	pi->ystart = tile->ystart;
-	pi->xend = tile->xend;
-	pi->yend = tile->yend;
-
-	pi->picomp = 0;
-	pi->pirlvl = 0;
-	pi->x = 0;
-	pi->y = 0;
-	pi->compno = 0;
-	pi->rlvlno = 0;
-	pi->prcno = 0;
-	pi->lyrno = 0;
-	pi->xstep = 0;
-	pi->ystep = 0;
-
-	pi->pchgno = -1;
-
-	pi->defaultpchg.prgord = tile->cp->prgord;
-	pi->defaultpchg.compnostart = 0;
-	pi->defaultpchg.compnoend = pi->numcomps;
-	pi->defaultpchg.rlvlnostart = 0;
-	pi->defaultpchg.rlvlnoend = pi->maxrlvls;
-	pi->defaultpchg.lyrnoend = pi->numlyrs;
-	pi->pchg = 0;
-
-	pi->valid = 0;
-
-	return pi;
+                        pirlvl->numprcs = rlvl->numprcs;
+                        if (!(pirlvl->prclyrnos = jas_malloc(pirlvl->numprcs *
+                          sizeof(long)))) {
+                                jpc_pi_destroy(pi);
+                                return 0;
+                        }
+                }
+        }
+
+        pi->maxrlvls = 0;
+        for (compno = 0, tcomp = tile->tcomps, picomp = pi->picomps, cmpt =
+          dec->cmpts; compno < pi->numcomps; ++compno, ++tcomp, ++picomp,
+          ++cmpt) {
+                picomp->hsamp = cmpt->hstep;
+                picomp->vsamp = cmpt->vstep;
+                for (rlvlno = 0, pirlvl = picomp->pirlvls, rlvl = tcomp->rlvls;
+                  rlvlno < picomp->numrlvls; ++rlvlno, ++pirlvl, ++rlvl) {
+                        pirlvl->prcwidthexpn = rlvl->prcwidthexpn;
+                        pirlvl->prcheightexpn = rlvl->prcheightexpn;
+                        for (prcno = 0, prclyrno = pirlvl->prclyrnos;
+                          prcno < pirlvl->numprcs; ++prcno, ++prclyrno) {
+                                *prclyrno = 0;
+                        }
+                        pirlvl->numhprcs = rlvl->numhprcs;
+                }
+                if (pi->maxrlvls < tcomp->numrlvls) {
+                        pi->maxrlvls = tcomp->numrlvls;
+                }
+        }
+
+        pi->numlyrs = tile->cp->numlyrs;
+        pi->xstart = tile->xstart;
+        pi->ystart = tile->ystart;
+        pi->xend = tile->xend;
+        pi->yend = tile->yend;
+
+        pi->picomp = 0;
+        pi->pirlvl = 0;
+        pi->x = 0;
+        pi->y = 0;
+        pi->compno = 0;
+        pi->rlvlno = 0;
+        pi->prcno = 0;
+        pi->lyrno = 0;
+        pi->xstep = 0;
+        pi->ystep = 0;
+
+        pi->pchgno = -1;
+
+        pi->defaultpchg.prgord = tile->cp->prgord;
+        pi->defaultpchg.compnostart = 0;
+        pi->defaultpchg.compnoend = pi->numcomps;
+        pi->defaultpchg.rlvlnostart = 0;
+        pi->defaultpchg.rlvlnoend = pi->maxrlvls;
+        pi->defaultpchg.lyrnoend = pi->numlyrs;
+        pi->pchg = 0;
+
+        pi->valid = 0;
+
+        return pi;
 }
 
 long jpc_dec_lookahead(jas_stream_t *in)
 {
-	uint_fast16_t x;
-	if (jpc_getuint16(in, &x)) {
-		return -1;
-	}
-	if (jas_stream_ungetc(in, x & 0xff) == EOF ||
-	  jas_stream_ungetc(in, x >> 8) == EOF) {
-		return -1;
-	}
-	if (x >= JPC_MS_INMIN && x <= JPC_MS_INMAX) {
-		return x;
-	}
-	return 0;
+        uint_fast16_t x;
+        if (jpc_getuint16(in, &x)) {
+                return -1;
+        }
+        if (jas_stream_ungetc(in, x & 0xff) == EOF ||
+          jas_stream_ungetc(in, x >> 8) == EOF) {
+                return -1;
+        }
+        if (x >= JPC_MS_INMIN && x <= JPC_MS_INMAX) {
+                return x;
+        }
+        return 0;
 }
diff --git a/converter/other/jpeg2000/libjasper/jpc/jpc_t2dec.h b/converter/other/jpeg2000/libjasper/jpc/jpc_t2dec.h
index 923d7c1a..8e94232a 100644
--- a/converter/other/jpeg2000/libjasper/jpc/jpc_t2dec.h
+++ b/converter/other/jpeg2000/libjasper/jpc/jpc_t2dec.h
@@ -6,14 +6,14 @@
  */
 
 /* __START_OF_JASPER_LICENSE__
- * 
+ *
  * JasPer Software License
- * 
+ *
  * IMAGE POWER JPEG-2000 PUBLIC LICENSE
  * ************************************
- * 
+ *
  * GRANT:
- * 
+ *
  * Permission is hereby granted, free of charge, to any person (the "User")
  * obtaining a copy of this software and associated documentation, to deal
  * in the JasPer Software without restriction, including without limitation
@@ -21,22 +21,22 @@
  * and/or sell copies of the JasPer Software (in source and binary forms),
  * and to permit persons to whom the JasPer Software is furnished to do so,
  * provided further that the License Conditions below are met.
- * 
+ *
  * License Conditions
  * ******************
- * 
+ *
  * A.  Redistributions of source code must retain the above copyright notice,
  * and this list of conditions, and the following disclaimer.
- * 
+ *
  * B.  Redistributions in binary form must reproduce the above copyright
  * notice, and this list of conditions, and the following disclaimer in
  * the documentation and/or other materials provided with the distribution.
- * 
+ *
  * C.  Neither the name of Image Power, Inc. nor any other contributor
  * (including, but not limited to, the University of British Columbia and
  * Michael David Adams) may be used to endorse or promote products derived
  * from this software without specific prior written permission.
- * 
+ *
  * D.  User agrees that it shall not commence any action against Image Power,
  * Inc., the University of British Columbia, Michael David Adams, or any
  * other contributors (collectively "Licensors") for infringement of any
@@ -56,17 +56,17 @@
  * trade dress, or service mark rights); and (v) divisions, continuations,
  * renewals, reissues and extensions of the foregoing (as and to the extent
  * applicable) now existing, hereafter filed, issued or acquired.
- * 
+ *
  * E.  If User commences an infringement action against any Licensor(s) then
  * such Licensor(s) shall have the right to terminate User's license and
  * all sublicenses that have been granted hereunder by User to other parties.
- * 
+ *
  * F.  This software is for use only in hardware or software products that
  * are compliant with ISO/IEC 15444-1 (i.e., JPEG-2000 Part 1).  No license
  * or right to this Software is granted for products that do not comply
  * with ISO/IEC 15444-1.  The JPEG-2000 Part 1 standard can be purchased
  * from the ISO.
- * 
+ *
  * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS LICENSE.
  * NO USE OF THE JASPER SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER
  * THIS DISCLAIMER.  THE JASPER SOFTWARE IS PROVIDED BY THE LICENSORS AND
@@ -106,7 +106,7 @@
  * TECHNOLOGY OR PRODUCTS FOR HIGH RISK ACTIVITIES AND WILL ENSURE THAT ITS
  * CUSTOMERS AND END-USERS OF ITS PRODUCTS ARE PROVIDED WITH A COPY OF THE
  * NOTICE SPECIFIED IN THIS SECTION.
- * 
+ *
  * __END_OF_JASPER_LICENSE__
  */
 
diff --git a/converter/other/jpeg2000/libjasper/jpc/jpc_t2enc.c b/converter/other/jpeg2000/libjasper/jpc/jpc_t2enc.c
index 1444dc7b..9eb2e92c 100644
--- a/converter/other/jpeg2000/libjasper/jpc/jpc_t2enc.c
+++ b/converter/other/jpeg2000/libjasper/jpc/jpc_t2enc.c
@@ -6,14 +6,14 @@
  */
 
 /* __START_OF_JASPER_LICENSE__
- * 
+ *
  * JasPer Software License
- * 
+ *
  * IMAGE POWER JPEG-2000 PUBLIC LICENSE
  * ************************************
- * 
+ *
  * GRANT:
- * 
+ *
  * Permission is hereby granted, free of charge, to any person (the "User")
  * obtaining a copy of this software and associated documentation, to deal
  * in the JasPer Software without restriction, including without limitation
@@ -21,22 +21,22 @@
  * and/or sell copies of the JasPer Software (in source and binary forms),
  * and to permit persons to whom the JasPer Software is furnished to do so,
  * provided further that the License Conditions below are met.
- * 
+ *
  * License Conditions
  * ******************
- * 
+ *
  * A.  Redistributions of source code must retain the above copyright notice,
  * and this list of conditions, and the following disclaimer.
- * 
+ *
  * B.  Redistributions in binary form must reproduce the above copyright
  * notice, and this list of conditions, and the following disclaimer in
  * the documentation and/or other materials provided with the distribution.
- * 
+ *
  * C.  Neither the name of Image Power, Inc. nor any other contributor
  * (including, but not limited to, the University of British Columbia and
  * Michael David Adams) may be used to endorse or promote products derived
  * from this software without specific prior written permission.
- * 
+ *
  * D.  User agrees that it shall not commence any action against Image Power,
  * Inc., the University of British Columbia, Michael David Adams, or any
  * other contributors (collectively "Licensors") for infringement of any
@@ -56,17 +56,17 @@
  * trade dress, or service mark rights); and (v) divisions, continuations,
  * renewals, reissues and extensions of the foregoing (as and to the extent
  * applicable) now existing, hereafter filed, issued or acquired.
- * 
+ *
  * E.  If User commences an infringement action against any Licensor(s) then
  * such Licensor(s) shall have the right to terminate User's license and
  * all sublicenses that have been granted hereunder by User to other parties.
- * 
+ *
  * F.  This software is for use only in hardware or software products that
  * are compliant with ISO/IEC 15444-1 (i.e., JPEG-2000 Part 1).  No license
  * or right to this Software is granted for products that do not comply
  * with ISO/IEC 15444-1.  The JPEG-2000 Part 1 standard can be purchased
  * from the ISO.
- * 
+ *
  * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS LICENSE.
  * NO USE OF THE JASPER SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER
  * THIS DISCLAIMER.  THE JASPER SOFTWARE IS PROVIDED BY THE LICENSORS AND
@@ -106,7 +106,7 @@
  * TECHNOLOGY OR PRODUCTS FOR HIGH RISK ACTIVITIES AND WILL ENSURE THAT ITS
  * CUSTOMERS AND END-USERS OF ITS PRODUCTS ARE PROVIDED WITH A COPY OF THE
  * NOTICE SPECIFIED IN THIS SECTION.
- * 
+ *
  * __END_OF_JASPER_LICENSE__
  */
 
@@ -124,7 +124,6 @@
 #include <stdlib.h>
 #include <assert.h>
 
-#include "jasper/jas_fix.h"
 #include "jasper/jas_malloc.h"
 #include "jasper/jas_math.h"
 #include "jasper/jas_debug.h"
@@ -142,563 +141,563 @@
 
 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;
+        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 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, 0);
-	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;
+        jpc_enc_tile_t *tile;
+        jpc_pi_t *pi;
+
+        tile = enc->curtile;
+
+        jpc_init_t2state(enc, 0);
+        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, int compno, int lvlno, int prcno, int 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 included;
-	int ret;
-	jpc_tagtreenode_t *leaf;
-	int n;
-	int t1;
-	int t2;
-	int adjust;
-	int maxadjust;
-	int datalen;
-	int numnewpasses;
-	int passcount;
-	jpc_enc_tile_t *tile;
-	jpc_enc_prc_t *prc;
-	jpc_enc_cp_t *cp;
-	jpc_ms_t *ms;
-
-	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);
-	}
-
-	outb = jpc_bitstream_sopen(out, "w+");
-	assert(outb);
-
-	if (jpc_bitstream_putbit(outb, 1) == EOF) {
-		return -1;
-	}
-	JAS_DBGLOG(10, ("\n"));
-	JAS_DBGLOG(10, ("present. "));
-
-	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;
-			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;
-			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) {
-					return -1;
-				}
-			} else {
-				if (jpc_bitstream_putbit(outb, included) == EOF) {
-					return -1;
-				}
-			}
-			JAS_DBGLOG(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) {
-						return -1;
-					}
-					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;
-			}
-			numnewpasses = endpass - startpass;
-			if (jpc_putnumnewpasses(outb, numnewpasses)) {
-				return -1;
-			}
-			JAS_DBGLOG(10, ("numnewpasses=%d ", numnewpasses));
-
-			lastpass = endpass - 1;
-			n = startpass->start;
-			passcount = 1;
-			maxadjust = 0;
-			for (pass = startpass; pass != endpass; ++pass) {
-				if (pass->term || pass == lastpass) {
-					datalen = pass->end - n;
-					t1 = jpc_firstone(datalen) + 1;
-					t2 = cblk->numlenbits + jpc_floorlog2(passcount);
-					adjust = JAS_MAX(t1 - t2, 0);
-					maxadjust = JAS_MAX(adjust, maxadjust);
-					n += datalen;
-					passcount = 1;
-				} else {
-					++passcount;
-				}
-			}
-			if (jpc_putcommacode(outb, maxadjust)) {
-				return -1;
-			}
-			cblk->numlenbits += maxadjust;
-
-			lastpass = endpass - 1;
-			n = startpass->start;
-			passcount = 1;
-			for (pass = startpass; pass != endpass; ++pass) {
-				if (pass->term || pass == lastpass) {
-					datalen = pass->end - n;
+        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 included;
+        int ret;
+        jpc_tagtreenode_t *leaf;
+        int n;
+        int t1;
+        int t2;
+        int adjust;
+        int maxadjust;
+        int datalen;
+        int numnewpasses;
+        int passcount;
+        jpc_enc_tile_t *tile;
+        jpc_enc_prc_t *prc;
+        jpc_enc_cp_t *cp;
+        jpc_ms_t *ms;
+
+        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);
+        }
+
+        outb = jpc_bitstream_sopen(out, "w+");
+        assert(outb);
+
+        if (jpc_bitstream_putbit(outb, 1) == EOF) {
+                return -1;
+        }
+        JAS_DBGLOG(10, ("\n"));
+        JAS_DBGLOG(10, ("present. "));
+
+        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;
+                        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;
+                        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) {
+                                        return -1;
+                                }
+                        } else {
+                                if (jpc_bitstream_putbit(outb, included) == EOF) {
+                                        return -1;
+                                }
+                        }
+                        JAS_DBGLOG(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) {
+                                                return -1;
+                                        }
+                                        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;
+                        }
+                        numnewpasses = endpass - startpass;
+                        if (jpc_putnumnewpasses(outb, numnewpasses)) {
+                                return -1;
+                        }
+                        JAS_DBGLOG(10, ("numnewpasses=%d ", numnewpasses));
+
+                        lastpass = endpass - 1;
+                        n = startpass->start;
+                        passcount = 1;
+                        maxadjust = 0;
+                        for (pass = startpass; pass != endpass; ++pass) {
+                                if (pass->term || pass == lastpass) {
+                                        datalen = pass->end - n;
+                                        t1 = jpc_firstone(datalen) + 1;
+                                        t2 = cblk->numlenbits + jpc_floorlog2(passcount);
+                                        adjust = JAS_MAX(t1 - t2, 0);
+                                        maxadjust = JAS_MAX(adjust, maxadjust);
+                                        n += datalen;
+                                        passcount = 1;
+                                } else {
+                                        ++passcount;
+                                }
+                        }
+                        if (jpc_putcommacode(outb, maxadjust)) {
+                                return -1;
+                        }
+                        cblk->numlenbits += maxadjust;
+
+                        lastpass = endpass - 1;
+                        n = startpass->start;
+                        passcount = 1;
+                        for (pass = startpass; pass != endpass; ++pass) {
+                                if (pass->term || pass == lastpass) {
+                                        datalen = pass->end - n;
 assert(jpc_firstone(datalen) < cblk->numlenbits + jpc_floorlog2(passcount));
-					if (jpc_bitstream_putbits(outb, cblk->numlenbits + jpc_floorlog2(passcount), datalen) == EOF) {
-						return -1;
-					}
-					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;
-		}
-		jpc_putms(out, enc->cstate, ms);
-		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 < 0 || pass->lyrno > lyrno);
-				continue;
-			}
-
-			endpasses = &cblk->passes[cblk->numpasses];
-			startpass = pass;
-			endpass = startpass;
-			while (endpass != endpasses && endpass->lyrno == lyrno){
-				++endpass;
-			}
-			lastpass = endpass - 1;
-			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;
-
-		}
-	}
-
-	return 0;
+                                        if (jpc_bitstream_putbits(outb, cblk->numlenbits + jpc_floorlog2(passcount), datalen) == EOF) {
+                                                return -1;
+                                        }
+                                        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;
+                }
+                jpc_putms(out, enc->cstate, ms);
+                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 < 0 || pass->lyrno > lyrno);
+                                continue;
+                        }
+
+                        endpasses = &cblk->passes[cblk->numpasses];
+                        startpass = pass;
+                        endpass = startpass;
+                        while (endpass != endpasses && endpass->lyrno == lyrno){
+                                ++endpass;
+                        }
+                        lastpass = endpass - 1;
+                        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;
+
+                }
+        }
+
+        return 0;
 }
 
 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;
-	uint_fast32_t 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;
-					}
-				}
-			}
-		}
-	}
+        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;
+        uint_fast32_t 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;
-	uint_fast32_t 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;
-					}
-				}
-			}
-		}
-	}
+        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;
+        uint_fast32_t 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, int 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;
-	uint_fast32_t 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 = -1;
-								pass->lyrno = 0;
-							}
-						}
-					}
-				}
-			}
-		}
-	}
+        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;
+        uint_fast32_t 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 = -1;
+                                                                pass->lyrno = 0;
+                                                        }
+                                                }
+                                        }
+                                }
+                        }
+                }
+        }
 
 }
 
 jpc_pi_t *jpc_enc_pi_create(jpc_enc_cp_t *cp, jpc_enc_tile_t *tile)
 {
-	jpc_pi_t *pi;
-	int compno;
-	jpc_picomp_t *picomp;
-	jpc_pirlvl_t *pirlvl;
-	jpc_enc_tcmpt_t *tcomp;
-	int rlvlno;
-	jpc_enc_rlvl_t *rlvl;
-	int prcno;
-	int *prclyrno;
-
-	if (!(pi = jpc_pi_create0())) {
-		return 0;
-	}
-	pi->pktno = -1;
-	pi->numcomps = cp->numcmpts;
-	if (!(pi->picomps = jas_malloc(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_malloc(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) {
+        jpc_pi_t *pi;
+        int compno;
+        jpc_picomp_t *picomp;
+        jpc_pirlvl_t *pirlvl;
+        jpc_enc_tcmpt_t *tcomp;
+        int rlvlno;
+        jpc_enc_rlvl_t *rlvl;
+        int prcno;
+        int *prclyrno;
+
+        if (!(pi = jpc_pi_create0())) {
+                return 0;
+        }
+        pi->pktno = -1;
+        pi->numcomps = cp->numcmpts;
+        if (!(pi->picomps = jas_malloc(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_malloc(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_malloc(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;
+                        pirlvl->numprcs = rlvl->numprcs;
+                        if (rlvl->numprcs) {
+                                if (!(pirlvl->prclyrnos = jas_malloc(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;
 }
diff --git a/converter/other/jpeg2000/libjasper/jpc/jpc_t2enc.h b/converter/other/jpeg2000/libjasper/jpc/jpc_t2enc.h
index e97f8c06..8b5979de 100644
--- a/converter/other/jpeg2000/libjasper/jpc/jpc_t2enc.h
+++ b/converter/other/jpeg2000/libjasper/jpc/jpc_t2enc.h
@@ -6,14 +6,14 @@
  */
 
 /* __START_OF_JASPER_LICENSE__
- * 
+ *
  * JasPer Software License
- * 
+ *
  * IMAGE POWER JPEG-2000 PUBLIC LICENSE
  * ************************************
- * 
+ *
  * GRANT:
- * 
+ *
  * Permission is hereby granted, free of charge, to any person (the "User")
  * obtaining a copy of this software and associated documentation, to deal
  * in the JasPer Software without restriction, including without limitation
@@ -21,22 +21,22 @@
  * and/or sell copies of the JasPer Software (in source and binary forms),
  * and to permit persons to whom the JasPer Software is furnished to do so,
  * provided further that the License Conditions below are met.
- * 
+ *
  * License Conditions
  * ******************
- * 
+ *
  * A.  Redistributions of source code must retain the above copyright notice,
  * and this list of conditions, and the following disclaimer.
- * 
+ *
  * B.  Redistributions in binary form must reproduce the above copyright
  * notice, and this list of conditions, and the following disclaimer in
  * the documentation and/or other materials provided with the distribution.
- * 
+ *
  * C.  Neither the name of Image Power, Inc. nor any other contributor
  * (including, but not limited to, the University of British Columbia and
  * Michael David Adams) may be used to endorse or promote products derived
  * from this software without specific prior written permission.
- * 
+ *
  * D.  User agrees that it shall not commence any action against Image Power,
  * Inc., the University of British Columbia, Michael David Adams, or any
  * other contributors (collectively "Licensors") for infringement of any
@@ -56,17 +56,17 @@
  * trade dress, or service mark rights); and (v) divisions, continuations,
  * renewals, reissues and extensions of the foregoing (as and to the extent
  * applicable) now existing, hereafter filed, issued or acquired.
- * 
+ *
  * E.  If User commences an infringement action against any Licensor(s) then
  * such Licensor(s) shall have the right to terminate User's license and
  * all sublicenses that have been granted hereunder by User to other parties.
- * 
+ *
  * F.  This software is for use only in hardware or software products that
  * are compliant with ISO/IEC 15444-1 (i.e., JPEG-2000 Part 1).  No license
  * or right to this Software is granted for products that do not comply
  * with ISO/IEC 15444-1.  The JPEG-2000 Part 1 standard can be purchased
  * from the ISO.
- * 
+ *
  * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS LICENSE.
  * NO USE OF THE JASPER SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER
  * THIS DISCLAIMER.  THE JASPER SOFTWARE IS PROVIDED BY THE LICENSORS AND
@@ -106,7 +106,7 @@
  * TECHNOLOGY OR PRODUCTS FOR HIGH RISK ACTIVITIES AND WILL ENSURE THAT ITS
  * CUSTOMERS AND END-USERS OF ITS PRODUCTS ARE PROVIDED WITH A COPY OF THE
  * NOTICE SPECIFIED IN THIS SECTION.
- * 
+ *
  * __END_OF_JASPER_LICENSE__
  */
 
diff --git a/converter/other/jpeg2000/libjasper/jpc/jpc_tagtree.c b/converter/other/jpeg2000/libjasper/jpc/jpc_tagtree.c
index 2b13fcf1..1d026b85 100644
--- a/converter/other/jpeg2000/libjasper/jpc/jpc_tagtree.c
+++ b/converter/other/jpeg2000/libjasper/jpc/jpc_tagtree.c
@@ -6,14 +6,14 @@
  */
 
 /* __START_OF_JASPER_LICENSE__
- * 
+ *
  * JasPer Software License
- * 
+ *
  * IMAGE POWER JPEG-2000 PUBLIC LICENSE
  * ************************************
- * 
+ *
  * GRANT:
- * 
+ *
  * Permission is hereby granted, free of charge, to any person (the "User")
  * obtaining a copy of this software and associated documentation, to deal
  * in the JasPer Software without restriction, including without limitation
@@ -21,22 +21,22 @@
  * and/or sell copies of the JasPer Software (in source and binary forms),
  * and to permit persons to whom the JasPer Software is furnished to do so,
  * provided further that the License Conditions below are met.
- * 
+ *
  * License Conditions
  * ******************
- * 
+ *
  * A.  Redistributions of source code must retain the above copyright notice,
  * and this list of conditions, and the following disclaimer.
- * 
+ *
  * B.  Redistributions in binary form must reproduce the above copyright
  * notice, and this list of conditions, and the following disclaimer in
  * the documentation and/or other materials provided with the distribution.
- * 
+ *
  * C.  Neither the name of Image Power, Inc. nor any other contributor
  * (including, but not limited to, the University of British Columbia and
  * Michael David Adams) may be used to endorse or promote products derived
  * from this software without specific prior written permission.
- * 
+ *
  * D.  User agrees that it shall not commence any action against Image Power,
  * Inc., the University of British Columbia, Michael David Adams, or any
  * other contributors (collectively "Licensors") for infringement of any
@@ -56,17 +56,17 @@
  * trade dress, or service mark rights); and (v) divisions, continuations,
  * renewals, reissues and extensions of the foregoing (as and to the extent
  * applicable) now existing, hereafter filed, issued or acquired.
- * 
+ *
  * E.  If User commences an infringement action against any Licensor(s) then
  * such Licensor(s) shall have the right to terminate User's license and
  * all sublicenses that have been granted hereunder by User to other parties.
- * 
+ *
  * F.  This software is for use only in hardware or software products that
  * are compliant with ISO/IEC 15444-1 (i.e., JPEG-2000 Part 1).  No license
  * or right to this Software is granted for products that do not comply
  * with ISO/IEC 15444-1.  The JPEG-2000 Part 1 standard can be purchased
  * from the ISO.
- * 
+ *
  * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS LICENSE.
  * NO USE OF THE JASPER SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER
  * THIS DISCLAIMER.  THE JASPER SOFTWARE IS PROVIDED BY THE LICENSORS AND
@@ -106,7 +106,7 @@
  * TECHNOLOGY OR PRODUCTS FOR HIGH RISK ACTIVITIES AND WILL ENSURE THAT ITS
  * CUSTOMERS AND END-USERS OF ITS PRODUCTS ARE PROVIDED WITH A COPY OF THE
  * NOTICE SPECIFIED IN THIS SECTION.
- * 
+ *
  * __END_OF_JASPER_LICENSE__
  */
 
@@ -135,101 +135,101 @@
 
 static jpc_tagtree_t *jpc_tagtree_alloc(void)
 {
-	jpc_tagtree_t *tree;
+        jpc_tagtree_t *tree;
 
-	if (!(tree = jas_malloc(sizeof(jpc_tagtree_t)))) {
-		return 0;
-	}
-	tree->numleafsh_ = 0;
-	tree->numleafsv_ = 0;
-	tree->numnodes_ = 0;
-	tree->nodes_ = 0;
+        if (!(tree = jas_malloc(sizeof(jpc_tagtree_t)))) {
+                return 0;
+        }
+        tree->numleafsh_ = 0;
+        tree->numleafsv_ = 0;
+        tree->numnodes_ = 0;
+        tree->nodes_ = 0;
 
-	return tree;
+        return tree;
 }
 
 /* Create a tag tree. */
 
 jpc_tagtree_t *jpc_tagtree_create(int numleafsh, int numleafsv)
 {
-	int nplh[JPC_TAGTREE_MAXDEPTH];
-	int nplv[JPC_TAGTREE_MAXDEPTH];
-	jpc_tagtreenode_t *node;
-	jpc_tagtreenode_t *parentnode;
-	jpc_tagtreenode_t *parentnode0;
-	jpc_tagtree_t *tree;
-	int i;
-	int j;
-	int k;
-	int numlvls;
-	int n;
-
-	assert(numleafsh > 0 && numleafsv > 0);
-
-	if (!(tree = jpc_tagtree_alloc())) {
-		return 0;
-	}
-	tree->numleafsh_ = numleafsh;
-	tree->numleafsv_ = numleafsv;
-
-	numlvls = 0;
-	nplh[0] = numleafsh;
-	nplv[0] = numleafsv;
-	do {
-		n = nplh[numlvls] * nplv[numlvls];
-		nplh[numlvls + 1] = (nplh[numlvls] + 1) / 2;
-		nplv[numlvls + 1] = (nplv[numlvls] + 1) / 2;
-		tree->numnodes_ += n;
-		++numlvls;
-	} while (n > 1);
-
-	if (!(tree->nodes_ = jas_malloc(tree->numnodes_ * sizeof(jpc_tagtreenode_t)))) {
-		return 0;
-	}
-
-	/* Initialize the parent links for all nodes in the tree. */
-
-	node = tree->nodes_;
-	parentnode = &tree->nodes_[tree->numleafsh_ * tree->numleafsv_];
-	parentnode0 = parentnode;
-
-	for (i = 0; i < numlvls - 1; ++i) {
-		for (j = 0; j < nplv[i]; ++j) {
-			k = nplh[i];
-			while (--k >= 0) {
-				node->parent_ = parentnode;
-				++node;
-				if (--k >= 0) {
-					node->parent_ = parentnode;
-					++node;
-				}
-				++parentnode;
-			}
-			if ((j & 1) || j == nplv[i] - 1) {
-				parentnode0 = parentnode;
-			} else {
-				parentnode = parentnode0;
-				parentnode0 += nplh[i];
-			}
-		}
-	}
-	node->parent_ = 0;
-
-	/* Initialize the data values to something sane. */
-
-	jpc_tagtree_reset(tree);
-
-	return tree;
+        int nplh[JPC_TAGTREE_MAXDEPTH];
+        int nplv[JPC_TAGTREE_MAXDEPTH];
+        jpc_tagtreenode_t *node;
+        jpc_tagtreenode_t *parentnode;
+        jpc_tagtreenode_t *parentnode0;
+        jpc_tagtree_t *tree;
+        int i;
+        int j;
+        int k;
+        int numlvls;
+        int n;
+
+        assert(numleafsh > 0 && numleafsv > 0);
+
+        if (!(tree = jpc_tagtree_alloc())) {
+                return 0;
+        }
+        tree->numleafsh_ = numleafsh;
+        tree->numleafsv_ = numleafsv;
+
+        numlvls = 0;
+        nplh[0] = numleafsh;
+        nplv[0] = numleafsv;
+        do {
+                n = nplh[numlvls] * nplv[numlvls];
+                nplh[numlvls + 1] = (nplh[numlvls] + 1) / 2;
+                nplv[numlvls + 1] = (nplv[numlvls] + 1) / 2;
+                tree->numnodes_ += n;
+                ++numlvls;
+        } while (n > 1);
+
+        if (!(tree->nodes_ = jas_malloc(tree->numnodes_ * sizeof(jpc_tagtreenode_t)))) {
+                return 0;
+        }
+
+        /* Initialize the parent links for all nodes in the tree. */
+
+        node = tree->nodes_;
+        parentnode = &tree->nodes_[tree->numleafsh_ * tree->numleafsv_];
+        parentnode0 = parentnode;
+
+        for (i = 0; i < numlvls - 1; ++i) {
+                for (j = 0; j < nplv[i]; ++j) {
+                        k = nplh[i];
+                        while (--k >= 0) {
+                                node->parent_ = parentnode;
+                                ++node;
+                                if (--k >= 0) {
+                                        node->parent_ = parentnode;
+                                        ++node;
+                                }
+                                ++parentnode;
+                        }
+                        if ((j & 1) || j == nplv[i] - 1) {
+                                parentnode0 = parentnode;
+                        } else {
+                                parentnode = parentnode0;
+                                parentnode0 += nplh[i];
+                        }
+                }
+        }
+        node->parent_ = 0;
+
+        /* Initialize the data values to something sane. */
+
+        jpc_tagtree_reset(tree);
+
+        return tree;
 }
 
 /* Destroy a tag tree. */
 
 void jpc_tagtree_destroy(jpc_tagtree_t *tree)
 {
-	if (tree->nodes_) {
-		jas_free(tree->nodes_);
-	}
-	jas_free(tree);
+        if (tree->nodes_) {
+                jas_free(tree->nodes_);
+        }
+        jas_free(tree);
 }
 
 /******************************************************************************\
@@ -240,42 +240,42 @@ void jpc_tagtree_destroy(jpc_tagtree_t *tree)
 
 void jpc_tagtree_copy(jpc_tagtree_t *dsttree, jpc_tagtree_t *srctree)
 {
-	int n;
-	jpc_tagtreenode_t *srcnode;
-	jpc_tagtreenode_t *dstnode;
-
-	/* The two tag trees must have similar sizes. */
-	assert(srctree->numleafsh_ == dsttree->numleafsh_ &&
-	  srctree->numleafsv_ == dsttree->numleafsv_);
-
-	n = srctree->numnodes_;
-	srcnode = srctree->nodes_;
-	dstnode = dsttree->nodes_;
-	while (--n >= 0) {
-		dstnode->value_ = srcnode->value_;
-		dstnode->low_ = srcnode->low_;
-		dstnode->known_ = srcnode->known_;
-		++dstnode;
-		++srcnode;
-	}
+        int n;
+        jpc_tagtreenode_t *srcnode;
+        jpc_tagtreenode_t *dstnode;
+
+        /* The two tag trees must have similar sizes. */
+        assert(srctree->numleafsh_ == dsttree->numleafsh_ &&
+          srctree->numleafsv_ == dsttree->numleafsv_);
+
+        n = srctree->numnodes_;
+        srcnode = srctree->nodes_;
+        dstnode = dsttree->nodes_;
+        while (--n >= 0) {
+                dstnode->value_ = srcnode->value_;
+                dstnode->low_ = srcnode->low_;
+                dstnode->known_ = srcnode->known_;
+                ++dstnode;
+                ++srcnode;
+        }
 }
 
 /* Reset all of the state information associated with a tag tree. */
 
 void jpc_tagtree_reset(jpc_tagtree_t *tree)
 {
-	int n;
-	jpc_tagtreenode_t *node;
-
-	n = tree->numnodes_;
-	node = tree->nodes_;
-
-	while (--n >= 0) {
-		node->value_ = INT_MAX;
-		node->low_ = 0;
-		node->known_ = 0;
-		++node;
-	}
+        int n;
+        jpc_tagtreenode_t *node;
+
+        n = tree->numnodes_;
+        node = tree->nodes_;
+
+        while (--n >= 0) {
+                node->value_ = INT_MAX;
+                node->low_ = 0;
+                node->known_ = 0;
+                ++node;
+        }
 }
 
 /* Set the value associated with the specified leaf node, updating
@@ -283,22 +283,22 @@ the other nodes as necessary. */
 
 void jpc_tagtree_setvalue(jpc_tagtree_t *tree, jpc_tagtreenode_t *leaf, int value)
 {
-	jpc_tagtreenode_t *node;
+        jpc_tagtreenode_t *node;
 
-	assert(value >= 0);
+        assert(value >= 0);
 
-	node = leaf;
-	while (node && node->value_ > value) {
-		node->value_ = value;
-		node = node->parent_;
-	}
+        node = leaf;
+        while (node && node->value_ > value) {
+                node->value_ = value;
+                node = node->parent_;
+        }
 }
 
 /* Get a particular leaf node. */
 
 jpc_tagtreenode_t *jpc_tagtree_getleaf(jpc_tagtree_t *tree, int n)
 {
-	return &tree->nodes_[n];
+        return &tree->nodes_[n];
 }
 
 /* Invoke the tag tree encoding procedure. */
@@ -306,55 +306,55 @@ jpc_tagtreenode_t *jpc_tagtree_getleaf(jpc_tagtree_t *tree, int n)
 int jpc_tagtree_encode(jpc_tagtree_t *tree, jpc_tagtreenode_t *leaf, int threshold,
   jpc_bitstream_t *out)
 {
-	jpc_tagtreenode_t *stk[JPC_TAGTREE_MAXDEPTH - 1];
-	jpc_tagtreenode_t **stkptr;
-	jpc_tagtreenode_t *node;
-	int low;
-
-	assert(leaf);
-	assert(threshold >= 0);
-
-	/* Traverse to the root of the tree, recording the path taken. */
-	stkptr = stk;
-	node = leaf;
-	while (node->parent_) {
-		*stkptr++ = node;
-		node = node->parent_;
-	}
-
-	low = 0;
-	for (;;) {
-		if (low > node->low_) {
-			/* Deferred propagation of the lower bound downward in
-			  the tree. */
-			node->low_ = low;
-		} else {
-			low = node->low_;
-		}
-
-		while (low < threshold) {
-			if (low >= node->value_) {
-				if (!node->known_) {
-					if (jpc_bitstream_putbit(out, 1) == EOF) {
-						return -1;
-					}
-					node->known_ = 1;
-				}
-				break;
-			}
-			if (jpc_bitstream_putbit(out, 0) == EOF) {
-				return -1;
-			}
-			++low;
-		}
-		node->low_ = low;
-		if (stkptr == stk) {
-			break;
-		}
-		node = *--stkptr;
-
-	}
-	return (leaf->low_ < threshold) ? 1 : 0;
+        jpc_tagtreenode_t *stk[JPC_TAGTREE_MAXDEPTH - 1];
+        jpc_tagtreenode_t **stkptr;
+        jpc_tagtreenode_t *node;
+        int low;
+
+        assert(leaf);
+        assert(threshold >= 0);
+
+        /* Traverse to the root of the tree, recording the path taken. */
+        stkptr = stk;
+        node = leaf;
+        while (node->parent_) {
+                *stkptr++ = node;
+                node = node->parent_;
+        }
+
+        low = 0;
+        for (;;) {
+                if (low > node->low_) {
+                        /* Deferred propagation of the lower bound downward in
+                          the tree. */
+                        node->low_ = low;
+                } else {
+                        low = node->low_;
+                }
+
+                while (low < threshold) {
+                        if (low >= node->value_) {
+                                if (!node->known_) {
+                                        if (jpc_bitstream_putbit(out, 1) == EOF) {
+                                                return -1;
+                                        }
+                                        node->known_ = 1;
+                                }
+                                break;
+                        }
+                        if (jpc_bitstream_putbit(out, 0) == EOF) {
+                                return -1;
+                        }
+                        ++low;
+                }
+                node->low_ = low;
+                if (stkptr == stk) {
+                        break;
+                }
+                node = *--stkptr;
+
+        }
+        return (leaf->low_ < threshold) ? 1 : 0;
 
 }
 
@@ -363,47 +363,47 @@ int jpc_tagtree_encode(jpc_tagtree_t *tree, jpc_tagtreenode_t *leaf, int thresho
 int jpc_tagtree_decode(jpc_tagtree_t *tree, jpc_tagtreenode_t *leaf, int threshold,
   jpc_bitstream_t *in)
 {
-	jpc_tagtreenode_t *stk[JPC_TAGTREE_MAXDEPTH - 1];
-	jpc_tagtreenode_t **stkptr;
-	jpc_tagtreenode_t *node;
-	int low;
-	int ret;
-
-	assert(threshold >= 0);
-
-	/* Traverse to the root of the tree, recording the path taken. */
-	stkptr = stk;
-	node = leaf;
-	while (node->parent_) {
-		*stkptr++ = node;
-		node = node->parent_;
-	}
-
-	low = 0;
-	for (;;) {
-		if (low > node->low_) {
-			node->low_ = low;
-		} else {
-			low = node->low_;
-		}
-		while (low < threshold && low < node->value_) {
-			if ((ret = jpc_bitstream_getbit(in)) < 0) {
-				return -1;
-			}
-			if (ret) {
-				node->value_ = low;
-			} else {
-				++low;
-			}
-		}
-		node->low_ = low;
-		if (stkptr == stk) {
-			break;
-		}
-		node = *--stkptr;
-	}
-
-	return (node->value_ < threshold) ? 1 : 0;
+        jpc_tagtreenode_t *stk[JPC_TAGTREE_MAXDEPTH - 1];
+        jpc_tagtreenode_t **stkptr;
+        jpc_tagtreenode_t *node;
+        int low;
+        int ret;
+
+        assert(threshold >= 0);
+
+        /* Traverse to the root of the tree, recording the path taken. */
+        stkptr = stk;
+        node = leaf;
+        while (node->parent_) {
+                *stkptr++ = node;
+                node = node->parent_;
+        }
+
+        low = 0;
+        for (;;) {
+                if (low > node->low_) {
+                        node->low_ = low;
+                } else {
+                        low = node->low_;
+                }
+                while (low < threshold && low < node->value_) {
+                        if ((ret = jpc_bitstream_getbit(in)) < 0) {
+                                return -1;
+                        }
+                        if (ret) {
+                                node->value_ = low;
+                        } else {
+                                ++low;
+                        }
+                }
+                node->low_ = low;
+                if (stkptr == stk) {
+                        break;
+                }
+                node = *--stkptr;
+        }
+
+        return (node->value_ < threshold) ? 1 : 0;
 }
 
 /******************************************************************************\
@@ -412,15 +412,15 @@ int jpc_tagtree_decode(jpc_tagtree_t *tree, jpc_tagtreenode_t *leaf, int thresho
 
 void jpc_tagtree_dump(jpc_tagtree_t *tree, FILE *out)
 {
-	jpc_tagtreenode_t *node;
-	int n;
-
-	node = tree->nodes_;
-	n = tree->numnodes_;
-	while (--n >= 0) {
-		fprintf(out, "node %p, parent %p, value %d, lower %d, known %d\n",
-		  (void *) node, (void *) node->parent_, node->value_, node->low_,
-		  node->known_);
-		++node;
-	}
+        jpc_tagtreenode_t *node;
+        int n;
+
+        node = tree->nodes_;
+        n = tree->numnodes_;
+        while (--n >= 0) {
+                fprintf(out, "node %p, parent %p, value %d, lower %d, known %d\n",
+                  (void *) node, (void *) node->parent_, node->value_, node->low_,
+                  node->known_);
+                ++node;
+        }
 }
diff --git a/converter/other/jpeg2000/libjasper/jpc/jpc_tagtree.h b/converter/other/jpeg2000/libjasper/jpc/jpc_tagtree.h
index 1892b13f..cf1dc652 100644
--- a/converter/other/jpeg2000/libjasper/jpc/jpc_tagtree.h
+++ b/converter/other/jpeg2000/libjasper/jpc/jpc_tagtree.h
@@ -6,14 +6,14 @@
  */
 
 /* __START_OF_JASPER_LICENSE__
- * 
+ *
  * JasPer Software License
- * 
+ *
  * IMAGE POWER JPEG-2000 PUBLIC LICENSE
  * ************************************
- * 
+ *
  * GRANT:
- * 
+ *
  * Permission is hereby granted, free of charge, to any person (the "User")
  * obtaining a copy of this software and associated documentation, to deal
  * in the JasPer Software without restriction, including without limitation
@@ -21,22 +21,22 @@
  * and/or sell copies of the JasPer Software (in source and binary forms),
  * and to permit persons to whom the JasPer Software is furnished to do so,
  * provided further that the License Conditions below are met.
- * 
+ *
  * License Conditions
  * ******************
- * 
+ *
  * A.  Redistributions of source code must retain the above copyright notice,
  * and this list of conditions, and the following disclaimer.
- * 
+ *
  * B.  Redistributions in binary form must reproduce the above copyright
  * notice, and this list of conditions, and the following disclaimer in
  * the documentation and/or other materials provided with the distribution.
- * 
+ *
  * C.  Neither the name of Image Power, Inc. nor any other contributor
  * (including, but not limited to, the University of British Columbia and
  * Michael David Adams) may be used to endorse or promote products derived
  * from this software without specific prior written permission.
- * 
+ *
  * D.  User agrees that it shall not commence any action against Image Power,
  * Inc., the University of British Columbia, Michael David Adams, or any
  * other contributors (collectively "Licensors") for infringement of any
@@ -56,17 +56,17 @@
  * trade dress, or service mark rights); and (v) divisions, continuations,
  * renewals, reissues and extensions of the foregoing (as and to the extent
  * applicable) now existing, hereafter filed, issued or acquired.
- * 
+ *
  * E.  If User commences an infringement action against any Licensor(s) then
  * such Licensor(s) shall have the right to terminate User's license and
  * all sublicenses that have been granted hereunder by User to other parties.
- * 
+ *
  * F.  This software is for use only in hardware or software products that
  * are compliant with ISO/IEC 15444-1 (i.e., JPEG-2000 Part 1).  No license
  * or right to this Software is granted for products that do not comply
  * with ISO/IEC 15444-1.  The JPEG-2000 Part 1 standard can be purchased
  * from the ISO.
- * 
+ *
  * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS LICENSE.
  * NO USE OF THE JASPER SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER
  * THIS DISCLAIMER.  THE JASPER SOFTWARE IS PROVIDED BY THE LICENSORS AND
@@ -106,7 +106,7 @@
  * TECHNOLOGY OR PRODUCTS FOR HIGH RISK ACTIVITIES AND WILL ENSURE THAT ITS
  * CUSTOMERS AND END-USERS OF ITS PRODUCTS ARE PROVIDED WITH A COPY OF THE
  * NOTICE SPECIFIED IN THIS SECTION.
- * 
+ *
  * __END_OF_JASPER_LICENSE__
  */
 
@@ -133,7 +133,7 @@
 \******************************************************************************/
 
 /* The maximum allowable depth for a tag tree. */
-#define JPC_TAGTREE_MAXDEPTH	32
+#define JPC_TAGTREE_MAXDEPTH    32
 
 /******************************************************************************\
 * Types
@@ -145,17 +145,17 @@
 
 typedef struct jpc_tagtreenode_ {
 
-	/* The parent of this node. */
-	struct jpc_tagtreenode_ *parent_;
+        /* The parent of this node. */
+        struct jpc_tagtreenode_ *parent_;
 
-	/* The value associated with this node. */
-	int value_;
+        /* The value associated with this node. */
+        int value_;
 
-	/* The lower bound on the value associated with this node. */
-	int low_;
+        /* The lower bound on the value associated with this node. */
+        int low_;
 
-	/* A flag indicating if the value is known exactly. */
-	int known_;
+        /* A flag indicating if the value is known exactly. */
+        int known_;
 
 } jpc_tagtreenode_t;
 
@@ -165,17 +165,17 @@ typedef struct jpc_tagtreenode_ {
 
 typedef struct {
 
-	/* The number of leaves in the horizontal direction. */
-	int numleafsh_;
+        /* The number of leaves in the horizontal direction. */
+        int numleafsh_;
 
-	/* The number of leaves in the vertical direction. */
-	int numleafsv_;
+        /* The number of leaves in the vertical direction. */
+        int numleafsv_;
 
-	/* The total number of nodes in the tree. */
-	int numnodes_;
+        /* The total number of nodes in the tree. */
+        int numnodes_;
 
-	/* The nodes. */
-	jpc_tagtreenode_t *nodes_;
+        /* The nodes. */
+        jpc_tagtreenode_t *nodes_;
 
 } jpc_tagtree_t;
 
diff --git a/converter/other/jpeg2000/libjasper/jpc/jpc_tsfb.c b/converter/other/jpeg2000/libjasper/jpc/jpc_tsfb.c
index f7d66b57..a5772c53 100644
--- a/converter/other/jpeg2000/libjasper/jpc/jpc_tsfb.c
+++ b/converter/other/jpeg2000/libjasper/jpc/jpc_tsfb.c
@@ -6,14 +6,14 @@
  */
 
 /* __START_OF_JASPER_LICENSE__
- * 
+ *
  * JasPer Software License
- * 
+ *
  * IMAGE POWER JPEG-2000 PUBLIC LICENSE
  * ************************************
- * 
+ *
  * GRANT:
- * 
+ *
  * Permission is hereby granted, free of charge, to any person (the "User")
  * obtaining a copy of this software and associated documentation, to deal
  * in the JasPer Software without restriction, including without limitation
@@ -21,22 +21,22 @@
  * and/or sell copies of the JasPer Software (in source and binary forms),
  * and to permit persons to whom the JasPer Software is furnished to do so,
  * provided further that the License Conditions below are met.
- * 
+ *
  * License Conditions
  * ******************
- * 
+ *
  * A.  Redistributions of source code must retain the above copyright notice,
  * and this list of conditions, and the following disclaimer.
- * 
+ *
  * B.  Redistributions in binary form must reproduce the above copyright
  * notice, and this list of conditions, and the following disclaimer in
  * the documentation and/or other materials provided with the distribution.
- * 
+ *
  * C.  Neither the name of Image Power, Inc. nor any other contributor
  * (including, but not limited to, the University of British Columbia and
  * Michael David Adams) may be used to endorse or promote products derived
  * from this software without specific prior written permission.
- * 
+ *
  * D.  User agrees that it shall not commence any action against Image Power,
  * Inc., the University of British Columbia, Michael David Adams, or any
  * other contributors (collectively "Licensors") for infringement of any
@@ -56,17 +56,17 @@
  * trade dress, or service mark rights); and (v) divisions, continuations,
  * renewals, reissues and extensions of the foregoing (as and to the extent
  * applicable) now existing, hereafter filed, issued or acquired.
- * 
+ *
  * E.  If User commences an infringement action against any Licensor(s) then
  * such Licensor(s) shall have the right to terminate User's license and
  * all sublicenses that have been granted hereunder by User to other parties.
- * 
+ *
  * F.  This software is for use only in hardware or software products that
  * are compliant with ISO/IEC 15444-1 (i.e., JPEG-2000 Part 1).  No license
  * or right to this Software is granted for products that do not comply
  * with ISO/IEC 15444-1.  The JPEG-2000 Part 1 standard can be purchased
  * from the ISO.
- * 
+ *
  * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS LICENSE.
  * NO USE OF THE JASPER SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER
  * THIS DISCLAIMER.  THE JASPER SOFTWARE IS PROVIDED BY THE LICENSORS AND
@@ -106,7 +106,7 @@
  * TECHNOLOGY OR PRODUCTS FOR HIGH RISK ACTIVITIES AND WILL ENSURE THAT ITS
  * CUSTOMERS AND END-USERS OF ITS PRODUCTS ARE PROVIDED WITH A COPY OF THE
  * NOTICE SPECIFIED IN THIS SECTION.
- * 
+ *
  * __END_OF_JASPER_LICENSE__
  */
 
@@ -134,8 +134,8 @@
 *
 \******************************************************************************/
 
-#define	bandnotovind(tsfbnode, x)	((x) / (tsfbnode)->numhchans)
-#define	bandnotohind(tsfbnode, x)	((x) % (tsfbnode)->numhchans)
+#define bandnotovind(tsfbnode, x)       ((x) / (tsfbnode)->numhchans)
+#define bandnotohind(tsfbnode, x)       ((x) % (tsfbnode)->numhchans)
 
 static jpc_tsfb_t *jpc_tsfb_create(void);
 static jpc_tsfbnode_t *jpc_tsfbnode_create(void);
@@ -158,74 +158,74 @@ static int jpc_tsfbnode_getequivfilters(jpc_tsfbnode_t *tsfbnode, int cldind,
 
 jpc_tsfb_t *jpc_tsfb_wavelet(jpc_qmfb1d_t *hqmfb, jpc_qmfb1d_t *vqmfb, int numdlvls)
 {
-	jpc_tsfb_t *tsfb;
-	int dlvlno;
-	jpc_tsfbnode_t *curnode;
-	jpc_tsfbnode_t *prevnode;
-	int childno;
-	if (!(tsfb = jpc_tsfb_create())) {
-		return 0;
-	}
-	prevnode = 0;
-	for (dlvlno = 0; dlvlno < numdlvls; ++dlvlno) {
-		if (!(curnode = jpc_tsfbnode_create())) {
-			jpc_tsfb_destroy(tsfb);
-			return 0;
-		}
-		if (prevnode) {
-			prevnode->children[0] = curnode;
-			++prevnode->numchildren;
-			curnode->parent = prevnode;
-		} else {
-			tsfb->root = curnode;
-			curnode->parent = 0;
-		}
-		if (hqmfb) {
-			curnode->numhchans = jpc_qmfb1d_getnumchans(hqmfb);
-			if (!(curnode->hqmfb = jpc_qmfb1d_copy(hqmfb))) {
-				jpc_tsfb_destroy(tsfb);
-				return 0;
-			}
-		} else {
-			curnode->hqmfb = 0;
-			curnode->numhchans = 1;
-		}
-		if (vqmfb) {
-			curnode->numvchans = jpc_qmfb1d_getnumchans(vqmfb);
-			if (!(curnode->vqmfb = jpc_qmfb1d_copy(vqmfb))) {
-				jpc_tsfb_destroy(tsfb);
-				return 0;
-			}
-		} else {
-			curnode->vqmfb = 0;
-			curnode->numvchans = 1;
-		}
-		curnode->maxchildren = curnode->numhchans * curnode->numvchans;
-		for (childno = 0; childno < curnode->maxchildren;
-		  ++childno) {
-			curnode->children[childno] = 0;
-		}
-		prevnode = curnode;
-	}
-	return tsfb;
+        jpc_tsfb_t *tsfb;
+        int dlvlno;
+        jpc_tsfbnode_t *curnode;
+        jpc_tsfbnode_t *prevnode;
+        int childno;
+        if (!(tsfb = jpc_tsfb_create())) {
+                return 0;
+        }
+        prevnode = 0;
+        for (dlvlno = 0; dlvlno < numdlvls; ++dlvlno) {
+                if (!(curnode = jpc_tsfbnode_create())) {
+                        jpc_tsfb_destroy(tsfb);
+                        return 0;
+                }
+                if (prevnode) {
+                        prevnode->children[0] = curnode;
+                        ++prevnode->numchildren;
+                        curnode->parent = prevnode;
+                } else {
+                        tsfb->root = curnode;
+                        curnode->parent = 0;
+                }
+                if (hqmfb) {
+                        curnode->numhchans = jpc_qmfb1d_getnumchans(hqmfb);
+                        if (!(curnode->hqmfb = jpc_qmfb1d_copy(hqmfb))) {
+                                jpc_tsfb_destroy(tsfb);
+                                return 0;
+                        }
+                } else {
+                        curnode->hqmfb = 0;
+                        curnode->numhchans = 1;
+                }
+                if (vqmfb) {
+                        curnode->numvchans = jpc_qmfb1d_getnumchans(vqmfb);
+                        if (!(curnode->vqmfb = jpc_qmfb1d_copy(vqmfb))) {
+                                jpc_tsfb_destroy(tsfb);
+                                return 0;
+                        }
+                } else {
+                        curnode->vqmfb = 0;
+                        curnode->numvchans = 1;
+                }
+                curnode->maxchildren = curnode->numhchans * curnode->numvchans;
+                for (childno = 0; childno < curnode->maxchildren;
+                  ++childno) {
+                        curnode->children[childno] = 0;
+                }
+                prevnode = curnode;
+        }
+        return tsfb;
 }
 
 static jpc_tsfb_t *jpc_tsfb_create()
 {
-	jpc_tsfb_t *tsfb;
-	if (!(tsfb = jas_malloc(sizeof(jpc_tsfb_t)))) {
-		return 0;
-	}
-	tsfb->root = 0;
-	return tsfb;
+        jpc_tsfb_t *tsfb;
+        if (!(tsfb = jas_malloc(sizeof(jpc_tsfb_t)))) {
+                return 0;
+        }
+        tsfb->root = 0;
+        return tsfb;
 }
 
 void jpc_tsfb_destroy(jpc_tsfb_t *tsfb)
 {
-	if (tsfb->root) {
-		jpc_tsfbnode_destroy(tsfb->root);
-	}
-	jas_free(tsfb);
+        if (tsfb->root) {
+                jpc_tsfbnode_destroy(tsfb->root);
+        }
+        jas_free(tsfb);
 }
 
 /******************************************************************************\
@@ -234,83 +234,83 @@ void jpc_tsfb_destroy(jpc_tsfb_t *tsfb)
 
 void jpc_tsfb_analyze(jpc_tsfb_t *tsfb, int flags, jas_seq2d_t *x)
 {
-	if (tsfb->root) {
-		jpc_tsfbnode_analyze(tsfb->root, flags, x);
-	}
+        if (tsfb->root) {
+                jpc_tsfbnode_analyze(tsfb->root, flags, x);
+        }
 }
 
 static void jpc_tsfbnode_analyze(jpc_tsfbnode_t *node, int flags, jas_seq2d_t *x)
 {
-	jpc_tsfbnodeband_t nodebands[JPC_TSFB_MAXBANDSPERNODE];
-	int numbands;
-	jas_seq2d_t *y;
-	int bandno;
-	jpc_tsfbnodeband_t *band;
-
-	if (node->vqmfb) {
-		jpc_qmfb1d_analyze(node->vqmfb, flags | JPC_QMFB1D_VERT, x);
-	}
-	if (node->hqmfb) {
-		jpc_qmfb1d_analyze(node->hqmfb, flags, x);
-	}
-	if (node->numchildren > 0) {
-		qmfb2d_getbands(node->hqmfb, node->vqmfb, jas_seq2d_xstart(x),
-		  jas_seq2d_ystart(x), jas_seq2d_xend(x), jas_seq2d_yend(x),
-		  JPC_TSFB_MAXBANDSPERNODE, &numbands, nodebands);
-		y = jas_seq2d_create(0, 0, 0, 0);
-		assert(y);
-		for (bandno = 0, band = nodebands; bandno < numbands; ++bandno, ++band) {
-			if (node->children[bandno]) {
-				if (band->xstart != band->xend && band->ystart != band->yend) {
-					jas_seq2d_bindsub(y, x, band->locxstart, band->locystart,
-					  band->locxend, band->locyend);
-					jas_seq2d_setshift(y, band->xstart, band->ystart);
-					jpc_tsfbnode_analyze(node->children[bandno], flags, y);
-				}
-			}
-		}
-		jas_matrix_destroy(y);
-	}
+        jpc_tsfbnodeband_t nodebands[JPC_TSFB_MAXBANDSPERNODE];
+        int numbands;
+        jas_seq2d_t *y;
+        int bandno;
+        jpc_tsfbnodeband_t *band;
+
+        if (node->vqmfb) {
+                jpc_qmfb1d_analyze(node->vqmfb, flags | JPC_QMFB1D_VERT, x);
+        }
+        if (node->hqmfb) {
+                jpc_qmfb1d_analyze(node->hqmfb, flags, x);
+        }
+        if (node->numchildren > 0) {
+                qmfb2d_getbands(node->hqmfb, node->vqmfb, jas_seq2d_xstart(x),
+                  jas_seq2d_ystart(x), jas_seq2d_xend(x), jas_seq2d_yend(x),
+                  JPC_TSFB_MAXBANDSPERNODE, &numbands, nodebands);
+                y = jas_seq2d_create(0, 0, 0, 0);
+                assert(y);
+                for (bandno = 0, band = nodebands; bandno < numbands; ++bandno, ++band) {
+                        if (node->children[bandno]) {
+                                if (band->xstart != band->xend && band->ystart != band->yend) {
+                                        jas_seq2d_bindsub(y, x, band->locxstart, band->locystart,
+                                          band->locxend, band->locyend);
+                                        jas_seq2d_setshift(y, band->xstart, band->ystart);
+                                        jpc_tsfbnode_analyze(node->children[bandno], flags, y);
+                                }
+                        }
+                }
+                jas_matrix_destroy(y);
+        }
 }
 
 void jpc_tsfb_synthesize(jpc_tsfb_t *tsfb, int flags, jas_seq2d_t *x)
 {
-	if (tsfb->root) {
-		jpc_tsfbnode_synthesize(tsfb->root, flags, x);
-	}
+        if (tsfb->root) {
+                jpc_tsfbnode_synthesize(tsfb->root, flags, x);
+        }
 }
 
 static void jpc_tsfbnode_synthesize(jpc_tsfbnode_t *node, int flags, jas_seq2d_t *x)
 {
-	jpc_tsfbnodeband_t nodebands[JPC_TSFB_MAXBANDSPERNODE];
-	int numbands;
-	jas_seq2d_t *y;
-	int bandno;
-	jpc_tsfbnodeband_t *band;
-
-	if (node->numchildren > 0) {
-		qmfb2d_getbands(node->hqmfb, node->vqmfb, jas_seq2d_xstart(x),
-		  jas_seq2d_ystart(x), jas_seq2d_xend(x), jas_seq2d_yend(x),
-		  JPC_TSFB_MAXBANDSPERNODE, &numbands, nodebands);
-		y = jas_seq2d_create(0, 0, 0, 0);
-		for (bandno = 0, band = nodebands; bandno < numbands; ++bandno, ++band) {
-			if (node->children[bandno]) {
-				if (band->xstart != band->xend && band->ystart != band->yend) {
-					jas_seq2d_bindsub(y, x, band->locxstart, band->locystart,
-					  band->locxend, band->locyend);
-					jas_seq2d_setshift(y, band->xstart, band->ystart);
-					jpc_tsfbnode_synthesize(node->children[bandno], flags, y);
-				}
-			}
-		}
-		jas_seq2d_destroy(y);
-	}
-	if (node->hqmfb) {
-		jpc_qmfb1d_synthesize(node->hqmfb, flags, x);
-	}
-	if (node->vqmfb) {
-		jpc_qmfb1d_synthesize(node->vqmfb, flags | JPC_QMFB1D_VERT, x);
-	}
+        jpc_tsfbnodeband_t nodebands[JPC_TSFB_MAXBANDSPERNODE];
+        int numbands;
+        jas_seq2d_t *y;
+        int bandno;
+        jpc_tsfbnodeband_t *band;
+
+        if (node->numchildren > 0) {
+                qmfb2d_getbands(node->hqmfb, node->vqmfb, jas_seq2d_xstart(x),
+                  jas_seq2d_ystart(x), jas_seq2d_xend(x), jas_seq2d_yend(x),
+                  JPC_TSFB_MAXBANDSPERNODE, &numbands, nodebands);
+                y = jas_seq2d_create(0, 0, 0, 0);
+                for (bandno = 0, band = nodebands; bandno < numbands; ++bandno, ++band) {
+                        if (node->children[bandno]) {
+                                if (band->xstart != band->xend && band->ystart != band->yend) {
+                                        jas_seq2d_bindsub(y, x, band->locxstart, band->locystart,
+                                          band->locxend, band->locyend);
+                                        jas_seq2d_setshift(y, band->xstart, band->ystart);
+                                        jpc_tsfbnode_synthesize(node->children[bandno], flags, y);
+                                }
+                        }
+                }
+                jas_seq2d_destroy(y);
+        }
+        if (node->hqmfb) {
+                jpc_qmfb1d_synthesize(node->hqmfb, flags, x);
+        }
+        if (node->vqmfb) {
+                jpc_qmfb1d_synthesize(node->vqmfb, flags | JPC_QMFB1D_VERT, x);
+        }
 }
 
 /******************************************************************************\
@@ -321,114 +321,114 @@ static void jpc_tsfbnode_synthesize(jpc_tsfbnode_t *node, int flags, jas_seq2d_t
 int jpc_tsfb_getbands(jpc_tsfb_t *tsfb, uint_fast32_t xstart, uint_fast32_t ystart,
   uint_fast32_t xend, uint_fast32_t yend, jpc_tsfb_band_t *bands)
 {
-	jpc_tsfb_band_t *savbands;
-	savbands = bands;
-	if (!tsfb->root) {
-		bands[0].xstart = xstart;
-		bands[0].ystart = ystart;
-		bands[0].xend = xend;
-		bands[0].yend = yend;
-		bands[0].locxstart = xstart;
-		bands[0].locystart = ystart;
-		bands[0].locxend = xend;
-		bands[0].locyend = yend;
-		bands[0].orient = JPC_TSFB_LL;
-		bands[0].synenergywt = JPC_FIX_ONE;
-		++bands;
-	} else {
-		jpc_tsfbnode_getbandstree(tsfb->root, xstart, ystart,
-		  xstart, ystart, xend, yend, &bands);
-	}
-	return bands - savbands;
+        jpc_tsfb_band_t *savbands;
+        savbands = bands;
+        if (!tsfb->root) {
+                bands[0].xstart = xstart;
+                bands[0].ystart = ystart;
+                bands[0].xend = xend;
+                bands[0].yend = yend;
+                bands[0].locxstart = xstart;
+                bands[0].locystart = ystart;
+                bands[0].locxend = xend;
+                bands[0].locyend = yend;
+                bands[0].orient = JPC_TSFB_LL;
+                bands[0].synenergywt = JPC_FIX_ONE;
+                ++bands;
+        } else {
+                jpc_tsfbnode_getbandstree(tsfb->root, xstart, ystart,
+                  xstart, ystart, xend, yend, &bands);
+        }
+        return bands - savbands;
 }
 
 static void jpc_tsfbnode_getbandstree(jpc_tsfbnode_t *node, uint_fast32_t posxstart,
   uint_fast32_t posystart, uint_fast32_t xstart, uint_fast32_t ystart,
   uint_fast32_t xend, uint_fast32_t yend, jpc_tsfb_band_t **bands)
 {
-	jpc_tsfbnodeband_t nodebands[JPC_TSFB_MAXBANDSPERNODE];
-	jpc_tsfbnodeband_t *nodeband;
-	int nodebandno;
-	int numnodebands;
-	jpc_tsfb_band_t *band;
-	jas_seq_t *hfilter;
-	jas_seq_t *vfilter;
-
-	qmfb2d_getbands(node->hqmfb, node->vqmfb, xstart, ystart, xend, yend,
-	  JPC_TSFB_MAXBANDSPERNODE, &numnodebands, nodebands);
-	if (node->numchildren > 0) {
-		for (nodebandno = 0, nodeband = nodebands;
-		  nodebandno < numnodebands; ++nodebandno, ++nodeband) {
-			if (node->children[nodebandno]) {
-				jpc_tsfbnode_getbandstree(node->children[
-				  nodebandno], posxstart +
-				  nodeband->locxstart - xstart, posystart +
-				  nodeband->locystart - ystart, nodeband->xstart,
-				  nodeband->ystart, nodeband->xend,
-				  nodeband->yend, bands);
-
-			}
-		}
-	}
+        jpc_tsfbnodeband_t nodebands[JPC_TSFB_MAXBANDSPERNODE];
+        jpc_tsfbnodeband_t *nodeband;
+        int nodebandno;
+        int numnodebands;
+        jpc_tsfb_band_t *band;
+        jas_seq_t *hfilter;
+        jas_seq_t *vfilter;
+
+        qmfb2d_getbands(node->hqmfb, node->vqmfb, xstart, ystart, xend, yend,
+          JPC_TSFB_MAXBANDSPERNODE, &numnodebands, nodebands);
+        if (node->numchildren > 0) {
+                for (nodebandno = 0, nodeband = nodebands;
+                  nodebandno < numnodebands; ++nodebandno, ++nodeband) {
+                        if (node->children[nodebandno]) {
+                                jpc_tsfbnode_getbandstree(node->children[
+                                  nodebandno], posxstart +
+                                  nodeband->locxstart - xstart, posystart +
+                                  nodeband->locystart - ystart, nodeband->xstart,
+                                  nodeband->ystart, nodeband->xend,
+                                  nodeband->yend, bands);
+
+                        }
+                }
+        }
 assert(numnodebands == 4 || numnodebands == 3);
-	for (nodebandno = 0, nodeband = nodebands; nodebandno < numnodebands;
-	  ++nodebandno, ++nodeband) {
-		if (!node->children[nodebandno]) {
-			band = *bands;
-			band->xstart = nodeband->xstart;
-			band->ystart = nodeband->ystart;
-			band->xend = nodeband->xend;
-			band->yend = nodeband->yend;
-			band->locxstart = posxstart + nodeband->locxstart -
-			  xstart;
-			band->locystart = posystart + nodeband->locystart -
-			  ystart;
-			band->locxend = band->locxstart + band->xend -
-			  band->xstart;
-			band->locyend = band->locystart + band->yend -
-			  band->ystart;
-			if (numnodebands == 4) {
-				switch (nodebandno) {
-				case 0:
-					band->orient = JPC_TSFB_LL;
-					break;
-				case 1:
-					band->orient = JPC_TSFB_HL;
-					break;
-				case 2:
-					band->orient = JPC_TSFB_LH;
-					break;
-				case 3:
-					band->orient = JPC_TSFB_HH;
-					break;
-				default:
-					abort();
-					break;
-				}
-			} else {
-				switch (nodebandno) {
-				case 0:
-					band->orient = JPC_TSFB_HL;
-					break;
-				case 1:
-					band->orient = JPC_TSFB_LH;
-					break;
-				case 2:
-					band->orient = JPC_TSFB_HH;
-					break;
-				default:
-					abort();
-					break;
-				}
-			}
-			jpc_tsfbnode_getequivfilters(node, nodebandno, band->xend - band->xstart, band->yend - band->ystart, &hfilter, &vfilter);
-			band->synenergywt = jpc_fix_mul(jpc_seq_norm(hfilter),
-			  jpc_seq_norm(vfilter));
-			jas_seq_destroy(hfilter);
-			jas_seq_destroy(vfilter);
-			++(*bands);
-		}
-	}
+        for (nodebandno = 0, nodeband = nodebands; nodebandno < numnodebands;
+          ++nodebandno, ++nodeband) {
+                if (!node->children[nodebandno]) {
+                        band = *bands;
+                        band->xstart = nodeband->xstart;
+                        band->ystart = nodeband->ystart;
+                        band->xend = nodeband->xend;
+                        band->yend = nodeband->yend;
+                        band->locxstart = posxstart + nodeband->locxstart -
+                          xstart;
+                        band->locystart = posystart + nodeband->locystart -
+                          ystart;
+                        band->locxend = band->locxstart + band->xend -
+                          band->xstart;
+                        band->locyend = band->locystart + band->yend -
+                          band->ystart;
+                        if (numnodebands == 4) {
+                                switch (nodebandno) {
+                                case 0:
+                                        band->orient = JPC_TSFB_LL;
+                                        break;
+                                case 1:
+                                        band->orient = JPC_TSFB_HL;
+                                        break;
+                                case 2:
+                                        band->orient = JPC_TSFB_LH;
+                                        break;
+                                case 3:
+                                        band->orient = JPC_TSFB_HH;
+                                        break;
+                                default:
+                                        abort();
+                                        break;
+                                }
+                        } else {
+                                switch (nodebandno) {
+                                case 0:
+                                        band->orient = JPC_TSFB_HL;
+                                        break;
+                                case 1:
+                                        band->orient = JPC_TSFB_LH;
+                                        break;
+                                case 2:
+                                        band->orient = JPC_TSFB_HH;
+                                        break;
+                                default:
+                                        abort();
+                                        break;
+                                }
+                        }
+                        jpc_tsfbnode_getequivfilters(node, nodebandno, band->xend - band->xstart, band->yend - band->ystart, &hfilter, &vfilter);
+                        band->synenergywt = jpc_fix_mul(jpc_seq_norm(hfilter),
+                          jpc_seq_norm(vfilter));
+                        jas_seq_destroy(hfilter);
+                        jas_seq_destroy(vfilter);
+                        ++(*bands);
+                }
+        }
 }
 
 /******************************************************************************\
@@ -437,37 +437,37 @@ assert(numnodebands == 4 || numnodebands == 3);
 
 static jpc_tsfbnode_t *jpc_tsfbnode_create()
 {
-	jpc_tsfbnode_t *node;
-	if (!(node = jas_malloc(sizeof(jpc_tsfbnode_t)))) {
-		return 0;
-	}
-	node->numhchans = 0;
-	node->numvchans = 0;
-	node->numchildren = 0;
-	node->maxchildren = 0;
-	node->hqmfb = 0;
-	node->vqmfb = 0;
-	node->parent = 0;
-	return node;
+        jpc_tsfbnode_t *node;
+        if (!(node = jas_malloc(sizeof(jpc_tsfbnode_t)))) {
+                return 0;
+        }
+        node->numhchans = 0;
+        node->numvchans = 0;
+        node->numchildren = 0;
+        node->maxchildren = 0;
+        node->hqmfb = 0;
+        node->vqmfb = 0;
+        node->parent = 0;
+        return node;
 }
 
 static void jpc_tsfbnode_destroy(jpc_tsfbnode_t *node)
 {
-	jpc_tsfbnode_t **child;
-	int childno;
-	for (childno = 0, child = node->children; childno < node->maxchildren;
-	  ++childno, ++child) {
-		if (*child) {
-			jpc_tsfbnode_destroy(*child);
-		}
-	}
-	if (node->hqmfb) {
-		jpc_qmfb1d_destroy(node->hqmfb);
-	}
-	if (node->vqmfb) {
-		jpc_qmfb1d_destroy(node->vqmfb);
-	}
-	jas_free(node);
+        jpc_tsfbnode_t **child;
+        int childno;
+        for (childno = 0, child = node->children; childno < node->maxchildren;
+          ++childno, ++child) {
+                if (*child) {
+                        jpc_tsfbnode_destroy(*child);
+                }
+        }
+        if (node->hqmfb) {
+                jpc_qmfb1d_destroy(node->hqmfb);
+        }
+        if (node->vqmfb) {
+                jpc_qmfb1d_destroy(node->vqmfb);
+        }
+        jas_free(node);
 }
 
 
@@ -481,182 +481,182 @@ static void qmfb2d_getbands(jpc_qmfb1d_t *hqmfb, jpc_qmfb1d_t *vqmfb,
   uint_fast32_t xstart, uint_fast32_t ystart, uint_fast32_t xend,
   uint_fast32_t yend, int maxbands, int *numbandsptr, jpc_tsfbnodeband_t *bands)
 {
-	jpc_qmfb1dband_t hbands[JPC_QMFB1D_MAXCHANS];
-	jpc_qmfb1dband_t vbands[JPC_QMFB1D_MAXCHANS];
-	int numhbands;
-	int numvbands;
-	int numbands;
-	int bandno;
-	int hbandno;
-	int vbandno;
-	jpc_tsfbnodeband_t *band;
-
-	if (hqmfb) {
-		jpc_qmfb1d_getbands(hqmfb, 0, xstart, ystart, xend, yend,
-		  JPC_QMFB1D_MAXCHANS, &numhbands, hbands);
-	} else {
-		numhbands = 1;
-		hbands[0].start = xstart;
-		hbands[0].end = xend;
-		hbands[0].locstart = xstart;
-		hbands[0].locend = xend;
-	}
-	if (vqmfb) {
-		jpc_qmfb1d_getbands(vqmfb, JPC_QMFB1D_VERT, xstart, ystart, xend,
-		  yend, JPC_QMFB1D_MAXCHANS, &numvbands, vbands);
-	} else {
-		numvbands = 1;
-		vbands[0].start = ystart;
-		vbands[0].end = yend;
-		vbands[0].locstart = ystart;
-		vbands[0].locend = yend;
-	}
-	numbands = numhbands * numvbands;
-	*numbandsptr = numbands;
-	for (bandno = 0, band = bands; bandno < numbands; ++bandno, ++band) {
-		hbandno = bandno % numhbands;
-		vbandno = bandno / numhbands;
-		band->xstart = hbands[hbandno].start;
-		band->ystart = vbands[vbandno].start;
-		band->xend = hbands[hbandno].end;
-		band->yend = vbands[vbandno].end;
-		band->locxstart = hbands[hbandno].locstart;
-		band->locystart = vbands[vbandno].locstart;
-		band->locxend = hbands[hbandno].locend;
-		band->locyend = vbands[vbandno].locend;
-		assert(band->xstart <= band->xend &&
-		  band->ystart <= band->yend);
-		if (band->xstart == band->xend) {
-			band->yend = band->ystart;
-			band->locyend = band->locystart;
-		} else if (band->ystart == band->yend) {
-			band->xend = band->xstart;
-			band->locxend = band->locxstart;
-		}
-	}
+        jpc_qmfb1dband_t hbands[JPC_QMFB1D_MAXCHANS];
+        jpc_qmfb1dband_t vbands[JPC_QMFB1D_MAXCHANS];
+        int numhbands;
+        int numvbands;
+        int numbands;
+        int bandno;
+        int hbandno;
+        int vbandno;
+        jpc_tsfbnodeband_t *band;
+
+        if (hqmfb) {
+                jpc_qmfb1d_getbands(hqmfb, 0, xstart, ystart, xend, yend,
+                  JPC_QMFB1D_MAXCHANS, &numhbands, hbands);
+        } else {
+                numhbands = 1;
+                hbands[0].start = xstart;
+                hbands[0].end = xend;
+                hbands[0].locstart = xstart;
+                hbands[0].locend = xend;
+        }
+        if (vqmfb) {
+                jpc_qmfb1d_getbands(vqmfb, JPC_QMFB1D_VERT, xstart, ystart, xend,
+                  yend, JPC_QMFB1D_MAXCHANS, &numvbands, vbands);
+        } else {
+                numvbands = 1;
+                vbands[0].start = ystart;
+                vbands[0].end = yend;
+                vbands[0].locstart = ystart;
+                vbands[0].locend = yend;
+        }
+        numbands = numhbands * numvbands;
+        *numbandsptr = numbands;
+        for (bandno = 0, band = bands; bandno < numbands; ++bandno, ++band) {
+                hbandno = bandno % numhbands;
+                vbandno = bandno / numhbands;
+                band->xstart = hbands[hbandno].start;
+                band->ystart = vbands[vbandno].start;
+                band->xend = hbands[hbandno].end;
+                band->yend = vbands[vbandno].end;
+                band->locxstart = hbands[hbandno].locstart;
+                band->locystart = vbands[vbandno].locstart;
+                band->locxend = hbands[hbandno].locend;
+                band->locyend = vbands[vbandno].locend;
+                assert(band->xstart <= band->xend &&
+                  band->ystart <= band->yend);
+                if (band->xstart == band->xend) {
+                        band->yend = band->ystart;
+                        band->locyend = band->locystart;
+                } else if (band->ystart == band->yend) {
+                        band->xend = band->xstart;
+                        band->locxend = band->locxstart;
+                }
+        }
 }
 
 static int jpc_tsfbnode_getequivfilters(jpc_tsfbnode_t *tsfbnode, int cldind,
   int width, int height, jas_seq_t **hfilter, jas_seq_t **vfilter)
 {
-	jas_seq_t *hseq;
-	jas_seq_t *vseq;
-	jpc_tsfbnode_t *node;
-	jas_seq2d_t *hfilters[JPC_QMFB1D_MAXCHANS];
-	jas_seq2d_t *vfilters[JPC_QMFB1D_MAXCHANS];
-	int numhchans;
-	int numvchans;
-	jas_seq_t *tmpseq;
-
-	hseq = 0;
-	vseq = 0;
-
-	if (!(hseq = jas_seq_create(0, 1))) {
-		goto error;
-	}
-	jas_seq_set(hseq, 0, jpc_inttofix(1));
-	if (!(vseq = jas_seq_create(0, 1))) {
-		goto error;
-	}
-	jas_seq_set(vseq, 0, jpc_inttofix(1));
-
-	node = tsfbnode;
-	while (node) {
-		if (node->hqmfb) {
-			numhchans = jpc_qmfb1d_getnumchans(node->hqmfb);
-			if (jpc_qmfb1d_getsynfilters(node->hqmfb, width, hfilters)) {
-				goto error;
-			}
-			if (!(tmpseq = jpc_seq_upsample(hseq, numhchans))) {
-				goto error;
-			}
-			jas_seq_destroy(hseq);
-			hseq = tmpseq;
-			if (!(tmpseq = jpc_seq_conv(hseq, hfilters[bandnotohind(node, cldind)]))) {
-				goto error;
-			}
-			jas_seq_destroy(hfilters[0]);
-			jas_seq_destroy(hfilters[1]);
-			jas_seq_destroy(hseq);
-			hseq = tmpseq;
-		}
-		if (node->vqmfb) {
-			numvchans = jpc_qmfb1d_getnumchans(node->vqmfb);
-			if (jpc_qmfb1d_getsynfilters(node->vqmfb, height, vfilters)) {
-				abort();
-			}
-			if (!(tmpseq = jpc_seq_upsample(vseq, numvchans))) {
-				goto error;
-			}
-			jas_seq_destroy(vseq);
-			vseq = tmpseq;
-			if (!(tmpseq = jpc_seq_conv(vseq, vfilters[bandnotovind(node, cldind)]))) {
-				goto error;
-			}
-			jas_seq_destroy(vfilters[0]);
-			jas_seq_destroy(vfilters[1]);
-			jas_seq_destroy(vseq);
-			vseq = tmpseq;
-		}
-		if (node->parent) {
-			cldind = jpc_tsfbnode_findchild(node->parent, node);
-		}
-		node = node->parent;
-	}
-
-	*hfilter = hseq;
-	*vfilter = vseq;
-
-	return 0;
+        jas_seq_t *hseq;
+        jas_seq_t *vseq;
+        jpc_tsfbnode_t *node;
+        jas_seq2d_t *hfilters[JPC_QMFB1D_MAXCHANS];
+        jas_seq2d_t *vfilters[JPC_QMFB1D_MAXCHANS];
+        int numhchans;
+        int numvchans;
+        jas_seq_t *tmpseq;
+
+        hseq = 0;
+        vseq = 0;
+
+        if (!(hseq = jas_seq_create(0, 1))) {
+                goto error;
+        }
+        jas_seq_set(hseq, 0, jpc_inttofix(1));
+        if (!(vseq = jas_seq_create(0, 1))) {
+                goto error;
+        }
+        jas_seq_set(vseq, 0, jpc_inttofix(1));
+
+        node = tsfbnode;
+        while (node) {
+                if (node->hqmfb) {
+                        numhchans = jpc_qmfb1d_getnumchans(node->hqmfb);
+                        if (jpc_qmfb1d_getsynfilters(node->hqmfb, width, hfilters)) {
+                                goto error;
+                        }
+                        if (!(tmpseq = jpc_seq_upsample(hseq, numhchans))) {
+                                goto error;
+                        }
+                        jas_seq_destroy(hseq);
+                        hseq = tmpseq;
+                        if (!(tmpseq = jpc_seq_conv(hseq, hfilters[bandnotohind(node, cldind)]))) {
+                                goto error;
+                        }
+                        jas_seq_destroy(hfilters[0]);
+                        jas_seq_destroy(hfilters[1]);
+                        jas_seq_destroy(hseq);
+                        hseq = tmpseq;
+                }
+                if (node->vqmfb) {
+                        numvchans = jpc_qmfb1d_getnumchans(node->vqmfb);
+                        if (jpc_qmfb1d_getsynfilters(node->vqmfb, height, vfilters)) {
+                                abort();
+                        }
+                        if (!(tmpseq = jpc_seq_upsample(vseq, numvchans))) {
+                                goto error;
+                        }
+                        jas_seq_destroy(vseq);
+                        vseq = tmpseq;
+                        if (!(tmpseq = jpc_seq_conv(vseq, vfilters[bandnotovind(node, cldind)]))) {
+                                goto error;
+                        }
+                        jas_seq_destroy(vfilters[0]);
+                        jas_seq_destroy(vfilters[1]);
+                        jas_seq_destroy(vseq);
+                        vseq = tmpseq;
+                }
+                if (node->parent) {
+                        cldind = jpc_tsfbnode_findchild(node->parent, node);
+                }
+                node = node->parent;
+        }
+
+        *hfilter = hseq;
+        *vfilter = vseq;
+
+        return 0;
 
 error:
-	if (hseq) {
-		jas_seq_destroy(hseq);
-	}
-	if (vseq) {
-		jas_seq_destroy(vseq);
-	}
-	return -1;
+        if (hseq) {
+                jas_seq_destroy(hseq);
+        }
+        if (vseq) {
+                jas_seq_destroy(vseq);
+        }
+        return -1;
 
 }
 
 static int jpc_tsfbnode_findchild(jpc_tsfbnode_t *parnode, jpc_tsfbnode_t *cldnode)
 {
-	int i;
-
-	for (i = 0; i < parnode->maxchildren; i++) {
-		if (parnode->children[i] == cldnode)
-			return i;
-	}
-	assert(0);
-	return -1;
+        int i;
+
+        for (i = 0; i < parnode->maxchildren; i++) {
+                if (parnode->children[i] == cldnode)
+                        return i;
+        }
+        assert(0);
+        return -1;
 }
 
 jpc_tsfb_t *jpc_cod_gettsfb(int qmfbid, int numlevels)
 {
-	jpc_tsfb_t *tsfb;
-
-	switch (qmfbid) {
-	case JPC_COX_RFT:
-		qmfbid = JPC_QMFB1D_FT;
-		break;
-	case JPC_COX_INS:
-		qmfbid = JPC_QMFB1D_NS;
-		break;
-	default:
-		assert(0);
-		qmfbid = 10;
-		break;
-	}
+        jpc_tsfb_t *tsfb;
+
+        switch (qmfbid) {
+        case JPC_COX_RFT:
+                qmfbid = JPC_QMFB1D_FT;
+                break;
+        case JPC_COX_INS:
+                qmfbid = JPC_QMFB1D_NS;
+                break;
+        default:
+                assert(0);
+                qmfbid = 10;
+                break;
+        }
 
 {
-	jpc_qmfb1d_t *hqmfb;
-	hqmfb = jpc_qmfb1d_make(qmfbid);
-	assert(hqmfb);
-	tsfb = jpc_tsfb_wavelet(hqmfb, hqmfb, numlevels);
-	assert(tsfb);
-	jpc_qmfb1d_destroy(hqmfb);
+        jpc_qmfb1d_t *hqmfb;
+        hqmfb = jpc_qmfb1d_make(qmfbid);
+        assert(hqmfb);
+        tsfb = jpc_tsfb_wavelet(hqmfb, hqmfb, numlevels);
+        assert(tsfb);
+        jpc_qmfb1d_destroy(hqmfb);
 }
 
-	return tsfb;
+        return tsfb;
 }
diff --git a/converter/other/jpeg2000/libjasper/jpc/jpc_tsfb.h b/converter/other/jpeg2000/libjasper/jpc/jpc_tsfb.h
index 8670c22e..3558cadb 100644
--- a/converter/other/jpeg2000/libjasper/jpc/jpc_tsfb.h
+++ b/converter/other/jpeg2000/libjasper/jpc/jpc_tsfb.h
@@ -6,14 +6,14 @@
  */
 
 /* __START_OF_JASPER_LICENSE__
- * 
+ *
  * JasPer Software License
- * 
+ *
  * IMAGE POWER JPEG-2000 PUBLIC LICENSE
  * ************************************
- * 
+ *
  * GRANT:
- * 
+ *
  * Permission is hereby granted, free of charge, to any person (the "User")
  * obtaining a copy of this software and associated documentation, to deal
  * in the JasPer Software without restriction, including without limitation
@@ -21,22 +21,22 @@
  * and/or sell copies of the JasPer Software (in source and binary forms),
  * and to permit persons to whom the JasPer Software is furnished to do so,
  * provided further that the License Conditions below are met.
- * 
+ *
  * License Conditions
  * ******************
- * 
+ *
  * A.  Redistributions of source code must retain the above copyright notice,
  * and this list of conditions, and the following disclaimer.
- * 
+ *
  * B.  Redistributions in binary form must reproduce the above copyright
  * notice, and this list of conditions, and the following disclaimer in
  * the documentation and/or other materials provided with the distribution.
- * 
+ *
  * C.  Neither the name of Image Power, Inc. nor any other contributor
  * (including, but not limited to, the University of British Columbia and
  * Michael David Adams) may be used to endorse or promote products derived
  * from this software without specific prior written permission.
- * 
+ *
  * D.  User agrees that it shall not commence any action against Image Power,
  * Inc., the University of British Columbia, Michael David Adams, or any
  * other contributors (collectively "Licensors") for infringement of any
@@ -56,17 +56,17 @@
  * trade dress, or service mark rights); and (v) divisions, continuations,
  * renewals, reissues and extensions of the foregoing (as and to the extent
  * applicable) now existing, hereafter filed, issued or acquired.
- * 
+ *
  * E.  If User commences an infringement action against any Licensor(s) then
  * such Licensor(s) shall have the right to terminate User's license and
  * all sublicenses that have been granted hereunder by User to other parties.
- * 
+ *
  * F.  This software is for use only in hardware or software products that
  * are compliant with ISO/IEC 15444-1 (i.e., JPEG-2000 Part 1).  No license
  * or right to this Software is granted for products that do not comply
  * with ISO/IEC 15444-1.  The JPEG-2000 Part 1 standard can be purchased
  * from the ISO.
- * 
+ *
  * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS LICENSE.
  * NO USE OF THE JASPER SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER
  * THIS DISCLAIMER.  THE JASPER SOFTWARE IS PROVIDED BY THE LICENSORS AND
@@ -106,7 +106,7 @@
  * TECHNOLOGY OR PRODUCTS FOR HIGH RISK ACTIVITIES AND WILL ENSURE THAT ITS
  * CUSTOMERS AND END-USERS OF ITS PRODUCTS ARE PROVIDED WITH A COPY OF THE
  * NOTICE SPECIFIED IN THIS SECTION.
- * 
+ *
  * __END_OF_JASPER_LICENSE__
  */
 
@@ -132,19 +132,19 @@
 * Constants.
 \******************************************************************************/
 
-#define	JPC_TSFB_MAXBANDS	(JPC_TSFB_MAXDEPTH * 3 + 1)
-#define	JPC_TSFB_MAXDEPTH	32
-#define	JPC_TSFB_RITIMODE	JPC_QMFB1D_RITIMODE
+#define JPC_TSFB_MAXBANDS       (JPC_TSFB_MAXDEPTH * 3 + 1)
+#define JPC_TSFB_MAXDEPTH       32
+#define JPC_TSFB_RITIMODE       JPC_QMFB1D_RITIMODE
 
-#define	JPC_TSFB_MAXBANDSPERNODE	(JPC_QMFB1D_MAXCHANS * JPC_QMFB1D_MAXCHANS)
+#define JPC_TSFB_MAXBANDSPERNODE        (JPC_QMFB1D_MAXCHANS * JPC_QMFB1D_MAXCHANS)
 
-#define	JPC_TSFB_PRUNEVERT	0x01
-#define	JPC_TSFB_PRUNEHORZ	0x02
+#define JPC_TSFB_PRUNEVERT      0x01
+#define JPC_TSFB_PRUNEHORZ      0x02
 
-#define JPC_TSFB_LL	0
-#define JPC_TSFB_LH	1
-#define JPC_TSFB_HL	2
-#define JPC_TSFB_HH	3
+#define JPC_TSFB_LL     0
+#define JPC_TSFB_LH     1
+#define JPC_TSFB_HL     2
+#define JPC_TSFB_HH     3
 
 /******************************************************************************\
 * Types.
@@ -152,45 +152,45 @@
 
 typedef struct {
 
-	int xstart;
-	int ystart;
-	int xend;
-	int yend;
-	int locxstart;
-	int locystart;
-	int locxend;
-	int locyend;
+        int xstart;
+        int ystart;
+        int xend;
+        int yend;
+        int locxstart;
+        int locystart;
+        int locxend;
+        int locyend;
 
 } jpc_tsfbnodeband_t;
 
 typedef struct jpc_tsfbnode_s {
 
-	int numhchans;
-	int numvchans;
-	jpc_qmfb1d_t *hqmfb;
-	jpc_qmfb1d_t *vqmfb;
-	int maxchildren;
-	int numchildren;
-	struct jpc_tsfbnode_s *children[JPC_TSFB_MAXBANDSPERNODE];
-	struct jpc_tsfbnode_s *parent;
+        int numhchans;
+        int numvchans;
+        jpc_qmfb1d_t *hqmfb;
+        jpc_qmfb1d_t *vqmfb;
+        int maxchildren;
+        int numchildren;
+        struct jpc_tsfbnode_s *children[JPC_TSFB_MAXBANDSPERNODE];
+        struct jpc_tsfbnode_s *parent;
 
 } jpc_tsfbnode_t;
 
 typedef struct {
-	jpc_tsfbnode_t *root;
+        jpc_tsfbnode_t *root;
 } jpc_tsfb_t;
 
 typedef struct {
-	int xstart;
-	int ystart;
-	int xend;
-	int yend;
-	int orient;
-	int locxstart;
-	int locystart;
-	int locxend;
-	int locyend;
-	jpc_fix_t synenergywt;
+        int xstart;
+        int ystart;
+        int xend;
+        int yend;
+        int orient;
+        int locxstart;
+        int locystart;
+        int locxend;
+        int locyend;
+        jpc_fix_t synenergywt;
 } jpc_tsfb_band_t;
 
 /******************************************************************************\
diff --git a/converter/other/jpeg2000/libjasper/jpc/jpc_util.c b/converter/other/jpeg2000/libjasper/jpc/jpc_util.c
index fede2bef..12a41c3f 100644
--- a/converter/other/jpeg2000/libjasper/jpc/jpc_util.c
+++ b/converter/other/jpeg2000/libjasper/jpc/jpc_util.c
@@ -114,9 +114,9 @@
  * $Id$
  */
 
-/******************************************************************************\
+/*****************************************************************************\
 * Includes
-\******************************************************************************/
+\*****************************************************************************/
 
 #include <assert.h>
 #include <stdio.h>
@@ -133,111 +133,136 @@
 #include "jpc_flt.h"
 #include "jpc_util.h"
 
-/******************************************************************************\
+/*****************************************************************************\
 * Miscellaneous Functions
-\******************************************************************************/
+\*****************************************************************************/
 
-int jpc_atoaf(const char *s, int *numvalues, double **values)
-{
-	static 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 ((cp = strtok(buf, delim))) {
-		++n;
-		while ((cp = strtok(0, delim))) {
-			if (cp[0] != '\0') {
-				++n;
-			}
-		}
-	}
-
-	if (n) {
-		if (!(vs = jas_malloc(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] != '\0') {
-					vs[n] = atof(cp);
-					++n;
-				}
-			}
-		}
-	} else {
-		vs = 0;
-	}
-
-	*numvalues = n;
-	*values = vs;
-
-	return 0;
+static unsigned int
+countOfTokens(const char * const s,
+                          const char * const delim) {
+
+        unsigned int n;
+        char buf[4096];
+        const char * cp;
+
+        strncpy(buf, s, sizeof(buf));
+        buf[sizeof(buf) - 1] = '\0';
+        n = 0;  /* initial value */
+        if ((cp = strtok(buf, delim))) {
+                ++n;
+                while ((cp = strtok(0, delim))) {
+                        if (cp[0] != '\0') {
+                                ++n;
+                        }
+                }
+        }
+        return n;
+}
+
+
+
+int
+jpc_atoaf(const char * const s,
+                  int *        const numvaluesP,
+                  double **    const valuesP) {
+/*----------------------------------------------------------------------------
+   Parse a string like "3.2,9,-5".  Return as *numvaluesP the number of
+   values in the string and as *valuesP a malloced array of the values.
+
+   But if the string is empty (*numvaluesP is zero), return *valuesP NULL.
+
+   Delimiters can be comma as in the example or space, tab, or newline.
+-----------------------------------------------------------------------------*/
+        char const delim[] = ", \t\n";
+
+        unsigned int const valueCt = countOfTokens(s, delim);
+
+        if (valueCt > 0) {
+                unsigned int i;
+                double * vs;
+                const char * cp;
+                char buf[4096];
+
+                if (!(vs = jas_malloc(valueCt * sizeof(double)))) {
+                        return -1;
+                }
+
+                strncpy(buf, s, sizeof(buf));
+                buf[sizeof(buf) - 1] = '\0';
+                i = 0;
+                if ((cp = strtok(buf, delim))) {
+                        vs[i] = atof(cp);
+                        ++i;
+                        while ((cp = strtok(0, delim))) {
+                                if (cp[0] != '\0') {
+                                        vs[i] = atof(cp);
+                                        ++i;
+                                }
+                        }
+                }
+                assert(i == valueCt);
+                *numvaluesP = valueCt;
+                *valuesP    = vs;
+        } else {
+                *valuesP    = NULL;
+                *numvaluesP = 0;
+        }
+        return 0;
 }
 
 jas_seq_t *jpc_seq_upsample(jas_seq_t *x, int m)
 {
-	jas_seq_t *z;
-	int i;
+        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);
-	}
+        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;
+        return z;
 }
 
 jpc_fix_t jpc_seq_norm(jas_seq_t *x)
 {
-	jpc_fix_t s;
-	int i;
+        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)));
-	}
+        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)));
+        return jpc_dbltofix(sqrt(jpc_fixtodbl(s)));
 }
 
 jas_seq_t *jpc_seq_conv(jas_seq_t *x, 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);
-	assert(z);
-	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;
+        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);
+        assert(z);
+        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;
 }
diff --git a/converter/other/jpeg2000/libjasper/jpc/jpc_util.h b/converter/other/jpeg2000/libjasper/jpc/jpc_util.h
index c23fc33b..f1d90385 100644
--- a/converter/other/jpeg2000/libjasper/jpc/jpc_util.h
+++ b/converter/other/jpeg2000/libjasper/jpc/jpc_util.h
@@ -4,14 +4,14 @@
  */
 
 /* __START_OF_JASPER_LICENSE__
- * 
+ *
  * JasPer Software License
- * 
+ *
  * IMAGE POWER JPEG-2000 PUBLIC LICENSE
  * ************************************
- * 
+ *
  * GRANT:
- * 
+ *
  * Permission is hereby granted, free of charge, to any person (the "User")
  * obtaining a copy of this software and associated documentation, to deal
  * in the JasPer Software without restriction, including without limitation
@@ -19,22 +19,22 @@
  * and/or sell copies of the JasPer Software (in source and binary forms),
  * and to permit persons to whom the JasPer Software is furnished to do so,
  * provided further that the License Conditions below are met.
- * 
+ *
  * License Conditions
  * ******************
- * 
+ *
  * A.  Redistributions of source code must retain the above copyright notice,
  * and this list of conditions, and the following disclaimer.
- * 
+ *
  * B.  Redistributions in binary form must reproduce the above copyright
  * notice, and this list of conditions, and the following disclaimer in
  * the documentation and/or other materials provided with the distribution.
- * 
+ *
  * C.  Neither the name of Image Power, Inc. nor any other contributor
  * (including, but not limited to, the University of British Columbia and
  * Michael David Adams) may be used to endorse or promote products derived
  * from this software without specific prior written permission.
- * 
+ *
  * D.  User agrees that it shall not commence any action against Image Power,
  * Inc., the University of British Columbia, Michael David Adams, or any
  * other contributors (collectively "Licensors") for infringement of any
@@ -54,17 +54,17 @@
  * trade dress, or service mark rights); and (v) divisions, continuations,
  * renewals, reissues and extensions of the foregoing (as and to the extent
  * applicable) now existing, hereafter filed, issued or acquired.
- * 
+ *
  * E.  If User commences an infringement action against any Licensor(s) then
  * such Licensor(s) shall have the right to terminate User's license and
  * all sublicenses that have been granted hereunder by User to other parties.
- * 
+ *
  * F.  This software is for use only in hardware or software products that
  * are compliant with ISO/IEC 15444-1 (i.e., JPEG-2000 Part 1).  No license
  * or right to this Software is granted for products that do not comply
  * with ISO/IEC 15444-1.  The JPEG-2000 Part 1 standard can be purchased
  * from the ISO.
- * 
+ *
  * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS LICENSE.
  * NO USE OF THE JASPER SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER
  * THIS DISCLAIMER.  THE JASPER SOFTWARE IS PROVIDED BY THE LICENSORS AND
@@ -104,7 +104,7 @@
  * TECHNOLOGY OR PRODUCTS FOR HIGH RISK ACTIVITIES AND WILL ENSURE THAT ITS
  * CUSTOMERS AND END-USERS OF ITS PRODUCTS ARE PROVIDED WITH A COPY OF THE
  * NOTICE SPECIFIED IN THIS SECTION.
- * 
+ *
  * __END_OF_JASPER_LICENSE__
  */
 
diff --git a/converter/other/jpeg2000/libjasper_compat.h b/converter/other/jpeg2000/libjasper_compat.h
index 45dd904b..103b1d09 100644
--- a/converter/other/jpeg2000/libjasper_compat.h
+++ b/converter/other/jpeg2000/libjasper_compat.h
@@ -49,7 +49,7 @@ pmjas_image_decode(jas_stream_t * const in,
 
     if (jasperP) {
         *imagePP = jasperP;
-        *errorP  = errorP;
+        *errorP  = NULL;
     } else {
         pm_asprintf(errorP, "Failed.  Details may have been written to "
                     "Standard Error");
diff --git a/converter/other/jpeg2000/pamtojpeg2k.c b/converter/other/jpeg2000/pamtojpeg2k.c
index a886c390..ea9ad492 100644
--- a/converter/other/jpeg2000/pamtojpeg2k.c
+++ b/converter/other/jpeg2000/pamtojpeg2k.c
@@ -35,7 +35,7 @@ enum compmode {COMPMODE_INTEGER, COMPMODE_REAL};
 
 enum progression {PROG_LRCP, PROG_RLCP, PROG_RPCL, PROG_PCRL, PROG_CPRL};
 
-struct cmdlineInfo {
+struct CmdlineInfo {
     /* All the information the user supplied in the command line,
        in a form easy for the program to use.
     */
@@ -53,6 +53,8 @@ struct cmdlineInfo {
     enum compmode compmode;
     unsigned int compressionSpec;
     float        compression;
+    unsigned int size;
+    unsigned int sizeSpec;
     char *       ilyrrates;
     enum progression progression;
     unsigned int numrlvls;
@@ -73,10 +75,10 @@ struct cmdlineInfo {
 
 static void
 parseCommandLine(int argc, char ** argv,
-                 struct cmdlineInfo * const cmdlineP) {
+                 struct CmdlineInfo * const cmdlineP) {
 /*----------------------------------------------------------------------------
    Note that many of the strings that this function returns in the
-   *cmdline_p structure are actually in the supplied argv array.  And
+   *cmdlineP structure are actually in the supplied argv array.  And
    sometimes, one of these strings is actually just a suffix of an entry
    in argv!
 -----------------------------------------------------------------------------*/
@@ -126,6 +128,8 @@ parseCommandLine(int argc, char ** argv,
             &modeSpec,           0);
     OPTENT3(0, "compression",  OPT_FLOAT,  &cmdlineP->compression,
             &cmdlineP->compressionSpec,    0);
+    OPTENT3(0, "size",         OPT_UINT,   &cmdlineP->size,
+            &cmdlineP->sizeSpec,           0);
     OPTENT3(0, "ilyrrates",    OPT_STRING, &cmdlineP->ilyrrates,
             &ilyrratesSpec,      0);
     OPTENT3(0, "progression",  OPT_STRING, &progressionOpt,
@@ -219,6 +223,9 @@ parseCommandLine(int argc, char ** argv,
     if (!debuglevelSpec)
         cmdlineP->debuglevel = 0;
 
+    if (cmdlineP->compressionSpec && cmdlineP->sizeSpec)
+        pm_error("You cannot specify by -compression and -size");
+
     if (argc - 1 == 0)
         cmdlineP->inputFilename = strdup("-");  /* he wants stdin */
     else if (argc - 1 == 1)
@@ -307,7 +314,7 @@ static void
 createJasperImage(struct pam *   const inpamP,
                   jas_image_t ** const jasperPP) {
 
-	jas_image_cmptparm_t * cmptparms;
+        jas_image_cmptparm_t * cmptparms;
     unsigned int plane;
 
     MALLOCARRAY_NOFAIL(cmptparms, inpamP->depth);
@@ -372,9 +379,11 @@ convertToJasperImage(struct pam *   const inpamP,
 
 static void
 writeJpc(jas_image_t *      const jasperP,
-         struct cmdlineInfo const cmdline,
-         FILE *             const ofP) {
-
+         struct CmdlineInfo const cmdline,
+         int                const ofd) {
+/*----------------------------------------------------------------------------
+   Write the image *jasperP to open file 'ofd'.
+-----------------------------------------------------------------------------*/
     jas_stream_t * outStreamP;
     const char * options;
     const char * ilyrratesOpt;
@@ -403,6 +412,8 @@ writeJpc(jas_image_t *      const jasperP,
 
     if (cmdline.compressionSpec)
         sprintf(rateOpt, "rate=%1.9f", 1.0/cmdline.compression);
+    else if (cmdline.sizeSpec)
+        sprintf(rateOpt, "rate=%uB", cmdline.size);
     else {
         /* No 'rate' option.  This means there is no constraint on the image
            size, so the encoder will compress losslessly.  Note that the
@@ -459,7 +470,7 @@ writeJpc(jas_image_t *      const jasperP,
     pm_strfree(ilyrratesOpt);
 
     /* Open the output image file (Standard Output) */
-    outStreamP = jas_stream_fdopen(fileno(ofP), "w+b");
+    outStreamP = jas_stream_fdopen(ofd, "w+b");
     if (outStreamP == NULL)
         pm_error("Unable to open output stream.  jas_stream_fdopen() "
                  "failed");
@@ -478,7 +489,7 @@ writeJpc(jas_image_t *      const jasperP,
             pm_error("jas_image_encode() failed to encode the JPEG 2000 "
                      "image.  Rc=%d", rc);
     }
-	jas_stream_flush(outStreamP);
+        jas_stream_flush(outStreamP);
 
     {
         int rc;
@@ -490,7 +501,7 @@ writeJpc(jas_image_t *      const jasperP,
                      "jas_stream_close() rc = %d", rc);
     }
 
-	jas_image_clearfmts();
+        jas_image_clearfmts();
 
     pm_strfree(options);
 }
@@ -500,7 +511,7 @@ writeJpc(jas_image_t *      const jasperP,
 int
 main(int argc, char **argv)
 {
-    struct cmdlineInfo cmdline;
+    struct CmdlineInfo cmdline;
     FILE * ifP;
     struct pam inpam;
     jas_image_t * jasperP;
@@ -526,9 +537,9 @@ main(int argc, char **argv)
 
     convertToJasperImage(&inpam, &jasperP);
 
-    writeJpc(jasperP, cmdline, stdout);
+    writeJpc(jasperP, cmdline, fileno(stdout));
 
-	jas_image_destroy(jasperP);
+        jas_image_destroy(jasperP);
 
     pm_close(ifP);
 
diff --git a/converter/other/jpegdatasource.c b/converter/other/jpegdatasource.c
index 1f53c2a4..34393a7b 100644
--- a/converter/other/jpegdatasource.c
+++ b/converter/other/jpegdatasource.c
@@ -7,18 +7,18 @@
    This data source manager is the same as the Jpeg library's built in
    "stdio" one, except that it looks ahead and one can query it to see
    if there is any data in the stream that the Jpeg library hasn't seen
-   yet.  Thus, you can use it in a program that reads multiple JPEG 
+   yet.  Thus, you can use it in a program that reads multiple JPEG
    images and know when to stop.  You can also nicely handle completely
    empty input files more gracefully than just crying input error.
 
-   This data source manager does 4K fread() reads and passes 4K buffers 
+   This data source manager does 4K fread() reads and passes 4K buffers
    to the Jpeg library.  It reads one 4K block ahead, so there is up to
    8K of image buffered at any time.
 
    By Bryan Henderson, San Jose CA 2002.10.13
 *****************************************************************************/
 
-#include <ctype.h>	   
+#include <ctype.h>
 #include <stdlib.h>
 #include <stdio.h>
 #include <errno.h>
@@ -92,7 +92,7 @@ dsFillInputBuffer(j_decompress_ptr const cinfoP) {
            truncation and pad out the image with gray.
         */
         srcP->prematureEof = TRUE;
-        
+
         srcP->jpegSourceMgr.next_input_byte = jfifEoiMarker;
         srcP->jpegSourceMgr.bytes_in_buffer = sizeof(jfifEoiMarker);
     } else {
@@ -107,7 +107,7 @@ dsFillInputBuffer(j_decompress_ptr const cinfoP) {
         }
 
         /* Fill the new "next" buffer */
-        srcP->bytesInNextBuffer = 
+        srcP->bytesInNextBuffer =
             fread(srcP->nextBuffer, 1, BUFFER_SIZE, srcP->ifP);
     }
     return TRUE;
@@ -166,7 +166,7 @@ dsPrematureEof(struct sourceManager * const srcP) {
 
 
 
-struct sourceManager * 
+struct sourceManager *
 dsCreateSource(const char * const fileName) {
 
     struct sourceManager * srcP;
@@ -182,22 +182,24 @@ dsCreateSource(const char * const fileName) {
     srcP->jpegSourceMgr.skip_input_data = dsSkipInputData;
     srcP->jpegSourceMgr.resync_to_restart = jpeg_resync_to_restart;
     srcP->jpegSourceMgr.term_source = dsTermSource;
-    
+
     srcP->prematureEof = FALSE;
     srcP->currentBuffer = srcP->buffer1;
     srcP->nextBuffer = srcP->buffer2;
-    srcP->jpegSourceMgr.bytes_in_buffer = 
+    srcP->jpegSourceMgr.bytes_in_buffer =
         fread(srcP->currentBuffer, 1, BUFFER_SIZE, srcP->ifP);
     srcP->jpegSourceMgr.next_input_byte = srcP->currentBuffer;
-    srcP->bytesInNextBuffer = 
+    srcP->bytesInNextBuffer =
         fread(srcP->nextBuffer, 1, BUFFER_SIZE, srcP->ifP);
 
     return srcP;
 }
 
+
+
 void
 dsDestroySource(struct sourceManager * const srcP) {
-    
+
     pm_close(srcP->ifP);
     free(srcP);
 
@@ -209,3 +211,6 @@ struct jpeg_source_mgr *
 dsJpegSourceMgr(struct sourceManager * const srcP) {
     return &srcP->jpegSourceMgr;
 }
+
+
+
diff --git a/converter/other/jpegdatasource.h b/converter/other/jpegdatasource.h
index 58648fe4..70d55d11 100644
--- a/converter/other/jpegdatasource.h
+++ b/converter/other/jpegdatasource.h
@@ -3,7 +3,7 @@
 
 #include "pm_c_util.h"
 
-struct sourceManager * 
+struct sourceManager *
 dsCreateSource(const char * const fileName);
 
 void
diff --git a/converter/other/jpegtopnm.c b/converter/other/jpegtopnm.c
index 98552c00..33f69be9 100644
--- a/converter/other/jpegtopnm.c
+++ b/converter/other/jpegtopnm.c
@@ -4,13 +4,13 @@
   This program is part of the Netpbm package.
 
   This program converts from the JFIF format, which is based on JPEG, to
-  the fundamental ppm or pgm format (depending on whether the JFIF 
+  the fundamental ppm or pgm format (depending on whether the JFIF
   image is gray scale or color).
 
   This program is by Bryan Henderson on 2000.03.20, but is derived
   with permission from the program djpeg, which is in the Independent
   Jpeg Group's JPEG library package.  Under the terms of that permission,
-  redistribution of this software is restricted as described in the 
+  redistribution of this software is restricted as described in the
   file README.JPEG.
 
   Copyright (C) 1991-1998, Thomas G. Lane.
@@ -45,14 +45,15 @@
     (http://topo.math.u-psud.fr/~bousch/exifdump.py) and Jhead
     (http://www.sentex.net/~mwandel/jhead).
 
-    
+
 *****************************************************************************/
 
 #define _DEFAULT_SOURCE 1  /* New name for SVID & BSD source defines */
 #define _BSD_SOURCE 1      /* Make sure strdup() is in string.h */
 #define _XOPEN_SOURCE 500  /* Make sure strdup() is in string.h */
 
-#include <ctype.h>		/* to declare isprint() */
+#include <stdbool.h>
+#include <ctype.h>              /* to declare isprint() */
 #include <string.h>
 #include <stdlib.h>
 #include <stdio.h>
@@ -73,76 +74,79 @@
 
 #define EXIT_WARNING 2  /* Goes with EXIT_FAILURE, EXIT_SUCCESS in stdlib.h */
 
-enum inklevel {NORMAL, ADOBE, GUESS};
+enum Inklevel {NORMAL, ADOBE, GUESS};
    /* This describes image samples that represent ink levels.  NORMAL
       means 0 is no ink; ADOBE means 0 is maximum ink.  GUESS means we
-      don't know what 0 means, so we have to guess from information in 
+      don't know what 0 means, so we have to guess from information in
       the image.
       */
 
-enum colorspace {
+enum Colorspace {
     /* These are the color spaces in which we can get pixels from the
        JPEG decompressor.  We include only those that are possible
        given our particular inputs to the decompressor.  The
        decompressor is theoretically capable of other, e.g. YCCK.
        Unlike the JPEG library, this type distinguishes between the
-       Adobe and non-Adobe style of CMYK samples.  
+       Adobe and non-Adobe style of CMYK samples.
     */
     GRAYSCALE_COLORSPACE,
-    RGB_COLORSPACE, 
-    CMYK_NORMAL_COLORSPACE, 
+    RGB_COLORSPACE,
+    CMYK_NORMAL_COLORSPACE,
     CMYK_ADOBE_COLORSPACE
     };
 
-struct cmdlineInfo {
+struct CmdlineInfo {
     /* All the information the user supplied in the command line,
        in a form easy for the program to use.
     */
-    char *input_filespec;
-    char *exif_filespec;
-        /* Filespec in which to save EXIF information.  NULL means don't
+    char * inputFileName;
+    char * exifFileName;
+        /* Name of file in which to save EXIF information.  NULL means don't
            save.  "-" means standard output
         */
-    unsigned int verbose;
-    unsigned int nosmooth;
-    J_DCT_METHOD dct_method;
-    long int max_memory_to_use;
-    unsigned int trace_level;
-    enum inklevel inklevel;
-    unsigned int comments;
-    unsigned int dumpexif;
-    unsigned int multiple;
-    unsigned int repair;
+    unsigned int  verbose;
+    unsigned int  nosmooth;
+    J_DCT_METHOD  dctMethod;
+    long int      maxMemoryToUse;
+    unsigned int  traceLevel;
+    enum Inklevel inklevel;
+    unsigned int  comments;
+    unsigned int  dumpexif;
+    unsigned int  traceexif;
+    unsigned int  multiple;
+    unsigned int  repair;
 };
 
 
 static bool displayComments;
     /* User wants comments from the JPEG to be displayed */
 
-static void 
-interpret_maxmemory(bool         const maxmemorySpec,
-                    const char * const maxmemory, 
-                    long int *   const max_memory_to_use_p) { 
+static void
+interpretMaxmemory(bool         const maxmemorySpec,
+                   const char * const maxmemory,
+                   long int *   const maxMemoryToUseP) {
 /*----------------------------------------------------------------------------
    Interpret the "maxmemory" command line option.
 -----------------------------------------------------------------------------*/
     long int lval;
     char ch;
-    
+
     if (!maxmemorySpec) {
-        *max_memory_to_use_p = -1;  /* unspecified */
+        *maxMemoryToUseP = -1;  /* unspecified */
     } else if (sscanf(maxmemory, "%ld%c", &lval, &ch) < 1) {
         pm_error("Invalid value for --maxmemory option: '%s'.", maxmemory);
     } else {
         if (ch == 'm' || ch == 'M') lval *= 1000L;
-        *max_memory_to_use_p = lval * 1000L;
+        *maxMemoryToUseP = lval * 1000L;
     }
 }
 
 
+
 static void
-interpret_adobe(const int adobe, const int notadobe, 
-                enum inklevel * const inklevel_p) {
+interpretAdobe(int             const adobe,
+               int             const notadobe,
+               enum Inklevel * const inklevelP) {
 /*----------------------------------------------------------------------------
    Interpret the adobe/notadobe command line options
 -----------------------------------------------------------------------------*/
@@ -150,11 +154,11 @@ interpret_adobe(const int adobe, const int notadobe,
         pm_error("You cannot specify both -adobe and -notadobe options.");
     else {
         if (adobe)
-            *inklevel_p = ADOBE;
+            *inklevelP = ADOBE;
         else if (notadobe)
-            *inklevel_p = NORMAL;
-        else 
-            *inklevel_p = GUESS;
+            *inklevelP = NORMAL;
+        else
+            *inklevelP = GUESS;
     }
 }
 
@@ -163,7 +167,7 @@ interpret_adobe(const int adobe, const int notadobe,
 static void
 parseCommandLine(int                  const argc,
                  char **              const argv,
-                 struct cmdlineInfo * const cmdlineP) {
+                 struct CmdlineInfo * const cmdlineP) {
 /*----------------------------------------------------------------------------
    Note that many of the strings that this function returns in the
    *cmdlineP structure are actually in the supplied argv array.  And
@@ -173,7 +177,7 @@ parseCommandLine(int                  const argc,
    On the other hand, unlike other option processing functions, we do
    not change argv at all.
 -----------------------------------------------------------------------------*/
-    optEntry *option_def;
+    optEntry * option_def;
         /* Instructions to pm_optParseOptions3 on how to parse our options.
          */
     optStruct3 opt;
@@ -192,7 +196,7 @@ parseCommandLine(int                  const argc,
 
     MALLOCARRAY_NOFAIL(option_def, 100);
     MALLOCARRAY_NOFAIL(argv_parse, argc);
-    
+
     /* argv, except we modify it as we parse */
 
     option_def_index = 0;   /* incremented by OPTENTRY */
@@ -200,67 +204,69 @@ parseCommandLine(int                  const argc,
     OPTENT3(0, "dct",         OPT_STRING, &dctval,
             &dctvalSpec, 0);
     OPTENT3(0, "maxmemory",   OPT_STRING, &maxmemory,
-            &maxmemorySpec, 0); 
+            &maxmemorySpec, 0);
     OPTENT3(0, "nosmooth",    OPT_FLAG,   NULL, &cmdlineP->nosmooth,      0);
-    OPTENT3(0, "tracelevel",  OPT_UINT,   &cmdlineP->trace_level,   
+    OPTENT3(0, "tracelevel",  OPT_UINT,   &cmdlineP->traceLevel,
             &tracelevelSpec, 0);
     OPTENT3(0, "adobe",       OPT_FLAG,   NULL, &adobe,                   0);
     OPTENT3(0, "notadobe",    OPT_FLAG,   NULL, &notadobe,                0);
     OPTENT3(0, "comments",    OPT_FLAG,   NULL, &cmdlineP->comments,      0);
-    OPTENT3(0, "exif",        OPT_STRING, &cmdlineP->exif_filespec, 
+    OPTENT3(0, "exif",        OPT_STRING, &cmdlineP->exifFileName,
             &exifSpec, 0);
     OPTENT3(0, "dumpexif",    OPT_FLAG,   NULL, &cmdlineP->dumpexif,      0);
     OPTENT3(0, "multiple",    OPT_FLAG,   NULL, &cmdlineP->multiple,      0);
     OPTENT3(0, "repair",      OPT_FLAG,   NULL, &cmdlineP->repair,        0);
+    OPTENT3(0, "traceexif",   OPT_FLAG,   NULL, &cmdlineP->traceexif,     0);
 
     opt.opt_table = option_def;
-    opt.short_allowed = FALSE;  /* We have no short (old-fashioned) options */
-    opt.allowNegNum = FALSE;  /* We may have parms that are negative numbers */
+    opt.short_allowed = false;  /* We have no short (old-fashioned) options */
+    opt.allowNegNum = false;  /* We may have parms that are negative numbers */
 
     /* Make private copy of arguments for pm_optParseOptions to corrupt */
     argc_parse = argc;
     for (i=0; i < argc; ++i)
         argv_parse[i] = argv[i];
 
-    pm_optParseOptions3( &argc_parse, argv_parse, opt, sizeof(opt), 0);
-        /* Uses and sets argc_parse, argv_parse, 
+    pm_optParseOptions3(&argc_parse, argv_parse, opt, sizeof(opt), 0);
+        /* Uses and sets argc_parse, argv_parse,
            and some of *cmdlineP and others. */
 
     if (!tracelevelSpec)
-        cmdlineP->trace_level = 0;
+        cmdlineP->traceLevel = 0;
 
     if (!exifSpec)
-        cmdlineP->exif_filespec = NULL;
+        cmdlineP->exifFileName = NULL;
 
     if (argc_parse - 1 == 0)
-        cmdlineP->input_filespec = strdup("-");  /* he wants stdin */
+        cmdlineP->inputFileName = strdup("-");  /* he wants stdin */
     else if (argc_parse - 1 == 1)
-        cmdlineP->input_filespec = strdup(argv_parse[1]);
-    else 
+        cmdlineP->inputFileName = strdup(argv_parse[1]);
+    else
         pm_error("Too many arguments.  The only argument accepted "
                  "is the input file specification");
 
     if (!dctvalSpec)
-        cmdlineP->dct_method = JDCT_DEFAULT;
+        cmdlineP->dctMethod = JDCT_DEFAULT;
     else {
         if (streq(dctval, "int"))
-            cmdlineP->dct_method = JDCT_ISLOW;
+            cmdlineP->dctMethod = JDCT_ISLOW;
         else if (streq(dctval, "fast"))
-            cmdlineP->dct_method = JDCT_IFAST;
+            cmdlineP->dctMethod = JDCT_IFAST;
         else if (streq(dctval, "float"))
-            cmdlineP->dct_method = JDCT_FLOAT;
+            cmdlineP->dctMethod = JDCT_FLOAT;
         else pm_error("Invalid value for the --dct option: '%s'.", dctval);
     }
 
-    interpret_maxmemory(maxmemorySpec, maxmemory, 
-                        &cmdlineP->max_memory_to_use);
+    interpretMaxmemory(maxmemorySpec, maxmemory,
+                       &cmdlineP->maxMemoryToUse);
 
-    interpret_adobe(adobe, notadobe, &cmdlineP->inklevel);
+    interpretAdobe(adobe, notadobe, &cmdlineP->inklevel);
 
     free(argv_parse);
 }
 
 
+
 /*
  * Marker processor for COM and interesting APPn markers.
  * This replaces the library's built-in processor, which just skips the marker.
@@ -270,70 +276,73 @@ parseCommandLine(int                  const argc,
 
 #if 0
 static unsigned int
-jpeg_getc (j_decompress_ptr cinfo)
+jpegGetc (j_decompress_ptr const cinfoP) {
+
 /* Read next byte */
-{
-  struct jpeg_source_mgr * datasrc = cinfo->src;
-
-  if (datasrc->bytes_in_buffer == 0) {
-      if (! (*datasrc->fill_input_buffer) (cinfo)) 
-          pm_error("Can't suspend here.");
-  }
-  datasrc->bytes_in_buffer--;
-  return GETJOCTET(*datasrc->next_input_byte++);
+    struct jpeg_source_mgr * datasrcP = cinfoP->src;
+
+    if (datasrcP->bytes_in_buffer == 0) {
+        if (! (*datasrcP->fill_input_buffer) (cinfoP))
+            pm_error("Can't suspend here.");
+    }
+    datasrcP->bytes_in_buffer--;
+    return GETJOCTET(*datasrcP->next_input_byte++);
 }
 
 
-static boolean
-print_text_marker (j_decompress_ptr cinfo) {
+
+static bool
+printTextMarker(j_decompress_ptr const cinfoP) {
 /*----------------------------------------------------------------------------
    This is a routine that you can register with the Jpeg decompressor
    with e.g.
 
-     jpeg_set_marker_processor(cinfoP, JPEG_APP0 + app_type, 
-                               print_text_marker);
+     jpeg_set_marker_processor(cinfoP, JPEG_APP0 + appType,
+                               printTextMarker);
 
   The decompressor then calls it when it encounters a miscellaneous marker
   of the specified type (e.g. APP1).  At that time, the jpeg input stream
   is positioned to the marker contents -- first 2 bytes of length information,
   MSB first, where the length includes those two bytes, then the data.
-  
+
   We just get and print the contents of the marker.
 
   This routine is no longer used; it is kept as an example in case we want
   to use it in the future.  Instead, we use jpeg_save_markers() and have
   the Jpeg library store all the markers in memory for our later access.
 -----------------------------------------------------------------------------*/
-    const boolean traceit = (cinfo->err->trace_level >= 1);
-    const boolean display_value = 
-        traceit || (cinfo->unread_marker == JPEG_COM && displayComments);
-    
+    const bool traceit = (cinfoP->err->trace_level >= 1);
+    const bool display_value =
+        traceit || (cinfoP->unread_marker == JPEG_COM && displayComments);
+
     INT32 length;
     unsigned int ch;
-    unsigned int lastch = 0;
-    
-    length = jpeg_getc(cinfo) << 8;
-    length += jpeg_getc(cinfo);
-    length -= 2;			/* discount the length word itself */
+    unsigned int lastch;
+
+    lastch = 0;  /* initial value */
+
+    length = jpeg_getc(cinfoP) << 8;
+    length += jpeg_getc(cinfoP);
+    length -= 2;                        /* discount the length word itself */
 
     if (traceit) {
-        if (cinfo->unread_marker == JPEG_COM)
+        if (cinfoP->unread_marker == JPEG_COM)
             fprintf(stderr, "Comment, length %ld:\n", (long) length);
-        else			/* assume it is an APPn otherwise */
+        else                    /* assume it is an APPn otherwise */
             fprintf(stderr, "APP%d, length %ld:\n",
-                    cinfo->unread_marker - JPEG_APP0, (long) length);
+                    cinfoP->unread_marker - JPEG_APP0, (long) length);
     }
-    
-    if (cinfo->unread_marker == JPEG_COM && displayComments)
+
+    if (cinfoP->unread_marker == JPEG_COM && displayComments)
         fprintf(stderr, "COMMENT: ");
-    
+
     while (--length >= 0) {
-        ch = jpeg_getc(cinfo);
+        ch = jpeg_getc(cinfoP);
         if (display_value) {
             /* Emit the character in a readable form.
              * Nonprintables are converted to \nnn form,
              * while \ is converted to \\.
-             * Newlines in CR, CR/LF, or LF form will be printed as one 
+             * Newlines in CR, CR/LF, or LF form will be printed as one
              * newline.
              */
             if (ch == '\r') {
@@ -351,18 +360,18 @@ print_text_marker (j_decompress_ptr cinfo) {
           lastch = ch;
         }
     }
-    
+
     if (display_value)
         fprintf(stderr, "\n");
-    
-    return TRUE;
+
+    return true;
 }
 #endif
 
 
 
 static void
-print_marker(struct jpeg_marker_struct const marker) {
+printMarker(struct jpeg_marker_struct const marker) {
 
     if (marker.original_length != marker.data_length) {
         /* This should be impossible, because we asked for up to 65535
@@ -376,12 +385,12 @@ print_marker(struct jpeg_marker_struct const marker) {
         int i;
         JOCTET lastch;
 
-        lastch = 0;
+        lastch = 0;  /* initial value */
         for (i = 0; i < marker.data_length; i++) {
             /* Emit the character in a readable form.
              * Nonprintables are converted to \nnn form,
              * while \ is converted to \\.
-             * Newlines in CR, CR/LF, or LF form will be printed as one 
+             * Newlines in CR, CR/LF, or LF form will be printed as one
              * newline.
              */
             if (marker.data[i] == '\r') {
@@ -403,33 +412,34 @@ print_marker(struct jpeg_marker_struct const marker) {
 }
 
 
+
 typedef struct rgb {unsigned int r; unsigned int g; unsigned int b;} rgb_type;
 
 
 static rgb_type *
-read_rgb(JSAMPLE *ptr, const enum colorspace color_space, 
-         const unsigned int maxval) {
+read_rgb(JSAMPLE *       const ptr,
+         enum Colorspace const colorspace,
+         unsigned int    const maxval) {
 /*----------------------------------------------------------------------------
   Return the RGB triple corresponding to the color of the JPEG pixel at
-  'ptr', which is in color space 'color_space'.  
+  'ptr', which is in color space 'color_space'.
 
   Assume 'maxval' is the maximum sample value in the input pixel, and also
   use it for the maximum sample value in the return value.
 -----------------------------------------------------------------------------*/
     static rgb_type rgb;  /* Our return value */
 
-    switch (color_space) {
+    switch (colorspace) {
     case RGB_COLORSPACE: {
         rgb.r = GETJSAMPLE(*(ptr+0));
-        rgb.g = GETJSAMPLE(*(ptr+1)); 
-        rgb.b = GETJSAMPLE(*(ptr+2)); 
-    }
-        break;
+        rgb.g = GETJSAMPLE(*(ptr+1));
+        rgb.b = GETJSAMPLE(*(ptr+2));
+    } break;
     case CMYK_NORMAL_COLORSPACE: {
-        const int c = GETJSAMPLE(*(ptr+0));
-        const int m = GETJSAMPLE(*(ptr+1));
-        const int y = GETJSAMPLE(*(ptr+2));
-        const int k = GETJSAMPLE(*(ptr+3));
+        int const c = GETJSAMPLE(*(ptr+0));
+        int const m = GETJSAMPLE(*(ptr+1));
+        int const y = GETJSAMPLE(*(ptr+2));
+        int const k = GETJSAMPLE(*(ptr+3));
 
         /* I swapped m and y below, because they looked wrong.
            -Bryan 2000.08.20
@@ -437,74 +447,71 @@ read_rgb(JSAMPLE *ptr, const enum colorspace color_space,
         rgb.r = ((maxval-k)*(maxval-c))/maxval;
         rgb.g = ((maxval-k)*(maxval-m))/maxval;
         rgb.b = ((maxval-k)*(maxval-y))/maxval;
-    }
-        break;
+    } break;
     case CMYK_ADOBE_COLORSPACE: {
-        const int c = GETJSAMPLE(*(ptr+0));
-        const int m = GETJSAMPLE(*(ptr+1));
-        const int y = GETJSAMPLE(*(ptr+2));
-        const int k = GETJSAMPLE(*(ptr+3));
+        int const c = GETJSAMPLE(*(ptr+0));
+        int const m = GETJSAMPLE(*(ptr+1));
+        int const y = GETJSAMPLE(*(ptr+2));
+        int const k = GETJSAMPLE(*(ptr+3));
 
         rgb.r = (k*c)/maxval;
         rgb.g = (k*m)/maxval;
         rgb.b = (k*y)/maxval;
-    }
-        break;
+    } break;
     default:
         pm_error("Internal error: unknown color space %d passed to "
-                 "read_rgb().", (int) color_space);
+                 "read_rgb().", (int) colorspace);
     }
-    return(&rgb);
+    return &rgb;
 }
 
 
 
-/* pnmbuffer is declared global because it would be improper to pass a
-   pointer to it as input to copy_pixel_row(), since it isn't
-   logically a parameter of the operation, but rather is private to
-   copy_pixel_row().  But it would be impractical to allocate and free
-   the storage with every call to copy_pixel_row().
-*/
-static xel * pnmbuffer;      /* Output buffer.  Input to pnm_writepnmrow() */
-
 static void
-copyPixelRow(JSAMPROW        const jpegbuffer,
-             unsigned int    const width, 
-             unsigned int    const samplesPerPixel, 
-             enum colorspace const colorSpace,
-             FILE *          const ofP,
-             int             const format,
-             xelval          const maxval) {
+convertPixelRow(JSAMPROW        const jpegbuffer,
+                unsigned int    const width,
+                unsigned int    const samplesPerPixel,
+                enum Colorspace const colorSpace,
+                int             const format,
+                xelval          const maxval,
+                xel *           const pnmbuffer) {
+/*----------------------------------------------------------------------------
+  Convert the pixels in 'jpegbuffer' from libjpeg format to libnetpbm
+  format in 'pnmbuffer'.
 
+  The row has 'width' pixels and the data in 'jpegbuffer' is formatted with
+  'samplesPerPixel' samples per pixel with colorspace 'colorSpace'.
+
+  The output Netpbm data is in format 'format' with maxval 'maxval'.
+-----------------------------------------------------------------------------*/
     JSAMPLE * ptr;
     unsigned int outputCursor;     /* Cursor into output buffer 'pnmbuffer' */
 
     ptr = &jpegbuffer[0];  /* Start at beginning of input row */
-    
+
     for (outputCursor = 0; outputCursor < width; ++outputCursor) {
         xel currentPixel;
         if (samplesPerPixel >= 3) {
-            const rgb_type * const rgb_p = read_rgb(ptr, colorSpace, maxval);
-            PPM_ASSIGN(currentPixel, rgb_p->r, rgb_p->g, rgb_p->b);
+            const rgb_type * const rgbP = read_rgb(ptr, colorSpace, maxval);
+            PPM_ASSIGN(currentPixel, rgbP->r, rgbP->g, rgbP->b);
         } else {
             PNM_ASSIGN1(currentPixel, GETJSAMPLE(*ptr));
         }
         ptr += samplesPerPixel;  /* move to next pixel of input */
         pnmbuffer[outputCursor] = currentPixel;
     }
-    pnm_writepnmrow(ofP, pnmbuffer, width, maxval, format, FALSE);
 }
 
 
 
 static void
-set_color_spaces(const J_COLOR_SPACE jpeg_color_space,
-                 int * const output_type_p,
-                 J_COLOR_SPACE * const out_color_space_p) {
+setColorSpaces(J_COLOR_SPACE   const jpegColorSpace,
+               int *           const outputTypeP,
+               J_COLOR_SPACE * const outColorSpaceP) {
 /*----------------------------------------------------------------------------
-   Decide what type of output (PPM or PGM) we shall generate and what 
+   Decide what type of output (PPM or PGM) we shall generate and what
    color space we must request from the JPEG decompressor, based on the
-   color space of the input JPEG image, 'jpeg_color_space'.
+   color space of the input JPEG image, 'jpegColorSpace'.
 
    Write to stderr a message telling which type we picked.
 
@@ -515,72 +522,71 @@ set_color_spaces(const J_COLOR_SPACE jpeg_color_space,
        CMYK or YCCK to RGB, but can translate YCCK to CMYK.
     */
 
-    switch (jpeg_color_space) {
+    switch (jpegColorSpace) {
     case JCS_UNKNOWN:
         pm_error("Input JPEG image has 'unknown' color space "
-                 "(JCS_UNKNOWN).\n"
+                 "(JCS_UNKNOWN).  "
                  "We cannot interpret this image.");
         break;
     case JCS_GRAYSCALE:
-        *output_type_p = PGM_TYPE;
-        *out_color_space_p = JCS_GRAYSCALE;
+        *outputTypeP    = PGM_TYPE;
+        *outColorSpaceP = JCS_GRAYSCALE;
         break;
     case JCS_RGB:
-        *output_type_p = PPM_TYPE;
-        *out_color_space_p = JCS_RGB;
+        *outputTypeP    = PPM_TYPE;
+        *outColorSpaceP = JCS_RGB;
         break;
     case JCS_YCbCr:
-        *output_type_p = PPM_TYPE;
-        *out_color_space_p = JCS_RGB;
+        *outputTypeP    = PPM_TYPE;
+        *outColorSpaceP = JCS_RGB;
         /* Design note:  We found this YCbCr->RGB conversion increases
            user mode CPU time by 2.5%.  2002.10.12
         */
         break;
     case JCS_CMYK:
-        *output_type_p = PPM_TYPE;
-        *out_color_space_p = JCS_CMYK;
+        *outputTypeP    = PPM_TYPE;
+        *outColorSpaceP = JCS_CMYK;
         break;
     case JCS_YCCK:
-        *output_type_p = PPM_TYPE;
-        *out_color_space_p = JCS_CMYK;
+        *outputTypeP    = PPM_TYPE;
+        *outColorSpaceP = JCS_CMYK;
         break;
     default:
-        pm_error("Internal error: unknown color space code %d passed "
-                 "to set_color_spaces().", jpeg_color_space);
+        pm_error("INTERNAL ERROR: unknown color space code %d passed "
+                 "to setColorSpaces().", jpegColorSpace);
     }
-    pm_message("WRITING %s FILE", 
-               *output_type_p == PPM_TYPE ? "PPM" : "PGM");
+    pm_message("WRITING %s FILE", pnm_formattypenm(*outputTypeP));
 }
 
 
 
 static const char *
-colorspace_name(const J_COLOR_SPACE jpeg_color_space) {
-
-    const char *retval;
-
-    switch(jpeg_color_space) {
-    case JCS_UNKNOWN: retval = "JCS_UNKNOWN"; break;
-    case JCS_GRAYSCALE: retval= "JCS_GRAYSCALE"; break;
-    case JCS_RGB: retval = "JCS_RGB"; break;
-    case JCS_YCbCr: retval = "JCS_YCbCr"; break;
-    case JCS_CMYK: retval = "JCS_CMYK"; break;
-    case JCS_YCCK: retval = "JCS_YCCK"; break;
-    default: retval = "invalid"; break;
+colorspaceName(J_COLOR_SPACE const jpegColorSpace) {
+
+    const char * retval;
+
+    switch(jpegColorSpace) {
+    case JCS_UNKNOWN:   retval = "JCS_UNKNOWN";   break;
+    case JCS_GRAYSCALE: retval = "JCS_GRAYSCALE"; break;
+    case JCS_RGB:       retval = "JCS_RGB";       break;
+    case JCS_YCbCr:     retval = "JCS_YCbCr";     break;
+    case JCS_CMYK:      retval = "JCS_CMYK";      break;
+    case JCS_YCCK:      retval = "JCS_YCCK";      break;
+    default:            retval = "invalid";       break;
     };
-    return(retval);
+    return retval;
 }
 
 
 
 static void
-print_verbose_info_about_header(struct jpeg_decompress_struct const cinfo){
+printVerboseInfoAboutHeader(struct jpeg_decompress_struct const cinfo){
 
     struct jpeg_marker_struct * markerP;
 
-    pm_message("input color space is %d (%s)\n", 
-               cinfo.jpeg_color_space, 
-               colorspace_name(cinfo.jpeg_color_space));
+    pm_message("input color space is %d (%s)",
+               cinfo.jpeg_color_space,
+               colorspaceName(cinfo.jpeg_color_space));
 
     /* Note that raw information about marker, including marker type code,
        was already printed by the jpeg library, because of the jpeg library
@@ -595,15 +601,15 @@ print_verbose_info_about_header(struct jpeg_decompress_struct const cinfo){
     for (markerP = cinfo.marker_list; markerP; markerP = markerP->next) {
         if (markerP->marker == JPEG_COM)
             pm_message("Comment marker (COM):");
-        else if (markerP->marker >= JPEG_APP0 && 
+        else if (markerP->marker >= JPEG_APP0 &&
                  markerP->marker <= JPEG_APP0+15)
-            pm_message("Miscellaneous marker type APP%d:", 
+            pm_message("Miscellaneous marker type APP%d:",
                        markerP->marker - JPEG_APP0);
         else
             pm_message("Miscellaneous marker of unknown type (0x%X):",
                        markerP->marker);
-        
-        print_marker(*markerP);
+
+        printMarker(*markerP);
     }
 }
 
@@ -611,80 +617,84 @@ print_verbose_info_about_header(struct jpeg_decompress_struct const cinfo){
 
 static void
 beginJpegInput(struct jpeg_decompress_struct * const cinfoP,
-               const boolean verbose, 
-               const J_DCT_METHOD dct_method, 
-               const int max_memory_to_use, 
-               const boolean nosmooth) {
+               bool                            const verbose,
+               J_DCT_METHOD                    const dctMethod,
+               int                             const maxMemoryToUse,
+               bool                            const nosmooth) {
 /*----------------------------------------------------------------------------
    Read the JPEG header, create decompressor object (and
    allocate memory for it), set up decompressor.
 -----------------------------------------------------------------------------*/
     /* Read file header, set default decompression parameters */
-    jpeg_read_header(cinfoP, TRUE);
+    jpeg_read_header(cinfoP, true);
 
-    cinfoP->dct_method = dct_method;
-    if (max_memory_to_use != -1)
-        cinfoP->mem->max_memory_to_use = max_memory_to_use;
+    cinfoP->dct_method = dctMethod;
+    if (maxMemoryToUse != -1)
+        cinfoP->mem->max_memory_to_use = maxMemoryToUse;
     if (nosmooth)
-        cinfoP->do_fancy_upsampling = FALSE;
-    
+        cinfoP->do_fancy_upsampling = false;
+
 }
 
 
 
 static void
-print_comments(struct jpeg_decompress_struct const cinfo) {
-    
+printComments(struct jpeg_decompress_struct const cinfo) {
+
     struct jpeg_marker_struct * markerP;
 
     for (markerP = cinfo.marker_list;
-         markerP; markerP = markerP->next) 
+         markerP; markerP = markerP->next) {
         if (markerP->marker == JPEG_COM) {
             pm_message("COMMENT:");
-            print_marker(*markerP);
+            printMarker(*markerP);
         }
+    }
 }
 
 
 
 static void
-print_exif_info(struct jpeg_marker_struct const marker) {
+printExifInfo(struct jpeg_marker_struct const marker,
+              bool                      const wantTagTrace) {
 /*----------------------------------------------------------------------------
    Dump as informational messages the contents of the Jpeg miscellaneous
    marker 'marker', assuming it is an Exif header.
 -----------------------------------------------------------------------------*/
-    bool const wantTagTrace = false;
     exif_ImageInfo imageInfo;
     const char * error;
 
     assert(marker.data_length >= 6);
 
-    exif_parse(marker.data+6, marker.data_length-6, 
+    exif_parse(marker.data+6, marker.data_length-6,
                &imageInfo, wantTagTrace, &error);
 
     if (error) {
         pm_message("EXIF header is invalid.  %s", error);
         pm_strfree(error);
-    } else
-        exif_showImageInfo(&imageInfo, stderr);
+    } else {
+        exif_showImageInfo(&imageInfo);
+
+        exif_terminateImageInfo(&imageInfo);
+    }
 }
 
 
 
-static boolean
-is_exif(struct jpeg_marker_struct const marker) {
+static bool
+isExif(struct jpeg_marker_struct const marker) {
 /*----------------------------------------------------------------------------
-   Return true iff the JPEG miscellaneous marker 'marker' is an Exif 
+   Return true iff the JPEG miscellaneous marker 'marker' is an Exif
    header.
 -----------------------------------------------------------------------------*/
-    boolean retval;
-    
+    bool retval;
+
     if (marker.marker == JPEG_APP0+1) {
         if (marker.data_length >=6 && memcmp(marker.data, "Exif", 4) == 0)
-            retval = TRUE;
-        else retval = FALSE;
+            retval = true;
+        else retval = false;
     }
-    else retval = FALSE;
+    else retval = false;
 
     return retval;
 }
@@ -692,69 +702,71 @@ is_exif(struct jpeg_marker_struct const marker) {
 
 
 static void
-dump_exif(struct jpeg_decompress_struct const cinfo) {
+dumpExif(struct jpeg_decompress_struct const cinfo,
+         bool                          const wantTrace) {
 /*----------------------------------------------------------------------------
    Dump as informational messages the contents of all EXIF headers in
    the image, interpreted.  An EXIF header is an APP1 marker.
 -----------------------------------------------------------------------------*/
     struct jpeg_marker_struct * markerP;
-    boolean found_one;
+    bool foundOne;
 
-    found_one = FALSE;  /* initial value */
-
-    for (markerP = cinfo.marker_list; markerP; markerP = markerP->next) 
-        if (is_exif(*markerP)) {
+    for (markerP = cinfo.marker_list, foundOne = false;
+         markerP;
+         markerP = markerP->next) {
+        if (isExif(*markerP)) {
             pm_message("EXIF INFO:");
-            print_exif_info(*markerP);
-            found_one = TRUE;
+            printExifInfo(*markerP, wantTrace);
+            foundOne = true;
         }
-    if (!found_one)
+    }
+    if (!foundOne)
         pm_message("No EXIF info in image.");
 }
 
 
 
 static void
-save_exif(struct jpeg_decompress_struct const cinfo, 
-          const char *                  const exif_filespec) {
+saveExif(struct jpeg_decompress_struct const cinfo,
+         const char *                  const exifFileName) {
 /*----------------------------------------------------------------------------
-  Write the contents of the first Exif header in the image into the
-  file with filespec 'exif_filespec'.  Start with the two byte length
-  field.  If 'exif_filespec' is "-", write to standard output.
+  Write the contents of the first Exif header in the image into the file with
+  name 'exifFileName'.  Start with the two byte length field.  If
+  'exifFileName' is "-", write to standard output.
 
-  If there is no Exif header in the image, write just zero, as a two
-  byte pure binary integer.
+  If there is no Exif header in the image, write just zero, as a two byte pure
+  binary integer.
 -----------------------------------------------------------------------------*/
-    FILE * exif_file;
+    FILE * exifFileP;
     struct jpeg_marker_struct * markerP;
 
-    exif_file = pm_openw(exif_filespec);
+    exifFileP = pm_openw(exifFileName);
 
-    for (markerP = cinfo.marker_list; 
-         markerP && !is_exif(*markerP);
+    for (markerP = cinfo.marker_list;
+         markerP && !isExif(*markerP);
          markerP = markerP->next);
 
     if (markerP) {
-        pm_writebigshort(exif_file, markerP->data_length+2);
-        if (ferror(exif_file))
-            pm_error("Write of Exif header to %s failed on first byte.",
-                     exif_filespec);
+        pm_writebigshort(exifFileP, markerP->data_length+2);
+        if (ferror(exifFileP))
+            pm_error("Write of Exif header to file '%s' failed on first byte.",
+                     exifFileName);
         else {
             int rc;
 
-            rc = fwrite(markerP->data, 1, markerP->data_length, exif_file);
+            rc = fwrite(markerP->data, 1, markerP->data_length, exifFileP);
             if (rc != markerP->data_length)
                 pm_error("Write of Exif header to '%s' failed.  Wrote "
                          "length successfully, but then failed after "
-                         "%d characters of data.", exif_filespec, rc);
+                         "%d characters of data.", exifFileName, rc);
         }
     } else {
         /* There is no Exif header in the image */
-        pm_writebigshort(exif_file, 0);
-        if (ferror(exif_file))
-            pm_error("Write of Exif header file '%s' failed.", exif_filespec);
+        pm_writebigshort(exifFileP, 0);
+        if (ferror(exifFileP))
+            pm_error("Write of Exif header file '%s' failed.", exifFileName);
     }
-    pm_close(exif_file);
+    pm_close(exifFileP);
 }
 
 
@@ -762,25 +774,25 @@ save_exif(struct jpeg_decompress_struct const cinfo,
 static void
 tellDetails(struct jpeg_decompress_struct const cinfo,
             xelval                        const maxval,
-            int                           const output_type) {
+            int                           const outputType) {
 
-    print_verbose_info_about_header(cinfo);
+    printVerboseInfoAboutHeader(cinfo);
 
-    pm_message("Input image data precision = %d bits", 
+    pm_message("Input image data precision = %d bits",
                cinfo.data_precision);
     pm_message("Output file will have format %c%c "
-               "with max sample value of %d.", 
-               (char) (output_type/256), (char) (output_type % 256),
+               "with max sample value of %d.",
+               (char) (outputType/256), (char) (outputType % 256),
                maxval);
-}  
+}
 
 
 
-static enum colorspace
+static enum Colorspace
 computeColorSpace(struct jpeg_decompress_struct * const cinfoP,
-                  enum inklevel                   const inklevel) {
-    
-    enum colorspace colorSpace;
+                  enum Inklevel                   const inklevel) {
+
+    enum Colorspace colorSpace;
 
     if (cinfoP->out_color_space == JCS_GRAYSCALE)
         colorSpace = GRAYSCALE_COLORSPACE;
@@ -806,33 +818,53 @@ computeColorSpace(struct jpeg_decompress_struct * const cinfoP,
 
 static void
 convertRaster(struct jpeg_decompress_struct * const cinfoP,
-              enum colorspace                 const color_space,
+              enum Colorspace                 const colorspace,
               FILE *                          const ofP,
               xelval                          const format,
               unsigned int                    const maxval) {
-              
+/*----------------------------------------------------------------------------
+   Read the raster from the input and write it out in Netpbm format
+   to file *ofP, in format 'format', with maxval 'maxval'.
+-----------------------------------------------------------------------------*/
     JSAMPROW jpegbuffer;  /* Input buffer.  Filled by jpeg_scanlines() */
 
-    jpegbuffer = ((*cinfoP->mem->alloc_sarray)
-                  ((j_common_ptr) cinfoP, JPOOL_IMAGE,
-                   cinfoP->output_width * cinfoP->output_components, 
-                   (JDIMENSION) 1)
-        )[0];
+    xel * pnmbuffer;      /* Output buffer */
+
+    if (cinfoP->output_width > UINT_MAX/cinfoP->output_components)
+        pm_error("Image is too wide (%u columns) for computations",
+                 cinfoP->output_width);
+
+    MALLOCARRAY(jpegbuffer,
+                cinfoP->output_width * cinfoP->output_components);
+
+    if (!jpegbuffer)
+        pm_error("Failed to allocated a buffer for a row of %u columns "
+                 "of %u samples each",
+                 cinfoP->output_width, cinfoP->output_components);
+
+    pnmbuffer = pnm_allocrow(cinfoP->output_width);
 
     while (cinfoP->output_scanline < cinfoP->output_height) {
         jpeg_read_scanlines(cinfoP, &jpegbuffer, 1);
-        if (ofP)
-            copyPixelRow(jpegbuffer, cinfoP->output_width, 
-                         cinfoP->out_color_components,
-                         color_space, ofP, format, maxval);
+        if (ofP) {
+            convertPixelRow(jpegbuffer, cinfoP->output_width,
+                            cinfoP->out_color_components,
+                            colorspace, format, maxval, pnmbuffer);
+
+            pnm_writepnmrow(ofP, pnmbuffer, cinfoP->output_width,
+                            maxval, format, false);
+        }
     }
+
+    free(jpegbuffer);
+    pnm_freerow(pnmbuffer);
 }
 
 
 
 static void
-convertImage(FILE *                          const ofP, 
-             struct cmdlineInfo              const cmdline,
+convertImage(FILE *                          const ofP,
+             struct CmdlineInfo              const cmdline,
              struct jpeg_decompress_struct * const cinfoP) {
 
     int format;
@@ -840,23 +872,23 @@ convertImage(FILE *                          const ofP,
            or PGM_TYPE, which conveniently also pass as format values
            PPM_FORMAT and PGM_FORMAT.
         */
-    xelval maxval;  
+    xelval maxval;
         /* The maximum value of a sample (color component), both in the input
            and the output.
         */
-    enum colorspace color_space;
+    enum Colorspace colorspace;
         /* The color space of the pixels coming out of the JPEG decompressor */
 
-    beginJpegInput(cinfoP, cmdline.verbose, 
-                   cmdline.dct_method, 
-                   cmdline.max_memory_to_use, cmdline.nosmooth);
-                   
-    set_color_spaces(cinfoP->jpeg_color_space, &format,
-                     &cinfoP->out_color_space);
+    beginJpegInput(cinfoP, cmdline.verbose,
+                   cmdline.dctMethod,
+                   cmdline.maxMemoryToUse, cmdline.nosmooth);
+
+    setColorSpaces(cinfoP->jpeg_color_space, &format,
+                   &cinfoP->out_color_space);
 
     maxval = pm_bitstomaxval(cinfoP->data_precision);
 
-    if (cmdline.verbose) 
+    if (cmdline.verbose)
         tellDetails(*cinfoP, maxval, format);
 
     /* Calculate output image dimensions so we can allocate space */
@@ -868,22 +900,18 @@ convertImage(FILE *                          const ofP,
     if (ofP)
         /* Write pnm output header */
         pnm_writepnminit(ofP, cinfoP->output_width, cinfoP->output_height,
-                         maxval, format, FALSE);
+                         maxval, format, false);
 
-    pnmbuffer = pnm_allocrow(cinfoP->output_width);
-    
-    color_space = computeColorSpace(cinfoP, cmdline.inklevel);
-    
-    convertRaster(cinfoP, color_space, ofP, format, maxval);
+    colorspace = computeColorSpace(cinfoP, cmdline.inklevel);
+
+    convertRaster(cinfoP, colorspace, ofP, format, maxval);
 
     if (cmdline.comments)
-        print_comments(*cinfoP);
+        printComments(*cinfoP);
     if (cmdline.dumpexif)
-        dump_exif(*cinfoP);
-    if (cmdline.exif_filespec)
-        save_exif(*cinfoP, cmdline.exif_filespec);
-
-    pnm_freerow(pnmbuffer);
+        dumpExif(*cinfoP, cmdline.traceexif);
+    if (cmdline.exifFileName)
+        saveExif(*cinfoP, cmdline.exifFileName);
 
     /* Finish decompression and release decompressor memory. */
     jpeg_finish_decompress(cinfoP);
@@ -891,22 +919,21 @@ convertImage(FILE *                          const ofP,
 
 
 
-
 static void
 saveMarkers(struct jpeg_decompress_struct * const cinfoP) {
 
-    unsigned int app_type;
+    unsigned int appType;
     /* Get all the miscellaneous markers (COM and APPn) saved for our
        later access.
     */
     jpeg_save_markers(cinfoP, JPEG_COM, 65535);
-    for (app_type = 0; app_type <= 15; ++app_type) {
-        if (app_type == 0 || app_type == 14) {
+    for (appType = 0; appType <= 15; ++appType) {
+        if (appType == 0 || appType == 14) {
             /* The jpeg library uses APP0 and APP14 internally (see
                libjpeg.doc), so we don't mess with those.
             */
         } else
-            jpeg_save_markers(cinfoP, JPEG_APP0 + app_type, 65535);
+            jpeg_save_markers(cinfoP, JPEG_APP0 + appType, 65535);
     }
 }
 
@@ -914,10 +941,10 @@ saveMarkers(struct jpeg_decompress_struct * const cinfoP) {
 
 static void
 convertImages(FILE *                          const ofP,
-              struct cmdlineInfo              const cmdline,
+              struct CmdlineInfo              const cmdline,
               struct jpeg_decompress_struct * const cinfoP,
               struct sourceManager *          const sourceManagerP) {
-              
+
     if (cmdline.multiple) {
         unsigned int imageSequence;
         for (imageSequence = 0; dsDataLeft(sourceManagerP); ++imageSequence) {
@@ -943,19 +970,19 @@ convertImages(FILE *                          const ofP,
 
 
 int
-main(int argc, char **argv) {
+main(int argc, const char **argv) {
 
     FILE * ofP;
-    struct cmdlineInfo cmdline;
+    struct CmdlineInfo cmdline;
     struct jpeg_decompress_struct cinfo;
     struct jpeg_error_mgr jerr;
     struct sourceManager * sourceManagerP;
 
-    pnm_init(&argc, argv);
+    pm_proginit(&argc, argv);
 
-    parseCommandLine(argc, argv, &cmdline);
+    parseCommandLine(argc, (char **)argv, &cmdline);
 
-    if (cmdline.exif_filespec && streq(cmdline.exif_filespec, "-"))
+    if (cmdline.exifFileName && streq(cmdline.exifFileName, "-"))
         /* He's got exif going to stdout, so there can be no image output */
         ofP = NULL;
     else
@@ -967,14 +994,14 @@ main(int argc, char **argv) {
     cinfo.err = jpeg_std_error(&jerr);
     jpeg_create_decompress(&cinfo);
 
-    if (cmdline.trace_level == 0 && cmdline.verbose) 
+    if (cmdline.traceLevel == 0 && cmdline.verbose)
         cinfo.err->trace_level = 1;
-    else 
-        cinfo.err->trace_level = cmdline.trace_level;
-    
+    else
+        cinfo.err->trace_level = cmdline.traceLevel;
+
     saveMarkers(&cinfo);
 
-    sourceManagerP = dsCreateSource(cmdline.input_filespec);
+    sourceManagerP = dsCreateSource(cmdline.inputFileName);
 
     cinfo.src = dsJpegSourceMgr(sourceManagerP);
 
@@ -985,14 +1012,17 @@ main(int argc, char **argv) {
     if (ofP) {
         int rc;
         rc = fclose(ofP);
-        if (rc == EOF) 
+        if (rc == EOF)
             pm_error("Error writing output file.  Errno = %s (%d).",
                      strerror(errno), errno);
     }
 
     dsDestroySource(sourceManagerP);
 
-    free(cmdline.input_filespec);
-  
+    free(cmdline.inputFileName);
+
     exit(jerr.num_warnings > 0 ? EXIT_WARNING : EXIT_SUCCESS);
 }
+
+
+
diff --git a/converter/other/pamtoavs.c b/converter/other/pamtoavs.c
index 4764c9e8..2e2bf254 100644
--- a/converter/other/pamtoavs.c
+++ b/converter/other/pamtoavs.c
@@ -39,6 +39,7 @@ sample2char(sample const s,
 }
 
 
+
 #define THIS_SAMPLE_CHAR(PLANE) \
   sample2char(tuplerow[col][PLANE], pamP->maxval)
 
@@ -148,3 +149,5 @@ main(int argc, const char *argv[]) {
     return 0;
 }
 
+
+
diff --git a/converter/other/pamtodjvurle.c b/converter/other/pamtodjvurle.c
index cae9e026..cc3a119c 100644
--- a/converter/other/pamtodjvurle.c
+++ b/converter/other/pamtodjvurle.c
@@ -2,7 +2,7 @@
                                pamtodjvurle
 ******************************************************************************
   This program converts a PAM image to DjVu Color RLE format.
-  
+
   By Bryan Henderson, San Jose, CA April 2004.
 
   Contributed to the public domain by its author.
@@ -30,13 +30,13 @@ struct cmdlineInfo {
 
 
 
-static void 
-parseCommandLine(int argc, 
-                 char ** argv, 
+static void
+parseCommandLine(int argc,
+                 char ** argv,
                  struct cmdlineInfo  * const cmdlineP) {
 /* --------------------------------------------------------------------------
    Parse program command line described in Unix standard form by argc
-   and argv.  Return the information in the options as *cmdlineP.  
+   and argv.  Return the information in the options as *cmdlineP.
 
    If command line is internally inconsistent (invalid options, etc.),
    issue error message to stderr and abort program.
@@ -47,16 +47,16 @@ parseCommandLine(int argc,
     optEntry *option_def = malloc( 100*sizeof( optEntry ) );
     /* Instructions to pm_optParseOptions3 on how to parse our options. */
     optStruct3 opt;
-  
+
     unsigned int option_def_index;
     unsigned int transparentSpec;
 
     option_def_index = 0;   /* incremented by OPTENTRY */
-    OPTENT3(0, "transparent",   OPT_STRING, &cmdlineP->transparent, 
+    OPTENT3(0, "transparent",   OPT_STRING, &cmdlineP->transparent,
             &transparentSpec,        0);
     OPTENT3(0, "showcolormap",  OPT_FLAG, NULL,
             &cmdlineP->showcolormap,        0);
-  
+
     opt.opt_table = option_def;
     opt.short_allowed = FALSE;  /* We have no short (old-fashioned) options */
     opt.allowNegNum = FALSE;   /* We have no parms that are negative numbers */
@@ -73,7 +73,7 @@ parseCommandLine(int argc,
         cmdlineP->inputFilespec = argv[1];
     else
         cmdlineP->inputFilespec = "-";
-    
+
     if (argc-1 > 1)
         pm_error("Program takes at most one argument:  the file name.  "
                  "You specified %d", argc-1);
@@ -96,7 +96,7 @@ computeColorMap(struct pam *   const pamP,
     if (numColors > 0xFF0)
         pm_error("too many colors; "
                  "use pnmquant to reduce to no more than %u colors", 0xFF0);
-    
+
     if (show) {
         unsigned int colorIndex;
         fprintf(stderr, "Color map:\n");
@@ -123,7 +123,7 @@ makeDjvurleHeader(FILE *       const ofP,
                   struct pam * const pamP,
                   unsigned int const numColors,
                   tupletable   const colormap) {
-    
+
     unsigned int colorIndex;
 
     fprintf(ofP, "R6\n");
@@ -138,7 +138,7 @@ makeDjvurleHeader(FILE *       const ofP,
             blu = colormap[colorIndex]->tuple[PAM_BLU_PLANE];
         } else
             red = grn = blu = colormap[colorIndex]->tuple[0];
-        
+
         fputc(pnm_scalesample(red, pamP->maxval, 255), ofP);
         fputc(pnm_scalesample(grn, pamP->maxval, 255), ofP);
         fputc(pnm_scalesample(blu, pamP->maxval, 255), ofP);
@@ -166,18 +166,18 @@ colorEqual(tuple        comparand,
 
 
 
-static void 
-writeRleRun(FILE *       const ofP, 
+static void
+writeRleRun(FILE *       const ofP,
             struct pam * const pamP,
-            tuple        const color, 
+            tuple        const color,
             int          const count,
             tuplehash    const colorhash,
             tuple        const transcolor) {
 /*----------------------------------------------------------------------------
-  Write one DjVu Color RLE run to the file 'ofP'.  The run is 
+  Write one DjVu Color RLE run to the file 'ofP'.  The run is
   'count' pixels of color 'color', using the color index given by
   'colorhash' and assuming 'transcolor' is the transparent color.
-  
+
   'transcolor' is a 3-deep tuple with the same maxval as the image.
 -----------------------------------------------------------------------------*/
     uint32_t rlevalue;         /* RLE-encoded color/valuex */
@@ -192,7 +192,7 @@ writeRleRun(FILE *       const ofP,
             assert(found);
         }
         rlevalue = (index << 20) | count;
-      
+
         pm_writebiglong(ofP, rlevalue);
     }
 }
@@ -212,10 +212,10 @@ writeDjvurleRow(FILE *       const ofP,
 
     prevpixel = tupleRow[0];
     runlength = 0;
-    
+
     for (col = 0; col < pamP->width; ++col) {
         tuple const newpixel = tupleRow[col];      /* Current pixel color */
-        
+
         if (pnm_tupleequal(pamP, newpixel, prevpixel))
             /* This is a continuation of the current run */
             ++runlength;
@@ -223,7 +223,7 @@ writeDjvurleRow(FILE *       const ofP,
               /* The run is over.  Write it out and start a run of the next
                  color.
               */
-              writeRleRun(ofP, pamP, prevpixel, runlength, 
+              writeRleRun(ofP, pamP, prevpixel, runlength,
                           colorhash, transcolor);
               runlength = 1;
               prevpixel = newpixel;
@@ -232,7 +232,7 @@ writeDjvurleRow(FILE *       const ofP,
             /* Can't make the run any longer.  Write it out and start a
                new run.
             */
-            writeRleRun(ofP, pamP, prevpixel, runlength, 
+            writeRleRun(ofP, pamP, prevpixel, runlength,
                         colorhash, transcolor);
             runlength = 1;
         }
@@ -243,7 +243,7 @@ writeDjvurleRow(FILE *       const ofP,
 
 
 
-int 
+int
 main(int argc, char *argv[]) {
 
     FILE * const rlefile = stdout;
@@ -254,7 +254,7 @@ main(int argc, char *argv[]) {
     tuple ** tupleArray;       /* The image raster */
     tupletable colormap;       /* List of all of the colors used */
     unsigned int numColors;    /* Number of unique colors in the color map */
-    tuplehash colorhash; 
+    tuplehash colorhash;
         /* Mapping from color to index into colormap[] */
     tuple transcolor;
         /* Color that should be considered transparent */
@@ -268,10 +268,10 @@ main(int argc, char *argv[]) {
     tupleArray = pnm_readpam(ifP, &pam, PAM_STRUCT_SIZE(tuple_type));
 
     transcolor = pnm_parsecolor(cmdline.transparent, pam.maxval);
-    
+
     computeColorMap(&pam, tupleArray, &numColors, &colormap, &colorhash,
                     cmdline.showcolormap);
-    
+
     makeDjvurleHeader(rlefile, &pam, numColors, colormap);
 
     /* Write the raster */
@@ -279,11 +279,11 @@ main(int argc, char *argv[]) {
     {
         unsigned int row;
         for (row = 0; row < pam.height; ++row)
-            writeDjvurleRow(rlefile, &pam, tupleArray[row], colorhash, 
+            writeDjvurleRow(rlefile, &pam, tupleArray[row], colorhash,
                             transcolor);
     }
     /* Clean up */
-    
+
     pnm_freepamarray(tupleArray, &pam);
     pnm_freetupletable(&pam, colormap);
     pnm_destroytuplehash(colorhash);
@@ -292,3 +292,6 @@ main(int argc, char *argv[]) {
 
     return 0;
 }
+
+
+
diff --git a/converter/other/pamtofits.c b/converter/other/pamtofits.c
index 92e29c7e..fe81d94d 100644
--- a/converter/other/pamtofits.c
+++ b/converter/other/pamtofits.c
@@ -45,12 +45,12 @@ struct cmdlineInfo {
 
 
 
-static void 
+static void
 parseCommandLine(int argc, char ** argv,
                  struct cmdlineInfo * const cmdlineP) {
 /*--------------------------------------------------------------------------
    Parse program command line described in Unix standard form by argc
-   and argv.  Return the information in the options as *cmdlineP.  
+   and argv.  Return the information in the options as *cmdlineP.
 
    If command line is internally inconsistent (invalid options, etc.),
    issue error message to stderr and abort program.
@@ -95,7 +95,7 @@ parseCommandLine(int argc, char ** argv,
         cmdlineP->inputFileName = "-";
     else {
         cmdlineP->inputFileName = argv[1];
-        
+
         if (argc-1 > 1)
             pm_error("Too many arguments (%u).  The only non-option argument "
                      "is the input file name.", argc-1);
@@ -127,7 +127,7 @@ padToMultipleOf36Cards(unsigned int const nCardsAlreadyWritten) {
 
     unsigned int const npadCard = 36 - (nCardsAlreadyWritten % 36);
     unsigned int i;
-    
+
     for (i = 0; i < npadCard; ++i)
         writeHeaderCard("");
 }
@@ -146,7 +146,7 @@ writeFitsHeader(int    const bitpix,
 
     char buffer[80+1];
     unsigned int cardsWritten;
-                
+
     cardsWritten = 0;  /* initial value */
 
     sprintf(buffer, "%-20.20s%10.10s", "SIMPLE  =", "T");
@@ -178,7 +178,7 @@ writeFitsHeader(int    const bitpix,
     sprintf(buffer, "%-18.18s%12.5E", "BSCALE  =", bscale);
     writeHeaderCard(buffer);
     ++cardsWritten;
-    
+
     sprintf(buffer, "%-18.18s%12.5E", "BZERO   =", fitsBzero);
     writeHeaderCard(buffer);
     ++cardsWritten;
@@ -263,7 +263,7 @@ main(int argc, char * argv[]) {
            the default case, that PNM sample value is also the FITS "physical"
            value, but user options can change that.
         */
-    
+
     pnm_init(&argc, argv);
 
     parseCommandLine(argc, argv, &cmdline);
@@ -287,7 +287,7 @@ main(int argc, char * argv[]) {
     assert(datamax > datamin);
 
     bscale = (datamax - datamin) / pam.maxval;
-    
+
     if (pam.maxval > 255) {
         bitpix = 16;
         /* Because 16 bit FITS samples are signed, we have to do a 2**15
@@ -315,3 +315,6 @@ main(int argc, char * argv[]) {
 
     return 0;
 }
+
+
+
diff --git a/converter/other/pamtogif.c b/converter/other/pamtogif.c
index 9b833214..c41c778c 100644
--- a/converter/other/pamtogif.c
+++ b/converter/other/pamtogif.c
@@ -22,6 +22,12 @@
 static bool verbose;
 
 
+enum TransparencyType {TRANS_NONE, TRANS_COLOR, TRANS_ALPHA};
+    /* The source of transparency for the GIF: nothing is transparent,
+       All pixels of a certain color are transparent, or the alpha plane
+       in the input tells what is transparent.
+    */
+
 typedef unsigned int StringCode;
     /* A code to be place in the GIF raster.  It represents
        a string of one or more pixels.  You interpret this in the context
@@ -85,15 +91,20 @@ struct CmdlineInfo {
 
 static unsigned int
 pamAlphaPlane(struct pam * const pamP) {
+/*----------------------------------------------------------------------------
+   The number of the alpha plane, or zero if there is no alpha plane, as
+   indicated by *pamP.
 
+   Note that the alpha plane is never zero in any Netpbm tuple type.
+-----------------------------------------------------------------------------*/
     unsigned int alphaPlane;
 
     if (streq(pamP->tuple_type, "RGB_ALPHA"))
         alphaPlane = 3;
     else if (streq(pamP->tuple_type, "GRAYSCALE_ALPHA"))
-        alphaPlane = 2;
+        alphaPlane = 1;
     else if (streq(pamP->tuple_type, "BLACKANDWHITE_ALPHA"))
-        alphaPlane = 2;
+        alphaPlane = 1;
     else
         alphaPlane = 0;
 
@@ -107,7 +118,7 @@ pamAlphaPlane(struct pam * const pamP) {
 
 
 static void
-parseCommandLine(int argc, char ** argv,
+parseCommandLine(int argc, const char ** argv,
                  struct CmdlineInfo * const cmdlineP) {
 /*----------------------------------------------------------------------------
    Parse the program arguments (given by argc and argv) into a form
@@ -161,7 +172,7 @@ parseCommandLine(int argc, char ** argv,
     opt.short_allowed = FALSE;  /* We have no short (old-fashioned) options */
     opt.allowNegNum = FALSE;  /* We have no parms that are negative numbers */
 
-    pm_optParseOptions3(&argc, argv, opt, sizeof(opt), 0);
+    pm_optParseOptions4(&argc, argv, opt, sizeof(opt), 0);
         /* Uses and sets argc, argv, and some of *cmdlineP and others. */
 
     if (argc-1 == 0)
@@ -201,9 +212,9 @@ Putword(int const w, FILE * const fp) {
 
 
 static int
-closestColor(tuple         const color,
-             struct pam *  const pamP,
-             struct Cmap * const cmapP) {
+closestColor(tuple               const color,
+             struct pam *        const pamP,
+             const struct Cmap * const cmapP) {
 /*----------------------------------------------------------------------------
    Return the colormap index of the color in the colormap *cmapP
    that is closest to the color 'color', whose format is specified by
@@ -305,7 +316,7 @@ rowReader_destroy(RowReader * const rdrP) {
 
 
 static void
-rowReaderSkipRows(RowReader *  const rdrP,
+rowReader_skipRows(RowReader *  const rdrP,
                   unsigned int const rowCount,
                   bool *       const eofP) {
 /*----------------------------------------------------------------------------
@@ -336,7 +347,7 @@ rowReaderSkipRows(RowReader *  const rdrP,
 
 
 static void
-rowReaderGotoNextInterlaceRow(RowReader * const rdrP) {
+rowReader_gotoNextInterlaceRow(RowReader * const rdrP) {
 /*----------------------------------------------------------------------------
   Position reader to the next row in the interlace pattern, assuming it
   is now positioned immediately after the current row.
@@ -352,16 +363,16 @@ rowReaderGotoNextInterlaceRow(RowReader * const rdrP) {
 
     switch (rdrP->pass) {
     case MULT8PLUS0:
-        rowReaderSkipRows(rdrP, 7, &endOfPass);
+        rowReader_skipRows(rdrP, 7, &endOfPass);
         break;
     case MULT8PLUS4:
-        rowReaderSkipRows(rdrP, 7, &endOfPass);
+        rowReader_skipRows(rdrP, 7, &endOfPass);
         break;
     case MULT4PLUS2:
-        rowReaderSkipRows(rdrP, 3, &endOfPass);
+        rowReader_skipRows(rdrP, 3, &endOfPass);
         break;
     case MULT2PLUS1:
-        rowReaderSkipRows(rdrP, 1, &endOfPass);
+        rowReader_skipRows(rdrP, 1, &endOfPass);
         break;
     }
 
@@ -376,15 +387,15 @@ rowReaderGotoNextInterlaceRow(RowReader * const rdrP) {
         switch (rdrP->pass) {
         case MULT8PLUS0:
             rdrP->pass = MULT8PLUS4;
-            rowReaderSkipRows(rdrP, 4, &endOfPass);
+            rowReader_skipRows(rdrP, 4, &endOfPass);
             break;
         case MULT8PLUS4:
             rdrP->pass = MULT4PLUS2;
-            rowReaderSkipRows(rdrP, 2, &endOfPass);
+            rowReader_skipRows(rdrP, 2, &endOfPass);
             break;
         case MULT4PLUS2:
             rdrP->pass = MULT2PLUS1;
-            rowReaderSkipRows(rdrP, 1, &endOfPass);
+            rowReader_skipRows(rdrP, 1, &endOfPass);
             break;
         case MULT2PLUS1:
             rdrP->eof = TRUE;
@@ -395,9 +406,8 @@ rowReaderGotoNextInterlaceRow(RowReader * const rdrP) {
 
 
 
-
 static void
-rowReaderGotoNextStraightRow(RowReader * const rdrP) {
+rowReader_gotoNextStraightRow(RowReader * const rdrP) {
 /*----------------------------------------------------------------------------
   Position reader to the next row in a straight, non-interlace
   pattern, assuming the file is now positioned immediately after the
@@ -424,32 +434,39 @@ rowReader_read(RowReader * const rdrP,
     ++rdrP->nextRow;
 
     if (rdrP->interlace)
-        rowReaderGotoNextInterlaceRow(rdrP);
+        rowReader_gotoNextInterlaceRow(rdrP);
     else
-        rowReaderGotoNextStraightRow(rdrP);
+        rowReader_gotoNextStraightRow(rdrP);
 }
 
 
 
 static unsigned int
-gifPixel(struct pam *   const pamP,
-         tuple          const tuple,
-         unsigned int   const alphaPlane,
-         sample         const alphaThreshold,
-         struct Cmap *  const cmapP) {
+gifPixel(struct pam *        const pamP,
+         tuple               const tuple,
+         unsigned int        const alphaPlane,
+         sample              const alphaThreshold,
+         const struct Cmap * const cmapP) {
 /*----------------------------------------------------------------------------
-   Return as *colorIndexP the colormap index of the tuple 'tuple',
-   whose format is described by *pamP, using colormap *cmapP.
+   Return the colormap index of the tuple 'tuple', whose format is described
+   by *pamP, using colormap *cmapP.
+
+   'alphaPlane' is the number of the plane in 'tuple' to use for transparency,
+   or zero if we aren't to use any plane for transparency.  (note that Caller
+   cannot specify plane 0 for transparency).
 
-   'alphaThreshold' is the alpha level below which we consider a
-   pixel transparent for GIF purposes.
+   'alphaThreshold' is the alpha level below which we consider a pixel
+   transparent for GIF purposes.
+
+   If 'alphaPlane' is nonzero, we assume *cmapP contains a transparent
+   entry.
 -----------------------------------------------------------------------------*/
     int colorIndex;
 
-    if (alphaPlane && tuple[alphaPlane] < alphaThreshold &&
-        cmapP->haveTransparent)
+    if (alphaPlane && tuple[alphaPlane] < alphaThreshold) {
+        assert(cmapP->haveTransparent);
         colorIndex = cmapP->transparent;
-    else {
+    } else {
         int found;
 
         pnm_lookuptuple(pamP, cmapP->tuplehash, tuple,
@@ -1251,80 +1268,6 @@ writePixelUncompressed(LzwCompressor * const lzwP,
 }
 
 
-static void
-writeRaster(struct pam *  const pamP,
-            RowReader *   const rowReaderP,
-            unsigned int  const alphaPlane,
-            unsigned int  const alphaThreshold,
-            struct Cmap * const cmapP,
-            unsigned int  const initBits,
-            FILE *        const ofP,
-            bool          const lzw,
-            bool          const noclear) {
-/*----------------------------------------------------------------------------
-   Write the raster to file 'ofP'.
-
-   Get the raster to write from 'rowReaderP', which gives tuples whose
-   format is described by 'pamP'.
-
-   Use the colormap 'cmapP' to generate the raster ('rowReaderP' gives
-   pixel values as RGB samples; the GIF raster is colormap indices).
-
-   Write the raster using LZW compression, or uncompressed depending
-   on 'lzw'.
-
-   If 'noclear', don't use any GIF clear codes in the output; i.e. don't
-   recompute the string table from current input.  Once the string table gets
-   to maximum size, just keep using that table for the rest of the image.
------------------------------------------------------------------------------*/
-    LzwCompressor * lzwP;
-    tuple * tuplerow;
-    unsigned int nRowsDone;
-        /* Number of rows we have read so far from the the input (the
-           last of which is the one we're working on now).  Note that
-           in case of interlace, this is not the same thing as the row
-           number of the current row.
-        */
-
-    lzwP = lzw_create(ofP, initBits, lzw, noclear, pamP->height * pamP->width);
-
-    tuplerow = pnm_allocpamrow(pamP);
-
-    lzw_clearBlock(lzwP);
-
-    nRowsDone = 0;
-
-    while (nRowsDone < pamP->height) {
-        unsigned int col;
-
-        rowReader_read(rowReaderP, tuplerow);
-
-        for (col = 0; col < pamP->width; ++col) {
-            unsigned int const colorIndex =
-                gifPixel(pamP, tuplerow[col], alphaPlane, alphaThreshold,
-                         cmapP);
-
-                /* The value for the pixel in the GIF image.  I.e. the colormap
-                   index.
-                */
-            if (lzw)
-                lzw_encodePixel(lzwP, colorIndex);
-            else
-                writePixelUncompressed(lzwP, colorIndex);
-        }
-        ++nRowsDone;
-    }
-    /* Gif is no good with no pixels; fortunately, that's impossible: */
-    assert(nRowsDone > 0);
-
-    lzw_flush(lzwP);
-
-    pnm_freepamrow(tuplerow);
-
-    lzw_destroy(lzwP);
-}
-
-
 
 static void
 writeGlobalColorMap(FILE *              const ofP,
@@ -1378,6 +1321,23 @@ writeGlobalColorMap(FILE *              const ofP,
 
 
 static void
+reportImageInfo(bool         const interlace,
+                unsigned int const background,
+                unsigned int const bitsPerPixel) {
+
+    if (verbose) {
+        if (interlace)
+            pm_message("interlaced");
+        else
+            pm_message("not interlaced");
+        pm_message("Background color index = %u", background);
+        pm_message("%u bits per pixel", bitsPerPixel);
+    }
+}
+
+
+
+static void
 writeGifHeader(FILE *              const ofP,
                unsigned int        const width,
                unsigned int        const height,
@@ -1434,6 +1394,15 @@ writeGifHeader(FILE *              const ofP,
 
 
 static void
+writeImageSeparator(FILE * const ofP) {
+
+    fputc(',', ofP);
+
+}
+
+
+
+static void
 writeImageHeader(FILE *       const ofP,
                  unsigned int const leftOffset,
                  unsigned int const topOffset,
@@ -1460,37 +1429,110 @@ writeImageHeader(FILE *       const ofP,
 
 
 static void
-reportImageInfo(bool         const interlace,
-                unsigned int const background,
-                unsigned int const bitsPerPixel) {
+writeRaster(struct pam *        const pamP,
+            RowReader *         const rowReaderP,
+            unsigned int        const alphaPlane,
+            unsigned int        const alphaThreshold,
+            const struct Cmap * const cmapP,
+            unsigned int        const initBits,
+            FILE *              const ofP,
+            bool                const lzw,
+            bool                const noclear) {
+/*----------------------------------------------------------------------------
+   Write the raster to file 'ofP'.
 
-    if (verbose) {
-        if (interlace)
-            pm_message("interlaced");
-        else
-            pm_message("not interlaced");
-        pm_message("Background color index = %u", background);
-        pm_message("%u bits per pixel", bitsPerPixel);
+   Get the raster to write from 'rowReaderP', which gives tuples whose
+   format is described by 'pamP'.
+
+   'alphaPlane' is the number of the plane in the tuples supplied by
+   'rowReaderP' that we should use for transparency information, and
+   'alphaThreshold' is the value in that plane below which we should consider
+   the pixel transparent for GIF purposes.
+
+   'alphaPlane' is zero to indicate we should not use any plane as an alpha
+   plane (so it's not possible to specify Plane 0 as alpha).
+
+   Use the colormap 'cmapP' to generate the raster ('rowReaderP' gives
+   pixel values as RGB samples; the GIF raster is colormap indices).
+
+   Write the raster using LZW compression, or uncompressed depending
+   on 'lzw'.
+
+   If 'noclear', don't use any GIF clear codes in the output; i.e. don't
+   recompute the string table from current input.  Once the string table gets
+   to maximum size, just keep using that table for the rest of the image.
+-----------------------------------------------------------------------------*/
+    LzwCompressor * lzwP;
+    tuple * tuplerow;
+    unsigned int nRowsDone;
+        /* Number of rows we have read so far from the the input (the
+           last of which is the one we're working on now).  Note that
+           in case of interlace, this is not the same thing as the row
+           number of the current row.
+        */
+
+    lzwP = lzw_create(ofP, initBits, lzw, noclear, pamP->height * pamP->width);
+
+    tuplerow = pnm_allocpamrow(pamP);
+
+    lzw_clearBlock(lzwP);
+
+    nRowsDone = 0;
+
+    while (nRowsDone < pamP->height) {
+        unsigned int col;
+
+        rowReader_read(rowReaderP, tuplerow);
+
+        for (col = 0; col < pamP->width; ++col) {
+            unsigned int const colorIndex =
+                gifPixel(pamP, tuplerow[col], alphaPlane, alphaThreshold,
+                         cmapP);
+
+                /* The value for the pixel in the GIF image.  I.e. the colormap
+                   index.
+                */
+            if (lzw)
+                lzw_encodePixel(lzwP, colorIndex);
+            else
+                writePixelUncompressed(lzwP, colorIndex);
+        }
+        ++nRowsDone;
     }
+    /* Gif is no good with no pixels; fortunately, that's impossible: */
+    assert(nRowsDone > 0);
+
+    lzw_flush(lzwP);
+
+    pnm_freepamrow(tuplerow);
+
+    lzw_destroy(lzwP);
 }
 
 
 
 static void
-gifEncode(struct pam *  const pamP,
-          FILE *        const ofP,
-          pm_filepos    const rasterPos,
-          bool          const gInterlace,
-          int           const background,
-          unsigned int  const bitsPerPixel,
-          struct Cmap * const cmapP,
-          char          const comment[],
-          float         const aspect,
-          bool          const lzw,
-          bool          const noclear) {
+writeEndOfImage(FILE * const ofP) {
 
-    unsigned int const leftOffset = 0;
-    unsigned int const topOffset  = 0;
+    /* An empty block marks the end of a series of blocks */
+
+    fputc(0, ofP);
+}
+
+
+
+static void
+writeGifImage(FILE *              const ofP,
+              unsigned int        const leftOffset,
+              unsigned int        const topOffset,
+              struct pam *        const pamP,
+              pm_filepos          const rasterPos,
+              bool                const gInterlace,
+              unsigned int        const bitsPerPixel,
+              bool                const lzw,
+              bool                const noclear,
+              bool                const usingAlpha,
+              const struct Cmap * const cmapP) {
 
     unsigned int const initCodeSize = bitsPerPixel <= 1 ? 2 : bitsPerPixel;
         /* The initial code size */
@@ -1500,10 +1542,56 @@ gifEncode(struct pam *  const pamP,
            pixels in the output image.
         */
 
-    unsigned int const alphaPlane = pamAlphaPlane(pamP);
+    unsigned int const alphaPlane = usingAlpha ? pamAlphaPlane(pamP) : 0;
 
     RowReader * rowReaderP;
 
+    writeImageSeparator(ofP);
+
+    writeImageHeader(ofP, leftOffset, topOffset, pamP->width, pamP->height,
+                     gInterlace, initCodeSize);
+
+    rowReaderP = rowReader_create(pamP, rasterPos, gInterlace);
+
+    writeRaster(pamP, rowReaderP, alphaPlane, alphaThreshold,
+                cmapP, initCodeSize + 1, ofP, lzw, noclear);
+
+    rowReader_destroy(rowReaderP);
+
+    writeEndOfImage(ofP);
+}
+
+
+
+static void
+writeGifStreamTerminator(FILE * const ofP) {
+
+    fputc(';', ofP);
+}
+
+
+
+static void
+writeGif(struct pam *        const pamP,
+         FILE *              const ofP,
+         pm_filepos          const rasterPos,
+         bool                const gInterlace,
+         int                 const background,
+         unsigned int        const bitsPerPixel,
+         const struct Cmap * const cmapP,
+         char                const comment[],
+         float               const aspect,
+         bool                const lzw,
+         bool                const noclear,
+         bool                const usingAlpha) {
+/*----------------------------------------------------------------------------
+   'usingAlpha' means use the alpha (transparency) plane, if there is one, to
+   determine which GIF pixels are transparent.  When this is true, the
+   colormap *cmapP must contain a transparent entry.
+-----------------------------------------------------------------------------*/
+    unsigned int const leftOffset = 0;
+    unsigned int const topOffset  = 0;
+
     reportImageInfo(gInterlace, background, bitsPerPixel);
 
     if (pamP->width > 65535)
@@ -1517,34 +1605,32 @@ gifEncode(struct pam *  const pamP,
     writeGifHeader(ofP, pamP->width, pamP->height, background,
                    bitsPerPixel, cmapP, comment, aspect);
 
-    /* Write an Image separator */
-    fputc(',', ofP);
+    writeGifImage(ofP, leftOffset, topOffset, pamP, rasterPos,
+                  gInterlace, bitsPerPixel, lzw, noclear, usingAlpha,
+                  cmapP);
 
-    writeImageHeader(ofP, leftOffset, topOffset, pamP->width, pamP->height,
-                     gInterlace, initCodeSize);
-
-    rowReaderP = rowReader_create(pamP, rasterPos, gInterlace);
-
-    /* Write the actual raster */
-
-    writeRaster(pamP, rowReaderP, alphaPlane, alphaThreshold,
-                cmapP, initCodeSize + 1, ofP, lzw, noclear);
-
-    rowReader_destroy(rowReaderP);
-
-    /* Write out a zero length data block (to end the series) */
-    fputc(0, ofP);
-
-    /* Write the GIF file terminator */
-    fputc(';', ofP);
+    writeGifStreamTerminator(ofP);
 }
 
 
 
 static void
-reportTransparent(struct Cmap * const cmapP) {
+reportTransparent(enum TransparencyType const transType,
+                  const struct Cmap *   const cmapP) {
 
     if (verbose) {
+        switch (transType) {
+        case TRANS_NONE:
+            pm_message("Not making transparent pixels");
+            break;
+        case TRANS_COLOR:
+            pm_message("Making pixels of a certain color transparent");
+            break;
+        case TRANS_ALPHA:
+            pm_message("Making pixels transparent per input alpha mask");
+            break;
+        }
+
         if (cmapP->haveTransparent) {
             tuple const color = cmapP->color[cmapP->transparent];
             pm_message("Color %u (%lu, %lu, %lu) is transparent",
@@ -1560,42 +1646,46 @@ reportTransparent(struct Cmap * const cmapP) {
 
 
 static void
-computeTransparent(char          const colorarg[],
-                   bool          const usingFakeTrans,
-                   unsigned int  const fakeTransparent,
-                   struct Cmap * const cmapP) {
+computeTransparent(enum TransparencyType const transType,
+                   char                  const colorarg[],
+                   unsigned int          const fakeTransparent,
+                   struct Cmap *         const cmapP) {
 /*----------------------------------------------------------------------------
    Figure out the color index (index into the colormap) of the color
-   that is to be transparent in the GIF.
+   that is to be transparent in the GIF and set it in the colormap.
 
-   colorarg[] is the string that specifies the color the user wants to
-   be transparent (e.g. "red", "#fefefe").  Its maxval is the maxval
-   of the colormap.  'cmap' is the full colormap except that its
-   'transparent' component isn't valid.
+   'transType' tells what the source of the transparency is.
 
-   colorarg[] is a standard Netpbm color specification, except that
-   may have a "=" prefix, which means it specifies a particular exact
-   color, as opposed to without the "=", which means "the color that
-   is closest to this and actually in the image."
+   If 'transType' says all pixels of a single foreground color are to be
+   transparent:
 
-   colorarg[] null means the color didn't ask for a particular color
-   to be transparent.
+     'colorarg' is the specification of that color.  Its
+     maxval is the maxval of the colormap.
 
-   Establish no transparent color if colorarg[] specifies an exact
-   color and that color is not in the image.  Also issue an
-   informational message.
+     colorarg[] is a standard Netpbm color specification (e.g. "red",
+     "#fefefe"), except that may have a "=" prefix, which means it specifies a
+     particular exact color, as opposed to without the "=", which means "the
+     color that is closest to this and actually in the image."
 
-   'usingFakeTrans' means pixels will be transparent because of something
-   other than their foreground color, and 'fakeTransparent' is the
-   color map index for transparent colors.
+     Establish no transparent color if colorarg[] specifies an exact
+     color and that color is not in the image.  Also issue an
+     informational message.
+
+   If 'transType' says an input alpha channel will dtermine what pixels are
+   transparent:
+
+     'fakeTransparent' is the special color map index for transparent pixels.
 -----------------------------------------------------------------------------*/
-    if (colorarg) {
+    switch (transType) {
+    case TRANS_COLOR: {
         const char * colorspec;
         bool exact;
         tuple transcolor;
         int found;
         int colorindex;
 
+        assert(colorarg);
+
         if (colorarg[0] == '=') {
             colorspec = &colorarg[1];
             exact = TRUE;
@@ -1619,13 +1709,16 @@ computeTransparent(char          const colorarg[],
             pm_message("Warning: specified transparent color "
                        "does not occur in image.");
         }
-    } else if (usingFakeTrans) {
+    } break;
+    case TRANS_ALPHA: {
         cmapP->haveTransparent = TRUE;
         cmapP->transparent = fakeTransparent;
-    } else
+    } break;
+    case TRANS_NONE: {
         cmapP->haveTransparent = FALSE;
-
-    reportTransparent(cmapP);
+    } break;
+    }  /* switch */
+    reportTransparent(transType, cmapP);
 }
 
 
@@ -1841,14 +1934,14 @@ computeColormapFromInput(struct pam *   const pamP,
 
 
 static void
-computeLibnetpbmColormap(struct pam *   const pamP,
-                         bool           const haveAlpha,
-                         const char *   const mapfile,
-                         tuple *        const color,
-                         tuplehash *    const tuplehashP,
-                         struct pam *   const mapPamP,
-                         unsigned int * const colorCountP,
-                         bool           const sort) {
+computeLibnetpbmColormap(struct pam *          const pamP,
+                         enum TransparencyType const transType,
+                         const char *          const mapfile,
+                         tuple *               const color,
+                         tuplehash *           const tuplehashP,
+                         struct pam *          const mapPamP,
+                         unsigned int *        const colorCountP,
+                         bool                  const sort) {
 /*----------------------------------------------------------------------------
    Compute a colormap, libnetpbm style, for the image described by
    'pamP', which is positioned to the raster.
@@ -1862,21 +1955,23 @@ computeLibnetpbmColormap(struct pam *   const pamP,
    The tuples of the color map have a meaningful depth of 1 (grayscale) or 3
    (color) and *mapPamP reflects that.
 
-   While we're at it, count the colors and validate that there aren't
-   too many.  Return the count as *colorCountP.  In determining if there are
-   too many, allow one slot for a fake transparency color if 'haveAlpha'
-   is true.  If there are too many, issue an error message and abort the
+   While we're at it, count the colors and validate that there aren't too
+   many.  Return the count as *colorCountP.  In determining if there are too
+   many, allow one slot for a fake transparency color if 'transType' is
+   'TRANS_ALPHA'.  If there are too many, issue an error message and abort the
    program.
 
    'sort' means to sort the colormap by red intensity, then by green
    intensity, then by blue intensity, as opposed to arbitrary order.
 -----------------------------------------------------------------------------*/
-    unsigned int const maxcolors = haveAlpha ? MAXCMAPSIZE - 1 : MAXCMAPSIZE;
+    unsigned int const maxcolors =
+        transType == TRANS_ALPHA ? MAXCMAPSIZE - 1 : MAXCMAPSIZE;
         /* The most colors we can tolerate in the image.  If we have
            our own made-up entry in the colormap for transparency, it
            isn't included in this count.
         */
-    unsigned int const nInputComp = haveAlpha ? pamP->depth - 1 : pamP->depth;
+    unsigned int const nInputComp =
+        pamAlphaPlane(pamP) ? pamP->depth - 1 : pamP->depth;
         /* Number of color components (not alpha) in the input image */
 
     unsigned int i;
@@ -1932,22 +2027,23 @@ destroyCmap(struct Cmap * const cmapP) {
 
 
 int
-main(int argc, char *argv[]) {
+main(int argc, const char ** argv) {
+
     struct CmdlineInfo cmdline;
     FILE * ifP;
     struct pam pam;
     unsigned int bitsPerPixel;
     pm_filepos rasterPos;
-
     struct Cmap cmap;
         /* The colormap, with all its accessories */
+    enum TransparencyType transType;
     unsigned int fakeTransparent;
         /* colormap index of the fake transparency color we're using to
-           implement the alpha mask.  Undefined if we're not doing an alpha
-           mask.
+           implement the alpha mask.  Defined only if 'transType' is
+           TRANS_ALPHA.
         */
 
-    pnm_init(&argc, argv);
+    pm_proginit(&argc, argv);
 
     parseCommandLine(argc, argv, &cmdline);
 
@@ -1959,13 +2055,17 @@ main(int argc, char *argv[]) {
 
     pm_tell2(ifP, &rasterPos, sizeof(rasterPos));
 
-    computeLibnetpbmColormap(&pam, !!pamAlphaPlane(&pam), cmdline.mapfile,
+    transType = cmdline.transparent ? TRANS_COLOR :
+        pamAlphaPlane(&pam) ? TRANS_ALPHA :
+        TRANS_NONE;
+
+    computeLibnetpbmColormap(&pam, transType, cmdline.mapfile,
                              cmap.color, &cmap.tuplehash,
                              &cmap.pam, &cmap.cmapSize, cmdline.sort);
 
     assert(cmap.pam.maxval == pam.maxval);
 
-    if (pamAlphaPlane(&pam)) {
+    if (transType == TRANS_ALPHA) {
         /* Add a fake entry to the end of the colormap for transparency.
            Make its color black.
         */
@@ -1974,13 +2074,12 @@ main(int argc, char *argv[]) {
 
     bitsPerPixel = cmap.cmapSize == 1 ? 1 : nSignificantBits(cmap.cmapSize-1);
 
-    computeTransparent(cmdline.transparent,
-                       !!pamAlphaPlane(&pam), fakeTransparent, &cmap);
+    computeTransparent(transType, cmdline.transparent, fakeTransparent, &cmap);
 
-    /* All set, let's do it. */
-    gifEncode(&pam, stdout, rasterPos,
-              cmdline.interlace, 0, bitsPerPixel, &cmap, cmdline.comment,
-              cmdline.aspect, !cmdline.nolzw, cmdline.noclear);
+    writeGif(&pam, stdout, rasterPos,
+             cmdline.interlace, 0, bitsPerPixel, &cmap, cmdline.comment,
+             cmdline.aspect, !cmdline.nolzw, cmdline.noclear,
+             transType==TRANS_ALPHA);
 
     destroyCmap(&cmap);
 
diff --git a/converter/other/pamtohdiff.c b/converter/other/pamtohdiff.c
index 8d785f5b..d28cdb14 100644
--- a/converter/other/pamtohdiff.c
+++ b/converter/other/pamtohdiff.c
@@ -64,7 +64,7 @@ parseCommandLine(int argc, char ** argv,
 
 
 
-int 
+int
 main(int argc, char *argv[]) {
     FILE *ifP;
     struct cmdlineInfo cmdline;
@@ -106,7 +106,7 @@ main(int argc, char *argv[]) {
        knows the "20" can't be +20, because that would create the
        sample 90 + 20 = 110, and violate maxval.  So it must be -80.
        Modulus arithmetic by the interpreter effectively makes that
-       decision.  
+       decision.
     */
 
 
@@ -115,7 +115,7 @@ main(int argc, char *argv[]) {
        all +/- half of maxval, you can see positive transitions as bright
        spots and negative transitions as dark spots.
     */
-    
+
     {
         unsigned int const bias = outpam.maxval/2;
         for (row = 0; row < inpam.height; ++row) {
@@ -124,7 +124,7 @@ main(int argc, char *argv[]) {
             for (col = 0; col < inpam.width; ++col) {
             unsigned int plane;
             for (plane = 0; plane < inpam.depth; ++plane) {
-                
+
                 sample const sampleValue = inrow[col][plane];
                 int const difference = sampleValue - prevrow[col][plane];
                 outrow[col][plane] = (difference + bias) % (outpam.maxval+1);
@@ -141,3 +141,5 @@ main(int argc, char *argv[]) {
     exit(0);
 }
 
+
+
diff --git a/converter/other/pamtohtmltbl.c b/converter/other/pamtohtmltbl.c
index d1482073..960d26b8 100644
--- a/converter/other/pamtohtmltbl.c
+++ b/converter/other/pamtohtmltbl.c
@@ -24,7 +24,7 @@ parseCommandLine(int argc, char ** argv,
                  struct cmdlineInfo * const cmdlineP) {
 /*----------------------------------------------------------------------------
    parse program command line described in Unix standard form by argc
-   and argv.  Return the information in the options as *cmdlineP.  
+   and argv.  Return the information in the options as *cmdlineP.
 
    If command line is internally inconsistent (invalid options, etc.),
    issue error message to stderr and abort program.
@@ -44,7 +44,7 @@ parseCommandLine(int argc, char ** argv,
     MALLOCARRAY_NOFAIL(option_def, 100);
 
     option_def_index = 0;   /* incremented by OPTENT3 */
-    OPTENT3(0, "verbose",     OPT_FLAG,   NULL,                  
+    OPTENT3(0, "verbose",     OPT_FLAG,   NULL,
             &cmdlineP->verbose,       0 );
     OPTENT3(0, "transparent", OPT_STRING, &cmdlineP->transparent,
             &transparentSpec,  0 );
@@ -71,23 +71,22 @@ parseCommandLine(int argc, char ** argv,
 
 
 
-
 static void
 pripix(struct pam * const pamP,
-       tuple        const color, 
-       unsigned int const rectWidth, 
-       unsigned int const rectHeight, 
+       tuple        const color,
+       unsigned int const rectWidth,
+       unsigned int const rectHeight,
        tuple        const transparentColor) {
 
     if (rectWidth > 0 && rectHeight > 0) {
         printf("<TD VALIGN=CENTER ALIGN=CENTER");
 
-        if (rectWidth != 1) 
+        if (rectWidth != 1)
             printf(" COLSPAN=%d", rectWidth);
-        if (rectHeight != 1) 
+        if (rectHeight != 1)
             printf(" ROWSPAN=%d", rectHeight);
 
-        if (transparentColor && 
+        if (transparentColor &&
             !pnm_tupleequal(pamP, color,transparentColor)) {
             /* No BGCOLOR attribute */
         } else {
@@ -123,7 +122,7 @@ findSameColorRectangle(struct pam *   const pamP,
                        unsigned int * const rectWidthP,
                        unsigned int * const rectHeightP) {
 /*----------------------------------------------------------------------------
-   Find the largest rectangle, in the image described by 'pam' and 
+   Find the largest rectangle, in the image described by 'pam' and
    'tuples', of uniform color, whose upper left corner is at (row, col).
 
    Return the width and height of that rectangle as *rectWidthP
@@ -142,23 +141,23 @@ findSameColorRectangle(struct pam *   const pamP,
         int j;
         for (j = 0; j <= i; ++j) {
             if (!my) {
-                if (i >= cny) 
+                if (i >= cny)
                     my = cny;
                 else {
                     if ((!mx || j < mx) && (j < cnx)) {
                         if (!pnm_tupleequal(pamP, tuples[row+i][col+j],
-                                            rectangleColor)) 
+                                            rectangleColor))
                             my = i;
                     }
                 }
             }
             if (!mx) {
-                if (i >= cnx) 
+                if (i >= cnx)
                     mx = cnx;
                 else {
                     if ((!my || (j < my)) && (j < cny)) {
                         if (!pnm_tupleequal(pamP, tuples[row+j][col+i],
-                                            rectangleColor)) 
+                                            rectangleColor))
                             mx = i;
                     }
                 }
@@ -204,7 +203,6 @@ freeOutputtedArray(bool **       const outputted,
 
 
 
-                       
 static void
 markNotOutputted(bool **      const outputted,
                  unsigned int const upperLeftCol,
@@ -218,10 +216,10 @@ markNotOutputted(bool **      const outputted,
     unsigned int const lowerRightCol = upperLeftCol + width;
     unsigned int const lowerRightRow = upperLeftRow + height;
     unsigned int row;
-    
+
     for (row = upperLeftRow; row < lowerRightRow; ++row) {
         unsigned int col;
-        for (col = upperLeftCol; col < lowerRightCol; ++col) 
+        for (col = upperLeftCol; col < lowerRightCol; ++col)
             outputted[row][col] = FALSE;
     }
 }
@@ -241,10 +239,10 @@ markOutputted(bool **      const outputted,
     unsigned int const lowerRightCol = upperLeftCol + width;
     unsigned int const lowerRightRow = upperLeftRow + height;
     unsigned int row;
-    
+
     for (row = upperLeftRow; row < lowerRightRow; ++row) {
         unsigned int col;
-        for (col = upperLeftCol; col < lowerRightCol; ++col) 
+        for (col = upperLeftCol; col < lowerRightCol; ++col)
             outputted[row][col] = TRUE;
     }
 }
@@ -294,17 +292,17 @@ main(int argc, char **argv) {
     for (row = 0; row < inpam.height; ++row) {
         unsigned int col;
         printf("<TR>\n");
-        pripix(&inpam, tuples[row][0], 1, 1, transparentColor); 
+        pripix(&inpam, tuples[row][0], 1, 1, transparentColor);
         markOutputted(outputted, 0, row, 1, 1);
 
         for (col = 1; col < inpam.width; ++col) {
             if (!outputted[row][col]) {
-                findSameColorRectangle(&inpam, tuples, row, col, 
+                findSameColorRectangle(&inpam, tuples, row, col,
                                        &rectWidth, &rectHeight);
                 if (cmdline.verbose)
                     pm_message("[%u/%u] [%u/%u]",
                                col, row, rectWidth, rectHeight);
-                pripix(&inpam, tuples[row][col], rectWidth, rectHeight, 
+                pripix(&inpam, tuples[row][col], rectWidth, rectHeight,
                        transparentColor);
                 markOutputted(outputted, col, row, rectWidth, rectHeight);
             }
@@ -320,3 +318,6 @@ main(int argc, char **argv) {
 
     return 0;
 }
+
+
+
diff --git a/converter/other/pamtompfont.c b/converter/other/pamtompfont.c
index 92f8de29..dd92fc7c 100644
--- a/converter/other/pamtompfont.c
+++ b/converter/other/pamtompfont.c
@@ -62,7 +62,7 @@ parseCommandLine(int argc, char ** argv,
     pm_optParseOptions3(&argc, argv, opt, sizeof(opt), 0);
         /* Uses and sets argc, argv, and some of *cmdlineP and others. */
 
-    if (argc-1 == 0) 
+    if (argc-1 == 0)
         cmdlineP->inputFilename = "-";
     else if (argc-1 != 1)
         pm_error("Program takes zero or one argument (filename).  You "
@@ -126,7 +126,7 @@ writeMpFontHeader(FILE *       const ofP,
 static void
 convertRaster(struct pam * const inpamP,
               FILE *       const ofP) {
-            
+
     tuple * tuplerow;
     unsigned char * outrow;
     unsigned int row;
@@ -150,7 +150,7 @@ convertRaster(struct pam * const inpamP,
             outrow[col] =
                 pnm_scalesample(tuplerow[col][0], inpamP->maxval, 255);
         }
-        
+
         fwrite(outrow, 1, inpamP->width, ofP);
     }
     free(outrow);
@@ -182,3 +182,6 @@ main(int argc, char *argv[]) {
 
     return 0;
 }
+
+
+
diff --git a/converter/other/pamtooctaveimg.c b/converter/other/pamtooctaveimg.c
index 28bc4cd4..b89b8229 100644
--- a/converter/other/pamtooctaveimg.c
+++ b/converter/other/pamtooctaveimg.c
@@ -144,7 +144,7 @@ convertToOctave(FILE * const ifP,
     pnm_readpaminit(ifP, &inpam, PAM_STRUCT_SIZE(allocation_depth));
 
     pnm_setminallocationdepth(&inpam, 3);
-    
+
     /* Output the image as a GNU Octave matrix.  For each row of the
      * input file we immediately output indexes into the colormap then,
      * when we're finished, we output the colormap as a second
@@ -191,14 +191,14 @@ main(int argc, char *argv[]) {
     inputName = argc-1 > 0 ? argv[1] : "-";
 
     ifP = pm_openr(inputName);
-    
+
     if (streq(inputName, "-"))
         fprintf(stdout, "# Created by pamtooctave\n");
     else
         fprintf(stdout, "# Created from '%s' by pamtooctave\n", inputName);
 
     convertToOctave(ifP, stdout);
-    
+
     pm_close(ifP);
 
     return 0;
diff --git a/converter/other/pamtopam.c b/converter/other/pamtopam.c
index 9cb82f7a..45f67d98 100644
--- a/converter/other/pamtopam.c
+++ b/converter/other/pamtopam.c
@@ -55,3 +55,6 @@ main(int argc, const char * argv[]) {
 
     return 0;
 }
+
+
+
diff --git a/converter/other/pamtopdbimg.c b/converter/other/pamtopdbimg.c
index ce2f7659..1ed08f9f 100644
--- a/converter/other/pamtopdbimg.c
+++ b/converter/other/pamtopdbimg.c
@@ -32,6 +32,7 @@
 #include <stdlib.h>
 #include <assert.h>
 #include <string.h>
+#include <time.h>
 #include <sys/stat.h>
 
 #include "pm_c_util.h"
@@ -45,7 +46,7 @@
 
 enum CompMode {COMPRESSED, MAYBE, UNCOMPRESSED};
 
-struct cmdlineInfo {
+struct CmdlineInfo {
     /* All the information the user supplied in the command line,
        in a form easy for the program to use.
     */
@@ -54,16 +55,17 @@ struct cmdlineInfo {
     const char * notefile;  /* NULL if not specified */
     enum CompMode compMode;
     unsigned int depth4;
+    unsigned int fixedtime;
 };
 
 
 
 static void
 parseCommandLine(int argc, const char ** argv,
-                 struct cmdlineInfo * const cmdlineP) {
+                 struct CmdlineInfo * const cmdlineP) {
 /*----------------------------------------------------------------------------
    parse program command line described in Unix standard form by argc
-   and argv.  Return the information in the options as *cmdlineP.  
+   and argv.  Return the information in the options as *cmdlineP.
 
    If command line is internally inconsistent (invalid options, etc.),
    issue error message to stderr and abort program.
@@ -71,9 +73,7 @@ parseCommandLine(int argc, const char ** argv,
    Note that the strings we return are stored in the storage that
    was passed to us as the argv array.  We also trash *argv.
 -----------------------------------------------------------------------------*/
-    optEntry *option_def;
-        /* Instructions to pm_optParseOptions3 on how to parse our options.
-         */
+    optEntry * option_def;  /* Used by OPTENT3 */
     optStruct3 opt;
 
     unsigned int option_def_index;
@@ -96,12 +96,14 @@ parseCommandLine(int argc, const char ** argv,
             &uncompressed,            0);
     OPTENT3(0, "4depth",              OPT_FLAG,      NULL,
             &cmdlineP->depth4,        0);
+    OPTENT3(0, "fixedtime",           OPT_FLAG,      NULL,
+            &cmdlineP->fixedtime,     0);
 
     opt.opt_table = option_def;
     opt.short_allowed = false;  /* We have no short (old-fashioned) options */
     opt.allowNegNum = false;  /* We have no parms that are negative numbers */
 
-    pm_optParseOptions3(&argc, (char **)argv, opt, sizeof(opt), 0);
+    pm_optParseOptions4(&argc, argv, opt, sizeof(opt), 0);
         /* Uses and sets argc, argv, and some of *cmdlineP and others. */
 
 
@@ -110,7 +112,7 @@ parseCommandLine(int argc, const char ** argv,
 
     if (!notefileSpec)
         cmdlineP->notefile = NULL;
-    
+
     if (compressed + uncompressed + maybeCompressed > 1)
         pm_error("You may specify only one of -compressed, -uncompressed, "
                  "-maybecompressed");
@@ -144,6 +146,42 @@ parseCommandLine(int argc, const char ** argv,
 
 
 
+static uint32_t const unixepoch = (66*365+17)*24*3600;
+    /* The unix epoch in Mac time (the Mac epoch is 00:00 UTC 1904.01.01).
+       The 17 is the number of leap years.
+    */
+
+
+
+static void
+setPdbHeader(PDBHEAD *    const pdbHeadP,
+             const char * const name,
+             bool         const wantFixedTime) {
+
+    STRSCPY(pdbHeadP->name, name);
+
+    {
+        /*
+         * All of the Image Viewer pdb files that I've come across have
+         * 3510939142U (1997.08.16 14:38:22 UTC) here.  I don't know where
+         * this bizarre datetime comes from but the real date works fine so
+         * I'm using it unless user asked for a fixed time (probably just so he
+         * gets repeatable output).
+         */
+
+        uint32_t const stdTime = 3510939142U;
+
+        uint32_t const hdrDt =
+            wantFixedTime ? stdTime : (uint32_t)time(NULL) + unixepoch;
+
+        pdbHeadP->ctime = pdbHeadP->mtime = hdrDt;
+    }
+    MEMSCPY(&pdbHeadP->type, IPDB_vIMG);
+    MEMSCPY(&pdbHeadP->id,   IPDB_View);
+}
+
+
+
 static int
 pdbheadWrite(PDBHEAD * const pdbheadP,
              FILE *    const fileP) {
@@ -232,7 +270,7 @@ imageWrite(IMAGE *   const imgP,
 static int
 textWrite(TEXT * const textP,
           FILE * const fileP) {
-    
+
     if (textP)
         fwrite(textP->data, 1, strlen(textP->data), fileP);
 
@@ -249,9 +287,9 @@ compressIfRequired(IPDB *     const pdbP,
 
     if (comp == IPDB_NOCOMPRESS) {
         *compressedDataP = pdbP->i->data;
-        *compressedSizeP = ipdb_img_size(pdbP->i);
+        *compressedSizeP = ipdb_imgSize(pdbP->i);
     } else {
-        int const uncompressedSz = ipdb_img_size(pdbP->i);
+        int const uncompressedSz = ipdb_imgSize(pdbP->i);
 
         unsigned char * outbuf;
         size_t          compressedSz;
@@ -303,7 +341,7 @@ ipdbWrite(IPDB * const pdbP,
     rc = pdbheadWrite(pdbP->p, fileP);
     if (rc != 0)
         pm_error("Failed to write PDB header.  %s", ipdb_err(rc));
-            
+
     rc = rechdrWrite(irP, fileP);
     if (rc != 0)
         pm_error("Failed to write image record header.  %s", ipdb_err(rc));
@@ -475,7 +513,7 @@ imageInsertInit(IPDB * const pdbP,
                      ipdb_typeName(type), MAX_SIZE(type));
         else {
             pdbP->i =
-                ipdb_image_alloc(name, type, adjustedWidth, adjustedHeight);
+                ipdb_imageCreate(name, type, adjustedWidth, adjustedHeight);
             if (pdbP->i == NULL)
                 pm_message("Could not get memory for %u x %u image",
                            adjustedWidth, adjustedHeight);
@@ -513,7 +551,7 @@ insertG16image(IPDB *          const pdbP,
         /* Pad with white on the bottom */
         for (; row < ipdb_height(pdbP); ++row)
             memset(outP, 0, rowSize);
-    } 
+    }
 }
 
 
@@ -544,7 +582,7 @@ insertGimage(IPDB *          const pdbP,
         /* Pad with white on the bottom */
         for (; row < ipdb_height(pdbP); ++row)
             memset(outP, 0, rowSize);
-    } 
+    }
 }
 
 
@@ -575,14 +613,14 @@ insertMimage(IPDB *          const pdbP,
         /* Pad with white on the bottom */
         for (; row < ipdb_height(pdbP); ++row)
             memset(outP, 0, rowSize);
-    } 
+    }
 }
 
 
 
 static int
 insertText(IPDB *       const pdbP,
-           const char * const s) {
+           const char * const content) {
 
     int retval;
 
@@ -591,17 +629,23 @@ insertText(IPDB *       const pdbP,
     else if (pdbP->p->num_recs == 2)
         retval = E_TEXTTHERE;
     else {
-        pdbP->t = ipdb_text_alloc(s);
+        pdbP->t = ipdb_textAlloc();
         if (pdbP->t == NULL)
             retval = ENOMEM;
         else {
-            pdbP->p->num_recs = 2;
+            pdbP->t->data = strdup(content);
 
-            pdbP->i->r->offset += 8;
-            pdbP->t->r->offset =
-                pdbP->i->r->offset + IMAGESIZE + ipdb_img_size(pdbP->i);
+            if (pdbP->t->data == NULL)
+                retval = ENOMEM;
+            else {
+                pdbP->p->num_recs = 2;
 
-            retval = 0;
+                pdbP->i->r->offset += 8;
+                pdbP->t->r->offset =
+                    pdbP->i->r->offset + IMAGESIZE + ipdb_imgSize(pdbP->i);
+
+                retval = 0;
+            }
         }
     }
     return retval;
@@ -689,7 +733,7 @@ readtxt(IPDB *       const pdbP,
 int
 main(int argc, const char **argv) {
 
-    struct cmdlineInfo cmdline;
+    struct CmdlineInfo cmdline;
     IPDB * pdbP;
     FILE * ifP;
     int comp;
@@ -709,11 +753,13 @@ main(int argc, const char **argv) {
     if (strlen(cmdline.title) > 31)
         pm_error("Title too long.  Max length is 31 characters.");
 
-    pdbP = ipdb_alloc(cmdline.title);
+    pdbP = ipdb_alloc();
 
     if (pdbP == NULL)
         pm_error("Failed to allocate IPDB structure");
 
+    setPdbHeader(pdbP->p, cmdline.title, cmdline.fixedtime);
+
     readimg(pdbP, ifP, cmdline.depth4);
 
     if (cmdline.notefile)
@@ -730,3 +776,6 @@ main(int argc, const char **argv) {
 
     return EXIT_SUCCESS;
 }
+
+
+
diff --git a/converter/other/pamtopfm.c b/converter/other/pamtopfm.c
index 25a8a0af..7991e0dd 100644
--- a/converter/other/pamtopfm.c
+++ b/converter/other/pamtopfm.c
@@ -2,7 +2,7 @@
                                   pamtopfm
 ******************************************************************************
   This program converts a PAM image to PFM (Portable Float Map).
-  
+
   By Bryan Henderson, San Jose, CA April 2004.
 
   Contributed to the public domain by its author.
@@ -37,13 +37,13 @@ static enum endian machineEndianness;
 
 
 
-static void 
-parseCommandLine(int argc, 
-                 char ** argv, 
+static void
+parseCommandLine(int argc,
+                 char ** argv,
                  struct cmdlineInfo  * const cmdlineP) {
 /* --------------------------------------------------------------------------
    Parse program command line described in Unix standard form by argc
-   and argv.  Return the information in the options as *cmdlineP.  
+   and argv.  Return the information in the options as *cmdlineP.
 
    If command line is internally inconsistent (invalid options, etc.),
    issue error message to stderr and abort program.
@@ -54,7 +54,7 @@ parseCommandLine(int argc,
     optEntry *option_def = malloc( 100*sizeof( optEntry ) );
     /* Instructions to pm_optParseOptions3 on how to parse our options. */
     optStruct3 opt;
-  
+
     unsigned int option_def_index;
     char * endianOpt;
     unsigned int endianSpec, scaleSpec;
@@ -62,7 +62,7 @@ parseCommandLine(int argc,
     option_def_index = 0;   /* incremented by OPTENTRY */
     OPTENT3(0, "endian",   OPT_STRING, &endianOpt, &endianSpec,        0);
     OPTENT3(0, "scale",    OPT_FLOAT,  &cmdlineP->scale, &scaleSpec,   0);
-  
+
     opt.opt_table = option_def;
     opt.short_allowed = FALSE;  /* We have no short (old-fashioned) options */
     opt.allowNegNum = FALSE;   /* We have no parms that are negative numbers */
@@ -93,7 +93,7 @@ parseCommandLine(int argc,
         cmdlineP->inputFilespec = argv[1];
     else
         cmdlineP->inputFilespec = "-";
-    
+
     if (argc-1 > 1)
         pm_error("Program takes at most one argument:  the file name.  "
                  "You specified %d", argc-1);
@@ -109,7 +109,7 @@ thisMachineEndianness(void) {
    that varies among typical machines.
 
    Big endianness is the natural format.  In this format, if an integer is
-   4 bytes, to be stored at memory address 100-103, the most significant 
+   4 bytes, to be stored at memory address 100-103, the most significant
    byte goes at 100, the next most significant at 101, and the least
    significant byte at 103.  This is natural because it matches the way
    humans read and write numbers.  I.e. 258 is stored as 0x00000102.
@@ -125,7 +125,7 @@ thisMachineEndianness(void) {
 
     unsigned char * const storedNumber = (unsigned char *)&testNumber;
     enum endian endianness;
-    
+
     if (storedNumber[0] == 0x01)
         endianness = ENDIAN_LITTLE;
     else
@@ -156,11 +156,11 @@ floatToPfmSample(float       const input,
         unsigned int i, j;
 
         MEMSCPY(&reversed, &input);
-        
-        for (i = 0, j = sizeof(pfmSample)-1; 
-             i < sizeof(pfmSample); 
+
+        for (i = 0, j = sizeof(pfmSample)-1;
+             i < sizeof(pfmSample);
              ++i, --j)
-            
+
             outputP->bytes[i] = reversed[j];
     }
 }
@@ -181,8 +181,8 @@ writePfmHeader(FILE *           const ofP,
                struct pfmHeader const pfmHeader) {
 
     const char * const magic = pfmHeader.color ? "PF" : "Pf";
-    float const scaleFactorEndian = 
-        pfmHeader.endian == ENDIAN_BIG ? 
+    float const scaleFactorEndian =
+        pfmHeader.endian == ENDIAN_BIG ?
             pfmHeader.scaleFactor :
             - pfmHeader.scaleFactor;
 
@@ -217,7 +217,7 @@ writePfmRow(struct pam * const pamP,
         unsigned int plane;
         for (plane = 0; plane < pamP->depth; ++plane) {
             pfmSample val;
-            floatToPfmSample(tuplenRow[col][plane] * scaleFactor, 
+            floatToPfmSample(tuplenRow[col][plane] * scaleFactor,
                              &val, endian);
             pfmRowBuffer[pfmCursor++] = val;
         }
@@ -226,7 +226,7 @@ writePfmRow(struct pam * const pamP,
 
     rc = fwrite(pfmRowBuffer, sizeof(pfmSample), pfmSamplesPerRow, ofP);
     if (rc != pfmSamplesPerRow)
-        pm_error("Unable to write to output file in the middle of row %d", 
+        pm_error("Unable to write to output file in the middle of row %d",
                  pfmRow);
 
 
@@ -238,9 +238,9 @@ static struct pfmHeader
 makePfmHeader(const struct pam * const pamP,
               float              const scaleFactor,
               enum endian        const endian) {
-    
+
     struct pfmHeader pfmHeader;
-    
+
     pfmHeader.width  = pamP->width;
     pfmHeader.height = pamP->height;
 
@@ -256,11 +256,12 @@ makePfmHeader(const struct pam * const pamP,
 
     pfmHeader.scaleFactor = scaleFactor;
     pfmHeader.endian = endian;
-        
+
     return pfmHeader;
 }
 
 
+
 int
 main(int argc, char **argv ) {
 
@@ -282,11 +283,11 @@ main(int argc, char **argv ) {
 
     tuplenArray = pnm_readpamn(ifP, &pam, PAM_STRUCT_SIZE(tuple_type));
 
-    writePfmHeader(stdout, 
+    writePfmHeader(stdout,
                    makePfmHeader(&pam, cmdline.scale, cmdline.endian));
 
     pfmSamplesPerRow = pam.width * pam.depth;
-    
+
     MALLOCARRAY_NOFAIL(pfmRowBuffer, pfmSamplesPerRow);
 
     /* PFMs are upside down like BMPs */
@@ -297,9 +298,12 @@ main(int argc, char **argv ) {
 
     pnm_freepamarrayn(tuplenArray, &pam);
     free(pfmRowBuffer);
-    
+
     pm_close(stdout);
     pm_close(pam.file);
 
     return 0;
 }
+
+
+
diff --git a/converter/other/pamtopng.c b/converter/other/pamtopng.c
index 3a987820..51203df5 100644
--- a/converter/other/pamtopng.c
+++ b/converter/other/pamtopng.c
@@ -30,8 +30,6 @@
 #include <stdlib.h>
 #include <time.h>
 #include <png.h>
-/* setjmp.h needs to be included after png.h */
-#include <setjmp.h>
 
 #include "pm_c_util.h"
 #include "mallocvar.h"
@@ -50,8 +48,8 @@ struct CmdlineInfo {
     const char * inputFileName;
     unsigned int verbose;
     unsigned int interlace;
-    unsigned int transparencySpec;
-    const char * transparency;
+    unsigned int transparentSpec;
+    const char * transparent;
     unsigned int chromaSpec;
     struct pngx_chroma chroma;
     unsigned int gammaSpec;
@@ -84,9 +82,9 @@ parseChromaOpt(const char *         const chromaOpt,
                    &chromaP->gx, &chromaP->gy,
                    &chromaP->bx, &chromaP->by);
 
-    if (count != 6)
-        pm_error("Invalid syntax for the -rgb option value '%s'.  "
-                 "Should be 6 floating point number: "
+    if (count != 8)
+        pm_error("Invalid syntax for the -chroma option value '%s'.  "
+                 "Should be 8 floating point numbers: "
                  "x and y for each of white, red, green, and blue",
                  chromaOpt);
 }
@@ -196,8 +194,8 @@ parseCommandLine (int                  argc,
             &cmdlineP->verbose,        0);
     OPTENT3(0,  "interlace",    OPT_FLAG,       NULL,
             &cmdlineP->interlace,      0);
-    OPTENT3(0,  "transparency", OPT_STRING,     &cmdlineP->transparency,
-            &cmdlineP->transparencySpec, 0);
+    OPTENT3(0,  "transparent", OPT_STRING,      &cmdlineP->transparent,
+            &cmdlineP->transparentSpec, 0);
     OPTENT3(0,  "chroma",       OPT_STRING,     &chroma,
             &cmdlineP->chromaSpec,     0);
     OPTENT3(0,  "gamma",        OPT_FLOAT,      &cmdlineP->gamma,
@@ -220,7 +218,7 @@ parseCommandLine (int                  argc,
     opt.allowNegNum = false;  /* we have no parms that are negative numbers */
 
     /* uses and sets argc, argv, and some of *cmdlineP and others */
-    pm_optParseOptions3(&argc, (char **)argv, opt, sizeof(opt), 0);
+    pm_optParseOptions4(&argc, argv, opt, sizeof(opt), 0);
 
     if (cmdlineP->chromaSpec)
         parseChromaOpt(chroma, &cmdlineP->chroma);
@@ -287,7 +285,17 @@ colorTypeFromInputType(const struct pam * const pamP) {
             pm_error("Input tuple type is GRAYSCALE, "
                      "but number of planes is %u instead of 1",
                      pamP->depth);
-    } else if (strneq(pamP->tuple_type, "BLACKANDWHITE", 3)) {
+     } else if (strneq(pamP->tuple_type, "BLACKANDWHITE_ALPHA", 19)) {
+        if (pamP->depth != 2)
+            pm_error("Input tuple type is BLACKANDWHITE_ALPHA, "
+                     "but number of planes is %u instead of 2",
+                     pamP->depth);
+        if (pamP->maxval != 1)
+            pm_error("Input tuple type is BLACKANDWHITE_ALPHA, "
+                     "but maxval is %u instead of 1", (unsigned)pamP->maxval);
+
+        retval = PNG_COLOR_TYPE_GRAY_ALPHA;
+    } else if (strneq(pamP->tuple_type, "BLACKANDWHITE", 13)) {
         if (pamP->depth != 1)
             pm_error("Input tuple type is BLACKANDWHITE, "
                      "but number of planes is %u instead of 1",
@@ -403,7 +411,7 @@ doTrnsChunk(const struct pam * const pamP,
     else {
         xelval const pngMaxval = pm_bitstomaxval(pngx_bitDepth(pngxP));
         png_color_16 const pngColor = parseAndScaleColor(trans, pngMaxval);
-            /* Transparency color from text format scaled from 16-bit to
+            /* Transparent color from text format scaled from 16-bit to
                maxval.
             */
 
@@ -519,7 +527,6 @@ doZtxtChunkSet(struct pngx * const pngxP,
 
 
 
-
 static void
 doItxtChunkSet(struct pngx * const pngxP,
                const char *  const textFileName) {
@@ -785,7 +792,8 @@ pngBitDepth(unsigned int const pnmBitDepth,
     unsigned int retval;
 
     if ((pngColorType == PNG_COLOR_TYPE_RGB ||
-         pngColorType == PNG_COLOR_TYPE_RGB_ALPHA) &&
+         pngColorType == PNG_COLOR_TYPE_RGB_ALPHA ||
+         pngColorType == PNG_COLOR_TYPE_GRAY_ALPHA) &&
         pnmBitDepth < 8) {
 
         retval = 8;
@@ -805,8 +813,8 @@ addAncillaryChunks(struct pam *       const pamP,
 /*----------------------------------------------------------------------------
   Where requested, add ancillary chunks.
 -----------------------------------------------------------------------------*/
-    if (cmdline.transparencySpec)
-        doTrnsChunk(pamP, pngxP,cmdline.transparency);
+    if (cmdline.transparentSpec)
+        doTrnsChunk(pamP, pngxP,cmdline.transparent);
 
     if (cmdline.chromaSpec)
         doChrmChunk(pngxP, cmdline.chroma);
diff --git a/converter/other/pamtopnm.c b/converter/other/pamtopnm.c
index f0ad451a..45ab1beb 100644
--- a/converter/other/pamtopnm.c
+++ b/converter/other/pamtopnm.c
@@ -33,9 +33,7 @@ parseCommandLine(int argc, const char ** argv,
    Note that the file spec array we return is stored in the storage that
    was passed to us as the argv array.
 -----------------------------------------------------------------------------*/
-    optEntry * option_def;
-        /* Instructions to OptParseOptions3 on how to parse our options.
-         */
+    optEntry * option_def;   /* Used by OPTENT3 */
     optStruct3 opt;
 
     unsigned int option_def_index;
@@ -49,10 +47,10 @@ parseCommandLine(int argc, const char ** argv,
     opt.short_allowed = FALSE;  /* We have no short (old-fashioned) options */
     opt.allowNegNum = FALSE;  /* We have no parms that are negative numbers */
 
-    pm_optParseOptions3(&argc, (char **)argv, opt, sizeof(opt), 0);
+    pm_optParseOptions4(&argc, argv, opt, sizeof(opt), 0);
         /* Uses and sets argc, argv, and some of *cmdlineP and others. */
 
-    if (argc-1 == 0) 
+    if (argc-1 == 0)
         cmdlineP->inputFileName = "-";
     else if (argc-1 != 1)
         pm_error("Program takes zero or one argument (filename).  You "
@@ -66,7 +64,7 @@ parseCommandLine(int argc, const char ** argv,
 
 
 static void
-validateTupleType(struct pam const inpam, 
+validateTupleType(struct pam const inpam,
                   int        const assumeTupleType) {
 /*----------------------------------------------------------------------------
    Make sure the image has a tuple type we know how to convert to PNM.
@@ -83,18 +81,18 @@ validateTupleType(struct pam const inpam,
     if (assumeTupleType) {
         /* User says tuple type is appropriate regardless of tuple_type. */
     } else {
-        if (inpam.depth >= 1 && 
-            strncmp(inpam.tuple_type, "BLACKANDWHITE", 
+        if (inpam.depth >= 1 &&
+            strncmp(inpam.tuple_type, "BLACKANDWHITE",
                     sizeof("BLACKANDWHITE")-1) == 0) {
             /* It's a PBMable image */
-        } else if (inpam.depth >= 1 && 
+        } else if (inpam.depth >= 1 &&
                    strncmp(inpam.tuple_type, "GRAYSCALE",
                            sizeof("GRAYSCALE")-1) == 0) {
             /* It's a PGMable image */
         } else if (inpam.depth >= 3 &&
                    strncmp(inpam.tuple_type, "RGB", sizeof("RGB")-1) == 0) {
             /* It's a PPMable image */
-        } else 
+        } else
             pm_error("PAM image does not have a depth and tuple_type "
                      "consistent with a PNM image.  "
                      "According to its "
@@ -129,12 +127,12 @@ main(int argc, const char **argv) {
 
         outpam = inpam;
         outpam.file = stdout;
-        
+
         if (inpam.depth < 3) {
             outpam.depth = 1;
             if (inpam.maxval == 1)
                 outpam.format = PBM_FORMAT;
-            else 
+            else
                 outpam.format = PGM_FORMAT;
         } else {
             outpam.depth = 3;
@@ -145,17 +143,17 @@ main(int argc, const char **argv) {
 
         {
             tuple *tuplerow;
-            
-            tuplerow = pnm_allocpamrow(&inpam);      
-            { 
+
+            tuplerow = pnm_allocpamrow(&inpam);
+            {
                 int row;
-                
+
                 for (row = 0; row < inpam.height; row++) {
                     pnm_readpamrow(&inpam, tuplerow);
                     pnm_writepamrow(&outpam, tuplerow);
                 }
             }
-            pnm_freepamrow(tuplerow);        
+            pnm_freepamrow(tuplerow);
         }
 
         pnm_nextimage(ifP, &eof);
@@ -163,3 +161,6 @@ main(int argc, const char **argv) {
 
     return 0;
 }
+
+
+
diff --git a/converter/other/pamtoqoi.c b/converter/other/pamtoqoi.c
new file mode 100644
index 00000000..a188cca9
--- /dev/null
+++ b/converter/other/pamtoqoi.c
@@ -0,0 +1,440 @@
+/*
+  pamtoqoi -  Converts PAM to a QOI - The "Quite OK Image" format file
+
+  This program is part of Netpbm.
+
+  ---------------------------------------------------------------------
+
+  QOI - The "Quite OK Image" format for fast, lossless image compression
+
+  Encoder by Dominic Szablewski - https://phoboslab.org
+
+  -- LICENSE: The MIT License(MIT)
+
+  Copyright(c) 2021 Dominic Szablewski
+
+  Permission is hereby granted, free of charge, to any person obtaining a copy
+  of this software and associated documentation files(the "Software"), to deal
+  in the Software without restriction, including without limitation the rights
+  to use, copy, modify, merge, publish, distribute, sublicense, and / or sell
+  copies of the Software, and to permit persons to whom the Software is
+  furnished to do so, subject to the following conditions :
+
+  The above copyright notice and this permission notice shall be included in
+  all copies or substantial portions of the Software.
+
+  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE
+  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+  SOFTWARE.
+
+  For more information on the format visit: https//qoiformat.org/ .
+
+  Modifications for Netpbm read routines by Akira F. Urushibata.
+
+*/
+
+#include <string.h>
+#include <assert.h>
+#include "pam.h"
+#include "nstring.h"
+#include "mallocvar.h"
+#include "shhopt.h"
+
+#include "qoi.h"
+
+
+
+struct CmdlineInfo {
+    /* All the information the user supplied in the command line,
+       in a form easy for the program to use.
+    */
+    const char * inputFileName;  /* '-' if stdin */
+};
+
+
+
+static void
+parseCommandLine(int                  argc,
+                 const char **        argv,
+                 struct CmdlineInfo * cmdlineP ) {
+/*----------------------------------------------------------------------------
+   Parse program command line described in Unix standard form by argc
+   and argv.  Return the information in the options as *cmdlineP.
+
+   If command line is internally inconsistent (invalid options, etc.),
+   issue error message to stderr and abort program.
+
+   Note that the strings we return are stored in the storage that
+   was passed to us as the argv array.  We also trash *argv.
+-----------------------------------------------------------------------------*/
+    optEntry * option_def;   /* Used by OPTENT3 */
+    optStruct3 opt;
+
+    unsigned int option_def_index;
+
+    MALLOCARRAY(option_def, 100);
+
+    OPTENTINIT;
+
+    opt.opt_table = option_def;
+    opt.short_allowed = FALSE;  /* We have no short (old-fashioned) options */
+    opt.allowNegNum = FALSE;  /* We have no parms that are negative numbers */
+
+    pm_optParseOptions4(&argc, argv, opt, sizeof(opt), 0);
+        /* Uses and sets argc, argv, and some of *cmdlineP and others. */
+
+    if (argc-1 < 1)
+        cmdlineP->inputFileName = "-";
+    else if (argc-1 == 1)
+        cmdlineP->inputFileName = argv[1];
+    else
+        pm_error("Program takes at most one argument: input file name.  "
+            "you specified %d", argc-1);
+}
+
+
+
+static void
+encodeQoiHeader(qoi_Desc const qoiDesc) {
+
+    assert (QOI_MAGIC_SIZE + 4 + 4 + 1 + 1 == QOI_HEADER_SIZE);
+
+    fwrite (qoi_magic, QOI_MAGIC_SIZE, 1, stdout);
+    pm_writebiglongu(stdout, qoiDesc.width);
+    pm_writebiglongu(stdout, qoiDesc.height);
+    putchar(qoiDesc.channelCt);
+    putchar(qoiDesc.colorspace);
+
+}
+
+
+
+enum Tupletype {BW, BWAlpha, GRAY, GRAYAlpha, RGB, RGBAlpha,
+                GRAY255, GRAY255Alpha, RGB255, RGB255Alpha};
+
+
+
+static void
+createSampleMap(sample    const oldMaxval,
+                sample ** const sampleMapP) {
+
+    unsigned int i;
+    sample * sampleMap;
+    sample   const newMaxval = 255;
+
+    MALLOCARRAY_NOFAIL(sampleMap, oldMaxval+1);
+
+    for (i = 0; i <= oldMaxval; ++i)
+        sampleMap[i] = ROUNDDIV(i * newMaxval, oldMaxval);
+
+    *sampleMapP = sampleMap;
+}
+
+
+
+static enum Tupletype
+tupleTypeFmPam(const char * const pamTupleType,
+               sample       const maxval) {
+
+    enum Tupletype retval;
+
+    if (streq(pamTupleType, PAM_PBM_TUPLETYPE)) {
+        if (maxval !=1)
+            pm_error("Invalid maxval (%lu) for tuple type '%s'.",
+                     maxval, pamTupleType);
+        else
+            retval =  BW;
+    } else if (streq(pamTupleType, PAM_PBM_ALPHA_TUPLETYPE)) {
+      if (maxval !=1)
+          pm_error("Invalid maxval (%lu) for tuple type '%s'.",
+                    maxval, pamTupleType);
+      else
+          retval =  BWAlpha;
+    } else if (maxval == 255) {
+        if (streq(pamTupleType, PAM_PPM_TUPLETYPE))
+            retval =  RGB255;
+        else if(streq(pamTupleType, PAM_PPM_ALPHA_TUPLETYPE))
+            retval =  RGB255Alpha;
+        else if(streq(pamTupleType, PAM_PGM_TUPLETYPE))
+            retval =  GRAY255;
+        else if(streq(pamTupleType, PAM_PGM_ALPHA_TUPLETYPE))
+            retval =  GRAY255Alpha;
+        else
+            pm_error("Don't know how to convert tuple type '%s'.",
+                     pamTupleType);
+    } else {
+        if (streq(pamTupleType, PAM_PPM_TUPLETYPE))
+            retval =  RGB;
+        else if(streq(pamTupleType, PAM_PPM_ALPHA_TUPLETYPE))
+            retval =  RGBAlpha;
+        else if(streq(pamTupleType, PAM_PGM_TUPLETYPE))
+            retval =  GRAY;
+        else if(streq(pamTupleType, PAM_PGM_ALPHA_TUPLETYPE))
+            retval =  GRAYAlpha;
+        else
+            pm_error("Don't know how to convert tuple type '%s'.",
+                     pamTupleType);
+    }
+
+    return retval;
+}
+
+
+
+#pragma GCC diagnostic push
+#pragma GCC diagnostic ignored "-Wreturn-type"
+
+static unsigned int
+channelCtFmTupleType(enum Tupletype const tupleType) {
+
+    switch (tupleType) {
+        case RGB:
+          return 3;
+        case RGB255:
+          return 3;
+        case RGBAlpha:
+          return 4;
+        case RGB255Alpha:
+          return 4;
+        case BW:
+        case GRAY:
+          return 3;
+        case GRAY255:
+          return 3;
+        case BWAlpha:
+        case GRAYAlpha:
+          return 4;
+        case GRAY255Alpha:
+          return 4;
+    }
+}
+#pragma GCC diagnostic pop
+
+
+
+static qoi_Rgba
+pxFmTuple(tuple          const tuple0,
+          const sample * const sampleMap,
+          enum Tupletype const tupleType) {
+/*----------------------------------------------------------------------------
+   Convert PAM tuple to qoi rgba pixel struct
+-----------------------------------------------------------------------------*/
+    qoi_Rgba px;
+
+    switch (tupleType) {
+    case RGB:
+        px.rgba.r = sampleMap[tuple0[PAM_RED_PLANE]];
+        px.rgba.g = sampleMap[tuple0[PAM_GRN_PLANE]];
+        px.rgba.b = sampleMap[tuple0[PAM_BLU_PLANE]];
+        px.rgba.a = 255;
+        break;
+    case RGB255:
+        px.rgba.r = tuple0[PAM_RED_PLANE];
+        px.rgba.g = tuple0[PAM_GRN_PLANE];
+        px.rgba.b = tuple0[PAM_BLU_PLANE];
+        px.rgba.a = 255;
+        break;
+    case RGBAlpha:
+        px.rgba.r = sampleMap[tuple0[PAM_RED_PLANE]];
+        px.rgba.g = sampleMap[tuple0[PAM_GRN_PLANE]];
+        px.rgba.b = sampleMap[tuple0[PAM_BLU_PLANE]];
+        px.rgba.a = sampleMap[tuple0[PAM_TRN_PLANE]];
+        break;
+    case RGB255Alpha:
+        px.rgba.r = tuple0[PAM_RED_PLANE];
+        px.rgba.g = tuple0[PAM_GRN_PLANE];
+        px.rgba.b = tuple0[PAM_BLU_PLANE];
+        px.rgba.a = tuple0[PAM_TRN_PLANE];
+        break;
+    case BW:
+    case GRAY : {
+        unsigned char const qoiSample = sampleMap[tuple0[0]];
+        px.rgba.r = qoiSample;
+        px.rgba.g = qoiSample;
+        px.rgba.b = qoiSample;
+        px.rgba.a = 255;
+    } break;
+    case GRAY255: {
+        unsigned char const qoiSample = tuple0[0];
+        px.rgba.r = qoiSample;
+        px.rgba.g = qoiSample;
+        px.rgba.b = qoiSample;
+        px.rgba.a = 255;
+    } break;
+    case BWAlpha:
+    case GRAYAlpha: {
+        unsigned char const qoiSample = sampleMap[tuple0[0]];
+        px.rgba.r = qoiSample;
+        px.rgba.g = qoiSample;
+        px.rgba.b = qoiSample;
+        px.rgba.a = sampleMap[tuple0[PAM_GRAY_TRN_PLANE]];
+    } break;
+    case GRAY255Alpha: {
+        unsigned char const qoiSample = tuple0[0];
+        px.rgba.r = qoiSample;
+        px.rgba.g = qoiSample;
+        px.rgba.b = qoiSample;
+        px.rgba.a = tuple0[PAM_GRAY_TRN_PLANE];
+    } break;
+    }
+
+    return px;
+}
+
+
+
+static void
+encodeNewPixel(qoi_Rgba const px,
+               qoi_Rgba const pxPrev) {
+
+    if (px.rgba.a == pxPrev.rgba.a) {
+        signed char const vr = px.rgba.r - pxPrev.rgba.r;
+        signed char const vg = px.rgba.g - pxPrev.rgba.g;
+        signed char const vb = px.rgba.b - pxPrev.rgba.b;
+
+        signed char const vgR = vr - vg;
+        signed char const vgB = vb - vg;
+
+        if (
+            vr > -3 && vr < 2 &&
+            vg > -3 && vg < 2 &&
+            vb > -3 && vb < 2
+            ) {
+            putchar(QOI_OP_DIFF |
+                    (vr + 2) << 4 | (vg + 2) << 2 | (vb + 2));
+        } else if (
+            vgR >  -9 && vgR <  8 &&
+            vg  > -33 && vg  < 32 &&
+            vgB >  -9 && vgB <  8
+            ) {
+            putchar(QOI_OP_LUMA    | (vg   + 32));
+            putchar((vgR + 8) << 4 | (vgB +  8));
+        } else {
+            putchar(QOI_OP_RGB);
+            putchar(px.rgba.r);
+            putchar(px.rgba.g);
+            putchar(px.rgba.b);
+        }
+    } else {
+        putchar(QOI_OP_RGBA);
+        putchar(px.rgba.r);
+        putchar(px.rgba.g);
+        putchar(px.rgba.b);
+        putchar(px.rgba.a);
+    }
+}
+
+
+
+static void
+qoiEncode(FILE           * const ifP,
+          struct pam     * const inpamP) {
+
+    tuple * tuplerow;
+    unsigned int row;
+
+    qoi_Rgba index[QOI_INDEX_SIZE];
+    qoi_Rgba pxPrev;
+    unsigned int run;
+    sample * sampleMap;
+    qoi_Desc qoiDesc;
+
+    enum Tupletype const tupleType =
+      tupleTypeFmPam(inpamP->tuple_type, inpamP->maxval);
+
+    if (inpamP->height > QOI_PIXELS_MAX / inpamP->width)
+        pm_error("Too many pixels for QOI: %u x %u (max is %u)",
+                 inpamP->height, inpamP->width, QOI_PIXELS_MAX);
+
+    qoiDesc.colorspace = QOI_SRGB;
+    qoiDesc.width      = inpamP->width;
+    qoiDesc.height     = inpamP->height;
+    qoiDesc.channelCt  = channelCtFmTupleType(tupleType);
+
+    encodeQoiHeader(qoiDesc);
+
+    tuplerow = pnm_allocpamrow(inpamP);
+
+    if (inpamP->maxval != 255)
+        createSampleMap(inpamP->maxval, &sampleMap);
+
+    qoi_clearQoiIndex(index);
+
+    pxPrev.rgba.r = 0;
+    pxPrev.rgba.g = 0;
+    pxPrev.rgba.b = 0;
+    pxPrev.rgba.a = 255;
+
+    /* Read and convert rows. */
+    for (row = 0, run = 0; row < inpamP->height; ++row) {
+        unsigned int col;
+
+        pnm_readpamrow(inpamP, tuplerow);
+
+        for (col = 0; col < inpamP->width; ++col) {
+            qoi_Rgba const px = pxFmTuple(tuplerow[col], sampleMap, tupleType);
+
+            if (px.v == pxPrev.v) {
+                ++run;
+                if (run == 62) {
+                    putchar(QOI_OP_RUN | (run - 1));
+                    run = 0;
+                }
+            } else {
+                unsigned int const indexPos = qoi_colorHash(px);
+
+                if (run > 0) {
+                    putchar(QOI_OP_RUN | (run - 1));
+                    run = 0;
+                }
+
+                if (index[indexPos].v == px.v) {
+                    putchar(QOI_OP_INDEX | indexPos);
+
+                } else {
+                    index[indexPos] = px;
+                    encodeNewPixel(px, pxPrev);
+                }
+            }
+            pxPrev = px;
+        }
+    }
+
+    if (run > 0)
+        putchar(QOI_OP_RUN | (run - 1));
+
+    fwrite(qoi_padding, sizeof(qoi_padding), 1, stdout);
+
+    if (inpamP->maxval != 255)
+        free(sampleMap);
+    pnm_freepamrow(tuplerow);
+}
+
+
+
+int
+main(int argc, const char **argv) {
+
+    struct CmdlineInfo cmdline;
+    struct pam inpam;
+    FILE * ifP;
+
+    pm_proginit(&argc, argv);
+
+    parseCommandLine(argc, argv, &cmdline);
+
+    ifP = pm_openr(cmdline.inputFileName);
+
+    pnm_readpaminit(ifP, &inpam, PAM_STRUCT_SIZE(tuple_type));
+
+    qoiEncode(ifP, &inpam);
+
+    return 0;
+}
+
+
+
diff --git a/converter/other/pamtosrf.c b/converter/other/pamtosrf.c
index 3800d77c..eb2d44bd 100644
--- a/converter/other/pamtosrf.c
+++ b/converter/other/pamtosrf.c
@@ -45,9 +45,7 @@ parseCommandLine(int argc, const char ** argv,
    Note that the strings we return are stored in the storage that
    was passed to us as the argv array.  We also trash *argv.
 -----------------------------------------------------------------------------*/
-  optEntry *option_def;
-      /* Instructions to pm_optParseOptions3 on how to parse our options.
-       */
+  optEntry * option_def;   /* Used by OPTENT3 */
   optStruct3 opt;
 
   unsigned int option_def_index;
@@ -62,7 +60,7 @@ parseCommandLine(int argc, const char ** argv,
   opt.short_allowed = FALSE;  /* We have no short (old-fashioned) options */
   opt.allowNegNum = FALSE;  /* We have no parms that are negative numbers */
 
-  pm_optParseOptions3(&argc, (char **)argv, opt, sizeof(opt), 0);
+  pm_optParseOptions4(&argc, argv, opt, sizeof(opt), 0);
       /* Uses and sets argc, argv, and some of *cmdlineP and others. */
 
   if (argc-1 < 1)
@@ -206,7 +204,7 @@ main(int argc, const char * argv[]) {
   }
 
   srf_write(stdout, &srf);
-    
+
   srf_term(&srf);
   pm_closer(ifP);
 
diff --git a/converter/other/pamtosvg/Makefile b/converter/other/pamtosvg/Makefile
index 83f150d0..d67281d5 100644
--- a/converter/other/pamtosvg/Makefile
+++ b/converter/other/pamtosvg/Makefile
@@ -18,8 +18,9 @@ ADDL_OBJECTS = \
 	fit.o \
 	spline.o \
 	curve.o \
+	point.o \
 	vector.o \
-	epsilon-equal.o \
+	epsilon.o \
 	autotrace.o \
 	pxl-outline.o \
 	bitmap.o \
diff --git a/converter/other/pamtosvg/autotrace.c b/converter/other/pamtosvg/autotrace.c
index e9902669..37f5d5ec 100644
--- a/converter/other/pamtosvg/autotrace.c
+++ b/converter/other/pamtosvg/autotrace.c
@@ -42,6 +42,8 @@ at_fitting_opts_new(void)
   return opts;
 }
 
+
+
 at_fitting_opts_type *
 at_fitting_opts_copy (at_fitting_opts_type * original)
 {
@@ -56,12 +58,16 @@ at_fitting_opts_copy (at_fitting_opts_type * original)
   return new_opts;
 }
 
-void 
+
+
+void
 at_fitting_opts_free(at_fitting_opts_type * opts)
 {
   free(opts);
 }
 
+
+
 at_output_opts_type *
 at_output_opts_new(void)
 {
@@ -71,6 +77,8 @@ at_output_opts_new(void)
   return opts;
 }
 
+
+
 at_output_opts_type *
 at_output_opts_copy(at_output_opts_type * original)
 {
@@ -79,19 +87,23 @@ at_output_opts_copy(at_output_opts_type * original)
   return opts;
 }
 
+
+
 void
 at_output_opts_free(at_output_opts_type * opts)
 {
   free(opts);
 }
 
+
+
 /* at_splines_new_full modifies its 'bitmap' argument
    when it does the thin_image thing.
 */
-at_spline_list_array_type * 
+at_spline_list_array_type *
 at_splines_new_full(at_bitmap_type *       const bitmap,
                     at_fitting_opts_type * const opts,
-                    at_msg_func                  msg_func, 
+                    at_msg_func                  msg_func,
                     void *                 const msg_data,
                     at_progress_func             notify_progress,
                     void *                 const progress_data,
@@ -128,20 +140,20 @@ at_splines_new_full(at_bitmap_type *       const bitmap,
         if (opts->centerline) {
             pixel background_color;
 
-            if (opts->backgroundSpec) 
+            if (opts->backgroundSpec)
                 background_color = opts->background_color;
             else
                 PPM_ASSIGN(background_color, 255, 255, 255);
-            
+
             pixelOutlineList =
-                find_centerline_pixels(*bitmap, background_color, 
+                find_centerline_pixels(*bitmap, background_color,
                                        notify_progress, progress_data,
                                        test_cancel, testcancel_data, &exp);
         } else
             pixelOutlineList =
                 find_outline_pixels(*bitmap,
                                     opts->backgroundSpec,
-                                    opts->background_color, 
+                                    opts->background_color,
                                     notify_progress, progress_data,
                                     test_cancel, testcancel_data, &exp);
 
@@ -150,8 +162,8 @@ at_splines_new_full(at_bitmap_type *       const bitmap,
             retval = NULL;
         else {
             at_spline_list_array_type * splinesP;
-        
-            MALLOCVAR_NOFAIL(splinesP); 
+
+            MALLOCVAR_NOFAIL(splinesP);
             fit_outlines_to_splines(pixelOutlineList, opts,
                                     haveDistMap ? &distanceMap : NULL,
                                     image_header.width,
@@ -180,7 +192,7 @@ at_splines_new_full(at_bitmap_type *       const bitmap,
 
 
 
-void 
+void
 at_splines_write(at_output_write_func                  outputWriter,
                  FILE *                          const writeto,
                  at_output_opts_type *           const optsArg,
@@ -195,7 +207,7 @@ at_splines_write(at_output_write_func                  outputWriter,
     lly = 0;
     urx = splinesP->width;
     ury = splinesP->height;
-    
+
     if (optsArg == NULL) {
         newOpts = true;
         optsP   = at_output_opts_new();
@@ -212,9 +224,12 @@ at_splines_write(at_output_write_func                  outputWriter,
 
 
 
-void 
+void
 at_splines_free(at_spline_list_array_type * const splines) {
 
     free_spline_list_array(splines);
     free(splines);
 }
+
+
+
diff --git a/converter/other/pamtosvg/autotrace.h b/converter/other/pamtosvg/autotrace.h
index 2ac81a08..e30105a2 100644
--- a/converter/other/pamtosvg/autotrace.h
+++ b/converter/other/pamtosvg/autotrace.h
@@ -46,12 +46,12 @@ typedef struct _at_spline_list_array_type at_spline_list_array_type;
 /* Third degree is the highest we deal with.  */
 typedef enum _at_polynomial_degree
 {
-  AT_LINEARTYPE = 1, 
-  AT_QUADRATICTYPE = 2, 
-  AT_CUBICTYPE = 3, 
+  AT_LINEARTYPE = 1,
+  AT_QUADRATICTYPE = 2,
+  AT_CUBICTYPE = 3,
   AT_PARALLELELLIPSETYPE = 4,
-  AT_ELLIPSETYPE = 5, 
-  AT_CIRCLETYPE = 6 
+  AT_ELLIPSETYPE = 5,
+  AT_CIRCLETYPE = 6
   /* not the real number of points to define a
      circle but to distinguish between a cubic spline */
 } at_polynomial_degree;
@@ -63,7 +63,7 @@ typedef enum _at_polynomial_degree
    straight line defined by the endpoints.  */
 struct _at_spline_type
 {
-  float_coord v[4];	/* The control points.  */
+  Point v[4];   /* The control points.  */
   at_polynomial_degree degree;
   float linearity;
 };
@@ -88,8 +88,8 @@ struct _at_spline_list_array_type
 
   /* splines bbox */
   unsigned short height, width;
-  
-  /* the values for following members are inherited from 
+
+  /* the values for following members are inherited from
      at_fitting_opts_type */
   bool backgroundSpec;
   pixel background_color;
@@ -101,7 +101,7 @@ struct _at_spline_list_array_type
 
 
 /* Fitting option.
-   With using at_fitting_opts_doc macro, the description of 
+   With using at_fitting_opts_doc macro, the description of
    each option could be get. e.g. at_fitting_opts_doc(background_color) */
 struct _at_fitting_opts_type {
     bool backgroundSpec;
@@ -122,7 +122,7 @@ struct _at_fitting_opts_type {
 
 struct _at_output_opts_type
 {
-  int dpi;			/* DPI is used only in MIF output.*/
+  int dpi;          /* DPI is used only in MIF output.*/
 };
 
 struct _at_bitmap_type
@@ -144,16 +144,16 @@ void (* at_msg_func) (const char * const msg,
                       at_msg_type  const msg_type,
                       void *       const client_data);
 
-typedef 
+typedef
 int (*at_output_write_func) (FILE *                          const file,
                              const char *                    const name,
                              int                             const llx,
-                             int                             const lly, 
+                             int                             const lly,
                              int                             const urx,
                              int                             const ury,
                              at_output_opts_type *           const opts,
                              at_spline_list_array_type       const shape,
-                             at_msg_func                           msg_func, 
+                             at_msg_func                           msg_func,
                              void *                          const msg_data);
 
 /*
@@ -181,7 +181,7 @@ bool (*at_testcancel_func) (void * const client_data);
  * TODO: internal data access, copy
  * --------------------------------------------------------------------- */
 at_fitting_opts_type * at_fitting_opts_new(void);
-at_fitting_opts_type * at_fitting_opts_copy (at_fitting_opts_type * original); 
+at_fitting_opts_type * at_fitting_opts_copy (at_fitting_opts_type * original);
 void at_fitting_opts_free(at_fitting_opts_type * opts);
 
 /* TODO: Gettextize */
@@ -206,8 +206,8 @@ void at_output_opts_free(at_output_opts_type * opts);
    args:
 
    NOTIFY_PROGRESS is called repeatedly inside at_splines_new_full
-   to notify the progress of the execution. This might be useful for 
-   interactive applications. NOTIFY_PROGRESS is called following 
+   to notify the progress of the execution. This might be useful for
+   interactive applications. NOTIFY_PROGRESS is called following
    format:
 
    NOTIFY_PROGRESS (percentage, progress_data);
@@ -215,27 +215,27 @@ void at_output_opts_free(at_output_opts_type * opts);
    test_cancel is called repeatedly inside at_splines_new_full
    to test whether the execution is canceled or not.
    If test_cancel returns TRUE, execution of at_splines_new_full
-   is stopped as soon as possible and returns NULL. If test_cancel 
+   is stopped as soon as possible and returns NULL. If test_cancel
    returns FALSE, nothing happens. test_cancel  is called following
    format:
 
    TEST_CANCEL (testcancel_data);
-   
-   NULL is valid value for notify_progress and/or test_cancel if 
-   you don't need to know the progress of the execution and/or 
-   cancel the execution */ 
 
-at_spline_list_array_type * 
+   NULL is valid value for notify_progress and/or test_cancel if
+   you don't need to know the progress of the execution and/or
+   cancel the execution */
+
+at_spline_list_array_type *
 at_splines_new_full(at_bitmap_type *       const bitmap,
                     at_fitting_opts_type * const opts,
-                    at_msg_func                  msg_func, 
+                    at_msg_func                  msg_func,
                     void *                 const msg_data,
                     at_progress_func             notify_progress,
                     void *                 const progress_data,
                     at_testcancel_func           test_cancel,
                     void *                 const testcancel_data);
 
-void 
+void
 at_splines_write(at_output_write_func                  output_writer,
                  FILE *                          const writeto,
                  at_output_opts_type *           const opts,
diff --git a/converter/other/pamtosvg/bitmap.c b/converter/other/pamtosvg/bitmap.c
index 84a8a8ae..8b8ce092 100644
--- a/converter/other/pamtosvg/bitmap.c
+++ b/converter/other/pamtosvg/bitmap.c
@@ -13,7 +13,7 @@ at_bitmap_new(unsigned short width,
 
     at_bitmap_type * bitmap;
 
-    MALLOCVAR_NOFAIL(bitmap); 
+    MALLOCVAR_NOFAIL(bitmap);
 
     *bitmap = at_bitmap_init(NULL, width, height, planes);
 
@@ -31,10 +31,10 @@ at_bitmap_copy(at_bitmap_type * src)
     width  = at_bitmap_get_width(src);
     height = at_bitmap_get_height(src);
     planes = at_bitmap_get_planes(src);
-    
+
     dist = at_bitmap_new(width, height, planes);
-    memcpy(dist->bitmap, 
-           src->bitmap, 
+    memcpy(dist->bitmap,
+           src->bitmap,
            width * height * planes * sizeof(unsigned char));
     return dist;
 }
@@ -48,7 +48,7 @@ at_bitmap_init(unsigned char * area,
                unsigned int planes) {
 
     at_bitmap_type bitmap;
-    
+
     if (area)
         bitmap.bitmap = area;
     else {
@@ -63,33 +63,41 @@ at_bitmap_init(unsigned char * area,
                    0, width * height * planes * sizeof(unsigned char));
         }
     }
-    
+
     bitmap.width  = width;
     bitmap.height = height;
     bitmap.np     =  planes;
 
-    return bitmap;  
+    return bitmap;
 }
 
-void 
+
+
+void
 at_bitmap_free (at_bitmap_type * bitmap)
 {
     free_bitmap (bitmap);
     free(bitmap);
 }
 
+
+
 unsigned short
 at_bitmap_get_width (at_bitmap_type * bitmap)
 {
     return bitmap->width;
 }
 
+
+
 unsigned short
 at_bitmap_get_height (at_bitmap_type * bitmap)
 {
     return bitmap->height;
 }
 
+
+
 unsigned short
 at_bitmap_get_planes (at_bitmap_type * bitmap)
 {
@@ -104,6 +112,8 @@ new_bitmap (unsigned short width, unsigned short height)
     return at_bitmap_init(NULL,width,height,1);
 }
 
+
+
 /* Free the storage that is allocated for a bitmap.  On the other hand,
    the bitmap might not have any storage allocated for it if it is zero
    in either dimension; in that case, don't free it.  */
@@ -114,3 +124,6 @@ free_bitmap (bitmap_type *b)
     if (b->bitmap != NULL)
         free (b->bitmap);
 }
+
+
+
diff --git a/converter/other/pamtosvg/bitmap.h b/converter/other/pamtosvg/bitmap.h
index b979e0c0..ae5da2a8 100644
--- a/converter/other/pamtosvg/bitmap.h
+++ b/converter/other/pamtosvg/bitmap.h
@@ -12,16 +12,16 @@
 /* at_ prefix removed version */
 typedef at_bitmap_type bitmap_type;
 #define BITMAP_PLANES(b)          AT_BITMAP_PLANES(b)
-#define BITMAP_BITS(b)            AT_BITMAP_BITS(b)  
-#define BITMAP_WIDTH(b)           AT_BITMAP_WIDTH(b)  
-#define BITMAP_HEIGHT(b)          AT_BITMAP_HEIGHT(b) 
+#define BITMAP_BITS(b)            AT_BITMAP_BITS(b)
+#define BITMAP_WIDTH(b)           AT_BITMAP_WIDTH(b)
+#define BITMAP_HEIGHT(b)          AT_BITMAP_HEIGHT(b)
 
 /* This is the pixel at [ROW,COL].  */
-#define BITMAP_PIXEL(b, row, col)					\
+#define BITMAP_PIXEL(b, row, col)                                       \
   ((b).bitmap + ((row) * (b).width + (col)) * (b).np)
 
-#define BITMAP_VALID_PIXEL(b, row, col)					\
-   	((row) < (b).height && (col) < (b).width)
+#define BITMAP_VALID_PIXEL(b, row, col)                                 \
+        ((row) < (b).height && (col) < (b).width)
 
 /* Allocate storage for the bits, set them all to white, and return an
    initialized structure.  */
@@ -32,12 +32,12 @@ extern void free_bitmap (bitmap_type *);
 
 
 at_bitmap_type * at_bitmap_new(unsigned short width,
-			       unsigned short height,
-			       unsigned int planes);
+                               unsigned short height,
+                               unsigned int planes);
 at_bitmap_type * at_bitmap_copy(at_bitmap_type * src);
 
-/* We have to export functions that allows internal datum 
-   access. Such functions might be useful for 
+/* We have to export functions that allows internal datum
+   access. Such functions might be useful for
    at_bitmap_new user. */
 unsigned short at_bitmap_get_width (at_bitmap_type * bitmap);
 unsigned short at_bitmap_get_height (at_bitmap_type * bitmap);
@@ -46,8 +46,8 @@ void at_bitmap_free (at_bitmap_type * bitmap);
 
 at_bitmap_type
 at_bitmap_init(unsigned char * area,
-	       unsigned short width,
-	       unsigned short height,
-	       unsigned int planes);
+               unsigned short width,
+               unsigned short height,
+               unsigned int planes);
 
 #endif /* not BITMAP_H */
diff --git a/converter/other/pamtosvg/curve.c b/converter/other/pamtosvg/curve.c
index 369a0cd3..bd0ca70b 100644
--- a/converter/other/pamtosvg/curve.c
+++ b/converter/other/pamtosvg/curve.c
@@ -18,71 +18,78 @@
    along with this program; if not, write to the Free Software
    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.  */
 
+#include <assert.h>
+
 #include "mallocvar.h"
 
 #include "logreport.h"
 #include "curve.h"
 
 
-static float_coord
-int_to_real_coord(pm_pixelcoord const int_coord) {
+static Point
+realCoordFromInt(pm_pixelcoord const int_coord) {
 /*----------------------------------------------------------------------------
   Turn an integer point into a real one.
 -----------------------------------------------------------------------------*/
-    float_coord real_coord;
+    Point real_coord;
 
     real_coord.x = int_coord.col;
     real_coord.y = int_coord.row;
     real_coord.z = 0.0;
-    
+
     return real_coord;
 }
 
 
 
-/* Return an entirely empty curve.  */
-
-curve *
-new_curve(void) {
-  curve * curveP;
+Curve *
+curve_new(void) {
+/*----------------------------------------------------------------------------
+  A new, entirely empty curve.
+-----------------------------------------------------------------------------*/
+    Curve * curveP;
 
-  MALLOCVAR_NOFAIL(curveP);
+    MALLOCVAR_NOFAIL(curveP);
 
-  curveP->point_list = NULL;
-  CURVE_LENGTH(curveP) = 0;
-  CURVE_CYCLIC(curveP) = false;
-  PREVIOUS_CURVE(curveP)  = NULL;
-  NEXT_CURVE(curveP)      = NULL;
+    curveP->pointList       = NULL;
+    CURVE_LENGTH(curveP)    = 0;
+    CURVE_CYCLIC(curveP)    = false;
+    PREVIOUS_CURVE(curveP)  = NULL;
+    NEXT_CURVE(curveP)      = NULL;
 
-  return curveP;
+    return curveP;
 }
 
 
-/* Don't copy the points or tangents, but copy everything else.  */
 
-curve_type
-copy_most_of_curve (curve_type old_curve)
-{
-  curve_type curve = new_curve ();
+Curve *
+curve_copyMost(Curve * const oldCurveP) {
+/*----------------------------------------------------------------------------
+  New curve that is the same as *curveP, except without any points.
+
+  Don't copy the points or tangents, but copy everything else.
+-----------------------------------------------------------------------------*/
+    Curve * curveP = curve_new();
 
-  CURVE_CYCLIC (curve) = CURVE_CYCLIC (old_curve);
-  PREVIOUS_CURVE (curve) = PREVIOUS_CURVE (old_curve);
-  NEXT_CURVE (curve) = NEXT_CURVE (old_curve);
+    CURVE_CYCLIC(curveP)   = CURVE_CYCLIC(oldCurveP);
+    PREVIOUS_CURVE(curveP) = PREVIOUS_CURVE(oldCurveP);
+    NEXT_CURVE(curveP)     = NEXT_CURVE(oldCurveP);
 
-  return curve;
+    return curveP;
 }
 
-void
-move_curve(curve * const dstP,
-           curve * const srcP) {
 
-    /* Move ownership of dynamically allocated memory from source 
-       to destination; destroy source.
-    */
 
+void
+curve_move(Curve * const dstP,
+           Curve * const srcP) {
+/*----------------------------------------------------------------------------
+  Move ownership of dynamically allocated memory from source to destination;
+  destroy source.
+-----------------------------------------------------------------------------*/
    if (CURVE_LENGTH(dstP) > 0)
-       free(dstP->point_list);
-    
+       free(dstP->pointList);
+
    *dstP = *srcP;
 
    free(srcP);
@@ -90,62 +97,124 @@ move_curve(curve * const dstP,
 
 
 
-/* The length of CURVE will be zero if we ended up not being able to fit
-   it (which in turn implies a problem elsewhere in the program, but at
-   any rate, we shouldn't try here to free the nonexistent curve).  */
-
 void
-free_curve(curve * const curveP) {
+curve_free(Curve * const curveP) {
+
+    /* The length of CURVE will be zero if we ended up not being able to fit
+       it (which in turn implies a problem elsewhere in the program, but at
+       any rate, we shouldn't try here to free the nonexistent curve).
+    */
 
-   if (CURVE_LENGTH(curveP) > 0)
-       free(curveP->point_list);
+     if (CURVE_LENGTH(curveP) > 0)
+         free(curveP->pointList);
 
-   free(curveP);
+     free(curveP);
 }
 
 
 
 void
-append_point(curve_type  const curve,
-             float_coord const coord) {
-
-    CURVE_LENGTH(curve)++;
-    REALLOCARRAY_NOFAIL(curve->point_list, CURVE_LENGTH(curve));
-    LAST_CURVE_POINT(curve) = coord;
+curve_appendPoint(Curve * const curveP,
+                  Point   const coord) {
+/*----------------------------------------------------------------------------
+  Like `append_pixel', for a point in real coordinates.
+-----------------------------------------------------------------------------*/
+    CURVE_LENGTH(curveP)++;
+    REALLOCARRAY_NOFAIL(curveP->pointList, CURVE_LENGTH(curveP));
+    LAST_CURVE_POINT(curveP) = coord;
     /* The t value does not need to be set.  */
 }
 
 
+
 void
-append_pixel(curve_type    const curve,
-             pm_pixelcoord const coord) {
+curve_appendPixel(Curve *       const curveP,
+                  pm_pixelcoord const coord) {
+/*----------------------------------------------------------------------------
+  Append the point 'coord' to the end of *curveP's list.
+-----------------------------------------------------------------------------*/
+    curve_appendPoint(curveP, realCoordFromInt(coord));
+}
+
+
+
+void
+curve_setDistance(Curve * const curveP) {
+/*----------------------------------------------------------------------------
+   Fill in the distance values in *curveP.
+
+   The distance value for point P on a curve is the distance P is along the
+   curve from the initial point, normalized so the entire curve is length 1.0
+   (i.e. t of the initial point is 0.0; t of the final point is 1.0).
+
+   There are a lot of curves that pass through the points indicated by
+   *curveP, but for practical computation of t, we just take the piecewise
+   linear locus that runs through all of them.  That means we can just step
+   through *curveP, adding up the distance from one point to the next to get
+   the t value for each point.
+
+   This is the "chord-length parameterization" method, which is described in
+   Plass & Stone.
+-----------------------------------------------------------------------------*/
+    unsigned int p;
+
+    LOG("\nAssigning initial t values:\n  ");
+
+    /* Algorithm: We do a pass through the curve establishing how far each
+       point is along the curve in absolute terms, and then another pass
+       to normalize those distances to the fraction of the curve (i.e.
+       if the curve is 5 units long and Point P is 2 units in, we record
+       2 units for Point P in the first pass, and then compute 0.2 as the
+       fraction of the curve length in the second pass.
 
-    append_point(curve, int_to_real_coord(coord));
+       In the first pass, we abuse the distance property of the CurvePoint
+       object to remember the unnormalized distances.
+    */
+
+    CURVE_DIST(curveP, 0) = 0.0;
+
+    for (p = 1; p < CURVE_LENGTH(curveP); ++p) {
+        Point const point      = CURVE_POINT(curveP, p);
+        Point const previous_p = CURVE_POINT(curveP, p - 1);
+        float const d          = point_distance(point, previous_p);
+        CURVE_DIST(curveP, p)  = CURVE_DIST(curveP, p - 1) + d;
+    }
+
+    assert(LAST_CURVE_DIST(curveP) != 0.0);
+
+    /* Normalize to a curve length of 1.0 */
+
+    for (p = 1; p < CURVE_LENGTH(curveP); ++p)
+        CURVE_DIST(curveP, p) =
+            CURVE_DIST(curveP, p) / LAST_CURVE_DIST(curveP);
+
+    curve_logEntire(curveP);
 }
 
 
-/* Print a curve in human-readable form.  It turns out we never care
-   about most of the points on the curve, and so it is pointless to
-   print them all out umpteen times.  What matters is that we have some
-   from the end and some from the beginning.  */
 
 #define NUM_TO_PRINT 3
 
-#define LOG_CURVE_POINT(c, p, print_t)					\
-  do									\
-    {									\
-      LOG2 ("(%.3f,%.3f)", CURVE_POINT (c, p).x, CURVE_POINT (c, p).y);	\
-      if (print_t)							\
-        LOG1 ("/%.2f", CURVE_T (c, p));					\
-    }									\
+#define LOG_CURVE_POINT(c, p, printDistance) \
+    do  \
+    {                                   \
+      LOG2 ("(%.3f,%.3f)", CURVE_POINT (c, p).x, CURVE_POINT (c, p).y); \
+      if (printDistance) \
+        LOG1 ("/%.2f", CURVE_DIST(c, p)); \
+    } \
   while (0)
 
 
 
 void
-log_curve(curve * const curveP,
-          bool    const print_t) {
-
+curve_log(Curve * const curveP,
+          bool    const printDistance) {
+/*----------------------------------------------------------------------------
+  Print a curve in human-readable form.  It turns out we never care
+  about most of the points on the curve, and so it is pointless to
+  print them all out umpteen times.  What matters is that we have some
+  from the end and some from the beginning.
+-----------------------------------------------------------------------------*/
     if (!log_file)
         return;
 
@@ -159,9 +228,9 @@ log_curve(curve * const curveP,
     /* If the curve is short enough, don't use ellipses.  */
     if (CURVE_LENGTH(curveP) <= NUM_TO_PRINT * 2) {
         unsigned int thisPoint;
-    
+
         for (thisPoint = 0; thisPoint < CURVE_LENGTH(curveP); ++thisPoint) {
-            LOG_CURVE_POINT(curveP, thisPoint, print_t);
+            LOG_CURVE_POINT(curveP, thisPoint, printDistance);
             LOG(" ");
 
             if (thisPoint != CURVE_LENGTH(curveP) - 1
@@ -173,7 +242,7 @@ log_curve(curve * const curveP,
         for (thisPoint = 0;
              thisPoint < NUM_TO_PRINT && thisPoint < CURVE_LENGTH(curveP);
              ++thisPoint) {
-            LOG_CURVE_POINT(curveP, thisPoint, print_t);
+            LOG_CURVE_POINT(curveP, thisPoint, printDistance);
             LOG(" ");
         }
 
@@ -183,18 +252,19 @@ log_curve(curve * const curveP,
              thisPoint < CURVE_LENGTH(curveP);
              ++thisPoint) {
             LOG(" ");
-            LOG_CURVE_POINT(curveP, thisPoint, print_t);
+            LOG_CURVE_POINT(curveP, thisPoint, printDistance);
         }
     }
     LOG(".\n");
 }
 
 
-/* Like `log_curve', but write the whole thing.  */
 
 void
-log_entire_curve(curve * const curveP) {
-
+curve_logEntire(Curve * const curveP) {
+/*----------------------------------------------------------------------------
+  Like `log_curve', but write the whole thing.
+-----------------------------------------------------------------------------*/
     unsigned int thisPoint;
 
     if (!log_file)
@@ -218,95 +288,104 @@ log_entire_curve(curve * const curveP) {
 
 
 
-/* Return an initialized but empty curve list.  */
-
-curve_list_type
-new_curve_list (void)
-{
-  curve_list_type curve_list;
+CurveList
+curve_newList(void) {
+/*----------------------------------------------------------------------------
+  A new initialized but empty curve list.
+-----------------------------------------------------------------------------*/
+    CurveList curveList;
 
-  curve_list.length = 0;
-  curve_list.data = NULL;
+    curveList.length = 0;
+    curveList.data   = NULL;
 
-  return curve_list;
+    return curveList;
 }
 
 
-/* Free a curve list and all the curves it contains.  */
 
 void
-free_curve_list(curve_list_type * const curveListP) {
-
+curve_freeList(CurveList * const curveListP) {
+/*----------------------------------------------------------------------------
+  Free curve list and all the curves it contains.
+-----------------------------------------------------------------------------*/
     unsigned int thisCurve;
 
     for (thisCurve = 0; thisCurve < curveListP->length; ++thisCurve)
-        free_curve(curveListP->data[thisCurve]);
+        curve_free(curveListP->data[thisCurve]);
 
     /* If the character was empty, it won't have any curves.  */
     if (curveListP->data != NULL)
-        free (curveListP->data);
+        free(curveListP->data);
 }
 
 
-/* Add an element to a curve list.  */
 
 void
-append_curve (curve_list_type *curve_list, curve_type curve)
-{
-  curve_list->length++;
-  REALLOCARRAY_NOFAIL(curve_list->data, curve_list->length);
-  curve_list->data[curve_list->length - 1] = curve; }
+curve_appendList(CurveList * const curveListP,
+                 Curve *     const curveP) {
+/*----------------------------------------------------------------------------
+  Add an element to a curve list.
+-----------------------------------------------------------------------------*/
+    ++curveListP->length;
+    REALLOCARRAY_NOFAIL(curveListP->data, curveListP->length);
+    curveListP->data[curveListP->length - 1] = curveP;
+}
 
 
-/* Return an initialized but empty curve list array.  */
 
-curve_list_array_type
-new_curve_list_array (void)
-{
-  curve_list_array_type curve_list_array;
+CurveListArray
+curve_newListArray(void) {
+/*----------------------------------------------------------------------------
+    An initialized but empty curve list array.
+-----------------------------------------------------------------------------*/
+    CurveListArray curveListArray;
 
-  CURVE_LIST_ARRAY_LENGTH (curve_list_array) = 0;
-  curve_list_array.data = NULL;
+    CURVE_LIST_ARRAY_LENGTH(curveListArray) = 0;
+    curveListArray.data = NULL;
 
-  return curve_list_array;
+    return curveListArray;
 }
 
 
-/* Free a curve list array and all the curve lists it contains.  */
 
 void
-free_curve_list_array(const curve_list_array_type * const curve_list_array,
-                      at_progress_func                    notify_progress, 
-                      void *                        const client_data) {
+curve_freeListArray(const CurveListArray * const curveListArrayP,
+                    at_progress_func             notify_progress,
+                    void *                 const clientData) {
+/*----------------------------------------------------------------------------
+  Free all the curve lists curveListArray contains.
+-----------------------------------------------------------------------------*/
+    unsigned int thisList;
 
-  unsigned this_list;
+    for (thisList = 0;
+         thisList < CURVE_LIST_ARRAY_LENGTH(*curveListArrayP);
+         ++thisList) {
 
-  for (this_list = 0; this_list < CURVE_LIST_ARRAY_LENGTH(*curve_list_array);
-       this_list++) {
       if (notify_progress)
-          notify_progress(((float)this_list)/
-                          (CURVE_LIST_ARRAY_LENGTH(*curve_list_array) *
+          notify_progress(((float)thisList)/
+                          (CURVE_LIST_ARRAY_LENGTH(*curveListArrayP) *
                            (float)3.0)+(float)0.666 ,
-                          client_data);
-      free_curve_list(&CURVE_LIST_ARRAY_ELT (*curve_list_array, this_list));
-  }
-  
-  /* If the character was empty, it won't have any curves.  */
-  if (curve_list_array->data != NULL)
-      free(curve_list_array->data);
+                          clientData);
+      curve_freeList(&CURVE_LIST_ARRAY_ELT(*curveListArrayP, thisList));
+    }
+
+    /* If the character was empty, it won't have any curves.  */
+    if (curveListArrayP->data)
+        free(curveListArrayP->data);
 }
 
 
-/* Add an element to a curve list array.  */
 
 void
-append_curve_list(curve_list_array_type * const curve_list_array,
-                  curve_list_type         const curve_list) {
-
-  CURVE_LIST_ARRAY_LENGTH (*curve_list_array)++;
-  REALLOCARRAY_NOFAIL(curve_list_array->data,
-                      CURVE_LIST_ARRAY_LENGTH(*curve_list_array));
-  LAST_CURVE_LIST_ARRAY_ELT (*curve_list_array) = curve_list;
+curve_appendArray(CurveListArray * const curveListArrayP,
+                  CurveList        const curveList) {
+/*----------------------------------------------------------------------------
+  Add an element to *curveListArrayP.
+-----------------------------------------------------------------------------*/
+    CURVE_LIST_ARRAY_LENGTH(*curveListArrayP)++;
+    REALLOCARRAY_NOFAIL(curveListArrayP->data,
+                        CURVE_LIST_ARRAY_LENGTH(*curveListArrayP));
+    LAST_CURVE_LIST_ARRAY_ELT(*curveListArrayP) = curveList;
 }
 
 
diff --git a/converter/other/pamtosvg/curve.h b/converter/other/pamtosvg/curve.h
index ba5f1833..946bb2f3 100644
--- a/converter/other/pamtosvg/curve.h
+++ b/converter/other/pamtosvg/curve.h
@@ -5,67 +5,71 @@
 
 #include "autotrace.h"
 #include "point.h"
-#include "vector.h"
 
 /* We are simultaneously manipulating two different representations of
    the same outline: one based on (x,y) positions in the plane, and one
    based on parametric splines.  (We are trying to match the latter to
    the former.)  Although the original (x,y)'s are pixel positions,
-   i.e., integers, after filtering they are reals.  */
+   i.e., integers, after filtering they are reals.
+*/
 
 typedef struct {
-    float_coord coord;
-    float       t;
-} point_type;
+/*----------------------------------------------------------------------------
+   A point in a curve (i.e. a component of a curve).
+-----------------------------------------------------------------------------*/
+    Point coord;
+        /* Location in space of the point */
+    float distance;
+        /* Distance point is along the curve, as a fraction of the
+           curve length.  This is invalid until after someone has called
+           curve_updateDistance() on the curve.
+        */
+} CurvePoint;
 
 
 
-typedef struct curve {
+typedef struct Curve {
 /*----------------------------------------------------------------------------
   An ordered list of contiguous points in the raster, with no corners
   in it.  I.e. something that could reasonably be fit to a spline.
 -----------------------------------------------------------------------------*/
-    point_type *   point_list;
+    CurvePoint *   pointList;
         /* Array of the points in the curve.  Malloc'ed.  Size is 'length'.
            if 'length' is zero, this is meaningless and no memory is
            allocated.
         */
-    unsigned       length;
+    unsigned int   length;
         /* Number of points in the curve */
     bool           cyclic;
+       /* The curve is cyclic, i.e. it didn't have any corners, after all, so
+          the last point is adjacent to the first.
+       */
 
     /* 'previous' and 'next' links are for the doubly linked list which is
        a chain of all curves in an outline.  The chain is a cycle for a
        closed outline and linear for an open outline.
     */
-    struct curve * previous;
-    struct curve * next;
-} curve;
-
-typedef struct curve * curve_type;
-
-/* Get at the coordinates and the t values.  */
-#define CURVE_POINT(c, n) ((c)->point_list[n].coord)
-#define LAST_CURVE_POINT(c) ((c)->point_list[(c)->length-1].coord)
-#define CURVE_T(c, n) ((c)->point_list[n].t)
-#define LAST_CURVE_T(c) ((c)->point_list[(c)->length-1].t)
-
-/* This is the length of `point_list'.  */
+    struct Curve * previous;
+    struct Curve * next;
+} Curve;
+
+#define CURVE_POINT(c, n) ((c)->pointList[n].coord)
+#define LAST_CURVE_POINT(c) ((c)->pointList[(c)->length-1].coord)
+#define CURVE_DIST(c, n) ((c)->pointList[n].distance)
+#define LAST_CURVE_DIST(c) ((c)->pointList[(c)->length-1].distance)
 #define CURVE_LENGTH(c)  ((c)->length)
 
-/* A curve is ``cyclic'' if it didn't have any corners, after all, so
-   the last point is adjacent to the first.  */
 #define CURVE_CYCLIC(c)  ((c)->cyclic)
 
 /* If the curve is cyclic, the next and previous points should wrap
    around; otherwise, if we get to the end, we return CURVE_LENGTH and
    -1, respectively.  */
-#define CURVE_NEXT(c, n)						\
-  ((n) + 1 >= CURVE_LENGTH (c)						\
-  ? CURVE_CYCLIC (c) ? ((n) + 1) % CURVE_LENGTH (c) : CURVE_LENGTH (c)	\
+#define CURVE_NEXT(c, n)                                                \
+  ((n) + 1 >= CURVE_LENGTH (c)                                          \
+  ? CURVE_CYCLIC (c) ? ((n) + 1) % CURVE_LENGTH (c) : CURVE_LENGTH (c)  \
   : (n) + 1)
-#define CURVE_PREV(c, n)						\
-  ((signed int) (n) - 1 < 0							\
+#define CURVE_PREV(c, n)                                                \
+  ((signed int) (n) - 1 < 0                                                     \
   ? CURVE_CYCLIC (c) ? (signed int) CURVE_LENGTH (c) + (signed int) (n) - 1 : -1\
   : (signed int) (n) - 1)
 
@@ -73,44 +77,41 @@ typedef struct curve * curve_type;
 #define NEXT_CURVE(c) ((c)->next)
 
 
-/* Return an entirely empty curve.  */
-extern curve_type new_curve (void);
+Curve *
+curve_new(void);
 
-/* Return a curve the same as C, except without any points.  */
-extern curve_type copy_most_of_curve (curve_type c);
+Curve *
+curve_copyMost(Curve * const curveP);
 
 void
-move_curve(curve * const dstP,
-           curve * const srcP);
+curve_move(Curve * const dstP,
+           Curve * const srcP);
 
 void
-free_curve(curve * const curveP);
+curve_free(Curve * const curveP);
 
-/* Like `append_pixel', for a point in real coordinates.  */
 void
-append_point(curve_type  const curve,
-             float_coord const coord);
+curve_appendPoint(Curve * const curveP,
+                  Point   const coord);
 
-/* Append the point P to the end of C's list.  */
 void
-append_pixel(curve_type    const c,
-             pm_pixelcoord const p);
-
-/* Write some or all, respectively, of the curve C in human-readable
-   form to the log file, if logging is enabled.  */
-extern void log_curve (curve_type c, bool print_t);
-extern void log_entire_curve (curve_type c);
-
-/* Display the curve C online, if displaying is enabled.  */
-extern void display_curve (curve_type);
+curve_appendPixel(Curve *       const curveP,
+                  pm_pixelcoord const p);
 
+void
+curve_setDistance(Curve * const curveP);
 
+void
+curve_log(Curve * const curveP,
+          bool    const print_t);
+void
+curve_logEntire(Curve * const curveP);
 
 typedef struct {
 /*----------------------------------------------------------------------------
    An ordered list of contiguous curves of a particular color.
 -----------------------------------------------------------------------------*/
-    curve ** data;
+    Curve ** data;
         /* data[i] is the handle of the ith curve in the list */
     unsigned length;
     bool     clockwise;
@@ -119,7 +120,7 @@ typedef struct {
         /* The curve list does not form a closed shape;  i.e. the last
            curve doesn't end where the first one starts.
         */
-} curve_list_type;
+} CurveList;
 
 /* Number of curves in the list.  */
 #define CURVE_LIST_LENGTH(c_l)  ((c_l).length)
@@ -134,21 +135,23 @@ typedef struct {
 #define CURVE_LIST_CLOCKWISE(c_l) ((c_l).clockwise)
 
 
-extern curve_list_type new_curve_list (void);
+CurveList
+curve_newList(void);
 
 void
-free_curve_list(curve_list_type * const curve_list);
+curve_freeList(CurveList * const curveListP);
 
-extern void append_curve (curve_list_type *, curve_type);
+void
+curve_appendList(CurveList * const curveListP,
+                 Curve *     const curveP);
 
 /* And a character is a list of outlines.  I named this
    `curve_list_array_type' because `curve_list_list_type' seemed pretty
    monstrous.  */
-typedef struct
-{
-  curve_list_type *data;
-  unsigned length;
-} curve_list_array_type;
+typedef struct {
+  CurveList * data;
+  unsigned    length;
+} CurveListArray;
 
 /* Turns out we can use the same definitions for lists of lists as for
    just lists.  But we define the usual names, just in case.  */
@@ -156,17 +159,16 @@ typedef struct
 #define CURVE_LIST_ARRAY_ELT CURVE_LIST_ELT
 #define LAST_CURVE_LIST_ARRAY_ELT LAST_CURVE_LIST_ELT
 
-curve_list_array_type
-new_curve_list_array(void);
+CurveListArray
+curve_newListArray(void);
 
 void
-free_curve_list_array(const curve_list_array_type * const curve_list_array,
-                      at_progress_func                    notify_progress, 
-                      void *                        const client_data);
+curve_freeListArray(const CurveListArray * const curveListArrayP,
+                    at_progress_func             notify_progress,
+                    void *                 const client_data);
 
 void
-append_curve_list(curve_list_array_type * const curve_list_array,
-                  curve_list_type         const curve_list);
+curve_appendArray(CurveListArray * const curveListArrayP,
+                  CurveList        const curveList);
 
 #endif
-
diff --git a/converter/other/pamtosvg/epsilon-equal.c b/converter/other/pamtosvg/epsilon.c
index 46d630c5..f5370475 100644
--- a/converter/other/pamtosvg/epsilon-equal.c
+++ b/converter/other/pamtosvg/epsilon.c
@@ -1,8 +1,6 @@
-/* epsilon-equal.c: define a error resist compare. */
-
 #include <math.h>
 
-#include "epsilon-equal.h"
+#include "epsilon.h"
 
 /* Numerical errors sometimes make a floating point number just slightly
    larger or smaller than its true value.  When it matters, we need to
@@ -13,7 +11,9 @@ epsilon_equal(float const v1,
               float const v2) {
 
     return
-        v1 == v2		       /* Usually they'll be exactly equal, anyway.  */
+        v1 == v2                       /* Usually they'll be exactly equal, anyway.  */
         || fabs(v1 - v2) <= REAL_EPSILON;
 }
 
+
+
diff --git a/converter/other/pamtosvg/epsilon-equal.h b/converter/other/pamtosvg/epsilon.h
index fa0437cd..c8e7c8bc 100644
--- a/converter/other/pamtosvg/epsilon-equal.h
+++ b/converter/other/pamtosvg/epsilon.h
@@ -1,7 +1,7 @@
 /* epsilon-equal.h: define an error resist compare. */
 
-#ifndef EPSILON_EQUAL_H
-#define EPSILON_EQUAL_H
+#ifndef EPSILON_H
+#define EPSILON_H
 
 #include "pm_c_util.h"
 
@@ -16,5 +16,5 @@ bool epsilon_equal(float const v1,
 
 #define REAL_EPSILON 0.00001
 
-#endif /* not EPSILON_EQUAL_H */
+#endif
 
diff --git a/converter/other/pamtosvg/exception.c b/converter/other/pamtosvg/exception.c
index 43761936..bf8228ae 100644
--- a/converter/other/pamtosvg/exception.c
+++ b/converter/other/pamtosvg/exception.c
@@ -1,4 +1,3 @@
-
 #include "exception.h"
 
 at_exception_type
@@ -10,7 +9,7 @@ at_exception_new(at_msg_func       client_func,
     e.msg_type = 0;
     e.client_func = client_func;
     e.client_data = client_data;
-    
+
     return e;
 }
 
@@ -31,7 +30,7 @@ at_exception_fatal(at_exception_type * const exception,
     if (exception) {
         exception->msg_type = AT_MSG_FATAL;
         if (exception->client_func) {
-            exception->client_func(message, 
+            exception->client_func(message,
                                    AT_MSG_FATAL,
                                    exception->client_data);
         }
@@ -47,9 +46,12 @@ at_exception_warning(at_exception_type * const exception,
     if (exception) {
         exception->msg_type = AT_MSG_WARNING;
         if (exception->client_func) {
-            exception->client_func(message, 
+            exception->client_func(message,
                                    AT_MSG_WARNING,
                                    exception->client_data);
         }
     }
 }
+
+
+
diff --git a/converter/other/pamtosvg/exception.h b/converter/other/pamtosvg/exception.h
index 113f65e6..06de7182 100644
--- a/converter/other/pamtosvg/exception.h
+++ b/converter/other/pamtosvg/exception.h
@@ -1,7 +1,7 @@
 /* exception.h: facility to handle error in autotrace */
 
 #ifndef AT_EXCEPTION_H
-#define AT_EXCEPTION_H 
+#define AT_EXCEPTION_H
 
 #include "autotrace.h"
 
@@ -10,8 +10,8 @@ extern "C" {
 #endif /* __cplusplus */
 
 /* Protocol:
-   If a function raises a FATAL(including propagation), 
-   the function must release resources allocated by the 
+   If a function raises a FATAL(including propagation),
+   the function must release resources allocated by the
    function itself.
 */
 typedef struct _at_exception_type at_exception_type;
diff --git a/converter/other/pamtosvg/fit.c b/converter/other/pamtosvg/fit.c
index 179b3bdf..9c6f20d4 100644
--- a/converter/other/pamtosvg/fit.c
+++ b/converter/other/pamtosvg/fit.c
@@ -34,90 +34,100 @@
 #include "message.h"
 #include "logreport.h"
 #include "spline.h"
+#include "point.h"
 #include "vector.h"
 #include "curve.h"
 #include "pxl-outline.h"
-#include "epsilon-equal.h"
+#include "epsilon.h"
 
 #define CUBE(x) ((x) * (x) * (x))
 
+typedef enum {LINEEND_INIT, LINEEND_TERM} LineEnd;
+
+static LineEnd
+otherEnd(LineEnd const thisEnd) {
+
+    switch (thisEnd) {
+    case LINEEND_INIT: return LINEEND_TERM;
+    case LINEEND_TERM: return LINEEND_INIT;
+    }
+    assert(false);  /* All cases handled above */
+    return LINEEND_INIT;  /* silence bogus compiler warning */
+}
+
+
+
 /* We need to manipulate lists of array indices.  */
 
-typedef struct index_list
-{
-  unsigned *data;
-  unsigned length;
-} index_list_type;
+typedef struct IndexList {
+    unsigned int * data;
+    unsigned int   length;
+} IndexList;
 
 /* The usual accessor macros.  */
 #define GET_INDEX(i_l, n)  ((i_l).data[n])
-#define INDEX_LIST_LENGTH(i_l)  ((i_l).length)
-#define GET_LAST_INDEX(i_l)  ((i_l).data[INDEX_LIST_LENGTH (i_l) - 1])
+#define INDEX_LIST_LENGTH(iL)  ((iL).length)
+#define GET_LAST_INDEX(iL)  ((iL).data[INDEX_LIST_LENGTH(iL) - 1])
 
 
 
 
 static pm_pixelcoord
-real_to_int_coord(float_coord const real_coord) {
+intCoordFmReal(Point const realCoord) {
 /*----------------------------------------------------------------------------
   Turn an real point into a integer one.
 -----------------------------------------------------------------------------*/
 
-    pm_pixelcoord int_coord;
+    pm_pixelcoord intCoord;
 
-    int_coord.col = ROUND(real_coord.x);
-    int_coord.row = ROUND(real_coord.y);
+    intCoord.col = ROUND(realCoord.x);
+    intCoord.row = ROUND(realCoord.y);
 
-    return int_coord;
+    return intCoord;
 }
 
 
+
 /* Lists of array indices (well, that is what we use it for).  */
 
-static index_list_type
-new_index_list (void)
-{
-  index_list_type index_list;
+static IndexList
+indexList_new(void) {
+
+    IndexList indexList;
 
-  index_list.data = NULL;
-  INDEX_LIST_LENGTH (index_list) = 0;
+    indexList.data = NULL;
+    INDEX_LIST_LENGTH(indexList) = 0;
 
-  return index_list;
+  return indexList;
 }
 
+
+
 static void
-free_index_list (index_list_type *index_list)
-{
-  if (INDEX_LIST_LENGTH (*index_list) > 0)
-    {
-      free (index_list->data);
-      index_list->data = NULL;
-      INDEX_LIST_LENGTH (*index_list) = 0;
+indexList_free(IndexList * const indexListP) {
+
+    if (INDEX_LIST_LENGTH(*indexListP) > 0) {
+        free(indexListP->data);
+        indexListP->data = NULL;
+        INDEX_LIST_LENGTH(*indexListP) = 0;
     }
 }
 
-static void
-append_index (index_list_type *list, unsigned new_index)
-{
-  INDEX_LIST_LENGTH (*list)++;
-  REALLOCARRAY_NOFAIL(list->data, INDEX_LIST_LENGTH(*list));
-  list->data[INDEX_LIST_LENGTH (*list) - 1] = new_index;
-}
 
 
-/* Return the Euclidean distance between P1 and P2.  */
+static void
+indexList_append(IndexList *  const listP,
+                 unsigned int const  newIndex) {
 
-static float
-distance (float_coord p1, float_coord p2)
-{
-  float x = p1.x - p2.x, y = p1.y - p2.y, z = p1.z - p2.z;
-  return (float) sqrt (SQR(x) + SQR(y) + SQR(z));
+    INDEX_LIST_LENGTH(*listP)++;
+    REALLOCARRAY_NOFAIL(listP->data, INDEX_LIST_LENGTH(*listP));
+    listP->data[INDEX_LIST_LENGTH(*listP) - 1] = newIndex;
 }
 
 
 
 static void
-appendCorner(index_list_type *  const cornerListP,
+appendCorner(IndexList       *  const cornerListP,
              unsigned int       const pixelSeq,
              pixel_outline_type const outline,
              float              const angle,
@@ -125,47 +135,49 @@ appendCorner(index_list_type *  const cornerListP,
 
     pm_pixelcoord const coord = O_COORDINATE(outline, pixelSeq);
 
-    append_index(cornerListP, pixelSeq);
+    indexList_append(cornerListP, pixelSeq);
     LOG4(" (%d,%d)%c%.3f", coord.col, coord.row, logType, angle);
 }
 
 
 
 static void
-find_vectors(unsigned int       const test_index,
-             pixel_outline_type const outline,
-             vector_type *      const in,
-             vector_type *      const out,
-             unsigned int       const corner_surround) {
+findVectors(unsigned int       const testIndex,
+            pixel_outline_type const outline,
+            Vector *      const inP,
+            Vector *      const outP,
+            unsigned int       const cornerSurround) {
 /*----------------------------------------------------------------------------
   Return the difference vectors coming in and going out of the outline
   OUTLINE at the point whose index is TEST_INDEX.  In Phoenix,
   Schneider looks at a single point on either side of the point we're
   considering.  That works for him because his points are not touching.
   But our points *are* touching, and so we have to look at
-  `corner_surround' points on either side, to get a better picture of
+  'cornerSurround' points on either side, to get a better picture of
   the outline's shape.
 -----------------------------------------------------------------------------*/
-    int i;
-    unsigned n_done;
-    pm_pixelcoord const candidate = O_COORDINATE(outline, test_index);
+    pm_pixelcoord const candidate = O_COORDINATE(outline, testIndex);
 
-    in->dx  = in->dy  = in->dz  = 0.0;
-    out->dx = out->dy = out->dz = 0.0;
+    unsigned int i;
+    unsigned int doneCt;
+
+    inP->dx  = inP->dy  = inP->dz  = 0.0;
+    outP->dx = outP->dy = outP->dz = 0.0;
 
-    /* Add up the differences from p of the `corner_surround' points
-       before p.
+    /* Add up the differences from p of the `corner_surround' points before p.
     */
-    for (i = O_PREV(outline, test_index), n_done = 0;
-         n_done < corner_surround;
-         i = O_PREV(outline, i), ++n_done)
-        *in = Vadd(*in, IPsubtract(O_COORDINATE(outline, i), candidate));
+    for (i = O_PREV(outline, testIndex), doneCt = 0;
+         doneCt < cornerSurround;
+         i = O_PREV(outline, i), ++doneCt)
+        *inP = vector_sum(*inP, vector_IPointDiff(O_COORDINATE(outline, i),
+                                                  candidate));
 
     /* And the points after p. */
-    for (i = O_NEXT (outline, test_index), n_done = 0;
-         n_done < corner_surround;
-         i = O_NEXT(outline, i), ++n_done)
-        *out = Vadd(*out, IPsubtract(O_COORDINATE(outline, i), candidate));
+    for (i = O_NEXT(outline, testIndex), doneCt = 0;
+         doneCt < cornerSurround;
+         i = O_NEXT(outline, i), ++doneCt)
+        *outP = vector_sum(*outP, vector_IPointDiff(O_COORDINATE(outline, i),
+                                                    candidate));
 }
 
 
@@ -179,8 +191,8 @@ lookAheadForBetterCorner(pixel_outline_type  const outline,
                          unsigned int *      const highestExaminedP,
                          float *             const bestCornerAngleP,
                          unsigned int *      const bestCornerIndexP,
-                         index_list_type *   const equallyGoodListP,
-                         index_list_type *   const cornerListP,
+                         IndexList *         const equallyGoodListP,
+                         IndexList *         const cornerListP,
                          at_exception_type * const exceptionP) {
 /*----------------------------------------------------------------------------
    'basePixelSeq' is the sequence position within 'outline' of a pixel
@@ -201,14 +213,14 @@ lookAheadForBetterCorner(pixel_outline_type  const outline,
 -----------------------------------------------------------------------------*/
     float bestCornerAngle;
     unsigned bestCornerIndex;
-    index_list_type equallyGoodList;
+    IndexList equallyGoodList;
     unsigned int q;
     unsigned int i;
 
     bestCornerIndex = basePixelSeq;     /* initial assumption */
     bestCornerAngle = baseCornerAngle;    /* initial assumption */
 
-    equallyGoodList = new_index_list();
+    equallyGoodList = indexList_new();
 
     q = basePixelSeq;
     i = basePixelSeq + 1;  /* Start with the next pixel */
@@ -217,14 +229,14 @@ lookAheadForBetterCorner(pixel_outline_type  const outline,
            i < O_LENGTH(outline) &&
            !at_exception_got_fatal(exceptionP)) {
 
-        vector_type inVector, outVector;
+        Vector inVector, outVector;
         float cornerAngle;
 
         /* Check the angle.  */
 
         q = i % O_LENGTH(outline);
-        find_vectors(q, outline, &inVector, &outVector, cornerSurround);
-        cornerAngle = Vangle(inVector, outVector, exceptionP);
+        findVectors(q, outline, &inVector, &outVector, cornerSurround);
+        cornerAngle = vector_angle(inVector, outVector, exceptionP);
         if (!at_exception_got_fatal(exceptionP)) {
             /* Perhaps the angle is sufficiently small that we want to
                consider this a corner, even if it's not the best
@@ -236,15 +248,15 @@ lookAheadForBetterCorner(pixel_outline_type  const outline,
                 appendCorner(cornerListP, q, outline, cornerAngle, '\\');
 
             if (epsilon_equal(cornerAngle, bestCornerAngle))
-                append_index(&equallyGoodList, q);
+                indexList_append(&equallyGoodList, q);
             else if (cornerAngle < bestCornerAngle) {
                 bestCornerAngle = cornerAngle;
                 /* We want to check `cornerSurround' pixels beyond the
                    new best corner.
                 */
                 i = bestCornerIndex = q;
-                free_index_list(&equallyGoodList);
-                equallyGoodList = new_index_list();
+                indexList_free(&equallyGoodList);
+                equallyGoodList = indexList_new();
             }
             ++i;
         }
@@ -279,10 +291,10 @@ establishCornerSearchLimits(pixel_outline_type  const outline,
 
 
 static void
-remove_adjacent_corners(index_list_type *   const list,
-                        unsigned int        const last_index,
-                        bool                const remove_adj_corners,
-                        at_exception_type * const exception) {
+removeAdjacentCorners(IndexList *         const listP,
+                      unsigned int        const lastIndex,
+                      bool                const mustRemoveAdjCorners,
+                      at_exception_type * const exception) {
 /*----------------------------------------------------------------------------
    Remove adjacent points from the index list LIST.  We do this by first
    sorting the list and then running through it.  Since these lists are
@@ -294,58 +306,61 @@ remove_adjacent_corners(index_list_type *   const list,
    We need to do this because the adjacent corners turn into
    two-pixel-long curves, which can be fit only by straight lines.
 -----------------------------------------------------------------------------*/
-  unsigned int j;
-  unsigned int last;
-  index_list_type new_list = new_index_list ();
+    unsigned int j;
+    unsigned int last;
+    IndexList newList;
 
-  for (j = INDEX_LIST_LENGTH (*list) - 1; j > 0; j--)
-    {
-      unsigned search;
-      unsigned temp;
-      /* Find maximal element below `j'.  */
-      unsigned max_index = j;
-
-      for (search = 0; search < j; search++)
-        if (GET_INDEX (*list, search) > GET_INDEX (*list, max_index))
-          max_index = search;
-
-      if (max_index != j)
-        {
-          temp = GET_INDEX (*list, j);
-          GET_INDEX (*list, j) = GET_INDEX (*list, max_index);
-          GET_INDEX (*list, max_index) = temp;
+    newList = indexList_new();  /* initial value */
+
+    for (j = INDEX_LIST_LENGTH (*listP) - 1; j > 0; --j) {
+        unsigned int search;
+        unsigned int maxIndex;
+            /* We find maximal element below `j' */
+
+        for (search = 0, maxIndex = j; search < j; ++search)
+            if (GET_INDEX (*listP, search) > GET_INDEX (*listP, maxIndex))
+                maxIndex = search;
+
+        if (maxIndex != j) {
+            unsigned int const temp = GET_INDEX (*listP, j);
+            GET_INDEX (*listP, j) = GET_INDEX (*listP, maxIndex);
+            GET_INDEX (*listP, maxIndex) = temp;
         }
     }
 
-  /* The list is sorted.  Now look for adjacent entries.  Each time
-     through the loop we insert the current entry and, if appropriate,
-     the next entry.  */
-  for (j = 0; j < INDEX_LIST_LENGTH (*list) - 1; j++)
-    {
-      unsigned current = GET_INDEX (*list, j);
-      unsigned next = GET_INDEX (*list, j + 1);
+    /* The list is sorted.  Now look for adjacent entries.  Each time through
+       the loop we insert the current entry and, if appropriate, the next
+       entry.
+    */
+    for (j = 0; j < INDEX_LIST_LENGTH(*listP) - 1; ++j) {
+        unsigned int const current = GET_INDEX(*listP, j);
+        unsigned int const next    = GET_INDEX(*listP, j + 1);
 
-      /* We should never have inserted the same element twice.  */
-      /* assert (current != next); */
+        /* We should never have inserted the same element twice.  */
+        /* assert (current != next); */
 
-      if ((remove_adj_corners) && ((next == current + 1) || (next == current)))
-        j++;
+        if ((mustRemoveAdjCorners) && ((next == current + 1) ||
+                                       (next == current)))
+            ++j;
 
-      append_index (&new_list, current);
+        indexList_append(&newList, current);
     }
 
-  /* Don't append the last element if it is 1) adjacent to the previous
-     one; or 2) adjacent to the very first one.  */
-  last = GET_LAST_INDEX (*list);
-  if (INDEX_LIST_LENGTH (new_list) == 0
-      || !(last == GET_LAST_INDEX (new_list) + 1
-           || (last == last_index && GET_INDEX (*list, 0) == 0)))
-    append_index (&new_list, last);
-
-  free_index_list (list);
-  *list = new_list;
+    /* Don't append the last element if it is 1) adjacent to the previous one;
+       or 2) adjacent to the very first one.
+    */
+    last = GET_LAST_INDEX(*listP);
+    if (INDEX_LIST_LENGTH(newList) == 0
+        || !(last == GET_LAST_INDEX(newList) + 1
+             || (last == lastIndex && GET_INDEX(*listP, 0) == 0)))
+        indexList_append(&newList, last);
+
+    indexList_free(listP);
+    *listP = newList;
 }
 
+
+
 /* A ``knee'' is a point which forms a ``right angle'' with its
    predecessor and successor.  See the documentation (the `Removing
    knees' section) for an example and more details.
@@ -386,29 +401,29 @@ remove_adjacent_corners(index_list_type *   const list,
 
 
 static void
-remove_knee_points(curve * const curveP,
+remove_knee_points(Curve * const curveP,
                    bool    const clockwise) {
 
     unsigned int const offset = CURVE_CYCLIC(curveP) ? 0 : 1;
-    curve * const trimmedCurveP = copy_most_of_curve(curveP);
+    Curve * const trimmedCurveP = curve_copyMost(curveP);
 
     pm_pixelcoord previous;
     unsigned int i;
 
     if (!CURVE_CYCLIC(curveP))
-        append_pixel(trimmedCurveP,
-                     real_to_int_coord(CURVE_POINT(curveP, 0)));
+        curve_appendPixel(trimmedCurveP,
+                          intCoordFmReal(CURVE_POINT(curveP, 0)));
 
-    previous = real_to_int_coord(CURVE_POINT(curveP,
-                                             CURVE_PREV(curveP, offset)));
+    previous = intCoordFmReal(CURVE_POINT(curveP,
+                                          CURVE_PREV(curveP, offset)));
 
     for (i = offset; i < CURVE_LENGTH(curveP) - offset; ++i) {
         pm_pixelcoord const current =
-            real_to_int_coord(CURVE_POINT(curveP, i));
+            intCoordFmReal(CURVE_POINT(curveP, i));
         pm_pixelcoord const next =
-            real_to_int_coord(CURVE_POINT(curveP, CURVE_NEXT(curveP, i)));
-        vector_type const prev_delta = IPsubtract(previous, current);
-        vector_type const next_delta = IPsubtract(next, current);
+            intCoordFmReal(CURVE_POINT(curveP, CURVE_NEXT(curveP, i)));
+        Vector const prev_delta = vector_IPointDiff(previous, current);
+        Vector const next_delta = vector_IPointDiff(next, current);
 
         if (ONLY_ONE_ZERO(prev_delta) && ONLY_ONE_ZERO(next_delta)
             && ((clockwise && CLOCKWISE_KNEE(prev_delta, next_delta))
@@ -417,26 +432,26 @@ remove_knee_points(curve * const curveP,
             LOG2(" (%d,%d)", current.col, current.row);
         else {
             previous = current;
-            append_pixel(trimmedCurveP, current);
+            curve_appendPixel(trimmedCurveP, current);
         }
     }
 
     if (!CURVE_CYCLIC(curveP))
-        append_pixel(trimmedCurveP,
-                     real_to_int_coord(LAST_CURVE_POINT(curveP)));
+        curve_appendPixel(trimmedCurveP,
+                          intCoordFmReal(LAST_CURVE_POINT(curveP)));
 
     if (CURVE_LENGTH(trimmedCurveP) == CURVE_LENGTH(curveP))
         LOG(" (none)");
 
     LOG(".\n");
 
-    move_curve(curveP, trimmedCurveP);
+    curve_move(curveP, trimmedCurveP);
 }
 
 
 
 static void
-filter(curve *             const curveP,
+filter(Curve *             const curveP,
        fitting_opts_type * const fittingOptsP) {
 /*----------------------------------------------------------------------------
   Smooth the curve by adding in neighboring points.  Do this
@@ -445,7 +460,7 @@ filter(curve *             const curveP,
     unsigned int const offset = CURVE_CYCLIC(curveP) ? 0 : 1;
 
     unsigned int iteration, thisPoint;
-    float_coord prevNewPoint;
+    Point prevNewPoint;
 
     /* We must have at least three points -- the previous one, the current
        one, and the next one.  But if we don't have at least five, we will
@@ -464,7 +479,7 @@ filter(curve *             const curveP,
     for (iteration = 0;
          iteration < fittingOptsP->filter_iterations;
          ++iteration) {
-        curve * const newcurveP = copy_most_of_curve(curveP);
+        Curve * const newcurveP = curve_copyMost(curveP);
 
         bool collapsed;
 
@@ -472,13 +487,13 @@ filter(curve *             const curveP,
 
         /* Keep the first point on the curve.  */
         if (offset)
-            append_point(newcurveP, CURVE_POINT(curveP, 0));
+            curve_appendPoint(newcurveP, CURVE_POINT(curveP, 0));
 
         for (thisPoint = offset;
              thisPoint < CURVE_LENGTH(curveP) - offset;
              ++thisPoint) {
-            vector_type in, out, sum;
-            float_coord newPoint;
+            Vector in, out, sum;
+            Point newPoint;
 
             /* Calculate the vectors in and out, computed by looking
                at n points on either side of this_point.  Experimental
@@ -487,7 +502,7 @@ filter(curve *             const curveP,
 
             signed int prev, prevprev; /* have to be signed */
             unsigned int next, nextnext;
-            float_coord candidate = CURVE_POINT(curveP, thisPoint);
+            Point candidate = CURVE_POINT(curveP, thisPoint);
 
             prev = CURVE_PREV(curveP, thisPoint);
             prevprev = CURVE_PREV(curveP, prev);
@@ -499,25 +514,32 @@ filter(curve *             const curveP,
             */
             in.dx = in.dy = in.dz = 0.0;
 
-            in = Vadd(in, Psubtract(CURVE_POINT(curveP, prev), candidate));
+            in = vector_sum(in,
+                            vector_fromTwoPoints(CURVE_POINT(curveP, prev),
+                                                 candidate));
             if (prevprev >= 0)
-                in = Vadd(in,
-                          Psubtract(CURVE_POINT(curveP, prevprev), candidate));
+                in = vector_sum(
+                    in,
+                    vector_fromTwoPoints(CURVE_POINT(curveP, prevprev),
+                                         candidate));
 
             /* And the points after p.  Don't use more points after p than we
                ended up with before it.
             */
             out.dx = out.dy = out.dz = 0.0;
 
-            out = Vadd(out, Psubtract(CURVE_POINT(curveP, next), candidate));
+            out = vector_sum(
+                out,
+                vector_fromTwoPoints(CURVE_POINT(curveP, next), candidate));
             if (nextnext < CURVE_LENGTH(curveP))
-                out = Vadd(out,
-                           Psubtract(CURVE_POINT(curveP, nextnext),
-                                     candidate));
+                out = vector_sum(
+                    out,
+                    vector_fromTwoPoints(CURVE_POINT(curveP, nextnext),
+                                         candidate));
 
             /* Start with the old point.  */
             newPoint = candidate;
-            sum = Vadd(in, out);
+            sum = vector_sum(in, out);
             /* We added 2*n+2 points, so we have to divide the sum by 2*n+2 */
             newPoint.x += sum.dx / 6;
             newPoint.y += sum.dy / 6;
@@ -532,31 +554,31 @@ filter(curve *             const curveP,
             /* Put the newly computed point into a separate curve, so it
                doesn't affect future computation (on this iteration).
             */
-            append_point(newcurveP, prevNewPoint = newPoint);
+            curve_appendPoint(newcurveP, prevNewPoint = newPoint);
         }
 
         if (collapsed)
-            free_curve(newcurveP);
+            curve_free(newcurveP);
         else {
             /* Just as with the first point, we have to keep the last
                point.
             */
             if (offset)
-                append_point(newcurveP, LAST_CURVE_POINT(curveP));
+                curve_appendPoint(newcurveP, LAST_CURVE_POINT(curveP));
 
             /* Set the original curve to the newly filtered one, and go
                again.
             */
-            move_curve(curveP, newcurveP);
+            curve_move(curveP, newcurveP);
         }
     }
-    log_curve(curveP, false);
+    curve_log(curveP, false);
 }
 
 
 
 static void
-removeAdjacent(index_list_type *   const cornerListP,
+removeAdjacent(IndexList *         const cornerListP,
                pixel_outline_type  const outline,
                fitting_opts_type * const fittingOptsP,
                at_exception_type * const exception) {
@@ -567,7 +589,7 @@ removeAdjacent(index_list_type *   const cornerListP,
     */
 
     if (INDEX_LIST_LENGTH(*cornerListP) > 0)
-        remove_adjacent_corners(
+        removeAdjacentCorners(
             cornerListP,
             O_LENGTH(outline) - (outline.open ? 2 : 1),
             fittingOptsP->remove_adjacent_corners,
@@ -576,10 +598,10 @@ removeAdjacent(index_list_type *   const cornerListP,
 
 
 
-static index_list_type
-find_corners(pixel_outline_type  const outline,
-             fitting_opts_type * const fittingOptsP,
-             at_exception_type * const exceptionP) {
+static IndexList
+findCorners(pixel_outline_type  const outline,
+            fitting_opts_type * const fittingOptsP,
+            at_exception_type * const exceptionP) {
 
     /* We consider a point to be a corner if (1) the angle defined by
        the `corner_surround' points coming into it and going out from
@@ -589,9 +611,9 @@ find_corners(pixel_outline_type  const outline,
     */
     unsigned int p;
     unsigned int firstPixelSeq, lastPixelSeq;
-    index_list_type cornerList;
+    IndexList cornerList;
 
-    cornerList = new_index_list();
+    cornerList = indexList_new();
 
     if (O_LENGTH(outline) <= fittingOptsP->corner_surround * 2 + 1)
         return cornerList;
@@ -601,13 +623,13 @@ find_corners(pixel_outline_type  const outline,
 
     /* Consider each pixel on the outline in turn.  */
     for (p = firstPixelSeq; p <= lastPixelSeq;) {
-        vector_type inVector, outVector;
+        Vector inVector, outVector;
         float cornerAngle;
 
         /* Check if the angle is small enough.  */
-        find_vectors(p, outline, &inVector, &outVector,
+        findVectors(p, outline, &inVector, &outVector,
                      fittingOptsP->corner_surround);
-        cornerAngle = Vangle(inVector, outVector, exceptionP);
+        cornerAngle = vector_angle(inVector, outVector, exceptionP);
         if (at_exception_got_fatal(exceptionP))
             goto cleanup;
 
@@ -624,7 +646,7 @@ find_corners(pixel_outline_type  const outline,
             */
             float bestCornerAngle;
             unsigned bestCornerIndex;
-            index_list_type equallyGoodList;
+            IndexList equallyGoodList;
             unsigned int q;
 
             if (cornerAngle <= fittingOptsP->corner_always_threshold)
@@ -663,7 +685,7 @@ find_corners(pixel_outline_type  const outline,
                     appendCorner(&cornerList, GET_INDEX(equallyGoodList, j),
                                  outline, bestCornerAngle, '@');
             }
-            free_index_list(&equallyGoodList);
+            indexList_free(&equallyGoodList);
 
             /* If we wrapped around in our search, we're done;
                otherwise, we move on to the pixel after the highest
@@ -683,19 +705,19 @@ cleanup:
 
 static void
 makeOutlineOneCurve(pixel_outline_type const outline,
-                    curve_list_type *  const curveListP) {
+                    CurveList *        const curveListP) {
 /*----------------------------------------------------------------------------
    Add to *curveListP a single curve that represents the outline 'outline'.
 
    That curve does not have beginning and ending slope information.
 -----------------------------------------------------------------------------*/
-    curve * curveP;
+    Curve * curveP;
     unsigned int pixelSeq;
 
-    curveP = new_curve();
+    curveP = curve_new();
 
     for (pixelSeq = 0; pixelSeq < O_LENGTH(outline); ++pixelSeq)
-        append_pixel(curveP, O_COORDINATE(outline, pixelSeq));
+        curve_appendPixel(curveP, O_COORDINATE(outline, pixelSeq));
 
     if (outline.open)
         CURVE_CYCLIC(curveP) = false;
@@ -706,17 +728,17 @@ makeOutlineOneCurve(pixel_outline_type const outline,
     NEXT_CURVE(curveP)     = curveP;
     PREVIOUS_CURVE(curveP) = curveP;
 
-    append_curve(curveListP, curveP);
+    curve_appendList(curveListP, curveP);
 }
 
 
 
 static void
 addCurveStartingAtCorner(pixel_outline_type const outline,
-                         index_list_type    const cornerList,
+                         IndexList          const cornerList,
                          unsigned int       const cornerSeq,
-                         curve_list_type *  const curveListP,
-                         curve **           const curCurvePP) {
+                         CurveList *        const curveListP,
+                         Curve **           const curCurvePP) {
 /*----------------------------------------------------------------------------
    Add to the list *curveListP a new curve that starts at the cornerSeq'th
    corner in outline 'outline' (whose corners are 'cornerList') and
@@ -730,7 +752,7 @@ addCurveStartingAtCorner(pixel_outline_type const outline,
     unsigned int const cornerPixelSeq = GET_INDEX(cornerList, cornerSeq);
 
     unsigned int lastPixelSeq;
-    curve * curveP;
+    Curve * curveP;
     unsigned int pixelSeq;
 
     if (cornerSeq + 1 >= cornerList.length)
@@ -740,16 +762,16 @@ addCurveStartingAtCorner(pixel_outline_type const outline,
         /* Go through the next corner */
         lastPixelSeq = GET_INDEX(cornerList, cornerSeq + 1);
 
-    curveP = new_curve();
+    curveP = curve_new();
 
     for (pixelSeq = cornerPixelSeq; pixelSeq <= lastPixelSeq; ++pixelSeq)
-        append_pixel(curveP, O_COORDINATE(outline, pixelSeq));
+        curve_appendPixel(curveP, O_COORDINATE(outline, pixelSeq));
 
-    append_curve(curveListP, curveP);
+    curve_appendList(curveListP, curveP);
     {
         /* Add the new curve to the outline chain */
 
-        curve * const oldCurCurveP = *curCurvePP;
+        Curve * const oldCurCurveP = *curCurvePP;
 
         if (oldCurCurveP) {
             NEXT_CURVE(oldCurCurveP) = curveP;
@@ -763,8 +785,8 @@ addCurveStartingAtCorner(pixel_outline_type const outline,
 
 static void
 divideOutlineWithCorners(pixel_outline_type const outline,
-                         index_list_type    const cornerList,
-                         curve_list_type *  const curveListP) {
+                         IndexList          const cornerList,
+                         CurveList *        const curveListP) {
 /*----------------------------------------------------------------------------
    Divide the outline 'outline' into curves at the corner points
    'cornerList' and add each curve to *curveListP.
@@ -788,7 +810,7 @@ divideOutlineWithCorners(pixel_outline_type const outline,
     unsigned int const firstCurveSeq = CURVE_LIST_LENGTH(*curveListP);
         /* Index in curve list of the first curve we add */
     unsigned int cornerSeq;
-    curve * curCurveP;
+    Curve * curCurveP;
         /* Pointer to the curve we most recently added for this outline.
            Null if none
         */
@@ -801,15 +823,15 @@ divideOutlineWithCorners(pixel_outline_type const outline,
         /* Start with a curve that contains the points up to the first
            corner
         */
-        curve * curveP;
+        Curve * curveP;
         unsigned int pixelSeq;
 
-        curveP = new_curve();
+        curveP = curve_new();
 
         for (pixelSeq = 0; pixelSeq <= GET_INDEX(cornerList, 0); ++pixelSeq)
-            append_pixel(curveP, O_COORDINATE(outline, pixelSeq));
+            curve_appendPixel(curveP, O_COORDINATE(outline, pixelSeq));
 
-        append_curve(curveListP, curveP);
+        curve_appendList(curveListP, curveP);
         curCurveP = curveP;  /* Only curve in outline chain now */
     } else {
         /* We'll pick up the pixels before the first corner at the end */
@@ -827,12 +849,12 @@ divideOutlineWithCorners(pixel_outline_type const outline,
            before the first corner to the last curve, and chain the last
            curve to the first one.
         */
-        curve * const firstCurveP = CURVE_LIST_ELT(*curveListP, firstCurveSeq);
+        Curve * const firstCurveP = CURVE_LIST_ELT(*curveListP, firstCurveSeq);
 
         unsigned int pixelSeq;
 
         for (pixelSeq = 0; pixelSeq <= GET_INDEX(cornerList, 0); ++pixelSeq)
-            append_pixel(curCurveP, O_COORDINATE(outline, pixelSeq));
+            curve_appendPixel(curCurveP, O_COORDINATE(outline, pixelSeq));
 
         NEXT_CURVE(curCurveP)       = firstCurveP;
         PREVIOUS_CURVE(firstCurveP) = curCurveP;
@@ -841,16 +863,16 @@ divideOutlineWithCorners(pixel_outline_type const outline,
 
 
 
-static curve_list_array_type
-split_at_corners(pixel_outline_list_type const pixel_list,
-                 fitting_opts_type *     const fitting_opts,
+static CurveListArray
+split_at_corners(pixel_outline_list_type const pixelList,
+                 fitting_opts_type *     const fittingOptsP,
                  at_exception_type *     const exception) {
 /*----------------------------------------------------------------------------
-   Find the corners in PIXEL_LIST, the list of points.  (Presumably we
+   Find the corners in 'pixelList', the list of points.  (Presumably we
    can't fit a single spline around a corner.)  The general strategy
    is to look through all the points, remembering which we want to
    consider corners.  Then go through that list, producing the
-   curve_list.  This is dictated by the fact that PIXEL_LIST does not
+   curve_list.  This is dictated by the fact that 'pixelList' does not
    necessarily start on a corner---it just starts at the character's
    first outline pixel, going left-to-right, top-to-bottom.  But we
    want all our splines to start and end on real corners.
@@ -860,41 +882,41 @@ split_at_corners(pixel_outline_list_type const pixel_list,
                      ***********
                   ******************
 
-   PIXEL_LIST will start at the pixel below the `x'.  If we considered
+   'pixelList' will start at the pixel below the `x'.  If we considered
    this pixel a corner, we would wind up matching a very small segment
    from there to the end of the line, probably as a straight line, which
    is certainly not what we want.
 
-   PIXEL_LIST has one element for each closed outline on the character.
+   'pixelList' has one element for each closed outline on the character.
    To preserve this information, we return an array of curve_lists, one
    element (which in turn consists of several curves, one between each
-   pair of corners) for each element in PIXEL_LIST.
+   pair of corners) for each element in 'pixelList'.
 
    The curves we return do not have beginning and ending slope
    information.
 -----------------------------------------------------------------------------*/
     unsigned outlineSeq;
-    curve_list_array_type curve_array;
+    CurveListArray curveArray;
 
-    curve_array = new_curve_list_array();
+    curveArray = curve_newListArray();
 
     LOG("\nFinding corners:\n");
 
     for (outlineSeq = 0;
-         outlineSeq < O_LIST_LENGTH(pixel_list);
+         outlineSeq < O_LIST_LENGTH(pixelList);
          ++outlineSeq) {
 
         pixel_outline_type const outline =
-            O_LIST_OUTLINE(pixel_list, outlineSeq);
+            O_LIST_OUTLINE(pixelList, outlineSeq);
 
-        index_list_type corner_list;
-        curve_list_type curve_list;
+        IndexList cornerList;
+        CurveList curveList;
 
-        curve_list = new_curve_list();
+        curveList = curve_newList();
 
-        CURVE_LIST_CLOCKWISE(curve_list) = O_CLOCKWISE(outline);
-        curve_list.color = outline.color;
-        curve_list.open  = outline.open;
+        CURVE_LIST_CLOCKWISE(curveList) = O_CLOCKWISE(outline);
+        curveList.color = outline.color;
+        curveList.open  = outline.open;
 
         LOG1("#%u:", outlineSeq);
 
@@ -904,43 +926,43 @@ split_at_corners(pixel_outline_list_type const pixel_list,
            either side of a point before it is conceivable that we might
            want another corner.
         */
-        if (O_LENGTH(outline) > fitting_opts->corner_surround * 2 + 2)
-            corner_list = find_corners(outline, fitting_opts, exception);
+        if (O_LENGTH(outline) > fittingOptsP->corner_surround * 2 + 2)
+            cornerList = findCorners(outline, fittingOptsP, exception);
 
         else {
             int const surround = (O_LENGTH(outline) - 3) / 2;
             if (surround >= 2) {
-                unsigned int const save_corner_surround =
-                    fitting_opts->corner_surround;
-                fitting_opts->corner_surround = surround;
-                corner_list = find_corners(outline, fitting_opts, exception);
-                fitting_opts->corner_surround = save_corner_surround;
+                unsigned int const oldCornerSurround =
+                    fittingOptsP->corner_surround;
+                fittingOptsP->corner_surround = surround;
+                cornerList = findCorners(outline, fittingOptsP, exception);
+                fittingOptsP->corner_surround = oldCornerSurround;
             } else {
-                corner_list.length = 0;
-                corner_list.data = NULL;
+                cornerList.length = 0;
+                cornerList.data = NULL;
             }
         }
 
-        if (corner_list.length == 0)
+        if (cornerList.length == 0)
             /* No corners.  Use all of the pixel outline as the one curve. */
-            makeOutlineOneCurve(outline, &curve_list);
+            makeOutlineOneCurve(outline, &curveList);
         else
-            divideOutlineWithCorners(outline, corner_list, &curve_list);
+            divideOutlineWithCorners(outline, cornerList, &curveList);
 
-        LOG1(" [%u].\n", corner_list.length);
-        free_index_list(&corner_list);
+        LOG1(" [%u].\n", cornerList.length);
+        indexList_free(&cornerList);
 
         /* And now add the just-completed curve list to the array.  */
-        append_curve_list(&curve_array, curve_list);
+        curve_appendArray(&curveArray, curveList);
     }
 
-    return curve_array;
+    return curveArray;
 }
 
 
 
 static void
-removeKnees(curve_list_type const curveList) {
+removeKnees(CurveList const curveList) {
 /*----------------------------------------------------------------------------
   Remove the extraneous ``knee'' points before filtering.  Since the
   corners have already been found, we don't need to worry about
@@ -949,6 +971,7 @@ removeKnees(curve_list_type const curveList) {
     unsigned int curveSeq;
 
     LOG("\nRemoving knees:\n");
+
     for (curveSeq = 0; curveSeq < curveList.length; ++curveSeq) {
         LOG1("#%u:", curveSeq);
         remove_knee_points(CURVE_LIST_ELT(curveList, curveSeq),
@@ -959,7 +982,7 @@ removeKnees(curve_list_type const curveList) {
 
 
 static void
-computePointWeights(curve_list_type     const curveList,
+computePointWeights(CurveList           const curveList,
                     fitting_opts_type * const fittingOptsP,
                     distance_map_type * const distP) {
 
@@ -968,12 +991,14 @@ computePointWeights(curve_list_type     const curveList,
     unsigned int curveSeq;
 
     for (curveSeq = 0; curveSeq < curveList.length; ++curveSeq) {
+        Curve * const curveP = CURVE_LIST_ELT(curveList, curveSeq);
+
         unsigned pointSeq;
-        curve_type const curve = CURVE_LIST_ELT(curveList, curveSeq);
-        for (pointSeq = 0; pointSeq < CURVE_LENGTH(curve); ++pointSeq) {
-            float_coord * const coordP = &CURVE_POINT(curve, pointSeq);
-            unsigned int x = coordP->x;
-            unsigned int y = height - (unsigned int)coordP->y - 1;
+
+        for (pointSeq = 0; pointSeq < CURVE_LENGTH(curveP); ++pointSeq) {
+            Point *      const coordP = &CURVE_POINT(curveP, pointSeq);
+            unsigned int const x = coordP->x;
+            unsigned int const y = height - (unsigned int)coordP->y - 1;
 
             float width, w;
 
@@ -1015,7 +1040,7 @@ computePointWeights(curve_list_type     const curveList,
 
 
 static void
-filterCurves(curve_list_type     const curveList,
+filterCurves(CurveList           const curveList,
              fitting_opts_type * const fittingOptsP) {
 
     unsigned int curveSeq;
@@ -1049,118 +1074,134 @@ logSplinesForCurve(unsigned int     const curveSeq,
 
 
 static void
-change_bad_lines(spline_list_type *        const spline_list,
-                 const fitting_opts_type * const fitting_opts) {
+changeBadLines(spline_list_type *        const splineListP,
+               const fitting_opts_type * const fittingOptsP) {
+
+    /* Unfortunately, we cannot tell in isolation whether a given spline
+       should be changed to a line or not.  That be known only after the
+       entire curve has been fit to a list of splines.  (The curve is the
+       pixel outline between two corners.)  After subdividing the curve, a
+       line may very well fit a portion of the curve just as well as the
+       spline---but unless a spline is truly close to being a line, it should
+       not be combined with other lines.
+    */
 
-/* Unfortunately, we cannot tell in isolation whether a given spline
-   should be changed to a line or not.  That can only be known after the
-   entire curve has been fit to a list of splines.  (The curve is the
-   pixel outline between two corners.)  After subdividing the curve, a
-   line may very well fit a portion of the curve just as well as the
-   spline---but unless a spline is truly close to being a line, it
-   should not be combined with other lines.  */
+    unsigned int const length = SPLINE_LIST_LENGTH(*splineListP);
 
-  unsigned this_spline;
-  bool found_cubic = false;
-  unsigned length = SPLINE_LIST_LENGTH (*spline_list);
+    unsigned int thisSpline;
+    bool foundCubic;
 
-  LOG1 ("\nChecking for bad lines (length %u):\n", length);
+    LOG1("\nChecking for bad lines (length %u):\n", length);
 
-  /* First see if there are any splines in the fitted shape.  */
-  for (this_spline = 0; this_spline < length; this_spline++)
-    {
-      if (SPLINE_DEGREE (SPLINE_LIST_ELT (*spline_list, this_spline)) ==
-       CUBICTYPE)
-        {
-          found_cubic = true;
-          break;
+    /* First see if there are any splines in the fitted shape.  */
+    for (thisSpline = 0, foundCubic = false;
+         thisSpline < length;
+         ++thisSpline) {
+        if (SPLINE_DEGREE(SPLINE_LIST_ELT(*splineListP, thisSpline)) ==
+            CUBICTYPE) {
+            foundCubic = true;
+            break;
         }
     }
 
-  /* If so, change lines back to splines (we haven't done anything to
-     their control points, so we only have to change the degree) unless
-     the spline is close enough to being a line.  */
-  if (found_cubic)
-    for (this_spline = 0; this_spline < length; this_spline++)
-      {
-        spline_type s = SPLINE_LIST_ELT (*spline_list, this_spline);
-
-        if (SPLINE_DEGREE (s) == LINEARTYPE)
-          {
-            LOG1 ("  #%u: ", this_spline);
-            if (SPLINE_LINEARITY (s) > fitting_opts->line_reversion_threshold)
-              {
-                LOG ("reverted, ");
-                SPLINE_DEGREE (SPLINE_LIST_ELT (*spline_list, this_spline))
-                  = CUBICTYPE;
-              }
-            LOG1 ("linearity %.3f.\n", SPLINE_LINEARITY (s));
-          }
-      }
-    else
-      LOG ("  No lines.\n");
+    /* If so, change lines back to splines (we haven't done anything to
+       their control points, so we only have to change the degree) unless
+       the spline is close enough to being a line.
+    */
+    if (foundCubic) {
+        unsigned int thisSpline;
+
+        for (thisSpline = 0; thisSpline < length; ++thisSpline) {
+            spline_type const s = SPLINE_LIST_ELT(*splineListP, thisSpline);
+
+            if (SPLINE_DEGREE(s) == LINEARTYPE) {
+                LOG1("  #%u: ", thisSpline);
+                if (SPLINE_LINEARITY(s) >
+                    fittingOptsP->line_reversion_threshold) {
+                    LOG("reverted, ");
+                    SPLINE_DEGREE(SPLINE_LIST_ELT(*splineListP, thisSpline))
+                        = CUBICTYPE;
+                }
+                LOG1("linearity %.3f.\n", SPLINE_LINEARITY(s));
+            }
+        }
+    } else
+        LOG("  No lines.\n");
 }
 
 
 
 static bool
-spline_linear_enough(spline_type *             const spline,
-                     curve_type                const curve,
-                     const fitting_opts_type * const fitting_opts) {
+splineLinearEnough(spline_type *             const splineP,
+                   Curve *                   const curve,
+                   const fitting_opts_type * const fittingOptsP) {
+
+    /* Supposing that we have accepted the error, another question arises:
+       would we be better off just using a straight line?
+    */
 
-/* Supposing that we have accepted the error, another question arises:
-   would we be better off just using a straight line?  */
+    float A, B, C;
+    unsigned int thisPoint;
+    float dist;
+    float startEndDist;
+    float threshold;
 
-  float A, B, C;
-  unsigned this_point;
-  float dist = 0.0, start_end_dist, threshold;
+    LOG ("Checking linearity:\n");
 
-  LOG ("Checking linearity:\n");
+    A = END_POINT(*splineP).x - BEG_POINT(*splineP).x;
+    B = END_POINT(*splineP).y - BEG_POINT(*splineP).y;
+    C = END_POINT(*splineP).z - BEG_POINT(*splineP).z;
 
-  A = END_POINT(*spline).x - START_POINT(*spline).x;
-  B = END_POINT(*spline).y - START_POINT(*spline).y;
-  C = END_POINT(*spline).z - START_POINT(*spline).z;
+    startEndDist = (float) (SQR(A) + SQR(B) + SQR(C));
+    LOG1("start_end_distance is %.3f.\n", sqrt(startEndDist));
 
-  start_end_dist = (float) (SQR(A) + SQR(B) + SQR(C));
-  LOG1 ("start_end_distance is %.3f.\n", sqrt(start_end_dist));
+    LOG3("  Line endpoints are (%.3f, %.3f, %.3f) and ",
+         BEG_POINT(*splineP).x,
+         BEG_POINT(*splineP).y,
+         BEG_POINT(*splineP).z);
+    LOG3("(%.3f, %.3f, %.3f)\n",
+         END_POINT(*splineP).x, END_POINT(*splineP).y, END_POINT(*splineP).z);
 
-  LOG3 ("  Line endpoints are (%.3f, %.3f, %.3f) and ", START_POINT(*spline).x, START_POINT(*spline).y, START_POINT(*spline).z);
-  LOG3 ("(%.3f, %.3f, %.3f)\n", END_POINT(*spline).x, END_POINT(*spline).y, END_POINT(*spline).z);
+    /* LOG3("  Line is %.3fx + %.3fy + %.3f = 0.\n", A, B, C); */
 
-  /* LOG3 ("  Line is %.3fx + %.3fy + %.3f = 0.\n", A, B, C); */
+    for (thisPoint = 0, dist = 0.0;
+         thisPoint < CURVE_LENGTH(curve);
+         ++thisPoint) {
 
-  for (this_point = 0; this_point < CURVE_LENGTH (curve); this_point++)
-    {
-      float a, b, c, w;
-      float t = CURVE_T (curve, this_point);
-      float_coord spline_point = evaluate_spline (*spline, t);
+        float const t           = CURVE_DIST(curve, thisPoint);
+        Point const splinePoint = evaluate_spline(*splineP, t);
+
+        float const a = splinePoint.x - BEG_POINT(*splineP).x;
+        float const b = splinePoint.y - BEG_POINT(*splineP).y;
+        float const c = splinePoint.z - BEG_POINT(*splineP).z;
 
-      a = spline_point.x - START_POINT(*spline).x;
-      b = spline_point.y - START_POINT(*spline).y;
-      c = spline_point.z - START_POINT(*spline).z;
-      w = (A*a + B*b + C*c) / start_end_dist;
+        float const w = (A*a + B*b + C*c) / startEndDist;
 
-      dist += (float)sqrt(SQR(a-A*w) + SQR(b-B*w) + SQR(c-C*w));
+        dist += (float)sqrt(SQR(a-A*w) + SQR(b-B*w) + SQR(c-C*w));
     }
-  LOG1 ("  Total distance is %.3f, ", dist);
-
-  dist /= (CURVE_LENGTH (curve) - 1);
-  LOG1 ("which is %.3f normalized.\n", dist);
-
-  /* We want reversion of short curves to splines to be more likely than
-     reversion of long curves, hence the second division by the curve
-     length, for use in `change_bad_lines'.  */
-  SPLINE_LINEARITY (*spline) = dist;
-  LOG1 ("  Final linearity: %.3f.\n", SPLINE_LINEARITY (*spline));
-  if (start_end_dist * (float) 0.5 > fitting_opts->line_threshold)
-    threshold = fitting_opts->line_threshold;
-  else
-    threshold = start_end_dist * (float) 0.5;
-  LOG1 ("threshold is %.3f .\n", threshold);
-  if (dist < threshold)
-    return true;
-  else
-    return false;
+    LOG1("  Total distance is %.3f, ", dist);
+
+    dist /= (CURVE_LENGTH (curve) - 1);
+
+    LOG1 ("which is %.3f normalized.\n", dist);
+
+    /* We want reversion of short curves to splines to be more likely than
+       reversion of long curves, hence the second division by the curve
+       length, for use in `change_bad_lines'.
+    */
+    SPLINE_LINEARITY(*splineP) = dist;
+    LOG1("  Final linearity: %.3f.\n", SPLINE_LINEARITY (*splineP));
+
+    if (startEndDist * (float) 0.5 > fittingOptsP->line_threshold)
+        threshold = fittingOptsP->line_threshold;
+    else
+        threshold = startEndDist * (float) 0.5;
+    LOG1("threshold is %.3f .\n", threshold);
+
+    if (dist < threshold)
+        return true;
+    else
+        return false;
 }
 
 
@@ -1168,16 +1209,16 @@ spline_linear_enough(spline_type *             const spline,
 /* Forward declaration for recursion */
 
 static spline_list_type *
-fitCurve(curve *                   const curveP,
-         vector_type               const begSlope,
-         vector_type               const endSlope,
+fitCurve(Curve *                   const curveP,
+         Vector                    const begSlope,
+         Vector                    const endSlope,
          const fitting_opts_type * const fittingOptsP,
          at_exception_type *       const exceptionP);
 
 
 
 static spline_list_type *
-fitWithLine(curve * const curveP) {
+fitWithLine(Curve * const curveP) {
 /*----------------------------------------------------------------------------
   Return a list of splines that fit curve *curveP in a very simple way:
   a single spline which is a straight line through the first and last
@@ -1190,7 +1231,7 @@ fitWithLine(curve * const curveP) {
     LOG("Fitting with straight line:\n");
 
     SPLINE_DEGREE(line) = LINEARTYPE;
-    START_POINT(line)   = CONTROL1(line) = CURVE_POINT(curveP, 0);
+    BEG_POINT(line)     = CONTROL1(line) = CURVE_POINT(curveP, 0);
     END_POINT(line)     = CONTROL2(line) = LAST_CURVE_POINT(curveP);
 
     /* Make sure that this line is never changed to a cubic.  */
@@ -1206,128 +1247,155 @@ fitWithLine(curve * const curveP) {
 
 
 
-#define B0(t) CUBE ((float) 1.0 - (t))
-#define B1(t) ((float) 3.0 * (t) * SQR ((float) 1.0 - (t)))
-#define B2(t) ((float) 3.0 * SQR (t) * ((float) 1.0 - (t)))
-#define B3(t) CUBE (t)
-
-static spline_type
-fitOneSpline(curve *             const curveP,
-             vector_type         const begSlope,
-             vector_type         const endSlope,
-             at_exception_type * const exceptionP) {
+static float
+b2(float const fracCurveDist) {
 /*----------------------------------------------------------------------------
-  Return a spline that fits the points of curve *curveP,
-  with slope 'begSlope' at its beginning and 'endSlope' at its end.
+   Some mysterious weighting function
 
-  Make it a cubic spline.
+   'fracCurveDist' is a fraction (range [0.0-1.0]) of the distance along
+   a curve that a point on the curve is.
 -----------------------------------------------------------------------------*/
-    /* We already have the start and end points of the spline, so all
-      we need are the control points.  And we know in what direction
-      each control point is from its respective end point, so all we
-      need to figure out is its distance.  (The control point's
-      distance from the end point is an indication of how long the
-      curve goes in its direction).
+    return 3.0 * SQR(fracCurveDist) * (1.0 - fracCurveDist);
+}
 
-      We call the distance from an end point to the associated control
-      point "alpha".
 
-      We want to find starting and ending alpha that minimize the
-      least-square error in approximating *curveP with the spline.
 
-      How we do that is a complete mystery to me, but the original author
-      said to see pp.57--59 of the Phoenix thesis.  I haven't seen that.
+struct Mat22 {
+    struct { float beg; float end; } beg;
+    struct { float beg; float end; } end;
+};
 
-      In our expression of the math here, we use a struct with "beg" and
-      "end" members where the paper uses a matrix with "1" and "2"
-      subscripts, respectively.  A C array is a closer match to a math
-      matrix, but we think the struct is easier to read.
+struct Mat2 { float beg; float end; };
 
-      The B?(t) here corresponds to B_i^3(U_i) there.
-      The Bernstein polynomials of degree n are defined by
-      B_i^n(t) = { n \choose i } t^i (1-t)^{n-i}, i = 0..n
+struct VectorBegEndPair {
+    Vector beg;
+    Vector end;
+};
 
-    */
-    struct vectorPair {
-        vector_type beg;
-        vector_type end;
-    };
-    struct vectorPair tang;
 
-    float X_Cend_det, Cbeg_X_det, C_det;
-    spline_type spline;
-    vector_type begVector, endVector;
-    unsigned i;
-    struct vectorPair * A;  /* malloc'ed array */
-        /* I don't know the meaning of this array, but it is one entry for
-           each point in the curve (A[i] is for the ith point in the curve).
-        */
-    struct {
-        struct { float beg; float end; } beg;
-        struct { float beg; float end; } end;
-    } C;
-    struct { float beg; float end; } X;
+static void
+computeCX(Curve *                 const curveP,
+          struct VectorBegEndPair const tang,
+          struct Mat22 *          const cP,
+          struct Mat2 *           const xP) {
 
-    tang.beg = begSlope; tang.end = endSlope;
+    Vector const begVector = vector_fromPoint(CURVE_POINT(curveP, 0));
+    Vector const endVector = vector_fromPoint(LAST_CURVE_POINT(curveP));
 
-    MALLOCARRAY_NOFAIL(A, CURVE_LENGTH(curveP));
+    unsigned int pointSeq;
 
-    BEG_POINT(spline) = CURVE_POINT(curveP, 0);
-    END_POINT(spline) = LAST_CURVE_POINT(curveP);
-    begVector = make_vector(BEG_POINT(spline));
-    endVector = make_vector(END_POINT(spline));
+    cP->beg.beg = 0.0; cP->beg.end = 0.0; cP->end.beg = 0.0; cP->end.end = 0.0;
+        /* initial value */
 
-    for (i = 0; i < CURVE_LENGTH(curveP); ++i) {
-        A[i].beg = Vmult_scalar(tang.beg, B1(CURVE_T(curveP, i)));
-        A[i].end = Vmult_scalar(tang.end, B2(CURVE_T(curveP, i)));
-    }
+    xP->beg = 0.0; xP->end = 0.0; /* initial value */
 
-    C.beg.beg = 0.0; C.beg.end = 0.0; C.end.end = 0.0;  /* initial value */
+    for (pointSeq = 0; pointSeq < CURVE_LENGTH(curveP); ++pointSeq) {
+        float const curveDistFmBeg = CURVE_DIST(curveP, pointSeq);
+        float const curveDistToEnd = 1.0 - curveDistFmBeg;
+        struct VectorBegEndPair a;  /* constant */
+            /* I don't know the meaning of this, but the vectors of the pair
+               are in the direction of the beginning and points of the curve,
+               respectively, with magnitude a function of the fractional
+               distance from their respective endpoints of the current point.
+               "Fractional distance" means e.g. "this point is 20% of the way
+               to the end of the curve from its beginning".  The function is
 
-    X.beg = 0.0; X.end = 0.0; /* initial value */
+                 3 * <fracdistance> * SQR(1-<fracdistance>) .
+            */
+        Vector temp, temp0, temp1;
 
-    for (i = 0; i < CURVE_LENGTH(curveP); ++i) {
-        struct vectorPair * const AP = &A[i];
-        vector_type temp, temp0, temp1, temp2, temp3;
+        a.beg = vector_scaled(tang.beg, b2(curveDistToEnd));
+        a.end = vector_scaled(tang.end, b2(curveDistFmBeg));
 
-        C.beg.beg += Vdot(AP->beg, AP->beg);
-        C.beg.end += Vdot(AP->beg, AP->end);
-        /* C.end.beg = Vdot(AP->end, AP->beg) is done outside of loop */
-        C.end.end += Vdot(AP->end, AP->end);
+        cP->beg.beg += vector_dotProduct(a.beg, a.beg);
+        cP->beg.end += vector_dotProduct(a.beg, a.end);
+        cP->end.beg += vector_dotProduct(a.end, a.beg);
+        cP->end.end += vector_dotProduct(a.end, a.end);
 
         /* Now the right-hand side of the equation in the paper.  */
-        temp0 = Vmult_scalar(begVector, B0(CURVE_T(curveP, i)));
-        temp1 = Vmult_scalar(begVector, B1(CURVE_T(curveP, i)));
-        temp2 = Vmult_scalar(endVector, B2(CURVE_T(curveP, i)));
-        temp3 = Vmult_scalar(endVector, B3(CURVE_T(curveP, i)));
+        temp0 = vector_scaled(begVector,
+                              CUBE(curveDistToEnd) + b2(curveDistToEnd));
+        temp1 = vector_scaled(endVector,
+                              CUBE(curveDistFmBeg) + b2(curveDistFmBeg));
 
-        temp = make_vector(
-            Vsubtract_point(CURVE_POINT(curveP, i),
-                            Vadd(temp0, Vadd(temp1, Vadd(temp2, temp3)))));
+        temp = vector_fromPoint(
+            vector_diffPoint(
+                CURVE_POINT(curveP, pointSeq), vector_sum(temp0, temp1)));
 
-        X.beg += Vdot(temp, AP->beg);
-        X.end += Vdot(temp, AP->end);
+        xP->beg += vector_dotProduct(temp, a.beg);
+        xP->end += vector_dotProduct(temp, a.end);
     }
-    free(A);
+}
 
-    C.end.beg = C.beg.end;
 
-    X_Cend_det  = X.beg * C.end.end - X.end * C.beg.end;
-    Cbeg_X_det  = C.beg.beg * X.end - C.beg.end * X.beg;
-    C_det = C.beg.beg * C.end.end - C.end.beg * C.beg.end;
-    if (C_det == 0.0) {
-        LOG("zero determinant of C matrix");
-        at_exception_fatal(exceptionP, "zero determinant of C matrix");
-    } else {
-        struct { float beg; float end; } alpha;  /* constant */
-        alpha.beg = X_Cend_det / C_det;
-        alpha.end = Cbeg_X_det / C_det;
-
-        CONTROL1(spline) = Vadd_point(BEG_POINT(spline),
-                                      Vmult_scalar(tang.beg, alpha.beg));
-        CONTROL2(spline) = Vadd_point(END_POINT(spline),
-                                      Vmult_scalar(tang.end, alpha.end));
-        SPLINE_DEGREE(spline) = CUBICTYPE;
+
+static spline_type
+fitOneSpline(Curve *             const curveP,
+             Vector              const begSlope,
+             Vector              const endSlope,
+             at_exception_type * const exceptionP) {
+/*----------------------------------------------------------------------------
+  Return a spline that best fits the points of curve *curveP, passing through
+  the endpoints of *curveP and having slope 'begSlope' at its beginning and
+  'endSlope' at its end (both are unit vectors).
+
+  Make it a cubic spline.
+-----------------------------------------------------------------------------*/
+    /* We already have the start and end points of the spline, so all we need
+       are the control points.  And we know in what direction each control
+       point is from its respective end point, so all we need to figure out is
+       its distance.  (The control point's distance from the end point is an
+       indication of how long the curve goes in its direction).
+
+       We call the distance from an end point to the associated control point
+       "alpha".
+
+       We want to find starting and ending alpha that minimize the
+       least-square error in approximating *curveP with the spline.
+
+       How we do that is a complete mystery to me, but the original author
+       said to see pp. 57-59 of the Phoenix thesis.  Whatever that is, I
+       haven't seen it.
+
+       In our expression of the math here, we use a struct with "beg" and
+       "end" members where the paper uses a matrix with "1" and "2"
+       subscripts, respectively.  A C array is a closer match to a math
+       matrix, but we think the struct is easier to read.
+
+       The B?(t) here corresponds to B_i^3(U_i) there.
+       The Bernstein polynomials of degree n are defined by
+       B_i^n(t) = { n \choose i } t^i (1-t)^{n-i}, i = 0..n
+    */
+    struct VectorBegEndPair tang;
+    spline_type spline;
+    struct Mat22 C;
+    struct Mat2  X;
+
+    tang.beg = begSlope; tang.end = endSlope;
+
+    computeCX(curveP, tang, &C, &X);
+
+    {
+        float const XCendDet  = X.beg * C.end.end - X.end * C.beg.end;
+        float const CbegXDet  = C.beg.beg * X.end - C.beg.end * X.beg;
+        float const CDet = C.beg.beg * C.end.end - C.end.beg * C.beg.end;
+
+        if (CDet == 0.0) {
+            LOG("zero determinant of C matrix");
+            at_exception_fatal(exceptionP, "zero determinant of C matrix");
+        } else {
+            /* See above for meaning of "alpha */
+            float const alphaBeg = XCendDet / CDet;
+            float const alphaEnd = CbegXDet / CDet;
+
+            BEG_POINT(spline) = CURVE_POINT(curveP, 0);
+            END_POINT(spline) = LAST_CURVE_POINT(curveP);
+            CONTROL1(spline) = vector_sumPoint(
+                BEG_POINT(spline), vector_scaled(tang.beg, alphaBeg));
+            CONTROL2(spline) = vector_sumPoint(
+                END_POINT(spline), vector_scaled(tang.end, alphaEnd));
+            SPLINE_DEGREE(spline) = CUBICTYPE;
+        }
     }
     return spline;
 }
@@ -1344,158 +1412,150 @@ logSplineFit(spline_type const spline) {
 
     if (log_file) {
         LOG ("    ");
-        print_spline (log_file, spline);
+        print_spline(log_file, spline);
     }
 }
 
 
 
-static vector_type
-findHalfTangentBeg(curve *      const curveP,
-                   unsigned int const tangentSurround) {
+static Vector
+findHalfTangent(LineEnd      const toWhichEnd,
+                Curve *      const curveP,
+                unsigned int const tangentSurround) {
 /*----------------------------------------------------------------------------
-  Find the slope in the vicinity of the beginning of the curve
-  *curveP.
+  Find the slope in the vicinity of one of the ends of the curve *curveP,
+  as specified by 'toWhichEnd'.
 
-  To wit, this is the mean slope between the first point on the curve and
-  each of the 'tangentSurround' following points, up to half the curve.
+  To wit, this is the mean slope between the end point and each of the
+  'tangentSurround' adjacent points, up to half the curve.
 
-  For example, if 'tangentSurround' is 3 and the curve is 10 points
-  long, we imagine a line through Point 0 and Point 1, another through
-  Point 0 and Point 2, and a third through Point 0 and Point 3.  We
-  return the mean of the slopes of those 3 lines.
------------------------------------------------------------------------------*/
-    float_coord const tangentPoint = CURVE_POINT(curveP, 0);
-    vector_type const zeroZero = { 0.0, 0.0 };
-    unsigned int const surround =
-        MIN(CURVE_LENGTH(curveP) / 2, tangentSurround);
-
-    unsigned int p;
-    vector_type sum;
-    vector_type mean;
-    unsigned int n;
+  For example, if 'toWhichEnd' is LINEEND_INIT and 'tangentSurround' is 3 and
+  the curve is 10 points long, we imagine a line through Point 0 and Point 1,
+  another through Point 0 and Point 2, and a third through Point 0 and Point
+  3.  We return the mean of the slopes of those 3 lines.
 
-    for (p = 0, n = 0, sum = zeroZero; p < surround; ++p) {
-        unsigned int const thisIndex = p + 1;
-        float_coord  const thisPoint = CURVE_POINT(curveP, thisIndex);
+  Don't consider points that are identical to the end point (as there could
+  be no slope between those points) -- they're part of the count, but don't
+  contribute to the slope.  If _all_ of the points to be considered are
+  identical to the end point, arbitrarily return a horizontal slope.
 
-        /* Perhaps we should weight the tangent from `thisPoint' by some
-           factor dependent on the distance from the tangent point.
-        */
-        sum = Vadd(sum, Pdirection(thisPoint, tangentPoint));
-        ++n;
-    }
-
-    mean = Vmult_scalar(sum, 1.0 / n);
-
-    return mean;
-}
+  Return the slope as an unnormalized vector.  (I don't know if that was
+  intended by the designer, since it isn't sensible unless it's a
+  computational efficiency thing; it's just how I found the code).
 
-
-
-static vector_type
-findHalfTangentEnd(curve *      const curveP,
-                   unsigned int const tangentSurround) {
-/*----------------------------------------------------------------------------
-  Find the slope in the vicinity of the end of the curve
-  *curveP.
-
-  This is analogous to findHalfTangentBeg(), but at the other end of the
-  curve.
+  It is possible for the mean described above to be the zero vector, because
+  the mean of a vector pointing left and one pointing right is the zero
+  vector.  In that case, we use fewer "tangentSurround" points.
 -----------------------------------------------------------------------------*/
-    float_coord const tangentPoint =
-        CURVE_POINT(curveP, CURVE_LENGTH(curveP) - 1);
-    vector_type const zeroZero = { 0.0, 0.0 };
-    unsigned int const surround =
-        MIN(CURVE_LENGTH(curveP) / 2, tangentSurround);
-
-    unsigned int p;
-    vector_type sum;
-    vector_type mean;
-    unsigned int n;
-
-    for (p = 0, n = 0, sum = zeroZero; p < surround; ++p) {
-        unsigned int const thisIndex = CURVE_LENGTH(curveP) - 1 - p;
-        float_coord  const thisPoint = CURVE_POINT(curveP, thisIndex);
+    Point  const tangentPoint =
+        CURVE_POINT(curveP,
+                    toWhichEnd == LINEEND_INIT ? 0 : CURVE_LENGTH(curveP) - 1);
+    Vector  const zeroZero = { 0.0, 0.0 };
+
+    unsigned int surroundCt;
+    bool         gotNonzero;
+    Vector  mean;
+
+    for (surroundCt = MIN(CURVE_LENGTH(curveP) / 2, tangentSurround),
+             gotNonzero = false;
+         !gotNonzero;
+         --surroundCt) {
+
+        unsigned int i;
+        Vector sum;
+        unsigned int n;
+
+        for (i = 0, n = 0, sum = zeroZero; i < surroundCt; ++i) {
+            unsigned int const thisIndex =
+                toWhichEnd == LINEEND_INIT ?
+                    i + 1 :  CURVE_LENGTH(curveP) - 1 - i;
+            Point const thisPoint = CURVE_POINT(curveP, thisIndex);
+
+            if (!point_equal(thisPoint, tangentPoint)) {
+                /* Perhaps we should weight the tangent from `thisPoint' by
+                   some factor dependent on the distance from the tangent
+                   point.
+                */
+                sum = vector_sum(sum, vector_pointDirection(thisPoint,
+                                                            tangentPoint));
+                ++n;
+            }
+        }
+        mean = n > 0 ? vector_scaled(sum, 1.0 / n) : vector_horizontal();
 
-        sum = Vadd(sum, Pdirection(tangentPoint, thisPoint));
-        ++n;
+        if (vector_equal(mean, vector_zero())) {
+            /* We have points on multiple sides of the endpoint whose vectors
+               happen to add up to zero, which is not usable.
+            */
+            assert(surroundCt > 0);
+        } else
+            gotNonzero = true;
     }
 
-    mean = Vmult_scalar(sum, 1.0 / n);
-
     return mean;
 }
 
 
 
-static vector_type
-findHalfTangent(bool         const toStartPoint,
-                curve *      const curveP,
-                unsigned int const tangentSurround) {
-
-    if (toStartPoint)
-        return findHalfTangentBeg(curveP, tangentSurround);
-    else
-        return findHalfTangentEnd(curveP, tangentSurround);
-}
-
-
-
 static void
-findTangent(curve *       const curveP,
-            bool          const toStartPoint,
-            curve *       const adjacentCurveP,
-            unsigned int  const tangentSurroundArg,
-            vector_type * const tangentP) {
+findTangent(Curve *       const curveP,
+            LineEnd       const toWhichEnd,
+            Curve *       const adjacentCurveP,
+            unsigned int  const tangentSurround,
+            Vector *      const tangentP) {
 /*----------------------------------------------------------------------------
   Find an approximation to the slope of *curveP (i.e. slope of tangent
-  line) at an endpoint (the first point if 'toStartPoint' is true,
-  else the last).
-
-  If 'adjacentCurveP' is non-null, consider points on the adjacent
-  curve to *curveP.  The adjacent curve is *adjacentCurveP.  Adjacent
-  means the previous curve in the outline chain for the slope at the
-  start point ('toStartPoint' == true), the next curve otherwise.
-  If *curveP is cyclic, then it is its own adjacent curve.
+  line) at an endpoint (per 'toWhichEnd').
+
+  This approximation is the mean of the slopes between the end of the curve
+  and the 'tangentSurround' points leading up to it (but not more than one
+  point beyond the midpoint of the curve).  Note that the curve may loop.
+  Since there is no slope between two identical points, we ignore points that
+  are identical to the endpoint.  They count toward the limit; they just
+  aren't included in the result.  If none of the points to be considered are
+  distinct from the endpoint, we arbitrarily consider the curve to be
+  horizontal there.
+
+  If 'adjacentCurveP' is non-null, average this slope with the slope of the
+  other end of curve *adjacentCurveP, which we assume is adjacent.  Adjacent
+  means the previous curve in the outline chain for the slope at the start
+  point ('toWhichEnd' == LINEEND_BEG), the next curve otherwise.  If *curveP
+  is cyclic, then it is its own adjacent curve.
 
   It is important to compute an accurate approximation, because the
   control points that we eventually decide upon to fit the curve will
   be placed on the half-lines defined by the slopes and endpoints, and
   we never recompute the tangent after this.
 -----------------------------------------------------------------------------*/
-    vector_type slope;
-    unsigned int tangentSurround;
+    Vector const slopeThisCurve =
+        findHalfTangent(toWhichEnd, curveP, tangentSurround);
 
     LOG2("  tangent to %s of curve %lx: ",
-         toStartPoint ? "start" : "end", (unsigned long)curveP);
+         toWhichEnd == LINEEND_INIT ? "start" : "end", (unsigned long)curveP);
 
-    tangentSurround = tangentSurroundArg;  /* initial value */
-    do {
-        slope = findHalfTangent(toStartPoint, curveP, tangentSurround);
+    LOG3("(this curve half tangent (%.3f,%.3f,%.3f)) ",
+         slopeThisCurve.dx, slopeThisCurve.dy, slopeThisCurve.dz);
 
-        if (adjacentCurveP) {
-            vector_type const slopeAdj =
-                findHalfTangent(!toStartPoint, adjacentCurveP,
-                                tangentSurround);
+    if (adjacentCurveP) {
+        Vector const slopeAdjCurve =
+            findHalfTangent(otherEnd(toWhichEnd),
+                            adjacentCurveP,
+                            tangentSurround);
 
-            LOG3("(adjacent curve half tangent (%.3f,%.3f,%.3f)) ",
-                 slopeAdj.dx, slopeAdj.dy, slopeAdj.dz);
-            slope = Vmult_scalar(Vadd(slope, slopeAdj), 0.5);
-        }
-        --tangentSurround;
-    } while (slope.dx == 0.0 && slope.dy == 0.0);
-
-    *tangentP = slope;
+        LOG3("(adjacent curve half tangent (%.3f,%.3f,%.3f)) ",
+             slopeAdjCurve.dx, slopeAdjCurve.dy, slopeAdjCurve.dz);
+        *tangentP = vector_scaled(vector_sum(slopeThisCurve, slopeAdjCurve),
+                                  0.5);
+    } else
+        *tangentP = slopeThisCurve;
 
-    LOG3("(%.3f,%.3f,%.3f).\n",
-         tangentP->dx, tangentP->dy, tangentP->dz);
+    LOG3("(%.3f,%.3f,%.3f).\n", tangentP->dx, tangentP->dy, tangentP->dz);
 }
 
 
 
 static void
-findError(curve *             const curveP,
+findError(Curve *             const curveP,
           spline_type         const spline,
           float *             const errorP,
           unsigned int *      const worstPointP,
@@ -1523,10 +1583,10 @@ findError(curve *             const curveP,
     worstPoint = 0;
 
     for (thisPoint = 0; thisPoint < CURVE_LENGTH(curveP); ++thisPoint) {
-        float_coord const curvePoint = CURVE_POINT(curveP, thisPoint);
-        float const t = CURVE_T(curveP, thisPoint);
-        float_coord const splinePoint = evaluate_spline(spline, t);
-        float const thisError = distance(curvePoint, splinePoint);
+        Point const curvePoint  = CURVE_POINT(curveP, thisPoint);
+        float const t           = CURVE_DIST(curveP, thisPoint);
+        Point const splinePoint = evaluate_spline(spline, t);
+        float const thisError   = point_distance(curvePoint, splinePoint);
         if (thisError >= worstError) {
             worstPoint = thisPoint;
             worstError = thisError;
@@ -1554,56 +1614,12 @@ findError(curve *             const curveP,
 
 
 static void
-setInitialParameterValues(curve * const curveP) {
-/*----------------------------------------------------------------------------
-   Fill in the 't' values in *curveP.
-
-   The t value for point P on a curve is the distance P is along the
-   curve from the initial point, normalized so the entire curve is
-   length 1.0 (i.e. t of the initial point is 0.0; t of the final
-   point is 1.0).
-
-   There are a lot of curves that pass through the points indicated by
-   *curveP, but for practical computation of t, we just take the
-   piecewise linear locus that runs through all of them.  That means
-   we can just step through *curveP, adding up the distance from one
-   point to the next to get the t value for each point.
-
-   This is the "chord-length parameterization" method, which is
-   described in Plass & Stone.
------------------------------------------------------------------------------*/
-    unsigned int p;
-
-    LOG("\nAssigning initial t values:\n  ");
-
-    CURVE_T(curveP, 0) = 0.0;
-
-    for (p = 1; p < CURVE_LENGTH(curveP); ++p) {
-        float_coord const point      = CURVE_POINT(curveP, p);
-        float_coord const previous_p = CURVE_POINT(curveP, p - 1);
-        float const d = distance(point, previous_p);
-        CURVE_T(curveP, p) = CURVE_T(curveP, p - 1) + d;
-    }
-
-    assert(LAST_CURVE_T(curveP) != 0.0);
-
-    /* Normalize to a curve length of 1.0 */
-
-    for (p = 1; p < CURVE_LENGTH(curveP); ++p)
-        CURVE_T(curveP, p) = CURVE_T(curveP, p) / LAST_CURVE_T(curveP);
-
-    log_entire_curve(curveP);
-}
-
-
-
-static void
-subdivideCurve(curve *                   const curveP,
+subdivideCurve(Curve *                   const curveP,
                unsigned int              const subdivisionIndex,
                const fitting_opts_type * const fittingOptsP,
-               curve **                  const leftCurvePP,
-               curve **                  const rghtCurvePP,
-               vector_type *             const joinSlopeP) {
+               Curve **                  const leftCurvePP,
+               Curve **                  const rghtCurvePP,
+               Vector *                  const joinSlopeP) {
 /*----------------------------------------------------------------------------
   Split curve *curveP into two, at 'subdivisionIndex'.  (Actually,
   leave *curveP alone, but return as *leftCurvePP and *rghtCurvePP
@@ -1616,11 +1632,11 @@ subdivideCurve(curve *                   const curveP,
   To be precise, the point with sequence number 'subdivisionIndex'
   becomes the first pixel of the right-hand curve.
 -----------------------------------------------------------------------------*/
-    curve * leftCurveP;
-    curve * rghtCurveP;
+    Curve * leftCurveP;
+    Curve * rghtCurveP;
 
-    leftCurveP = new_curve();
-    rghtCurveP = new_curve();
+    leftCurveP = curve_new();
+    rghtCurveP = curve_new();
 
     LOG4("  Subdividing curve %lx into %lx and %lx at point #%u\n",
          (unsigned long)curveP,
@@ -1634,13 +1650,13 @@ subdivideCurve(curve *                   const curveP,
     CURVE_LENGTH(leftCurveP) = subdivisionIndex + 1;
     CURVE_LENGTH(rghtCurveP) = CURVE_LENGTH(curveP) - subdivisionIndex;
 
-    MALLOCARRAY_NOFAIL(leftCurveP->point_list, CURVE_LENGTH(leftCurveP));
-    memcpy(leftCurveP->point_list, &curveP->point_list[0],
-           CURVE_LENGTH(leftCurveP) * sizeof(curveP->point_list[0]));
+    MALLOCARRAY_NOFAIL(leftCurveP->pointList, CURVE_LENGTH(leftCurveP));
+    memcpy(leftCurveP->pointList, &curveP->pointList[0],
+           CURVE_LENGTH(leftCurveP) * sizeof(curveP->pointList[0]));
 
-    MALLOCARRAY_NOFAIL(rghtCurveP->point_list, CURVE_LENGTH(rghtCurveP));
-    memcpy(rghtCurveP->point_list, &curveP->point_list[subdivisionIndex],
-           CURVE_LENGTH(rghtCurveP) * sizeof(curveP->point_list[0]));
+    MALLOCARRAY_NOFAIL(rghtCurveP->pointList, CURVE_LENGTH(rghtCurveP));
+    memcpy(rghtCurveP->pointList, &curveP->pointList[subdivisionIndex],
+           CURVE_LENGTH(rghtCurveP) * sizeof(curveP->pointList[0]));
 
     /* We have to set up the two curves before finding the slope at
        the subdivision point.  The slope at that point must be the
@@ -1649,7 +1665,7 @@ subdivideCurve(curve *                   const curveP,
        point to compute the slope, hence we use adjacentCurveP.
     */
     findTangent(leftCurveP,
-                /* toStartPoint: */   false,
+                LINEEND_TERM,
                 /* adjacentCurveP: */ rghtCurveP,
                 fittingOptsP->tangent_surround, joinSlopeP);
 
@@ -1691,7 +1707,7 @@ leftRightConcat(const spline_list_type *  const leftSplineListP,
 
 
 static unsigned int
-divisionPoint(curve *      const curveP,
+divisionPoint(Curve *      const curveP,
               unsigned int const worstFitPoint) {
 /*----------------------------------------------------------------------------
    Return the sequence number of the point at which we should divide
@@ -1715,9 +1731,9 @@ divisionPoint(curve *      const curveP,
 
 
 static spline_list_type *
-divideAndFit(curve *                   const curveP,
-             vector_type               const begSlope,
-             vector_type               const endSlope,
+divideAndFit(Curve *                   const curveP,
+             Vector               const begSlope,
+             Vector               const endSlope,
              unsigned int              const subdivisionIndex,
              const fitting_opts_type * const fittingOptsP,
              at_exception_type *       const exceptionP) {
@@ -1733,11 +1749,11 @@ divideAndFit(curve *                   const curveP,
   Assume 'subdivisionIndex' leaves at least two pixels on each side.
 -----------------------------------------------------------------------------*/
     spline_list_type * retval;
-    curve * leftCurveP;
+    Curve * leftCurveP;
         /* The beginning (lower indexes) subcurve */
-    curve * rghtCurveP;
+    Curve * rghtCurveP;
         /* The other subcurve */
-    vector_type joinSlope;
+    Vector joinSlope;
         /* The slope of the end of the left subcurve and start of the right
            subcurve.
         */
@@ -1775,8 +1791,8 @@ divideAndFit(curve *                   const curveP,
         }
     }
 
-    free_curve(leftCurveP);
-    free_curve(rghtCurveP);
+    curve_free(leftCurveP);
+    curve_free(rghtCurveP);
 
     return retval;
 }
@@ -1784,9 +1800,9 @@ divideAndFit(curve *                   const curveP,
 
 
 static spline_list_type *
-fitWithLeastSquares(curve *                   const curveP,
-                    vector_type               const begSlope,
-                    vector_type               const endSlope,
+fitWithLeastSquares(Curve *                   const curveP,
+                    Vector                    const begSlope,
+                    Vector                    const endSlope,
                     const fitting_opts_type * const fittingOptsP,
                     at_exception_type *       const exceptionP) {
 /*----------------------------------------------------------------------------
@@ -1799,17 +1815,17 @@ fitWithLeastSquares(curve *                   const curveP,
 
     LOG("\nFitting with least squares:\n");
 
-    /* Phoenix reduces the number of points with a "linear spline
-       technique."  But for fitting letterforms, that is
-       inappropriate.  We want all the points we can get.
+    /* Phoenix reduces the number of points with a "linear spline technique."
+       But for fitting letterforms, that is inappropriate.  We want all the
+       points we can get.
     */
 
-    setInitialParameterValues(curveP);
+    curve_setDistance(curveP);
 
     if (CURVE_CYCLIC(curveP) && CURVE_LENGTH(curveP) < 4) {
         unsigned i;
         for (i = 0; i < CURVE_LENGTH(curveP); ++i) {
-            float_coord const point = CURVE_POINT(curveP, i);
+            Point const point = CURVE_POINT(curveP, i);
             fprintf(stderr, "point %u = (%f, %f)\n", i, point.x, point.y);
         }
     }
@@ -1831,7 +1847,7 @@ fitWithLeastSquares(curve *                   const curveP,
                see if the "curve" that was fit should really just be a
                straight line.
             */
-            if (spline_linear_enough(&spline, curveP, fittingOptsP)) {
+            if (splineLinearEnough(&spline, curveP, fittingOptsP)) {
                 SPLINE_DEGREE(spline) = LINEARTYPE;
                 LOG("Changed to line.\n");
             }
@@ -1859,9 +1875,9 @@ fitWithLeastSquares(curve *                   const curveP,
 
 
 static spline_list_type *
-fitCurve(curve *                   const curveP,
-         vector_type               const begSlope,
-         vector_type               const endSlope,
+fitCurve(Curve *                   const curveP,
+         Vector               const begSlope,
+         Vector               const endSlope,
          const fitting_opts_type * const fittingOptsP,
          at_exception_type *       const exceptionP) {
 /*----------------------------------------------------------------------------
@@ -1889,7 +1905,7 @@ fitCurve(curve *                   const curveP,
 
 
 static void
-fitCurves(curve_list_type           const curveList,
+fitCurves(CurveList                 const curveList,
           pixel                     const color,
           const fitting_opts_type * const fittingOptsP,
           spline_list_type *        const splinesP,
@@ -1908,19 +1924,19 @@ fitCurves(curve_list_type           const curveList,
          curveSeq < curveList.length && !at_exception_got_fatal(exceptionP);
          ++curveSeq) {
 
-        curve * const curveP = CURVE_LIST_ELT(curveList, curveSeq);
+        Curve * const curveP = CURVE_LIST_ELT(curveList, curveSeq);
 
-        vector_type begSlope, endSlope;
+        Vector begSlope, endSlope;
         spline_list_type * curveSplinesP;
 
         LOG2("\nFitting curve #%u (%lx):\n", curveSeq, (unsigned long)curveP);
 
         LOG("Finding tangents:\n");
-        findTangent(curveP, /* toStart */ true,
+        findTangent(curveP, LINEEND_INIT,
                     CURVE_CYCLIC(curveP) ? curveP : NULL,
                     fittingOptsP->tangent_surround,
                     &begSlope);
-        findTangent(curveP, /* toStart */ false,
+        findTangent(curveP, LINEEND_TERM,
                     CURVE_CYCLIC(curveP) ? curveP : NULL,
                     fittingOptsP->tangent_surround, &endSlope);
 
@@ -1937,7 +1953,7 @@ fitCurves(curve_list_type           const curveList,
                    back to curves, because they are in a list with other
                    curves.
                 */
-                change_bad_lines(curveSplinesP, fittingOptsP);
+                changeBadLines(curveSplinesP, fittingOptsP);
 
                 concat_spline_lists(&curveListSplines, *curveSplinesP);
                 free_spline_list(*curveSplinesP);
@@ -1971,7 +1987,7 @@ logFittedSplines(spline_list_type const curve_list_splines) {
 
 
 static void
-fitCurveList(curve_list_type     const curveList,
+fitCurveList(CurveList           const curveList,
              fitting_opts_type * const fittingOptsP,
              distance_map_type * const dist,
              pixel               const color,
@@ -1982,7 +1998,7 @@ fitCurveList(curve_list_type     const curveList,
   it.  CURVE_LIST represents a single closed paths, e.g., either the
   inside or outside outline of an `o'.
 -----------------------------------------------------------------------------*/
-    curve_type curve;
+    Curve * curveP;
     spline_list_type curveListSplines;
 
     removeKnees(curveList);
@@ -2007,9 +2023,9 @@ fitCurveList(curve_list_type     const curveList,
        and three points isn't enough to determine a spline.  Therefore,
        the fitting will fail.
     */
-    curve = CURVE_LIST_ELT(curveList, 0);
-    if (CURVE_CYCLIC(curve))
-        append_point(curve, CURVE_POINT(curve, 0));
+    curveP = CURVE_LIST_ELT(curveList, 0);
+    if (CURVE_CYCLIC(curveP))
+        curve_appendPoint(curveP, CURVE_POINT(curveP, 0));
 
     /* Finally, fit each curve in the list to a list of splines.  */
 
@@ -2024,7 +2040,7 @@ fitCurveList(curve_list_type     const curveList,
 
 
 static void
-fitCurvesToSplines(curve_list_array_type    const curveArray,
+fitCurvesToSplines(CurveListArray           const curveArray,
                    fitting_opts_type *      const fittingOptsP,
                    distance_map_type *      const dist,
                    unsigned short           const width,
@@ -2055,7 +2071,7 @@ fitCurvesToSplines(curve_list_array_type    const curveArray,
              !at_exception_got_fatal(exception) && !cancelled;
          ++splineListSeq) {
 
-        curve_list_type const curveList =
+        CurveList const curveList =
             CURVE_LIST_ARRAY_ELT(curveArray, splineListSeq);
 
         spline_list_type curveSplineList;
@@ -2096,14 +2112,14 @@ fit_outlines_to_splines(pixel_outline_list_type  const pixelOutlineList,
    Transform a list of pixels in the outlines of the original character to
    a list of spline lists fitted to those pixels.
 -----------------------------------------------------------------------------*/
-    curve_list_array_type const curveListArray =
+    CurveListArray const curveListArray =
         split_at_corners(pixelOutlineList, fittingOptsP, exception);
 
     fitCurvesToSplines(curveListArray, fittingOptsP, dist, width, height,
                        exception, notifyProgress, progressData,
                        testCancel, testcancelData, splineListArrayP);
 
-    free_curve_list_array(&curveListArray, notifyProgress, progressData);
+    curve_freeListArray(&curveListArray, notifyProgress, progressData);
 
     flush_log_output();
 }
diff --git a/converter/other/pamtosvg/fit.h b/converter/other/pamtosvg/fit.h
index 529da5c7..8c234f33 100644
--- a/converter/other/pamtosvg/fit.h
+++ b/converter/other/pamtosvg/fit.h
@@ -10,7 +10,7 @@
 #include "exception.h"
 
 /* See fit.c for descriptions of these variables, all of which can be
-   set using options. 
+   set using options.
 */
 typedef at_fitting_opts_type fitting_opts_type;
 
@@ -21,7 +21,7 @@ fit_outlines_to_splines(pixel_outline_list_type  const pixelOutlineList,
                         unsigned short           const width,
                         unsigned short           const height,
                         at_exception_type *      const exception,
-                        at_progress_func               notifyProgress, 
+                        at_progress_func               notifyProgress,
                         void *                   const progressData,
                         at_testcancel_func             testCancel,
                         void *                   const testcancelData,
diff --git a/converter/other/pamtosvg/image-header.h b/converter/other/pamtosvg/image-header.h
index adcf4771..ef387572 100644
--- a/converter/other/pamtosvg/image-header.h
+++ b/converter/other/pamtosvg/image-header.h
@@ -9,10 +9,10 @@
    the particular formats.  */
 typedef struct
 {
-  unsigned short hres, vres;	/* In pixels per inch.  */
-  unsigned short width, height;	/* In bits.  */
-  unsigned short depth;		/* Perhaps the depth?  */
-  unsigned format;		/* (for pbm) Whether packed or not.  */
+  unsigned short hres, vres;    /* In pixels per inch.  */
+  unsigned short width, height; /* In bits.  */
+  unsigned short depth;         /* Perhaps the depth?  */
+  unsigned format;              /* (for pbm) Whether packed or not.  */
 } image_header_type;
 
 #endif /* not IMAGE_HEADER_H */
diff --git a/converter/other/pamtosvg/image-proc.c b/converter/other/pamtosvg/image-proc.c
index d025ee1e..7462219c 100644
--- a/converter/other/pamtosvg/image-proc.c
+++ b/converter/other/pamtosvg/image-proc.c
@@ -53,7 +53,7 @@ new_distance_map(bitmap_type bitmap, unsigned char target_value, bool padded, at
         if (dist.d[y] == NULL)
             pm_error("Unable to get memory for distance map");
         memset(dist.d[y], 0, w * sizeof(float));
-        
+
         MALLOCARRAY(dist.weight[y], w);
         if (dist.weight[y] == NULL)
             pm_error("Unable to get memory for distance map");
@@ -72,7 +72,7 @@ new_distance_map(bitmap_type bitmap, unsigned char target_value, bool padded, at
           dist.weight[y][x] = 1.0F - fgray;
 /*        dist.weight[y][x] = 1.0F - (fgray * fgray);*/
 /*        dist.weight[y][x] = (fgray < 0.5F ? 1.0F - fgray : -2.0F * fgray * (fgray - 1.0F));*/
-	    }
+            }
       }
     }
     else
@@ -158,15 +158,15 @@ new_distance_map(bitmap_type bitmap, unsigned char target_value, bool padded, at
 
             /* lower-right neighbor */
             d = dist.d[y + 1][x + 1] + (float) M_SQRT2 * dist.weight[y][x];
-	        if (d < min) min = dist.d[y][x] = d;
+                if (d < min) min = dist.d[y][x] = d;
 
             /* lower neighbor */
             d = dist.d[y + 1][x] + dist.weight[y][x];
-	        if (d < min) min = dist.d[y][x] = d;
+                if (d < min) min = dist.d[y][x] = d;
 
             /* right neighbor */
             d = dist.d[y][x + 1] + dist.weight[y][x];
-	        if (d < min) min = dist.d[y][x] = d;
+                if (d < min) min = dist.d[y][x] = d;
 
             /* lower-left neighbor (except at the first column) */
             if (x - 1 >= 0)
@@ -180,6 +180,7 @@ new_distance_map(bitmap_type bitmap, unsigned char target_value, bool padded, at
 }
 
 
+
 /* Free the dynamically-allocated storage associated with a distance map. */
 
 void
@@ -193,19 +194,20 @@ free_distance_map(distance_map_type *dist)
 
     if (dist->d != NULL)
     {
-	for (y = 0; y < h; y++)
-	    free(dist->d[y]);
+        for (y = 0; y < h; y++)
+            free(dist->d[y]);
         free(dist->d);
     }
     if (dist->weight != NULL)
     {
-	for (y = 0; y < h; y++)
-	    free(dist->weight[y]);
+        for (y = 0; y < h; y++)
+            free(dist->weight[y]);
         free(dist->weight);
     }
 }
 
 
+
 #if 0
 void
 medial_axis(bitmap_type *bitmap, distance_map_type *dist,
@@ -233,7 +235,7 @@ medial_axis(bitmap_type *bitmap, distance_map_type *dist,
 
     if (bgSpec)
         bg = bg_color;
-    else 
+    else
         PPM_ASSIGN(bg, 255, 255, 255);
 
     f = d[0][0] + 0.5;
@@ -246,44 +248,44 @@ medial_axis(bitmap_type *bitmap, distance_map_type *dist,
 
     for (x = 1; x < w - 1; x++)
     {
-	    f = d[0][x] + 0.5;
-	    test = (f < d[0][x-1]) + (f < d[0][x+1]) + (f < d[1][x-1])
-	        + (f < d[1][x]) + (f < d[1][x+1]);
-	    if (test > 1) b[x] = PPM_GETR(bg);
+            f = d[0][x] + 0.5;
+            test = (f < d[0][x-1]) + (f < d[0][x+1]) + (f < d[1][x-1])
+                + (f < d[1][x]) + (f < d[1][x+1]);
+            if (test > 1) b[x] = PPM_GETR(bg);
     }
     b += w;
 
     for (y = 1; y < h - 1; y++)
     {
-	    f = d[y][0] + 0.5;
-	    test = (f < d[y-1][0]) + (f < d[y-1][1]) + (f < d[y][1])
-	        + (f < d[y+1][0]) + (f < d[y+1][1]);
-	    if (test > 1) b[0] = PPM_GETR(bg);
-
-	    for (x = 1; x < w - 1; x++)
-		{
-	        f = d[y][x] + 0.5;
-	        test = (f < d[y-1][x-1]) + (f < d[y-1][x]) + (f < d[y-1][x+1])
-		    + (f < d[y][x-1]) + (f < d[y][x+1])
-		    + (f < d[y+1][x-1]) + (f < d[y+1][x]) + (f < d[y+1][x+1]);
-	        if (test > 1) b[x] = PPM_GETR(bg)
-		}
-
-	    f = d[y][w-1] + 0.5;
-	    test = (f < d[y-1][w-1]) + (f < d[y-1][w-2]) + (f < d[y][w-2])
-	        + (f < d[y+1][w-1]) + (f < d[y+1][w-2]);
-	    if (test > 1)
-	        b[w-1] = PPM_GETR(bg);
+            f = d[y][0] + 0.5;
+            test = (f < d[y-1][0]) + (f < d[y-1][1]) + (f < d[y][1])
+                + (f < d[y+1][0]) + (f < d[y+1][1]);
+            if (test > 1) b[0] = PPM_GETR(bg);
+
+            for (x = 1; x < w - 1; x++)
+                {
+                f = d[y][x] + 0.5;
+                test = (f < d[y-1][x-1]) + (f < d[y-1][x]) + (f < d[y-1][x+1])
+                    + (f < d[y][x-1]) + (f < d[y][x+1])
+                    + (f < d[y+1][x-1]) + (f < d[y+1][x]) + (f < d[y+1][x+1]);
+                if (test > 1) b[x] = PPM_GETR(bg)
+                }
+
+            f = d[y][w-1] + 0.5;
+            test = (f < d[y-1][w-1]) + (f < d[y-1][w-2]) + (f < d[y][w-2])
+                + (f < d[y+1][w-1]) + (f < d[y+1][w-2]);
+            if (test > 1)
+                b[w-1] = PPM_GETR(bg);
 
         b += w;
     }
 
     for (x = 1; x < w - 1; x++)
     {
-	    f = d[h-1][x] + 0.5;
-	    test = (f < d[h-1][x-1]) + (f < d[h-1][x+1])
-	        + (f < d[h-2][x-1]) + (f < d[h-2][x]) + (f < d[h-2][x+1]);
-	    if (test > 1) b[x] = PPM_GETR(bg);
+            f = d[h-1][x] + 0.5;
+            test = (f < d[h-1][x-1]) + (f < d[h-1][x+1])
+                + (f < d[h-2][x-1]) + (f < d[h-2][x]) + (f < d[h-2][x+1]);
+            if (test > 1) b[x] = PPM_GETR(bg);
     }
 
     f = d[h-1][0] + 0.5;
@@ -314,27 +316,28 @@ binarize(bitmap_type *bitmap)
 
     if (spp == 1)
     {
-	    for (i = 0; i < npixels; i++)
-	        b[i] = (b[i] > GRAY_THRESHOLD ? WHITE : BLACK);
+            for (i = 0; i < npixels; i++)
+                b[i] = (b[i] > GRAY_THRESHOLD ? WHITE : BLACK);
     }
     else if (spp == 3)
     {
-	    unsigned char *rgb = b;
-	    for (i = 0; i < npixels; i++, rgb += 3)
-		{
-	        b[i] = (LUMINANCE(rgb[0], rgb[1], rgb[2]) > GRAY_THRESHOLD
-		        ? WHITE : BLACK);
-		}
-	    REALLOCARRAY_NOFAIL(bitmap->bitmap, npixels);
-	    bitmap->np = 1;
+            unsigned char *rgb = b;
+            for (i = 0; i < npixels; i++, rgb += 3)
+                {
+                b[i] = (LUMINANCE(rgb[0], rgb[1], rgb[2]) > GRAY_THRESHOLD
+                        ? WHITE : BLACK);
+                }
+            REALLOCARRAY_NOFAIL(bitmap->bitmap, npixels);
+            bitmap->np = 1;
     }
     else
     {
-	    WARNING1("binarize: don't know how to interpret %u-plane images", spp);
+            WARNING1("binarize: don't know how to interpret %u-plane images", spp);
     }
 }
 
 
+
 #if 0
 /* Thin a binary image, replacing the original image with the thinned one. */
 
@@ -351,9 +354,9 @@ ip_thin(bitmap_type input_b)
 
     if (BITMAP_PLANES(input_b) != 1)
     {
-	    FATAL1("thin: single-plane image required; "
-	        "%u-plane images cannot be thinned", BITMAP_PLANES(input_b));
-	    return b;
+            FATAL1("thin: single-plane image required; "
+                "%u-plane images cannot be thinned", BITMAP_PLANES(input_b));
+            return b;
     }
 
     /* Process and return a copy of the input image. */
@@ -364,149 +367,151 @@ ip_thin(bitmap_type input_b)
 
     /* Set background pixels to zero, foreground pixels to one. */
     for (i = 0; i < num_bytes; i++)
-	b.bitmap[i] = (b.bitmap[i] == BLACK ? 1 : 0);
+        b.bitmap[i] = (b.bitmap[i] == BLACK ? 1 : 0);
 
     again = true;
     while (again)
     {
-	again = false;
-
-	for (y = 1; y < h - 1; y++)
-	{
-	    for (x = 1; x < w - 1; x++)
-	    {
-		    /* During processing, pixels are used to store edge
-		       type codes, so we can't just test for WHITE or BLACK. */
-		    if (*BITMAP_PIXEL(b, y, x) == 0) continue;
-
-		    k = (!get_edge(b, y, x, &t)
-		        || (get_edge(b, y, x+1, &t) && *BITMAP_PIXEL(b, y-1, x)
-			    && *BITMAP_PIXEL(b, y+1, x))
-		        || (get_edge(b, y+1, x, &t) && *BITMAP_PIXEL(b, y, x-1)
-			    && *BITMAP_PIXEL(b, y, x+1))
-		        || (get_edge(b, y, x+1, &t) && get_edge(b, y+1, x+1, &t)
-			    && get_edge(b, y+1, x, &t)));
-		    if (k) continue;
-
-		    get_edge(b, y, x, &t);
-		    if (t.t01) *BITMAP_PIXEL(b, y, x) |= 4;
-		    *BITMAP_PIXEL(b, y, x) |= 2;
-		    again = true;
-	    }
-	}
-
-	for (y = 0; y < h; y++)
-	    for (x = 0; x < w; x++)
-		    if (*BITMAP_PIXEL(b, y, x) & 02) *BITMAP_PIXEL(b, y, x) = 0;
-
-	for (y = 1; y < h - 1; y++)
-	{
-	    for (x = 1; x < w - 1; x++)
-	    {
-		    if (*BITMAP_PIXEL(b, y, x) == 0) continue;
-
-		    k = (!get_edge(b, y, x, &t)
-		        || ((*BITMAP_PIXEL(b, y, x) & 04) == 0)
-		        || (get_edge(b, y+1, x, &t) && (*BITMAP_PIXEL(b, y, x-1))
-			    && *BITMAP_PIXEL(b, y, x+1))
-		        || (get_edge(b, y, x+1, &t) && *BITMAP_PIXEL(b, y-1, x)
-			    && *BITMAP_PIXEL(b, y+1, x))
-		        || (get_edge(b, y+1, x, &t) && get_edge(b, y, x+1, &t)
-			    && get_edge(b, y+1, x+1, &t)));
-		    if (k) continue;
-
-		    *BITMAP_PIXEL(b, y, x) |= 02;
-		    again = true;
-	    }
-	}
-
-	for (y = 0; y < h; y++)
-	{
-	    for (x = 0; x < w; x++)
-	    {
-		    if (*BITMAP_PIXEL(b, y, x) & 02) *BITMAP_PIXEL(b, y, x) = 0;
-		    else if (*BITMAP_PIXEL(b, y, x) > 0) *BITMAP_PIXEL(b, y, x) = 1;
-	    }
-	}
+        again = false;
+
+        for (y = 1; y < h - 1; y++)
+        {
+            for (x = 1; x < w - 1; x++)
+            {
+                    /* During processing, pixels are used to store edge
+                       type codes, so we can't just test for WHITE or BLACK. */
+                    if (*BITMAP_PIXEL(b, y, x) == 0) continue;
+
+                    k = (!get_edge(b, y, x, &t)
+                        || (get_edge(b, y, x+1, &t) && *BITMAP_PIXEL(b, y-1, x)
+                            && *BITMAP_PIXEL(b, y+1, x))
+                        || (get_edge(b, y+1, x, &t) && *BITMAP_PIXEL(b, y, x-1)
+                            && *BITMAP_PIXEL(b, y, x+1))
+                        || (get_edge(b, y, x+1, &t) && get_edge(b, y+1, x+1, &t)
+                            && get_edge(b, y+1, x, &t)));
+                    if (k) continue;
+
+                    get_edge(b, y, x, &t);
+                    if (t.t01) *BITMAP_PIXEL(b, y, x) |= 4;
+                    *BITMAP_PIXEL(b, y, x) |= 2;
+                    again = true;
+            }
+        }
+
+        for (y = 0; y < h; y++)
+            for (x = 0; x < w; x++)
+                    if (*BITMAP_PIXEL(b, y, x) & 02) *BITMAP_PIXEL(b, y, x) = 0;
+
+        for (y = 1; y < h - 1; y++)
+        {
+            for (x = 1; x < w - 1; x++)
+            {
+                    if (*BITMAP_PIXEL(b, y, x) == 0) continue;
+
+                    k = (!get_edge(b, y, x, &t)
+                        || ((*BITMAP_PIXEL(b, y, x) & 04) == 0)
+                        || (get_edge(b, y+1, x, &t) && (*BITMAP_PIXEL(b, y, x-1))
+                            && *BITMAP_PIXEL(b, y, x+1))
+                        || (get_edge(b, y, x+1, &t) && *BITMAP_PIXEL(b, y-1, x)
+                            && *BITMAP_PIXEL(b, y+1, x))
+                        || (get_edge(b, y+1, x, &t) && get_edge(b, y, x+1, &t)
+                            && get_edge(b, y+1, x+1, &t)));
+                    if (k) continue;
+
+                    *BITMAP_PIXEL(b, y, x) |= 02;
+                    again = true;
+            }
+        }
+
+        for (y = 0; y < h; y++)
+        {
+            for (x = 0; x < w; x++)
+            {
+                    if (*BITMAP_PIXEL(b, y, x) & 02) *BITMAP_PIXEL(b, y, x) = 0;
+                    else if (*BITMAP_PIXEL(b, y, x) > 0) *BITMAP_PIXEL(b, y, x) = 1;
+            }
+        }
     }
 
     /* Staircase removal; northward bias. */
     for (y = 1; y < h - 1; y++)
     {
-	    for (x = 1; x < w - 1; x++)
-		{
-	        if (*BITMAP_PIXEL(b, y, x) == 0) continue;
-
-	        k = !(*BITMAP_PIXEL(b, y-1, x)
-		        && ((*BITMAP_PIXEL(b, y, x+1) && !*BITMAP_PIXEL(b, y-1, x+1)
-		        && !*BITMAP_PIXEL(b, y+1, x-1)
-		        && (!*BITMAP_PIXEL(b, y, x-1) || !*BITMAP_PIXEL(b, y+1, x)))
-		        || (*BITMAP_PIXEL(b, y, x-1) && !*BITMAP_PIXEL(b, y-1, x-1)
-		        && !*BITMAP_PIXEL(b, y+1, x+1) &&
-		        (!*BITMAP_PIXEL(b, y, x+1) || !*BITMAP_PIXEL(b, y+1, x)))));
-	        if (k) continue;
-
-	        *BITMAP_PIXEL(b, y, x) |= 02;
-		}
+            for (x = 1; x < w - 1; x++)
+                {
+                if (*BITMAP_PIXEL(b, y, x) == 0) continue;
+
+                k = !(*BITMAP_PIXEL(b, y-1, x)
+                        && ((*BITMAP_PIXEL(b, y, x+1) && !*BITMAP_PIXEL(b, y-1, x+1)
+                        && !*BITMAP_PIXEL(b, y+1, x-1)
+                        && (!*BITMAP_PIXEL(b, y, x-1) || !*BITMAP_PIXEL(b, y+1, x)))
+                        || (*BITMAP_PIXEL(b, y, x-1) && !*BITMAP_PIXEL(b, y-1, x-1)
+                        && !*BITMAP_PIXEL(b, y+1, x+1) &&
+                        (!*BITMAP_PIXEL(b, y, x+1) || !*BITMAP_PIXEL(b, y+1, x)))));
+                if (k) continue;
+
+                *BITMAP_PIXEL(b, y, x) |= 02;
+                }
     }
     for (y = 0; y < h; y++)
     {
-	    for (x = 0; x < w; x++)
-		{
-	        if (*BITMAP_PIXEL(b, y, x) & 02) *BITMAP_PIXEL(b, y, x) = 0;
-	        else if (*BITMAP_PIXEL(b, y, x) > 0) *BITMAP_PIXEL(b, y, x) = 1;
-		}
+            for (x = 0; x < w; x++)
+                {
+                if (*BITMAP_PIXEL(b, y, x) & 02) *BITMAP_PIXEL(b, y, x) = 0;
+                else if (*BITMAP_PIXEL(b, y, x) > 0) *BITMAP_PIXEL(b, y, x) = 1;
+                }
     }
 
     /* Southward bias */
     for (y = 1; y < h - 1; y++)
     {
-	    for (x = 1; x < w - 1; x++)
-		{
-	        if (*BITMAP_PIXEL(b, y, x) == 0) continue;
-
-	        k = !(*BITMAP_PIXEL(b, y+1, x)
-		    && ((*BITMAP_PIXEL(b, y, x+1) && !*BITMAP_PIXEL(b, y+1, x+1)
-		    && !*BITMAP_PIXEL(b, y-1, x-1) && (!*BITMAP_PIXEL(b, y, x-1)
-		    || !*BITMAP_PIXEL(b, y-1, x))) || (*BITMAP_PIXEL(b, y, x-1)
-		    && !*BITMAP_PIXEL(b, y+1, x-1) && !*BITMAP_PIXEL(b, y-1, x+1)
-		    && (!*BITMAP_PIXEL(b, y, x+1) || !*BITMAP_PIXEL(b, y-1, x)) )));
-	        if (k) continue;
-
-	        *BITMAP_PIXEL(b, y, x) |= 02;
-		}
+            for (x = 1; x < w - 1; x++)
+                {
+                if (*BITMAP_PIXEL(b, y, x) == 0) continue;
+
+                k = !(*BITMAP_PIXEL(b, y+1, x)
+                    && ((*BITMAP_PIXEL(b, y, x+1) && !*BITMAP_PIXEL(b, y+1, x+1)
+                    && !*BITMAP_PIXEL(b, y-1, x-1) && (!*BITMAP_PIXEL(b, y, x-1)
+                    || !*BITMAP_PIXEL(b, y-1, x))) || (*BITMAP_PIXEL(b, y, x-1)
+                    && !*BITMAP_PIXEL(b, y+1, x-1) && !*BITMAP_PIXEL(b, y-1, x+1)
+                    && (!*BITMAP_PIXEL(b, y, x+1) || !*BITMAP_PIXEL(b, y-1, x)) )));
+                if (k) continue;
+
+                *BITMAP_PIXEL(b, y, x) |= 02;
+                }
     }
     for (y = 0; y < h; y++)
     {
-	    for (x = 0; x < w; x++)
-		{
-	        if (*BITMAP_PIXEL(b, y, x) & 02) *BITMAP_PIXEL(b, y, x) = 0;
-	        else if (*BITMAP_PIXEL(b, y, x) > 0) *BITMAP_PIXEL(b, y, x) = 1;
-		}
+            for (x = 0; x < w; x++)
+                {
+                if (*BITMAP_PIXEL(b, y, x) & 02) *BITMAP_PIXEL(b, y, x) = 0;
+                else if (*BITMAP_PIXEL(b, y, x) > 0) *BITMAP_PIXEL(b, y, x) = 1;
+                }
     }
 
     /* Set background pixels to WHITE, foreground pixels to BLACK. */
     for (i = 0; i < num_bytes; i++)
-	b.bitmap[i] = (b.bitmap[i] == 0 ? WHITE : BLACK);
+        b.bitmap[i] = (b.bitmap[i] == 0 ? WHITE : BLACK);
     return b;
 }
 
 
+
 bool get_edge(bitmap_type b, int y, int x, struct etyp *t)
 {
     t->t00 = 0; t->t01 = 0; t->t01s = 0; t->t11 = 0;
     check(*BITMAP_PIXEL(b, y - 1, x - 1), *BITMAP_PIXEL(b, y - 1, x),
-	*BITMAP_PIXEL(b, y - 1, x + 1), t);
+        *BITMAP_PIXEL(b, y - 1, x + 1), t);
     check(*BITMAP_PIXEL(b, y - 1, x + 1), *BITMAP_PIXEL(b, y, x + 1),
-	*BITMAP_PIXEL(b, y + 1, x + 1), t);
+        *BITMAP_PIXEL(b, y + 1, x + 1), t);
     check(*BITMAP_PIXEL(b, y + 1, x + 1), *BITMAP_PIXEL(b, y + 1, x),
-	*BITMAP_PIXEL(b, y + 1, x - 1), t);
+        *BITMAP_PIXEL(b, y + 1, x - 1), t);
     check(*BITMAP_PIXEL(b, y + 1, x - 1), *BITMAP_PIXEL(b, y, x - 1),
-	*BITMAP_PIXEL(b, y - 1, x - 1), t);
+        *BITMAP_PIXEL(b, y - 1, x - 1), t);
     return *BITMAP_PIXEL(b, y, x) && t->t00 && t->t11 && !t->t01s;
 }
 
 
+
 void check(int v1, int v2, int v3, struct etyp *t)
 {
     if (!v2 && (!v1 || !v3)) t->t00 = 1;
diff --git a/converter/other/pamtosvg/image-proc.h b/converter/other/pamtosvg/image-proc.h
index a5b86ec1..0607d3dd 100644
--- a/converter/other/pamtosvg/image-proc.h
+++ b/converter/other/pamtosvg/image-proc.h
@@ -25,7 +25,7 @@ typedef struct
 /* Allocate and compute a new distance map. */
 extern distance_map_type new_distance_map(bitmap_type,
     unsigned char target_value, bool padded,
-					  at_exception_type * exp);
+                                          at_exception_type * exp);
 
 /* Free the dynamically-allocated storage associated with a distance map. */
 extern void free_distance_map(distance_map_type*);
diff --git a/converter/other/pamtosvg/logreport.c b/converter/other/pamtosvg/logreport.c
index 7d726584..63568b96 100644
--- a/converter/other/pamtosvg/logreport.c
+++ b/converter/other/pamtosvg/logreport.c
@@ -15,3 +15,5 @@ flush_log_output (void)
     fflush (log_file);
 }
 
+
+
diff --git a/converter/other/pamtosvg/logreport.h b/converter/other/pamtosvg/logreport.h
index 577da8df..071d42c3 100644
--- a/converter/other/pamtosvg/logreport.h
+++ b/converter/other/pamtosvg/logreport.h
@@ -11,17 +11,17 @@ extern FILE *at_log_file;
 
 extern void flush_log_output (void);
 
-#define LOG(s)								\
+#define LOG(s)                                                          \
   do { if (log_file) fputs (s, log_file); } while (0)
-#define LOG1(s, e)							\
+#define LOG1(s, e)                                                      \
   do { if (log_file) fprintf (log_file, s, e); } while (0)
-#define LOG2(s, e1, e2)							\
+#define LOG2(s, e1, e2)                                                 \
   do { if (log_file) fprintf (log_file, s, e1, e2); } while (0)
-#define LOG3(s, e1, e2, e3)						\
+#define LOG3(s, e1, e2, e3)                                             \
   do { if (log_file) fprintf (log_file, s, e1, e2, e3); } while (0)
-#define LOG4(s, e1, e2, e3, e4)						\
+#define LOG4(s, e1, e2, e3, e4)                                         \
   do { if (log_file) fprintf (log_file, s, e1, e2, e3, e4); } while (0)
-#define LOG5(s, e1, e2, e3, e4, e5)					\
+#define LOG5(s, e1, e2, e3, e4, e5)                                     \
   do { if (log_file) fprintf (log_file, s, e1, e2, e3, e4, e5); } while (0)
 
 #endif /* not LOGREPORT_H */
diff --git a/converter/other/pamtosvg/message.h b/converter/other/pamtosvg/message.h
index 0d0b9db5..e6822432 100644
--- a/converter/other/pamtosvg/message.h
+++ b/converter/other/pamtosvg/message.h
@@ -13,18 +13,18 @@
 #define START_FATAL() do { fputs ("fatal: ", stderr); LOG("fatal: ")
 #define END_FATAL() fputs (".\n", stderr); exit (1); } while (0)
 
-#define FATAL(s)							\
+#define FATAL(s)                                                        \
   START_FATAL (); fprintf (stderr, "%s", s); LOG (s); END_FATAL ()
-#define FATAL1(s, e1)							\
+#define FATAL1(s, e1)                                                   \
   START_FATAL (); fprintf (stderr, s, e1); LOG1 (s, e1); END_FATAL ()
 
 
 #define START_WARNING() do { fputs ("warning: ", stderr); LOG ("warning: ")
 #define END_WARNING() fputs (".\n", stderr); } while (0)
 
-#define WARNING(s)							\
+#define WARNING(s)                                                      \
   START_WARNING (); fprintf (stderr, "%s", s); LOG (s); END_WARNING ()
-#define WARNING1(s, e1)							\
+#define WARNING1(s, e1)                                                 \
   START_WARNING (); fprintf (stderr, s, e1); LOG1 (s, e1); END_WARNING ()
 
 #endif /* not MESSAGE_H */
diff --git a/converter/other/pamtosvg/output-svg.c b/converter/other/pamtosvg/output-svg.c
index 53a8d4fd..59733094 100644
--- a/converter/other/pamtosvg/output-svg.c
+++ b/converter/other/pamtosvg/output-svg.c
@@ -26,15 +26,15 @@ static void
 outSplineList(FILE *           const fileP,
               spline_list_type const splineList,
               unsigned int     const height) {
-              
+
     unsigned splineSeq;
-        
+
     for (splineSeq = 0;
          splineSeq < SPLINE_LIST_LENGTH(splineList);
          ++splineSeq) {
-        
+
         spline_type const spline = SPLINE_LIST_ELT(splineList, splineSeq);
-        
+
         if (SPLINE_DEGREE(spline) == LINEARTYPE) {
             fprintf(fileP, "L%g %g",
                     END_POINT(spline).x, height - END_POINT(spline).y);
@@ -55,13 +55,13 @@ out_splines(FILE *                 const fileP,
 
     unsigned listSeq;
     pixel lastColor;
-    
+
     PPM_ASSIGN(lastColor, 0, 0, 0);
-    
+
     for (listSeq = 0;
          listSeq < SPLINE_LIST_ARRAY_LENGTH(shape);
          ++listSeq) {
-        
+
         spline_list_type const splineList =
             SPLINE_LIST_ARRAY_ELT(shape, listSeq);
         spline_type const first = SPLINE_LIST_ELT(splineList, 0);
@@ -82,7 +82,7 @@ out_splines(FILE *                 const fileP,
                     (shape.centerline || splineList.open) ? "fill" : "stroke");
         }
         fprintf(fileP, "M%g %g",
-                START_POINT(first).x, height - START_POINT(first).y);
+                BEG_POINT(first).x, height - BEG_POINT(first).y);
 
         outSplineList(fileP, splineList, height);
 
@@ -109,10 +109,10 @@ output_svg_writer(FILE *                    const fileP,
                   int                       const llx,
                   int                       const lly,
                   int                       const urx,
-                  int                       const ury, 
+                  int                       const ury,
                   at_output_opts_type *     const opts,
                   at_spline_list_array_type const shape,
-                  at_msg_func                     msg_func, 
+                  at_msg_func                     msg_func,
                   void *                    const msg_data) {
 
     int const width  = urx - llx;
@@ -125,6 +125,9 @@ output_svg_writer(FILE *                    const fileP,
     out_splines(fileP, shape, height);
 
     fputs("</svg>\n", fileP);
-    
+
     return 0;
 }
+
+
+
diff --git a/converter/other/pamtosvg/output-svg.h b/converter/other/pamtosvg/output-svg.h
index 46fc8f8f..a02e8334 100644
--- a/converter/other/pamtosvg/output-svg.h
+++ b/converter/other/pamtosvg/output-svg.h
@@ -26,10 +26,10 @@ output_svg_writer(FILE *                    const file,
                   int                       const llx,
                   int                       const lly,
                   int                       const urx,
-                  int                       const ury, 
+                  int                       const ury,
                   at_output_opts_type *     const opts,
                   at_spline_list_array_type const shape,
-                  at_msg_func                     msg_func, 
+                  at_msg_func                     msg_func,
                   void *                    const msg_data);
 
 
diff --git a/converter/other/pamtosvg/pamtosvg.c b/converter/other/pamtosvg/pamtosvg.c
index adf76801..03b0a80f 100644
--- a/converter/other/pamtosvg/pamtosvg.c
+++ b/converter/other/pamtosvg/pamtosvg.c
@@ -47,12 +47,12 @@ readImageToBitmap(FILE *            const ifP,
         unsigned int col;
 
         pnm_scaletuplerow(&pam, row255, tuples[row], 255);
-        
+
         for (col = 0; col < pam.width; ++col) {
             unsigned int plane;
 
             for (plane = 0; plane < pam.depth; ++plane) {
-                unsigned int const bitmapIndex = 
+                unsigned int const bitmapIndex =
                     (row * pam.width + col) * pam.depth + plane;
                 bitmapP->bitmap[bitmapIndex] = row255[col][plane];
             }
@@ -60,7 +60,7 @@ readImageToBitmap(FILE *            const ifP,
     }
     pnm_freepamrow(row255);
     pnm_freepamarray(tuples, &pam);
-    
+
     *bitmapPP = bitmapP;
 }
 
@@ -73,7 +73,7 @@ dotPrinter(float  const percentage,
     int * const currentP = (int *)clientData;
     float const unit     = (float)1.0 / (float)(dot_printer_max_column) ;
     int   const maximum  = (int)(percentage / unit);
-    
+
     while (*currentP < maximum) {
         fputc(dot_printer_char, stderr);
         (*currentP)++;
@@ -120,13 +120,13 @@ struct cmdlineInfo {
 };
 
 
-static void 
-parseCommandLine(int argc, 
-                 char ** argv, 
+static void
+parseCommandLine(int argc,
+                 char ** argv,
                  struct cmdlineInfo  * const cmdlineP) {
 /* --------------------------------------------------------------------------
    Parse program command line described in Unix standard form by argc
-   and argv.  Return the information in the options as *cmdlineP.  
+   and argv.  Return the information in the options as *cmdlineP.
 
    If command line is internally inconsistent (invalid options, etc.),
    issue error message to stderr and abort program.
@@ -139,7 +139,7 @@ parseCommandLine(int argc,
     optStruct3 opt;
 
     const char * background_colorOpt;
-  
+
     unsigned int option_def_index;
 
     MALLOCARRAY_NOFAIL(option_def, 100);
@@ -151,7 +151,7 @@ parseCommandLine(int argc,
             &background_colorOpt,        &cmdlineP->backgroundSpec,         0);
     OPTENT3(0, "centerline",          OPT_FLAG,
             NULL,                        &cmdlineP->centerline,             0);
-    OPTENT3(0, "corner-always-threshold", OPT_FLOAT, 
+    OPTENT3(0, "corner-always-threshold", OPT_FLOAT,
             &cmdlineP->corner_always_threshold, NULL,                       0);
     OPTENT3(0, "corner-surround",     OPT_UINT,
             &cmdlineP->corner_surround,  NULL,                              0);
@@ -173,11 +173,11 @@ parseCommandLine(int argc,
             NULL,                         &cmdlineP->preserve_width,        0);
     OPTENT3(0, "remove-adjacent-corners", OPT_UINT,
             NULL,                       &cmdlineP->remove_adjacent_corners, 0);
-    OPTENT3(0, "tangent-surround",    OPT_UINT,    
+    OPTENT3(0, "tangent-surround",    OPT_UINT,
             &cmdlineP->tangent_surround, NULL,                              0);
     OPTENT3(0, "report-progress",     OPT_FLAG,
             NULL,                       &cmdlineP->report_progress,         0);
-    OPTENT3(0, "width-weight-factor", OPT_FLOAT,    
+    OPTENT3(0, "width-weight-factor", OPT_FLOAT,
             &cmdlineP->width_weight_factor, NULL,                           0);
 
 
@@ -207,7 +207,7 @@ parseCommandLine(int argc,
         cmdlineP->inputFileName = "-";
     else {
         cmdlineP->inputFileName = argv[1];
-        
+
         if (argc-1 > 1)
             pm_error("Too many arguments (%u).  The only non-option argument "
                      "is the input file name.", argc-1);
@@ -228,7 +228,7 @@ fitSplines(at_bitmap_type *             const bitmapP,
     at_fitting_opts_type * fittingOptsP;
 
     progressStat = 0;
-           
+
     fittingOptsP = at_fitting_opts_new();
 
     fittingOptsP->backgroundSpec           = cmdline.backgroundSpec;
@@ -253,7 +253,7 @@ fitSplines(at_bitmap_type *             const bitmapP,
 
     at_fitting_opts_free(fittingOptsP);
 }
-  
+
 
 
 static void
@@ -267,12 +267,12 @@ writeSplines(at_spline_list_array_type * const splinesP,
 
     outputOptsP = at_output_opts_new();
     outputOptsP->dpi = cmdline.dpi;
-    
+
     at_splines_write(outputWriter, ofP, outputOptsP,
                      splinesP, exceptionHandler, NULL);
 
     at_output_opts_free(outputOptsP);
-}  
+}
 
 
 
@@ -315,13 +315,13 @@ filenameRoot(const char * const filename) {
         rootEnd = strlen(filename);
 
     MALLOCARRAY(buffer, rootEnd - rootStart + 1);
-    
+
     j = 0;
     for (i = rootStart; i < rootEnd; ++i)
         buffer[j++] = filename[i];
 
     buffer[j] = '\0';
-    
+
     return buffer;
 }
 
@@ -342,7 +342,7 @@ openLogFile(FILE **      const logFileP,
         if (inputRootName == NULL)
             pm_error("Can't find the root portion of file name '%s'",
                      inputFileArg);
-    
+
         pm_asprintf(&logfileName, "%s.log", inputRootName);
 
         pm_strfree(inputRootName);
@@ -352,7 +352,7 @@ openLogFile(FILE **      const logFileP,
 
     pm_strfree(logfileName);
 }
-    
+
 
 
 int
@@ -374,7 +374,7 @@ main(int argc, char * argv[]) {
         openLogFile(&log_file, cmdline.inputFileName);
 
     readImageToBitmap(ifP, &bitmapP);
-    
+
     if (cmdline.report_progress) {
         progressReporter = dotPrinter;
         fprintf(stderr, "%-15s", cmdline.inputFileName);
@@ -397,6 +397,9 @@ main(int argc, char * argv[]) {
 
     if (cmdline.report_progress)
         fputs("\n", stderr);
-    
+
     return 0;
 }
+
+
+
diff --git a/converter/other/pamtosvg/pamtosvg.test b/converter/other/pamtosvg/pamtosvg.test
deleted file mode 100644
index 3217287e..00000000
--- a/converter/other/pamtosvg/pamtosvg.test
+++ /dev/null
@@ -1,8 +0,0 @@
-echo "Test 1.  Should print nothing"
-# This will print nothing if successful (diff will find no difference)
-ppmmake black 20 20 | ppmdraw -script="line 5 2 15 17" | ./pamtosvg | \
-  diff testline.svg -
-
-echo "Test 2.  Should print nothing"
-# This will print nothing if successful (diff will find no difference)
-./pamtosvg ../../../testgrid.pbm | diff testgrid.svg -
diff --git a/converter/other/pamtosvg/point.c b/converter/other/pamtosvg/point.c
new file mode 100644
index 00000000..0e10b6b6
--- /dev/null
+++ b/converter/other/pamtosvg/point.c
@@ -0,0 +1,90 @@
+#include <stdbool.h>
+#include <math.h>
+
+#include "epsilon.h"
+
+#include "point.h"
+
+
+
+/* Operations on points with real coordinates.  It is not orthogonal,
+   but more convenient, to have the subtraction operator return a
+   vector, and the addition operator return a point.
+*/
+
+
+
+Point
+point_make(float const x,
+           float const y,
+           float const z) {
+
+    Point retval;
+
+    retval.x = x;
+    retval.y = y;
+    retval.z = z;
+
+    return retval;
+}
+
+
+
+bool
+point_equal(Point const comparand,
+            Point const comparator) {
+
+    return
+        epsilon_equal(comparand.x, comparator.x)
+        &&
+        epsilon_equal(comparand.y, comparator.y)
+        &&
+        epsilon_equal(comparand.z, comparator.z)
+        ;
+}
+
+
+
+Point
+point_sum(Point const coord1,
+          Point const coord2) {
+
+    Point retval;
+
+    retval.x = coord1.x + coord2.x;
+    retval.y = coord1.y + coord2.y;
+    retval.z = coord1.z + coord2.z;
+
+    return retval;
+}
+
+
+
+Point
+point_scaled(Point const coord,
+             float const r) {
+
+    Point retval;
+
+    retval.x = coord.x * r;
+    retval.y = coord.y * r;
+    retval.z = coord.z * r;
+
+    return retval;
+}
+
+
+
+float
+point_distance(Point const p1,
+               Point const p2) {
+/*----------------------------------------------------------------------------
+  Return the Euclidean distance between 'p1' and 'p2'.
+-----------------------------------------------------------------------------*/
+    float const x = p1.x - p2.x, y = p1.y - p2.y, z = p1.z - p2.z;
+
+    return (float) sqrt(SQR(x) + SQR(y) + SQR(z));
+}
+
+
+
diff --git a/converter/other/pamtosvg/point.h b/converter/other/pamtosvg/point.h
index 037ec8a0..0346f301 100644
--- a/converter/other/pamtosvg/point.h
+++ b/converter/other/pamtosvg/point.h
@@ -1,8 +1,31 @@
 #ifndef POINT_H_INCLUDED
 #define POINT_H_INCLUDED
 
+#include <stdbool.h>
+
 typedef struct {
   float x, y, z;
-} float_coord;
+} Point;
+
+Point
+point_make(float const x,
+           float const y,
+           float const z);
+
+bool
+point_equal(Point const comparand,
+            Point const comparator);
+
+Point
+point_sum(Point const coord1,
+          Point const coord2);
+
+Point
+point_scaled(Point const coord,
+             float const r);
+
+float
+point_distance(Point const p1,
+               Point const p2);
 
 #endif
diff --git a/converter/other/pamtosvg/pxl-outline.c b/converter/other/pamtosvg/pxl-outline.c
index 19451c04..ff7d6e25 100644
--- a/converter/other/pamtosvg/pxl-outline.c
+++ b/converter/other/pamtosvg/pxl-outline.c
@@ -85,7 +85,7 @@ getBitmapColor(bitmap_type  const bitmap,
     unsigned char * const p = BITMAP_PIXEL(bitmap, row, col);
 
     pixel pix;
-  
+
     if (bitmap.np >= 3)
         PPM_ASSIGN(pix, p[0], p[1], p[2]);
     else
@@ -96,7 +96,6 @@ getBitmapColor(bitmap_type  const bitmap,
 
 
 
-
 static void
 append_outline_pixel(pixel_outline_type * const pixelOutlineP,
                      pm_pixelcoord        const coord) {
@@ -156,6 +155,7 @@ is_outline_edge (edge_type edge, bitmap_type bitmap,
 }
 
 
+
 /* Is this really an edge and is it still unmarked? */
 
 static bool
@@ -173,13 +173,14 @@ is_unmarked_outline_edge(unsigned short row,
 }
 
 
+
 static bool
 is_valid_dir(unsigned int   const row,
              unsigned int   const col,
              direction_type const dir,
              bitmap_type    const bitmap,
              bitmap_type    const marked) {
-  
+
     return(!is_marked_dir(row, col, dir, marked)
            && COMPUTE_DELTA(ROW, dir)+row > 0
            && COMPUTE_DELTA(COL, dir)+col > 0
@@ -233,7 +234,7 @@ next_unmarked_pixel(unsigned int *   const row,
             break;
     } while (1);
 
-    if ((*row != orig_row || *col != orig_col) && 
+    if ((*row != orig_row || *col != orig_col) &&
         (!(is_other_dir_marked(orig_row, orig_col, test_dir, *marked) &&
            is_other_dir_marked(orig_row + COMPUTE_DELTA(ROW, test_dir),
                                orig_col + COMPUTE_DELTA(COL, test_dir),
@@ -297,7 +298,7 @@ findOneCenterline(bitmap_type    const bitmap,
         if (row == originalRow && col == originalCol)
             break;
 
-        
+
         {
             /* Add the new pixel to the output list. */
             pm_pixelcoord pos;
@@ -338,7 +339,7 @@ wrongDirection(unsigned int   const row,
 
 pixel_outline_list_type
 find_centerline_pixels(bitmap_type         const bitmap,
-                       pixel               const bg_color, 
+                       pixel               const bg_color,
                        at_progress_func          notify_progress,
                        void *              const progress_data,
                        at_testcancel_func        test_cancel,
@@ -349,7 +350,7 @@ find_centerline_pixels(bitmap_type         const bitmap,
   signed short row;
   bitmap_type marked = new_bitmap(bitmap.width, bitmap.height);
   unsigned int const max_progress = bitmap.height * bitmap.width;
-    
+
   O_LIST_LENGTH(outline_list) = 0;
   outline_list.data = NULL;
 
@@ -366,9 +367,9 @@ find_centerline_pixels(bitmap_type         const bitmap,
                               ((float) max_progress * (float)3.0),
                               progress_data);
 
-		  if (PPM_EQUAL(getBitmapColor(bitmap, row, col), bg_color)) {
-	          ++col;
-			  continue;
+                  if (PPM_EQUAL(getBitmapColor(bitmap, row, col), bg_color)) {
+                  ++col;
+                          continue;
           }
 
           dir = EAST;
@@ -380,8 +381,8 @@ find_centerline_pixels(bitmap_type         const bitmap,
                   if (wrongDirection(row, col, dir, bitmap, marked)) {
                       dir = SOUTHWEST;
                       if (wrongDirection(row, col, dir, bitmap, marked)) {
-						  ++col;
-						  continue;
+                                                  ++col;
+                                                  continue;
                       }
                   }
               }
@@ -454,8 +455,8 @@ find_centerline_pixels(bitmap_type         const bitmap,
                       free(partial_outline.data);
               } else
                   ++col;
-          }        
-            
+          }
+
           /* Outside outlines will start at a top edge, and move
              counterclockwise, and inside outlines will start at a
              bottom edge, and move clockwise.  This happens because of
@@ -493,6 +494,7 @@ append_pixel_outline (pixel_outline_list_type *outline_list,
 }
 
 
+
 /* Free the list of outline lists. */
 
 void
@@ -517,6 +519,7 @@ free_pixel_outline_list (pixel_outline_list_type *outline_list)
 }
 
 
+
 /* Return an empty list of pixels.  */
 
 
@@ -532,6 +535,8 @@ new_pixel_outline (void)
   return pixel_outline;
 }
 
+
+
 static void
 free_pixel_outline (pixel_outline_type * outline)
 {
@@ -543,6 +548,8 @@ free_pixel_outline (pixel_outline_type * outline)
     }
 }
 
+
+
 /* Concatenate two pixel lists. The two lists are assumed to have the
    same starting pixel and to proceed in opposite directions therefrom. */
 
@@ -569,6 +576,7 @@ concat_pixel_outline(pixel_outline_type *o1, const pixel_outline_type *o2)
 }
 
 
+
 /* If EDGE is not already marked, we mark it; otherwise, it's a fatal error.
    The position ROW and COL should be inside the bitmap MARKED. EDGE can be
    NO_EDGE. */
@@ -581,6 +589,7 @@ mark_edge (edge_type edge, unsigned short row,
 }
 
 
+
 /* Mark the direction of the pixel ROW/COL in MARKED. */
 
 static void
@@ -590,6 +599,7 @@ mark_dir(unsigned short row, unsigned short col, direction_type dir, bitmap_type
 }
 
 
+
 /* Test if the direction of pixel at ROW/COL in MARKED is marked. */
 
 static bool
@@ -599,6 +609,7 @@ is_marked_dir(unsigned short row, unsigned short col, direction_type dir, bitmap
 }
 
 
+
 static bool
 is_other_dir_marked(unsigned short row, unsigned short col, direction_type dir, bitmap_type marked)
 {
@@ -606,6 +617,7 @@ is_other_dir_marked(unsigned short row, unsigned short col, direction_type dir,
 }
 
 
+
 /* Return the number of pixels adjacent to pixel ROW/COL that are black. */
 
 static unsigned
@@ -615,18 +627,19 @@ num_neighbors(unsigned short row, unsigned short col, bitmap_type bitmap)
     pixel color = getBitmapColor(bitmap, row, col);
     for (dir = NORTH; dir <= NORTHEAST; dir++)
     {
-	int delta_r = COMPUTE_DELTA(ROW, dir);
-	int delta_c = COMPUTE_DELTA(COL, dir);
-	unsigned int test_row = row + delta_r;
-	unsigned int test_col = col + delta_c;
-	if (BITMAP_VALID_PIXEL(bitmap, test_row, test_col)
-	    && PPM_EQUAL(getBitmapColor(bitmap, test_row, test_col), color))
-	    ++count;
+        int delta_r = COMPUTE_DELTA(ROW, dir);
+        int delta_c = COMPUTE_DELTA(COL, dir);
+        unsigned int test_row = row + delta_r;
+        unsigned int test_col = col + delta_c;
+        if (BITMAP_VALID_PIXEL(bitmap, test_row, test_col)
+            && PPM_EQUAL(getBitmapColor(bitmap, test_row, test_col), color))
+            ++count;
     }
     return count;
 }
 
 
+
 /* Test if the edge EDGE at ROW/COL in MARKED is marked.  */
 
 static bool
@@ -679,7 +692,7 @@ nextClockwisePointTop(bitmap_type         const bitmap,
         posP->col = *col + 1;
         posP->row = bitmap.height - *row;
         return;
-    } 
+    }
 
     RETURN_IF_FATAL();
 
@@ -714,7 +727,7 @@ nextClockwisePointRight(bitmap_type         const bitmap,
          is_outline_edge(RIGHT, bitmap, *row-1, *col, color, exp))) {
 
          /* NORTH */
-        
+
         *edge = RIGHT;
         --*row;
         posP->col = *col+1;
@@ -723,7 +736,7 @@ nextClockwisePointRight(bitmap_type         const bitmap,
     }
 
     RETURN_IF_FATAL();
-    
+
     if ((*col+1 < marked.width && *row >= 1 &&
          !is_marked_edge(BOTTOM, *row-1, *col+1, marked) &&
          is_outline_edge(BOTTOM, bitmap, *row-1, *col+1,
@@ -740,7 +753,7 @@ nextClockwisePointRight(bitmap_type         const bitmap,
         posP->col = *col + 1;
         posP->row = bitmap.height - *row - 1;
         return;
-    } 
+    }
 
     RETURN_IF_FATAL();
 
@@ -769,7 +782,7 @@ nextClockwisePointBottom(bitmap_type         const bitmap,
                          bitmap_type         const marked,
                          at_exception_type * const exp,
                          pm_pixelcoord *     const posP) {
-    
+
     if ((*col+1 < marked.width &&
          !is_marked_edge(BOTTOM, *row, *col+1, marked) &&
          is_outline_edge(BOTTOM, bitmap, *row, *col+1, color, exp))) {
@@ -853,16 +866,16 @@ nextClockwisePointLeft(bitmap_type         const bitmap,
           is_marked_edge(TOP, *row+1, *col, marked)) &&
         !(is_marked_edge(BOTTOM, *row, *col-1, marked) &&
           is_marked_edge(LEFT, *row+1, *col, marked))) {
-        
+
         /* SOUTHWEST */
-        
+
         *edge = TOP;
         --*col;
         ++*row;
         posP->col = *col;
         posP->row = bitmap.height - *row;
         return;
-    } 
+    }
 
     RETURN_IF_FATAL();
 
@@ -889,21 +902,21 @@ nextClockwisePoint(bitmap_type         const bitmap,
                    bitmap_type         const marked,
                    at_exception_type * const exp,
                    pm_pixelcoord *     const posP) {
-    
+
     switch (*edge) {
     case TOP:
         nextClockwisePointTop(  bitmap, edge, row, col, color,
                                 marked, exp, posP);
         break;
-    case RIGHT: 
+    case RIGHT:
         nextClockwisePointRight(bitmap, edge, row, col, color,
                                 marked, exp, posP);
         break;
-    case BOTTOM: 
+    case BOTTOM:
         nextClockwisePointBottom(bitmap, edge, row, col, color,
                                  marked, exp, posP);
         break;
-    case LEFT: 
+    case LEFT:
         nextClockwisePointLeft(  bitmap, edge, row, col, color,
                                  marked, exp, posP);
         break;
@@ -952,7 +965,7 @@ nextCcwPointTop(bitmap_type         const bitmap,
     }
 
     RETURN_IF_FATAL();
-    
+
     if ((*col >= 1 && *row >= 1 &&
          !is_marked_edge(RIGHT, *row-1, *col-1, marked) &&
          is_outline_edge(RIGHT, bitmap, *row-1, *col-1, color, exp))) {
@@ -965,7 +978,7 @@ nextCcwPointTop(bitmap_type         const bitmap,
         posP->col = *col + 1;
         posP->row = bitmap.height - *row;
         return;
-    } 
+    }
 
     RETURN_IF_FATAL();
 
@@ -1000,7 +1013,7 @@ nextCcwPointRight(bitmap_type         const bitmap,
          is_outline_edge(RIGHT, bitmap, *row-1, *col, color, exp))) {
 
         /* NORTH */
-        
+
         *edge = RIGHT;
         --*row;
         posP->col = *col + 1;
@@ -1082,7 +1095,7 @@ nextCcwPointBottom(bitmap_type         const bitmap,
     }
 
     RETURN_IF_FATAL();
-    
+
     *edge = NO_EDGE;
 }
 
@@ -1124,7 +1137,7 @@ nextCcwPointLeft(bitmap_type         const bitmap,
     }
 
     RETURN_IF_FATAL();
-    
+
     if ((*col >= 1 && *row + 1 < marked.height &&
          !is_marked_edge(TOP, *row+1, *col-1, marked) &&
          is_outline_edge(TOP, bitmap, *row+1, *col-1, color, exp))) {
@@ -1144,6 +1157,8 @@ nextCcwPointLeft(bitmap_type         const bitmap,
     *edge = NO_EDGE;
 }
 
+
+
 static void
 nextCounterClockwisePoint(bitmap_type         const bitmap,
                           edge_type *         const edge,
@@ -1158,18 +1173,18 @@ nextCounterClockwisePoint(bitmap_type         const bitmap,
     case TOP:
         nextCcwPointTop(   bitmap, edge, row, col, color, marked, exp, posP);
         break;
-    case RIGHT: 
+    case RIGHT:
         nextCcwPointRight( bitmap, edge, row, col, color, marked, exp, posP);
         break;
-    case BOTTOM: 
+    case BOTTOM:
         nextCcwPointBottom(bitmap, edge, row, col, color, marked, exp, posP);
         break;
-    case LEFT: 
+    case LEFT:
         nextCcwPointLeft(  bitmap, edge, row, col, color, marked, exp, posP);
         break;
     case NO_EDGE:
         break;
-    default: 
+    default:
         *edge = NO_EDGE;
         break;
     }
@@ -1218,7 +1233,7 @@ find_one_outline(bitmap_type         const bitmap,
 
     pixel_outline_type outline;
     pm_pixelcoord pos;
-    
+
     outline = new_pixel_outline();
     outline.color = getBitmapColor(bitmap, originalRow, originalCol);
 
@@ -1228,7 +1243,7 @@ find_one_outline(bitmap_type         const bitmap,
 
     /* Set initial position */
     pos.col = col + ((edge == RIGHT) || (edge == BOTTOM) ? 1 : 0);
-    pos.row = bitmap.height - row - 1 + 
+    pos.row = bitmap.height - row - 1 +
         (edge == TOP || edge == RIGHT ? 1 : 0);
 
     do {
@@ -1237,7 +1252,7 @@ find_one_outline(bitmap_type         const bitmap,
             LOG2(" (%d,%d)", pos.col, pos.row);
             append_outline_pixel(&outline, pos);
         }
-        
+
         mark_edge(edge, row, col, marked);
         nextPoint(bitmap, &edge, &row, &col, &pos, outline.color, clockwise,
                   *marked, exp);
@@ -1255,7 +1270,7 @@ find_one_outline(bitmap_type         const bitmap,
 pixel_outline_list_type
 find_outline_pixels(bitmap_type         const bitmap,
                     bool                const bg_spec,
-                    pixel               const bg_color, 
+                    pixel               const bg_color,
                     at_progress_func          notify_progress,
                     void *              const progress_data,
                     at_testcancel_func        test_cancel,
@@ -1273,16 +1288,16 @@ find_outline_pixels(bitmap_type         const bitmap,
        to the list, marking the edges in it as we go.
     */
     unsigned int const max_progress = bitmap.height * bitmap.width;
-    
+
     pixel_outline_list_type outline_list;
     unsigned int row;
     bitmap_type marked;
-    
+
     marked = new_bitmap (bitmap.width, bitmap.height);
-    
+
     O_LIST_LENGTH(outline_list) = 0;
     outline_list.data = NULL;
-    
+
     for (row = 0; row < bitmap.height; ++row) {
         unsigned int col;
         for (col = 0; col < bitmap.width; ++col) {
@@ -1303,21 +1318,21 @@ find_outline_pixels(bitmap_type         const bitmap,
                 is_unmarked_outline_edge(row, col, TOP,
                                          bitmap, marked, color, exp)) {
                 pixel_outline_type outline;
-                
+
                 CHECK_FATAL();   /* FREE(DONE) outline_list */
-                
+
                 LOG1("#%u: (counterclockwise)", O_LIST_LENGTH(outline_list));
-                
+
                 outline = find_one_outline(bitmap, TOP, row, col, &marked,
                                            false, false, exp);
                 CHECK_FATAL();    /* FREE(DONE) outline_list */
-                
+
                 O_CLOCKWISE(outline) = false;
                 append_pixel_outline(&outline_list, outline);
-                
+
                 LOG1(" [%u].\n", O_LENGTH (outline));
             } else
-                CHECK_FATAL ();	/* FREE(DONE) outline_list */
+                CHECK_FATAL (); /* FREE(DONE) outline_list */
 
             /* A valid edge can be BOTTOM for an inside outline.
                Inside outlines are traced clockwise.
@@ -1328,20 +1343,20 @@ find_outline_pixels(bitmap_type         const bitmap,
                     is_unmarked_outline_edge(row-1, col, BOTTOM,
                                              bitmap, marked, colorAbove,exp)) {
                     CHECK_FATAL(); /* FREE(DONE) outline_list */
-                    
+
                     /* This lines are for debugging only:*/
                     if (is_background) {
                         pixel_outline_type outline;
-                    
+
                         LOG1("#%u: (clockwise)", O_LIST_LENGTH(outline_list));
-                        
+
                         outline = find_one_outline(bitmap, BOTTOM, row-1, col,
                                                    &marked, true, false, exp);
                         CHECK_FATAL(); /* FREE(DONE) outline_list */
-                        
+
                         O_CLOCKWISE(outline) = true;
                         append_pixel_outline(&outline_list, outline);
-                        
+
                         LOG1(" [%u].\n", O_LENGTH(outline));
                     } else {
                         find_one_outline(bitmap, BOTTOM, row-1, col,
@@ -1349,7 +1364,7 @@ find_outline_pixels(bitmap_type         const bitmap,
                         CHECK_FATAL(); /* FREE(DONE) outline_list */
                     }
                 } else
-                    CHECK_FATAL();	/* FREE(DONE) outline_list */
+                    CHECK_FATAL();      /* FREE(DONE) outline_list */
             }
             if (test_cancel && test_cancel(testcancel_data)) {
                 free_pixel_outline_list(&outline_list);
@@ -1366,3 +1381,5 @@ find_outline_pixels(bitmap_type         const bitmap,
     return outline_list;
 }
 
+
+
diff --git a/converter/other/pamtosvg/pxl-outline.h b/converter/other/pamtosvg/pxl-outline.h
index e37ccaf6..64e312cc 100644
--- a/converter/other/pamtosvg/pxl-outline.h
+++ b/converter/other/pamtosvg/pxl-outline.h
@@ -34,8 +34,8 @@ typedef struct
    after the last is the first, and the previous coordinate before the
    first is the last.  */
 #define O_NEXT(p_o, n) (((n) + 1) % O_LENGTH (p_o))
-#define O_PREV(p_o, n) ((n) == 0				\
-                         ? O_LENGTH (p_o) - 1			\
+#define O_PREV(p_o, n) ((n) == 0                                \
+                         ? O_LENGTH (p_o) - 1                   \
                          : (n) - 1)
 
 /* And the character turns into a list of such lists.  */
@@ -55,7 +55,7 @@ typedef struct
 pixel_outline_list_type
 find_outline_pixels (bitmap_type         const type,
                      bool                const bg_spec,
-                     pixel               const bg_color, 
+                     pixel               const bg_color,
                      at_progress_func          notify_progress,
                      void *              const progress_data,
                      at_testcancel_func        test_cancel,
@@ -65,7 +65,7 @@ find_outline_pixels (bitmap_type         const type,
 /* Find all pixels on the center line of the character C.  */
 pixel_outline_list_type
 find_centerline_pixels (bitmap_type         const type,
-                        pixel               const bg_color, 
+                        pixel               const bg_color,
                         at_progress_func          notify_progress,
                         void *              const progress_data,
                         at_testcancel_func        test_cancel,
diff --git a/converter/other/pamtosvg/spline.c b/converter/other/pamtosvg/spline.c
index 61167ec4..a62ce895 100644
--- a/converter/other/pamtosvg/spline.c
+++ b/converter/other/pamtosvg/spline.c
@@ -18,23 +18,24 @@ print_spline (FILE *f, spline_type s)
 
   if (SPLINE_DEGREE (s) == LINEARTYPE)
     fprintf (f, "(%.3f,%.3f)--(%.3f,%.3f).\n",
-                START_POINT (s).x, START_POINT (s).y,
+                BEG_POINT (s).x, BEG_POINT (s).y,
                 END_POINT (s).x, END_POINT (s).y);
 
   else if (SPLINE_DEGREE (s) == CUBICTYPE)
     fprintf (f, "(%.3f,%.3f)..ctrls(%.3f,%.3f)&(%.3f,%.3f)..(%.3f,%.3f).\n",
-                START_POINT (s).x, START_POINT (s).y,
-                CONTROL1 (s).x, CONTROL1 (s).y,
-                CONTROL2 (s).x, CONTROL2 (s).y,
-                END_POINT (s).x, END_POINT (s).y);
+             BEG_POINT (s).x, BEG_POINT (s).y,
+             CONTROL1  (s).x, CONTROL1  (s).y,
+             CONTROL2  (s).x, CONTROL2  (s).y,
+             END_POINT (s).x, END_POINT (s).y);
 }
 
 
+
 /* Evaluate the spline S at a given T value.  This is an implementation
    of de Casteljau's algorithm.  See Schneider's thesis, p.37.
    The variable names are taken from there.  */
 
-float_coord
+Point
 evaluate_spline (spline_type s, float t)
 {
   spline_type V[4];    /* We need degree+1 splines, but assert degree <= 3.  */
@@ -52,9 +53,9 @@ evaluate_spline (spline_type s, float t)
   for (j = 1; j <= degree; j++)
     for (i = 0; i <= degree - j; i++)
       {
-        float_coord t1 = Pmult_scalar (V[j - 1].v[i], one_minus_t);
-        float_coord t2 = Pmult_scalar (V[j - 1].v[i + 1], t);
-        float_coord temp = Padd (t1, t2);
+        Point t1 = point_scaled(V[j - 1].v[i], one_minus_t);
+        Point t2 = point_scaled(V[j - 1].v[i + 1], t);
+        Point temp = point_sum(t1, t2);
         V[j].v[i].x = temp.x;
         V[j].v[i].y = temp.y;
         V[j].v[i].z = temp.z;
@@ -64,6 +65,7 @@ evaluate_spline (spline_type s, float t)
 }
 
 
+
 /* Return a new, empty, spline list.  */
 
 spline_list_type *
@@ -76,7 +78,9 @@ new_spline_list (void)
   return answer;
 }
 
-spline_list_type 
+
+
+spline_list_type
 empty_spline_list (void)
 {
   spline_list_type answer;
@@ -85,6 +89,8 @@ empty_spline_list (void)
   return answer;
 }
 
+
+
 /* Return a new spline list with SPLINE as the first element.  */
 
 spline_list_type *
@@ -101,6 +107,7 @@ new_spline_list_with_spline (spline_type spline)
 }
 
 
+
 /* Free the storage in a spline list.  We don't have to free the
    elements, since they are arrays in automatic storage.  And we don't
    want to free the list if it was empty.  */
@@ -115,6 +122,7 @@ free_spline_list(spline_list_type spline_list) {
 }
 
 
+
 /* Append the spline S to the list SPLINE_LIST.  */
 
 void
@@ -128,6 +136,7 @@ append_spline (spline_list_type *l, spline_type s)
 }
 
 
+
 /* Tack the elements in the list S2 onto the end of S1.
    S2 is not changed.  */
 
@@ -149,6 +158,7 @@ concat_spline_lists (spline_list_type *s1, spline_list_type s2)
 }
 
 
+
 /* Return a new, empty, spline list array.  */
 
 spline_list_array_type
@@ -163,6 +173,7 @@ new_spline_list_array (void)
 }
 
 
+
 /* Free the storage in a spline list array.  We don't
    want to free the list if it is empty.  */
 void
@@ -182,6 +193,7 @@ free_spline_list_array (spline_list_array_type *spline_list_array)
 }
 
 
+
 /* Append the spline S to the list SPLINE_LIST_ARRAY.  */
 
 void
@@ -193,3 +205,5 @@ append_spline_list (spline_list_array_type *l, spline_list_type s)
   LAST_SPLINE_LIST_ARRAY_ELT (*l) = s;
 }
 
+
+
diff --git a/converter/other/pamtosvg/spline.h b/converter/other/pamtosvg/spline.h
index 96ceab4e..cfdce248 100644
--- a/converter/other/pamtosvg/spline.h
+++ b/converter/other/pamtosvg/spline.h
@@ -18,20 +18,19 @@ typedef at_spline_type spline_type;
 #define ELLIPSETYPE         AT_ELLIPSETYPE
 #define CIRCLETYPE          AT_CIRCLETYPE
 
-#define START_POINT(spl)        ((spl).v[0])
+#define BEG_POINT(spl)          ((spl).v[0])
 #define CONTROL1(spl)           ((spl).v[1])
 #define CONTROL2(spl)           ((spl).v[2])
-#define BEG_POINT(spl)          ((spl).v[0])
 #define END_POINT(spl)          ((spl).v[3])
 #define SPLINE_DEGREE(spl)      ((spl).degree)
 #define SPLINE_LINEARITY(spl)   ((spl).linearity)
 
 #ifndef _IMPORTING
 /* Print a spline on the given file.  */
-extern void print_spline (FILE *, spline_type);
+void print_spline (FILE *, spline_type);
 
 /* Evaluate SPLINE at the given T value.  */
-extern float_coord evaluate_spline (spline_type spline, float t);
+Point evaluate_spline (spline_type spline, float t);
 #endif
 
 /* Each outline in a character is typically represented by many
diff --git a/converter/other/pamtosvg/thin-image.c b/converter/other/pamtosvg/thin-image.c
index 364f67cc..ad15247f 100644
--- a/converter/other/pamtosvg/thin-image.c
+++ b/converter/other/pamtosvg/thin-image.c
@@ -27,78 +27,78 @@
 #include "logreport.h"
 #include "message.h"
 #include "bitmap.h"
- 
+
 #define PIXEL_SET(p, new)  ((void)memcpy((p), (new), sizeof(Pixel)))
 #define PIXEL_EQUAL(p1, p2) \
     ((p1)[0] == (p2)[0] && (p1)[1] == (p2)[1] && (p1)[2] == (p2)[2])
 
- 
-typedef unsigned char Pixel[3];  /* RGB pixel data type */ 
-
- 
-void thin3(bitmap_type *image, Pixel colour); 
-void thin1(bitmap_type *image, unsigned char colour); 
- 
- 
-/* -------------------------------- ThinImage - Thin binary image. --------------------------- * 
- *                                                            
- *    Description:                                                    
- *        Thins the supplied binary image using Rosenfeld's parallel   
- *        thinning algorithm.                                         
- *                                                                     
- *    On Entry:                                                        
- *        image = Image to thin.                                       
- *                                                                     
- * -------------------------------------------------------------------------------------------- */ 
- 
- 
-/* Direction masks:                  */ 
-/*   N     S     W        E            */ 
-static        unsigned int     masks[]         = { 0200, 0002, 0040, 0010 }; 
- 
-/*    True if pixel neighbor map indicates the pixel is 8-simple and  */ 
-/*    not an end point and thus can be deleted.  The neighborhood     */ 
-/*    map is defined as an integer of bits abcdefghi with a non-zero  */ 
-/*    bit representing a non-zero pixel.  The bit assignment for the  */ 
-/*    neighborhood is:                                                */ 
-/*                                                                    */ 
-/*                            a b c                                   */ 
-/*                            d e f                                   */ 
-/*                            g h i                                   */ 
- 
-static        unsigned char   todelete[512] = { 
-              0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 
-              0, 0, 0, 1, 0, 0, 1, 1, 0, 1, 1, 1, 0, 0, 1, 1, 
-              0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 
-              0, 0, 1, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 
-              0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 
-              0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 1, 1, 
-              0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 
-              0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 
-              0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 
-              0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 1, 1, 
-              0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 
-              1, 0, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 
-              0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 
-              1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 1, 1, 
-              0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 
-              1, 0, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 
-              0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 
-              0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 
-              0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 
-              1, 0, 1, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 
-              0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 
-              0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 
-              0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 
-              0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 
-              0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 
-              1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 1, 1, 
-              0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 
-              1, 0, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 
-              0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 
-              1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 1, 1, 
-              0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 
-              1, 0, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1}; 
+
+typedef unsigned char Pixel[3];  /* RGB pixel data type */
+
+
+void thin3(bitmap_type *image, Pixel colour);
+void thin1(bitmap_type *image, unsigned char colour);
+
+
+/* -------------------------------- ThinImage - Thin binary image. --------------------------- *
+ *
+ *    Description:
+ *        Thins the supplied binary image using Rosenfeld's parallel
+ *        thinning algorithm.
+ *
+ *    On Entry:
+ *        image = Image to thin.
+ *
+ * -------------------------------------------------------------------------------------------- */
+
+
+/* Direction masks:                  */
+/*   N     S     W        E            */
+static        unsigned int     masks[]         = { 0200, 0002, 0040, 0010 };
+
+/*    True if pixel neighbor map indicates the pixel is 8-simple and  */
+/*    not an end point and thus can be deleted.  The neighborhood     */
+/*    map is defined as an integer of bits abcdefghi with a non-zero  */
+/*    bit representing a non-zero pixel.  The bit assignment for the  */
+/*    neighborhood is:                                                */
+/*                                                                    */
+/*                            a b c                                   */
+/*                            d e f                                   */
+/*                            g h i                                   */
+
+static        unsigned char   todelete[512] = {
+              0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+              0, 0, 0, 1, 0, 0, 1, 1, 0, 1, 1, 1, 0, 0, 1, 1,
+              0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+              0, 0, 1, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1,
+              0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+              0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 1, 1,
+              0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+              0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1,
+              0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+              0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 1, 1,
+              0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+              1, 0, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
+              0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+              1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 1, 1,
+              0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+              1, 0, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
+              0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+              0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+              0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+              1, 0, 1, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1,
+              0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+              0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+              0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+              0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1,
+              0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+              1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 1, 1,
+              0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+              1, 0, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
+              0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+              1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 1, 1,
+              0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+              1, 0, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1};
 
 static pixel background;
 
@@ -106,268 +106,273 @@ static pixel background;
 void
 thin_image(bitmap_type *image, bool bgSpec, pixel bg,
            at_exception_type * exp)
-{ 
-    /* This is nasty as we need to call thin once for each  
-     * colour in the image the way I do this is to keep a second  
-     * copy of the bitmap and to use this to keep 
-     * track of which colours have not yet been processed, 
-     * trades time for pathological case memory.....*/ 
+{
+    /* This is nasty as we need to call thin once for each
+     * colour in the image the way I do this is to keep a second
+     * copy of the bitmap and to use this to keep
+     * track of which colours have not yet been processed,
+     * trades time for pathological case memory.....*/
     long m, n, num_pixels;
-    bitmap_type bm; 
+    bitmap_type bm;
     unsigned int const spp = image->np;
-	unsigned int const width = image->width;
-	unsigned int const height = image->height;
+        unsigned int const width = image->width;
+        unsigned int const height = image->height;
 
     if (bgSpec)
         background = bg;
-    else 
+    else
         PPM_ASSIGN(background, 255, 255, 255);
 
     /* Clone the image */
     bm.height = image->height;
     bm.width = image->width;
     bm.np = image->np;
-    MALLOCARRAY(bm.bitmap, height * width * spp); 
+    MALLOCARRAY(bm.bitmap, height * width * spp);
     if (bm.bitmap == NULL)
         pm_error("Unable to get memory for thin image bitmap clone");
-    memcpy(bm.bitmap, image->bitmap, height * width * spp); 
+    memcpy(bm.bitmap, image->bitmap, height * width * spp);
 
     num_pixels = height * width;
     switch (spp)
     {
-	case 3:
-	{
-	    Pixel *ptr = (Pixel*)bm.bitmap;
-	    Pixel bg_color;
-	    bg_color[0] = PPM_GETR(background);
-	    bg_color[1] = PPM_GETG(background);
-	    bg_color[2] = PPM_GETB(background);
-
-	    for (n = num_pixels - 1; n >= 0L; --n)
-	    {
-		Pixel p;
-
-		PIXEL_SET(p, ptr[n]);
-		if (!PIXEL_EQUAL(p, bg_color))
-		{ 
-		    /* we have a new colour in the image */ 
-		    LOG3("Thinning colour (%x, %x, %x)\n", p[0], p[1], p[2]);
-		    for (m = n - 1; m >= 0L; --m)
-		    {
-			if (PIXEL_EQUAL(ptr[m], p))
-			    PIXEL_SET(ptr[m], bg_color);
-		    }
-		    thin3(image, p); 
-		} 
-	    } 
-	    break;
-	} 
-
-	case 1:
-	{
-	    unsigned char * const ptr = bm.bitmap;
-	    unsigned char bg_color;
-
-	    if (PPM_ISGRAY(background))
+        case 3:
+        {
+            Pixel *ptr = (Pixel*)bm.bitmap;
+            Pixel bg_color;
+            bg_color[0] = PPM_GETR(background);
+            bg_color[1] = PPM_GETG(background);
+            bg_color[2] = PPM_GETB(background);
+
+            for (n = num_pixels - 1; n >= 0L; --n)
+            {
+                Pixel p;
+
+                PIXEL_SET(p, ptr[n]);
+                if (!PIXEL_EQUAL(p, bg_color))
+                {
+                    /* we have a new colour in the image */
+                    LOG3("Thinning colour (%x, %x, %x)\n", p[0], p[1], p[2]);
+                    for (m = n - 1; m >= 0L; --m)
+                    {
+                        if (PIXEL_EQUAL(ptr[m], p))
+                            PIXEL_SET(ptr[m], bg_color);
+                    }
+                    thin3(image, p);
+                }
+            }
+            break;
+        }
+
+        case 1:
+        {
+            unsigned char * const ptr = bm.bitmap;
+            unsigned char bg_color;
+
+            if (PPM_ISGRAY(background))
             bg_color = PPM_GETR(background);
-	    else
+            else
             bg_color = ppm_luminosity(background);
 
-	    for (n = num_pixels - 1; n >= 0L; --n)
-	    {
-		unsigned char c = ptr[n];
-		if (c != bg_color)
-		{ 
-		    LOG1 ("Thinning colour %x\n", c);
-		    for (m = n - 1; m >= 0L; --m)
-			if (ptr[m] == c) ptr[m] = bg_color;
-		    thin1(image, c); 
-		} 
-	    } 
-	    break;
-	} 
-
-	default:
-	{
-	  LOG1 ("thin_image: Don't know how to interpret %u-plane images", spp);
-	  at_exception_fatal(exp, "thin_image: wrong plane images are passed");
-	  goto cleanup;
-	}
+            for (n = num_pixels - 1; n >= 0L; --n)
+            {
+                unsigned char c = ptr[n];
+                if (c != bg_color)
+                {
+                    LOG1 ("Thinning colour %x\n", c);
+                    for (m = n - 1; m >= 0L; --m)
+                        if (ptr[m] == c) ptr[m] = bg_color;
+                    thin1(image, c);
+                }
+            }
+            break;
+        }
+
+        default:
+        {
+          LOG1 ("thin_image: Don't know how to interpret %u-plane images", spp);
+          at_exception_fatal(exp, "thin_image: wrong plane images are passed");
+          goto cleanup;
+        }
     }
  cleanup:
-    free (bm.bitmap); 
-} 
+    free (bm.bitmap);
+}
+
 
- 
-void thin3(bitmap_type *image, Pixel colour) 
-{ 
+
+void thin3(bitmap_type *image, Pixel colour)
+{
       Pixel *ptr, *y_ptr, *y1_ptr;
       Pixel bg_color;
-      unsigned int    xsize, ysize;   /* Image resolution             */ 
-      unsigned int    x, y;           /* Pixel location               */ 
-      unsigned int    i;              /* Pass index           */ 
-      unsigned int    pc      = 0;    /* Pass count           */ 
-      unsigned int    count   = 1;    /* Deleted pixel count          */ 
-      unsigned int    p, q;           /* Neighborhood maps of adjacent*/ 
-                                      /* cells                        */ 
-      unsigned char   *qb;            /* Neighborhood maps of previous*/ 
-                                      /* scanline                     */ 
-      unsigned int    m;              /* Deletion direction mask      */ 
- 
+      unsigned int    xsize, ysize;   /* Image resolution             */
+      unsigned int    x, y;           /* Pixel location               */
+      unsigned int    i;              /* Pass index           */
+      unsigned int    pc      = 0;    /* Pass count           */
+      unsigned int    count   = 1;    /* Deleted pixel count          */
+      unsigned int    p, q;           /* Neighborhood maps of adjacent*/
+                                      /* cells                        */
+      unsigned char   *qb;            /* Neighborhood maps of previous*/
+                                      /* scanline                     */
+      unsigned int    m;              /* Deletion direction mask      */
+
       bg_color[0] = PPM_GETR(background);
       bg_color[1] = PPM_GETG(background);
       bg_color[2] = PPM_GETB(background);
 
-      LOG (" Thinning image.....\n "); 
+      LOG (" Thinning image.....\n ");
       xsize = image->width;
       ysize = image->height;
-      MALLOCARRAY_NOFAIL(qb, xsize); 
-      qb[xsize-1] = 0;                /* Used for lower-right pixel   */ 
+      MALLOCARRAY_NOFAIL(qb, xsize);
+      qb[xsize-1] = 0;                /* Used for lower-right pixel   */
       ptr = (Pixel*)image->bitmap;
- 
-      while ( count ) {               /* Scan image while deletions   */ 
-          pc++; 
-          count = 0; 
- 
-          for ( i = 0 ; i < 4 ; i++ ) { 
- 
-              m = masks[i]; 
- 
-              /* Build initial previous scan buffer.                  */ 
-              p = PIXEL_EQUAL(ptr[0], colour); 
-              for ( x = 0 ; x < xsize-1 ; x++ ) 
+
+      while ( count ) {               /* Scan image while deletions   */
+          pc++;
+          count = 0;
+
+          for ( i = 0 ; i < 4 ; i++ ) {
+
+              m = masks[i];
+
+              /* Build initial previous scan buffer.                  */
+              p = PIXEL_EQUAL(ptr[0], colour);
+              for ( x = 0 ; x < xsize-1 ; x++ )
                   qb[x] = (unsigned char) (p = ((p<<1)&0006) | (unsigned int) PIXEL_EQUAL(ptr[x+1],
-				   colour)); 
- 
-              /* Scan image for pixel deletion candidates.            */ 
-	      y_ptr = ptr; y1_ptr = ptr + xsize; 
+                                   colour));
+
+              /* Scan image for pixel deletion candidates.            */
+              y_ptr = ptr; y1_ptr = ptr + xsize;
               for (y = 0; y < ysize - 1; y++, y_ptr += xsize, y1_ptr += xsize)
-	      { 
-                  q = qb[0]; 
-                  p = ((q<<2)&0330) | (unsigned int) PIXEL_EQUAL(y1_ptr[0], colour); 
- 
-                  for ( x = 0 ; x < xsize-1 ; x++ ) { 
-                      q = qb[x]; 
-                      p = ((p<<1)&0666) | ((q<<3)&0110) | 
-			  (unsigned int) PIXEL_EQUAL(y1_ptr[x+1], colour);
-                      qb[x] = (unsigned char) p; 
-                      if ((i != 2 || x != 0) && ((p&m) == 0) && todelete[p] ) { 
-                          count++;  /* delete the pixel */ 
-			  PIXEL_SET(y_ptr[x], bg_color);
-                      } 
-                  } 
- 
-                  /* Process right edge pixel.                        */ 
-                  p = (p<<1)&0666; 
-                  if  (i != 3 && (p&m) == 0 && todelete[p] ) { 
-                      count++; 
-		      PIXEL_SET(y_ptr[xsize-1], bg_color);
-                  } 
-              } 
- 
-	      if (i != 1)
-	      {
-            /* Process bottom scan line.                            */ 
-            q = qb[0]; 
-            p = ((q<<2)&0330); 
+              {
+                  q = qb[0];
+                  p = ((q<<2)&0330) | (unsigned int) PIXEL_EQUAL(y1_ptr[0], colour);
+
+                  for ( x = 0 ; x < xsize-1 ; x++ ) {
+                      q = qb[x];
+                      p = ((p<<1)&0666) | ((q<<3)&0110) |
+                          (unsigned int) PIXEL_EQUAL(y1_ptr[x+1], colour);
+                      qb[x] = (unsigned char) p;
+                      if ((i != 2 || x != 0) && ((p&m) == 0) && todelete[p] ) {
+                          count++;  /* delete the pixel */
+                          PIXEL_SET(y_ptr[x], bg_color);
+                      }
+                  }
+
+                  /* Process right edge pixel.                        */
+                  p = (p<<1)&0666;
+                  if  (i != 3 && (p&m) == 0 && todelete[p] ) {
+                      count++;
+                      PIXEL_SET(y_ptr[xsize-1], bg_color);
+                  }
+              }
+
+              if (i != 1)
+              {
+            /* Process bottom scan line.                            */
+            q = qb[0];
+            p = ((q<<2)&0330);
 
             y_ptr = ptr + xsize * (ysize - 1);
-            for ( x = 0 ; x < xsize ; x++ ) { 
-              q = qb[x]; 
-              p = ((p<<1)&0666) | ((q<<3)&0110); 
-              if ((i != 2 || x != 0) && (p&m) == 0 && todelete[p]) { 
-                count++; 
+            for ( x = 0 ; x < xsize ; x++ ) {
+              q = qb[x];
+              p = ((p<<1)&0666) | ((q<<3)&0110);
+              if ((i != 2 || x != 0) && (p&m) == 0 && todelete[p]) {
+                count++;
                 PIXEL_SET(y_ptr[x], bg_color);
-		      } 
-            } 
+                      }
+            }
            }
-          } 
-          LOG2 ("ThinImage: pass %d, %d pixels deleted\n", pc, count); 
-      } 
-      free (qb); 
-} 
-
- 
-void thin1(bitmap_type *image, unsigned char colour) 
-{ 
+          }
+          LOG2 ("ThinImage: pass %d, %d pixels deleted\n", pc, count);
+      }
+      free (qb);
+}
+
+
+
+void thin1(bitmap_type *image, unsigned char colour)
+{
       unsigned char *ptr, *y_ptr, *y1_ptr;
       unsigned char bg_color;
-      unsigned int    xsize, ysize;   /* Image resolution             */ 
-      unsigned int    x, y;           /* Pixel location               */ 
-      unsigned int    i;              /* Pass index           */ 
-      unsigned int    pc      = 0;    /* Pass count           */ 
-      unsigned int    count   = 1;    /* Deleted pixel count          */ 
-      unsigned int    p, q;           /* Neighborhood maps of adjacent*/ 
-                                      /* cells                        */ 
-      unsigned char   *qb;            /* Neighborhood maps of previous*/ 
-                                      /* scanline                     */ 
-      unsigned int    m;              /* Deletion direction mask      */ 
+      unsigned int    xsize, ysize;   /* Image resolution             */
+      unsigned int    x, y;           /* Pixel location               */
+      unsigned int    i;              /* Pass index           */
+      unsigned int    pc      = 0;    /* Pass count           */
+      unsigned int    count   = 1;    /* Deleted pixel count          */
+      unsigned int    p, q;           /* Neighborhood maps of adjacent*/
+                                      /* cells                        */
+      unsigned char   *qb;            /* Neighborhood maps of previous*/
+                                      /* scanline                     */
+      unsigned int    m;              /* Deletion direction mask      */
 
       if (PPM_ISGRAY(background))
           bg_color = PPM_GETR(background);
       else
           bg_color = ppm_luminosity(background);
 
-      LOG (" Thinning image.....\n "); 
+      LOG (" Thinning image.....\n ");
       xsize = image->width;
       ysize = image->height;
-      MALLOCARRAY_NOFAIL(qb, xsize); 
-      qb[xsize-1] = 0;                /* Used for lower-right pixel   */ 
+      MALLOCARRAY_NOFAIL(qb, xsize);
+      qb[xsize-1] = 0;                /* Used for lower-right pixel   */
       ptr = image->bitmap;
- 
-      while ( count ) {               /* Scan image while deletions   */ 
-          pc++; 
-          count = 0; 
- 
-          for ( i = 0 ; i < 4 ; i++ ) { 
- 
-              m = masks[i]; 
- 
-              /* Build initial previous scan buffer.                  */ 
-              p = (ptr[0] == colour); 
-              for ( x = 0 ; x < xsize-1 ; x++ ) 
-                  qb[x] = (unsigned char) (p = ((p<<1)&0006) | (unsigned int)(ptr[x+1] == colour)); 
- 
-              /* Scan image for pixel deletion candidates.            */ 
-	      y_ptr = ptr; y1_ptr = ptr + xsize; 
+
+      while ( count ) {               /* Scan image while deletions   */
+          pc++;
+          count = 0;
+
+          for ( i = 0 ; i < 4 ; i++ ) {
+
+              m = masks[i];
+
+              /* Build initial previous scan buffer.                  */
+              p = (ptr[0] == colour);
+              for ( x = 0 ; x < xsize-1 ; x++ )
+                  qb[x] = (unsigned char) (p = ((p<<1)&0006) | (unsigned int)(ptr[x+1] == colour));
+
+              /* Scan image for pixel deletion candidates.            */
+              y_ptr = ptr; y1_ptr = ptr + xsize;
               for (y = 0; y < ysize - 1; y++, y_ptr += xsize, y1_ptr += xsize)
-	      { 
-                  q = qb[0]; 
-                  p = ((q<<2)&0330) | (y1_ptr[0] == colour); 
- 
-                  for ( x = 0 ; x < xsize-1 ; x++ ) { 
-                      q = qb[x]; 
-                      p = ((p<<1)&0666) | ((q<<3)&0110) | (unsigned int) (y1_ptr[x+1]==colour); 
-                      qb[x] = (unsigned char) p; 
-                      if  ( ((p&m) == 0) && todelete[p] ) { 
-                          count++; 
-			  y_ptr[x] = bg_color;  /* delete the pixel */ 
-                      } 
-                  } 
- 
-                  /* Process right edge pixel.                        */ 
-                  p = (p<<1)&0666; 
-                  if  ( (p&m) == 0 && todelete[p] ) { 
-                      count++; 
+              {
+                  q = qb[0];
+                  p = ((q<<2)&0330) | (y1_ptr[0] == colour);
+
+                  for ( x = 0 ; x < xsize-1 ; x++ ) {
+                      q = qb[x];
+                      p = ((p<<1)&0666) | ((q<<3)&0110) | (unsigned int) (y1_ptr[x+1]==colour);
+                      qb[x] = (unsigned char) p;
+                      if  ( ((p&m) == 0) && todelete[p] ) {
+                          count++;
+                          y_ptr[x] = bg_color;  /* delete the pixel */
+                      }
+                  }
+
+                  /* Process right edge pixel.                        */
+                  p = (p<<1)&0666;
+                  if  ( (p&m) == 0 && todelete[p] ) {
+                      count++;
                       y_ptr[xsize-1] = bg_color;
-                  } 
-              } 
- 
-              /* Process bottom scan line.                            */ 
-	      q = qb[0]; 
-	      p = ((q<<2)&0330); 
- 
-	      y_ptr = ptr + xsize * (ysize - 1);
-              for ( x = 0 ; x < xsize ; x++ ) { 
-                  q = qb[x]; 
-                  p = ((p<<1)&0666) | ((q<<3)&0110); 
-                  if  ( (p&m) == 0 && todelete[p] ) { 
-                      count++; 
+                  }
+              }
+
+              /* Process bottom scan line.                            */
+              q = qb[0];
+              p = ((q<<2)&0330);
+
+              y_ptr = ptr + xsize * (ysize - 1);
+              for ( x = 0 ; x < xsize ; x++ ) {
+                  q = qb[x];
+                  p = ((p<<1)&0666) | ((q<<3)&0110);
+                  if  ( (p&m) == 0 && todelete[p] ) {
+                      count++;
                       y_ptr[x] = bg_color;
-                  } 
-              } 
-          } 
-          LOG2("thin1: pass %d, %d pixels deleted\n", pc, count); 
-      } 
-      free (qb); 
-} 
+                  }
+              }
+          }
+          LOG2("thin1: pass %d, %d pixels deleted\n", pc, count);
+      }
+      free (qb);
+}
+
+
+
diff --git a/converter/other/pamtosvg/vector.c b/converter/other/pamtosvg/vector.c
index 771e5f27..a02b933b 100644
--- a/converter/other/pamtosvg/vector.c
+++ b/converter/other/pamtosvg/vector.c
@@ -10,17 +10,41 @@
 
 #include "vector.h"
 #include "message.h"
-#include "epsilon-equal.h"
+#include "epsilon.h"
 
-static float acos_d (float, at_exception_type * excep);
+static float
+acosD(float               const v,
+      at_exception_type * const excepP) {
+
+    float vAdj;
+    float a;
+    float retval;
 
+    if (epsilon_equal(v, 1.0))
+        vAdj = 1.0;
+    else if (epsilon_equal(v, -1.0))
+        vAdj = -1.0;
+    else
+        vAdj = v;
 
-/* Given the point COORD, return the corresponding vector.  */
+    errno = 0;
+    a = acos(vAdj);
+    if (errno == ERANGE || errno == EDOM) {
+        at_exception_fatal(excepP, strerror(errno));
+        retval = 0.0;
+    } else
+        retval = a * 180.0 / M_PI;
+
+    return retval;
+}
 
-vector_type
-make_vector(float_coord const c) {
 
-    vector_type v;
+
+Vector
+vector_fromPoint(Point const c) {
+/* Vector corresponding to point 'c', taken as a vector from the origin.  */
+
+    Vector v;
 
     v.dx = c.x;
     v.dy = c.y;
@@ -31,12 +55,28 @@ make_vector(float_coord const c) {
 
 
 
+Vector
+vector_fromTwoPoints(Point const c1,
+                     Point const c2) {
+
+    Vector retval;
+
+    retval.dx = c1.x - c2.x;
+    retval.dy = c1.y - c2.y;
+    retval.dz = c1.z - c2.z;
+
+    return retval;
+}
+
+
+
 /* And the converse: given a vector, return the corresponding point.  */
 
-float_coord
-vector_to_point(vector_type const v) {
+Point
+vector_toPoint_point(Vector const v) {
+/* vector as a point, i.e., a displacement from the origin.  */
 
-    float_coord coord;
+    Point coord;
 
     coord.x = v.dx;
     coord.y = v.dy;
@@ -48,18 +88,18 @@ vector_to_point(vector_type const v) {
 
 
 float
-magnitude(vector_type const v) {
+vector_magnitude(Vector const v) {
 
     return sqrt(SQR(v.dx) + SQR(v.dy) + SQR(v.dz));
 }
 
 
 
-vector_type
-normalize(vector_type const v) {
+Vector
+vector_normalized(Vector const v) {
 
-    vector_type new_v;
-    float const m = magnitude(v);
+    Vector new_v;
+    float const m = vector_magnitude(v);
 
     if (m > 0.0) {
         new_v.dx = v.dx / m;
@@ -70,221 +110,194 @@ normalize(vector_type const v) {
         new_v.dy = v.dy;
         new_v.dz = v.dz;
     }
-    
+
     return new_v;
 }
 
 
 
-vector_type
-Vadd(vector_type const v1,
-     vector_type const v2) {
+Vector
+vector_sum(Vector const addend,
+           Vector const adder) {
 
-    vector_type new_v;
+    Vector retval;
 
-    new_v.dx = v1.dx + v2.dx;
-    new_v.dy = v1.dy + v2.dy;
-    new_v.dz = v1.dz + v2.dz;
+    retval.dx = addend.dx + adder.dx;
+    retval.dy = addend.dy + adder.dy;
+    retval.dz = addend.dz + adder.dz;
 
-    return new_v;
+    return retval;
 }
 
 
 
 float
-Vdot(vector_type const v1,
-     vector_type const v2) {
+vector_dotProduct(Vector const v1,
+                  Vector const v2) {
 
     return v1.dx * v2.dx + v1.dy * v2.dy + v1.dz * v2.dz;
 }
 
 
 
-vector_type
-Vmult_scalar(vector_type const v,
-             float       const r) {
+Vector
+vector_scaled(Vector const v,
+              float  const r) {
 
-    vector_type new_v;
+    Vector retval;
 
-    new_v.dx = v.dx * r;
-    new_v.dy = v.dy * r;
-    new_v.dz = v.dz * r;
+    retval.dx = v.dx * r;
+    retval.dy = v.dy * r;
+    retval.dz = v.dz * r;
 
-    return new_v;
+    return retval;
 }
 
 
 
-/* Given the IN_VECTOR and OUT_VECTOR, return the angle between them in
-   degrees, in the range zero to 180.
-*/
-
 float
-Vangle(vector_type         const in_vector, 
-       vector_type         const out_vector,
-       at_exception_type * const exP) {
-
-    vector_type const v1 = normalize(in_vector);
-    vector_type const v2 = normalize(out_vector);
-
-    return acos_d(Vdot(v2, v1), exP);
-}
+vector_angle(Vector              const inVector,
+             Vector              const outVector,
+             at_exception_type * const exP) {
 
+/* The angle between 'inVector' and 'outVector' in degrees, in the range zero
+   to 180.
+*/
 
+    Vector const v1 = vector_normalized(inVector);
+    Vector const v2 = vector_normalized(outVector);
 
-float_coord
-Vadd_point(float_coord const c,
-           vector_type const v) {
-
-    float_coord new_c;
-
-    new_c.x = c.x + v.dx;
-    new_c.y = c.y + v.dy;
-    new_c.z = c.z + v.dz;
-
-    return new_c;
+    return acosD(vector_dotProduct(v2, v1), exP);
 }
 
 
 
-float_coord
-Vsubtract_point(float_coord const c,
-                vector_type const v) {
+Point
+vector_sumPoint(Point const c,
+                Vector      const v) {
 
-    float_coord new_c;
+    Point retval;
 
-    new_c.x = c.x - v.dx;
-    new_c.y = c.y - v.dy;
-    new_c.z = c.z - v.dz;
+    retval.x = c.x + v.dx;
+    retval.y = c.y + v.dy;
+    retval.z = c.z + v.dz;
 
-    return new_c;
+    return retval;
 }
 
 
 
-pm_pixelcoord
-Vadd_int_point(pm_pixelcoord const c,
-               vector_type   const v) {
+Point
+vector_diffPoint(Point  const c,
+                 Vector const v) {
+
+    Point retval;
 
-    pm_pixelcoord a;
+    retval.x = c.x - v.dx;
+    retval.y = c.y - v.dy;
+    retval.z = c.z - v.dz;
 
-    a.col = ROUND ((float) c.col + v.dx);
-    a.row = ROUND ((float) c.row + v.dy);
-    
-    return a;
+    return retval;
 }
 
 
 
-vector_type
-Vabs(vector_type const v) {
+Vector
+vector_IPointDiff(pm_pixelcoord const coord1,
+                  pm_pixelcoord const coord2) {
 
-    vector_type new_v;
+    Vector retval;
 
-    new_v.dx = (float) fabs (v.dx);
-    new_v.dy = (float) fabs (v.dy);
-    new_v.dz = (float) fabs (v.dz);
+    retval.dx = (int) (coord1.col - coord2.col);
+    retval.dy = (int) (coord1.row - coord2.row);
+    retval.dz = 0.0;
 
-    return new_v;
+    return retval;
 }
 
 
 
-/* Operations on points.  */
+pm_pixelcoord
+vector_sumIntPoint(pm_pixelcoord const c,
+                   Vector        const v) {
 
-float_coord
-Padd(float_coord const coord1,
-     float_coord const coord2) {
+/* This returns the rounded sum.  */
 
-    float_coord sum;
+    pm_pixelcoord retval;
 
-    sum.x = coord1.x + coord2.x;
-    sum.y = coord1.y + coord2.y;
-    sum.z = coord1.z + coord2.z;
+    retval.col = ROUND ((float) c.col + v.dx);
+    retval.row = ROUND ((float) c.row + v.dy);
 
-    return sum;
+    return retval;
 }
 
 
 
-float_coord
-Pmult_scalar(float_coord const coord,
-             float       const r) {
+Vector
+vector_abs(Vector const v) {
+
+/* First-quadrant mirror of 'v' (both components unsigned) */
 
-    float_coord answer;
+    Vector retval;
 
-    answer.x = coord.x * r;
-    answer.y = coord.y * r;
-    answer.z = coord.z * r;
+    retval.dx = (float) fabs (v.dx);
+    retval.dy = (float) fabs (v.dy);
+    retval.dz = (float) fabs (v.dz);
 
-    return answer;
+    return retval;
 }
 
 
 
-vector_type
-Psubtract(float_coord const c1,
-          float_coord const c2) {
+Vector
+vector_pointDirection(Point const final,
+                      Point const initial) {
 
-    vector_type v;
+    return vector_normalized(vector_fromTwoPoints(final, initial));
+}
 
-    v.dx = c1.x - c2.x;
-    v.dy = c1.y - c2.y;
-    v.dz = c1.z - c2.z;
 
-    return v;
-}
 
+Vector
+vector_horizontal(void) {
 
+    Vector retval;
 
-vector_type
-Pdirection(float_coord const final,
-           float_coord const initial) {
+    retval.dx = 1.0;
+    retval.dy = 0.0;
+    retval.dz = 0.0;
 
-    return normalize(Psubtract(final, initial));
+    return retval;
 }
 
 
 
-/* Operations on integer points.  */
+Vector
+vector_zero(void) {
 
-vector_type
-IPsubtract(pm_pixelcoord const coord1,
-           pm_pixelcoord const coord2) {
+    Vector retval;
 
-    vector_type v;
+    retval.dx = 0.0;
+    retval.dy = 0.0;
+    retval.dz = 0.0;
 
-    v.dx = (int) (coord1.col - coord2.col);
-    v.dy = (int) (coord1.row - coord2.row);
-    v.dz = 0.0;
-    
-    return v;
+    return retval;
 }
 
 
 
-static float
-acos_d(float               const v,
-       at_exception_type * const excepP) {
+bool
+vector_equal(Vector const comparand,
+             Vector const comparator) {
 
-    float vAdj;
-    float a;
-    float retval;
+    return
+        epsilon_equal(comparand.dx, comparator.dx)
+        &&
+        epsilon_equal(comparand.dy, comparator.dy)
+        &&
+        epsilon_equal(comparand.dz, comparator.dz)
+        ;
+}
 
-    if (epsilon_equal(v, 1.0))
-        vAdj = 1.0;
-    else if (epsilon_equal(v, -1.0))
-        vAdj = -1.0;
-    else
-        vAdj = v;
 
-    errno = 0;
-    a = acos(vAdj);
-    if (errno == ERANGE || errno == EDOM) {
-        at_exception_fatal(excepP, strerror(errno));
-        retval = 0.0;
-    } else
-        retval = a * 180.0 / M_PI;
 
-    return retval;
-}
diff --git a/converter/other/pamtosvg/vector.h b/converter/other/pamtosvg/vector.h
index b5c85c38..65364c82 100644
--- a/converter/other/pamtosvg/vector.h
+++ b/converter/other/pamtosvg/vector.h
@@ -11,93 +11,79 @@
 typedef struct
 {
   float dx, dy, dz;
-} vector_type;
+} Vector;
 
 
-/* Consider a point as a vector from the origin.  */
-vector_type
-make_vector(float_coord const);
+Vector
+vector_fromPoint(Point const c);
 
-/* And a vector as a point, i.e., a displacement from the origin.  */
-float_coord
-vector_to_point(vector_type const);
+Vector
+vector_fromTwoPoints(Point const c1,
+                     Point const c2);
+
+Point
+vector_toPoint_point(Vector const v);
 
 
 /* Definitions for these common operations can be found in any decent
-   linear algebra book, and most calculus books.  */
+   linear algebra book, and most calculus books.
+*/
 
 float
-magnitude(vector_type const);
+vector_magnitude(Vector const v);
 
-vector_type
-normalize(vector_type const);
+Vector
+vector_normalized(Vector const v);
 
-vector_type
-Vadd(vector_type const,
-     vector_type const);
+Vector
+vector_sum(Vector const addend,
+           Vector const adder);
 
 float
-Vdot(vector_type const,
-     vector_type const);
+vector_dotProduct(Vector const v1,
+                  Vector const v2);
 
-vector_type
-Vmult_scalar(vector_type const,
-             float       const);
+Vector
+vector_scaled(Vector const v,
+              float  const r);
 
 float
-Vangle(vector_type         const in,
-       vector_type         const out,
-       at_exception_type * const exP);
-
-/* These operations could have been named `P..._vector' just as well as
-   V..._point, so we may as well allow both names.  */
-
-#define Padd_vector Vadd_point
-
-float_coord
-Vadd_point(float_coord const,
-           vector_type const);
+vector_angle(Vector              const inVector,
+             Vector              const outVector,
+             at_exception_type * const exP);
 
-#define Psubtract_vector Vsubtract_point
+Point
+vector_sumPoint(Point  const c,
+                Vector const v);
 
-float_coord
-Vsubtract_point(float_coord const,
-                vector_type const);
-
-vector_type
-Pdirection(float_coord const final,
-           float_coord const initial);
-
-/* This returns the rounded sum.  */
-#define IPadd_vector Vadd_int_point
+Point
+vector_diffPoint(Point  const c,
+                 Vector const v);
 
 pm_pixelcoord
-Vadd_int_point(pm_pixelcoord const c,
-               vector_type   const v);
+vector_sumIntPoint(pm_pixelcoord const c,
+                   Vector        const v);
+
+Vector
+vector_abs(Vector const v);
 
-/* Take the absolute value of both components.  */
-vector_type
-Vabs(vector_type const);
+Vector
+vector_pointDirection(Point const final,
+                      Point const initial);
 
-/* Operations on points with real coordinates.  It is not orthogonal,
-   but more convenient, to have the subtraction operator return a
-   vector, and the addition operator return a point.  */
-vector_type
-Psubtract(float_coord const,
-          float_coord const);
 
-vector_type
-IPsubtract(pm_pixelcoord const coord1,
-           pm_pixelcoord const coord2);
+Vector
+vector_IPointDiff(pm_pixelcoord const coord1,
+                  pm_pixelcoord const coord2);
 
-/* These are heavily used in spline fitting.  */
+Vector
+vector_horizontal(void);
 
-float_coord
-Padd(float_coord const,
-     float_coord const);
+Vector
+vector_zero(void);
 
-float_coord
-Pmult_scalar(float_coord const,
-             float       const);
+bool
+vector_equal(Vector const comparand,
+             Vector const comparator);
 
 #endif
diff --git a/converter/other/pamtotga.c b/converter/other/pamtotga.c
index 1daa1e25..c0fb524a 100644
--- a/converter/other/pamtotga.c
+++ b/converter/other/pamtotga.c
@@ -82,7 +82,7 @@ parseCommandLine(int argc, const char ** argv,
     opt.short_allowed = FALSE;  /* We have no short (old-fashioned) options */
     opt.allowNegNum = FALSE;  /* We have no parms that are negative numbers */
 
-    pm_optParseOptions3(&argc, (char **)argv, opt, sizeof(opt), 0);
+    pm_optParseOptions4(&argc, argv, opt, sizeof(opt), 0);
         /* Uses and sets argc, argv, and some of *cmdline_p and others. */
 
     if (cmap + cmap16 + mono + rgb > 1)
@@ -120,6 +120,7 @@ parseCommandLine(int argc, const char ** argv,
 }
 
 
+
 static void
 putPixel(struct pam *          const pamP,
          tuple                 const tuple,
@@ -271,7 +272,7 @@ computeOutName(struct CmdlineInfo const cmdline,
         workarea = strdup(cmdline.inputFileName);
         cp = strchr(workarea, '.');
         if (cp != NULL)
-        	*cp = '\0';	/* remove extension */
+                *cp = '\0';     /* remove extension */
     }
 
     if (workarea == NULL)
@@ -648,3 +649,6 @@ main(int argc, const char **argv) {
 
     return 0;
 }
+
+
+
diff --git a/converter/other/pamtotiff.c b/converter/other/pamtotiff.c
index 1718c933..584cb840 100644
--- a/converter/other/pamtotiff.c
+++ b/converter/other/pamtotiff.c
@@ -236,7 +236,7 @@ parseCommandLine(int                 argc,
     opt.short_allowed = false;  /* We have no short (old-fashioned) options */
     opt.allowNegNum = false;  /* We have no parms that are negative numbers */
 
-    pm_optParseOptions3(&argc, (char**)argv, opt, sizeof(opt), 0);
+    pm_optParseOptions4(&argc, argv, opt, sizeof(opt), 0);
     /* Uses and sets argc, argv, and some of *cmdlineP and others. */
 
     if (none + packbits + lzw + g3 + g4 + flate + adobeflate > 1)
@@ -1311,3 +1311,4 @@ main(int argc, const char *argv[]) {
 }
 
 
+
diff --git a/converter/other/pamtouil.c b/converter/other/pamtouil.c
index 01858cbc..46fb76e7 100644
--- a/converter/other/pamtouil.c
+++ b/converter/other/pamtouil.c
@@ -71,9 +71,9 @@ parseCommandLine(int argc, char ** argv,
     const char *outnameOpt;
 
     option_def_index = 0;   /* incremented by OPTENTRY */
-    OPTENT3(0, "name",       OPT_STRING, &outnameOpt, 
+    OPTENT3(0, "name",       OPT_STRING, &outnameOpt,
             &outnameSpec,       0);
-    OPTENT3(0, "verbose",    OPT_FLAG,   NULL, 
+    OPTENT3(0, "verbose",    OPT_FLAG,   NULL,
             &cmdlineP->verbose, 0);
 
     opt.opt_table = option_def;
@@ -87,7 +87,7 @@ parseCommandLine(int argc, char ** argv,
         cmdlineP->inputFilespec = "-";  /* stdin */
     else if (argc-1 == 1)
         cmdlineP->inputFilespec = argv[1];
-    else 
+    else
         pm_error("Too many arguments (%d).  "
                  "Only need one: the input filespec", argc-1);
 
@@ -98,7 +98,7 @@ parseCommandLine(int argc, char ** argv,
 
         /* Remove trailing "_icon" */
         barPos = strrchr(cmdlineP->outname, '_');
-        if (barPos && streq(barPos, "_icon")) 
+        if (barPos && streq(barPos, "_icon"))
             *barPos = '\0';
     } else {
         if (streq(cmdlineP->inputFilespec, "-"))
@@ -118,11 +118,10 @@ parseCommandLine(int argc, char ** argv,
 
 
 
-
 static char*
-genNumstr(int  const number, 
-          int  const base, 
-          char const low_char, 
+genNumstr(int  const number,
+          int  const base,
+          char const low_char,
           int  const digits ) {
 /*----------------------------------------------------------------------------
   Generate a string 'digits' characters long in newly malloc'ed
@@ -130,7 +129,7 @@ genNumstr(int  const number,
   the left with zero digits and truncate on the left if it doesn't fit.
 
   Use the characters 'low_char' to 'low_char' + 'base' to represent the
-  digits 0 to 'base'. 
+  digits 0 to 'base'.
 -----------------------------------------------------------------------------*/
     char* str;
     char* p;
@@ -156,11 +155,11 @@ genNumstr(int  const number,
 
 
 
-static const char * 
+static const char *
 uilName(const char * const rgbname,
         bool         const transparent) {
 /*----------------------------------------------------------------------------
-   Return a string in newly malloc'ed storage which is an appropriate 
+   Return a string in newly malloc'ed storage which is an appropriate
    color name for the UIL palette.  It is the same as the rgb name,
    except that blanks are replaced by underscores, and if 'transparent'
    is true, it is "background color".  The latter is a strange name of
@@ -176,7 +175,7 @@ uilName(const char * const rgbname,
         output = malloc(strlen(rgbname) + 5 + 1);
         if (output == NULL)
             pm_error( "out of memory allocating color name" );
-        
+
         for (i = 0; i < strlen(rgbname); ++i) {
             if (rgbname[i] == ' ')
                 output[i] = '_';
@@ -193,9 +192,9 @@ uilName(const char * const rgbname,
 
 static void
 genCmap(struct pam *   const pamP,
-        tupletable     const chv, 
-        unsigned int   const ncolors, 
-        cixel_map            cmap[MAXCOLORS], 
+        tupletable     const chv,
+        unsigned int   const ncolors,
+        cixel_map            cmap[MAXCOLORS],
         unsigned int * const charsppP,
         bool           const verbose) {
 
@@ -205,7 +204,7 @@ genCmap(struct pam *   const pamP,
     {
         /* Figure out how many characters per pixel we'll be using.
            Don't want to be forced to link with libm.a, so using a
-           division loop rather than a log function.  
+           division loop rather than a log function.
         */
         unsigned int i;
         for (*charsppP = 0, i = ncolors; i > 0; ++(*charsppP))
@@ -220,15 +219,15 @@ genCmap(struct pam *   const pamP,
         unsigned int indexOfName;
         bool transparent;
         int j;
-        
+
         if (pamP->depth-1 < PAM_TRN_PLANE)
             transparent = FALSE;
-        else 
-            transparent = 
+        else
+            transparent =
                 chv[colorIndex]->tuple[PAM_TRN_PLANE] < pamP->maxval/2;
 
         /* Generate color name string. */
-        colorname = pam_colorname(pamP, chv[colorIndex]->tuple, 
+        colorname = pam_colorname(pamP, chv[colorIndex]->tuple,
                                   PAM_COLORNAME_ENGLISH);
 
         /* We may have already assigned a character code to this color
@@ -236,11 +235,11 @@ genCmap(struct pam *   const pamP,
            two different colors because we said we wanted the closest
            matching color that has an English name, and we recognize
            only one transparent color.  If that's the case, we just
-           make a cross-reference.  
+           make a cross-reference.
         */
         nameAlreadyInCmap = FALSE;   /* initial assumption */
         for (j = 0; j < colorIndex; ++j) {
-            if (cmap[j].rgbname != NULL && 
+            if (cmap[j].rgbname != NULL &&
                 streq(colorname, cmap[j].rgbname) &&
                 cmap[j].transparent == transparent) {
                 nameAlreadyInCmap = TRUE;
@@ -257,15 +256,15 @@ genCmap(struct pam *   const pamP,
             cmap[colorIndex].rgbname = strdup(colorname);
             if (cmap[colorIndex].rgbname == NULL)
                 pm_error("out of memory allocating color name");
-            
+
             cmap[colorIndex].transparent = transparent;
-            
+
             /* Generate color value characters. */
-            cmap[colorIndex].cixel = 
+            cmap[colorIndex].cixel =
                 genNumstr(colorIndex, base, LOW_CHAR, *charsppP);
             if (verbose)
                 pm_message("Adding color '%s' %s = '%s' to UIL colormap",
-                           cmap[colorIndex].rgbname, 
+                           cmap[colorIndex].rgbname,
                            cmap[colorIndex].transparent ? "TRANS" : "OPAQUE",
                            cmap[colorIndex].cixel);
         }
@@ -286,8 +285,8 @@ writeUilHeader(const char * const outname) {
 
 
 static void
-writeColormap(const char * const outname, 
-              cixel_map          cmap[MAXCOLORS], 
+writeColormap(const char * const outname,
+              cixel_map          cmap[MAXCOLORS],
               unsigned int const ncolors) {
 
     {
@@ -297,8 +296,8 @@ writeColormap(const char * const outname,
         printf("\n");
         printf("value\n");
         for (i = 0; i < ncolors; ++i)
-            if (cmap[i].uilname != NULL && !cmap[i].transparent) 
-                printf("    %s : color( '%s' );\n", 
+            if (cmap[i].uilname != NULL && !cmap[i].transparent)
+                printf("    %s : color( '%s' );\n",
                        cmap[i].uilname, cmap[i].rgbname );
     }
     {
@@ -310,14 +309,14 @@ writeColormap(const char * const outname,
         printf("\n");
         printf("value\n");
         printf("  %s_rgb : color_table (\n", outname);
-        printedOne = FALSE; 
+        printedOne = FALSE;
         for (i = 0; i < ncolors; ++i)
             if (cmap[i].uilname != NULL) {
                 if (printedOne)
                     printf(",\n");
                 printf("    %s = '%s'", cmap[i].uilname, cmap[i].cixel);
                 printedOne = TRUE;
-            }     
+            }
         printf("\n");
         printf("    );\n");
     }
@@ -326,12 +325,12 @@ writeColormap(const char * const outname,
 
 
 static void
-writeRaster(struct pam *  const pamP, 
+writeRaster(struct pam *  const pamP,
             tuple **      const tuples,
             const char *  const outname,
-            cixel_map           cmap[MAXCOLORS], 
+            cixel_map           cmap[MAXCOLORS],
             unsigned int  const ncolors,
-            tuplehash     const cht, 
+            tuplehash     const cht,
             unsigned int  const charspp) {
 /*----------------------------------------------------------------------------
    Write out the ascii character-pixel image.
@@ -358,7 +357,7 @@ writeRaster(struct pam *  const pamP,
         if (row != pamP->height - 1)
             printf("',\n");
         else
-            printf("'\n"); 
+            printf("'\n");
     }
     printf(");\n");
     printf("\n");
@@ -433,3 +432,6 @@ main(int argc, char *argv[]) {
 
     return 0;
 }
+
+
+
diff --git a/converter/other/pamtowinicon.c b/converter/other/pamtowinicon.c
index 7df8f60d..4d73ccdf 100644
--- a/converter/other/pamtowinicon.c
+++ b/converter/other/pamtowinicon.c
@@ -47,7 +47,7 @@ parseCommandLine(int argc, const char **argv,
     opt3.short_allowed = false;
     opt3.allowNegNum   = false;
 
-    pm_optParseOptions3(&argc, (char **)argv, opt3, sizeof(opt3), 0);
+    pm_optParseOptions4(&argc, argv, opt3, sizeof(opt3), 0);
 
     if (pngthresholdSpec) {
         if (UINT_MAX / cmdlineP->pngthreshold < cmdlineP->pngthreshold)
@@ -177,6 +177,7 @@ get_rgbPixel(tuple **     const tuples,
 }
 
 
+
 static bool
 andMakesOpaque(const struct pam * const pamP,
                tuple **           const tuples,
@@ -701,7 +702,6 @@ blackenXor(const struct pam * const pamP,
 
 
 
-
 static void
 readAndScalePam(struct pam * const pamP,
                 bool         const doingPng,
@@ -974,6 +974,10 @@ convertOneImage(unsigned int     const imageNum,
 
     doingPng = pam.width * pam.height >= pngThreshold;
 
+    if (verbose)
+        pm_message("Image %2u: encoding as %s",
+                   imageNum, doingPng ? "PNG" : "BMP");
+
     readAndScalePam(&pam, doingPng, tuples);
 
     determineImageType(&pam, tuples, &getPixel,
diff --git a/converter/other/pamtoxvmini.c b/converter/other/pamtoxvmini.c
index b57bcc74..047de75a 100644
--- a/converter/other/pamtoxvmini.c
+++ b/converter/other/pamtoxvmini.c
@@ -23,16 +23,16 @@ typedef struct xvPalette {
 } xvPalette;
 
 
-struct cmdlineInfo {
+struct CmdlineInfo {
     const char * inputFileName;
 };
 
 
 
 static void
-parseCommandLine(int const argc,
-                 char *    argv[],
-                 struct cmdlineInfo * const cmdlineP) {
+parseCommandLine(int const                  argc,
+                 const char *               argv[],
+                 struct CmdlineInfo * const cmdlineP) {
 
     if (argc-1 < 1)
         cmdlineP->inputFileName = "-";
@@ -75,7 +75,7 @@ static void
 writeXvHeader(FILE *       const ofP,
               unsigned int const cols,
               unsigned int const rows) {
-           
+
     fprintf(ofP, "P7 332\n");
 
     fprintf(ofP, "# Created by Pamtoxvmini\n");
@@ -94,12 +94,14 @@ writeXvHeader(FILE *       const ofP,
 
 static void
 findClosestColor(struct pam *      const pamP,
-                 tuple             const tuple, 
+                 tuple             const tuple,
                  const xvPalette * const xvPaletteP,
                  unsigned int *    const paletteIndexP) {
 /*----------------------------------------------------------------------------
    Find the color in the palette *xvPaletteP that is closest to the color
    'tuple' and return its index in the palette.
+
+   *pamP gives the format of 'tuple', which must be RGB with maxval 255.
 -----------------------------------------------------------------------------*/
     unsigned int paletteIndex;
     unsigned int bestPaletteIndex;
@@ -118,12 +120,12 @@ findClosestColor(struct pam *      const pamP,
         unsigned int const tupleRed = tuple[PAM_RED_PLANE];
         unsigned int const tupleGrn = tuple[PAM_GRN_PLANE];
         unsigned int const tupleBlu = tuple[PAM_BLU_PLANE];
-        
+
         unsigned int const paletteRed = xvPaletteP->red[paletteIndex];
         unsigned int const paletteGrn = xvPaletteP->grn[paletteIndex];
         unsigned int const paletteBlu = xvPaletteP->blu[paletteIndex];
 
-        unsigned int const distance = 
+        unsigned int const distance =
             SQR((int)tupleRed - (int)paletteRed) +
             SQR((int)tupleGrn - (int)paletteGrn) +
             SQR((int)tupleBlu - (int)paletteBlu);
@@ -155,24 +157,29 @@ getPaletteIndexThroughCache(struct pam *      const pamP,
     int found;
     int paletteIndex;
 
+    /* As required by findClosestColor(): */
+    assert(pamP->depth >= 3);
+    assert(pamP->maxval == 255);
+
     pnm_lookuptuple(pamP, paletteHash, tuple, &found, &paletteIndex);
     if (found)
         *paletteIndexP = paletteIndex;
     else {
         int fits;
+
         findClosestColor(pamP, tuple, xvPaletteP, paletteIndexP);
-        
+
         pnm_addtotuplehash(pamP, paletteHash, tuple, *paletteIndexP, &fits);
-        
+
         if (!fits)
             pm_error("Can't get memory for palette hash.");
     }
 }
 
-    
+
 
 static void
-writeXvRaster(struct pam * const pamP,
+writeXvRaster(struct pam * const inpamP,
               xvPalette *  const xvPaletteP,
               FILE *       const ofP) {
 /*----------------------------------------------------------------------------
@@ -190,33 +197,40 @@ writeXvRaster(struct pam * const pamP,
     unsigned int row;
     unsigned char * xvrow;
     struct pam scaledPam;
+    struct pam scaledRgbPam;
+
+    pnm_setminallocationdepth(inpamP, 3);
 
     paletteHash = pnm_createtuplehash();
 
-    tuplerow = pnm_allocpamrow(pamP);
-    xvrow = (unsigned char*)pm_allocrow(pamP->width, 1);
+    tuplerow = pnm_allocpamrow(inpamP);
+    xvrow = (unsigned char*)pm_allocrow(inpamP->width, 1);
 
-    scaledPam = *pamP;
+    scaledPam = *inpamP;  /* initial value */
     scaledPam.maxval = 255;
 
-    for (row = 0; row < pamP->height; ++row) {
+    scaledRgbPam = scaledPam;  /* initial value */
+    scaledRgbPam.depth = MAX(3, scaledPam.depth);
+
+    for (row = 0; row < inpamP->height; ++row) {
         unsigned int col;
 
-        pnm_readpamrow(pamP, tuplerow);
-        pnm_scaletuplerow(pamP, tuplerow, tuplerow, scaledPam.maxval);
+        pnm_readpamrow(inpamP, tuplerow);
+        pnm_scaletuplerow(inpamP, tuplerow, tuplerow, scaledPam.maxval);
         pnm_makerowrgb(&scaledPam, tuplerow);
 
-        for (col = 0; col < scaledPam.width; ++col) {
+        for (col = 0; col < scaledRgbPam.width; ++col) {
             unsigned int paletteIndex;
 
-            getPaletteIndexThroughCache(&scaledPam, tuplerow[col], xvPaletteP,
-                                        paletteHash, &paletteIndex);
+            getPaletteIndexThroughCache(&scaledRgbPam, tuplerow[col],
+                                        xvPaletteP, paletteHash,
+                                        &paletteIndex);
 
             assert(paletteIndex < 256);
 
             xvrow[col] = paletteIndex;
         }
-        fwrite(xvrow, 1, scaledPam.width, ofP);
+        fwrite(xvrow, 1, scaledRgbPam.width, ofP);
     }
 
     pm_freerow((char*)xvrow);
@@ -227,16 +241,16 @@ writeXvRaster(struct pam * const pamP,
 
 
 
-int 
-main(int    argc,
-     char * argv[]) {
+int
+main(int          argc,
+     const char * argv[]) {
 
-    struct cmdlineInfo cmdline;
+    struct CmdlineInfo cmdline;
     FILE * ifP;
     struct pam pam;
     xvPalette xvPalette;
- 
-    pnm_init(&argc, argv);
+
+    pm_proginit(&argc, argv);
 
     parseCommandLine(argc, argv, &cmdline);
 
@@ -246,13 +260,14 @@ main(int    argc,
 
     pnm_readpaminit(ifP, &pam, PAM_STRUCT_SIZE(allocation_depth));
 
-    pnm_setminallocationdepth(&pam, 3);
-
     writeXvHeader(stdout, pam.width, pam.height);
-    
+
     writeXvRaster(&pam, &xvPalette, stdout);
 
     pm_close(ifP);
 
     return 0;
 }
+
+
+
diff --git a/converter/other/pbmtopgm.c b/converter/other/pbmtopgm.c
index 817fb5b3..8344bcf2 100644
--- a/converter/other/pbmtopgm.c
+++ b/converter/other/pbmtopgm.c
@@ -9,85 +9,121 @@
 #include "nstring.h"
 #include "pgm.h"
 
-int
-main(int argc, char *argv[]) {
 
-    gray *outrow, maxval;
-    int right, left, down, up;
-    bit **inbits;
-    int rows, cols;
-    FILE *ifd;
-    int row;
-    unsigned int width, height;
-    const char * const usage = "<w> <h> [pbmfile]";
-    const char * error; /* error message of pm_string_to_uint */
 
-    pgm_init( &argc, argv );
+struct CmdlineInfo {
+    unsigned int convCols;
+    unsigned int convRows;
+    const char * inputFileName;
+};
+
+
+
+static void
+parseCommandLine(int                  const argc,
+                 const char **        const argv,
+                 struct CmdlineInfo * const cmdlineP) {
+
+    const char * error; /* error message from pm_string_to_uint */
 
-    if (argc > 4 || argc < 3)
-        pm_usage(usage);
+    if (argc-1 < 2)
+        pm_error("Insufficient arguments (%d).  Need width and height "
+                 "of convolution kernel, in pixels", argc-1);
+    else {
+        pm_string_to_uint(argv[1], &cmdlineP->convCols, &error);
+        if (error)
+            pm_error("Invalid convolution kernel width argument.  %s", error);
 
-    pm_string_to_uint(argv[1], &width, &error);
-    if (error)
-        pm_error("Invalid width argument: %s", error);
-    pm_string_to_uint(argv[2], &height, &error);
-    if (error)
-        pm_error("Invalid height argument: %s", error);
-    if (width < 1 || height < 1)
-        pm_error("width and height must be > 0");
+        pm_string_to_uint(argv[2], &cmdlineP->convRows, &error);
+        if (error)
+            pm_error("Invalid convolution kernel height argument. %s", error);
+        if (cmdlineP->convCols < 1 || cmdlineP->convRows < 1)
+            pm_error("convolution kernel width and height must be > 0");
 
-    if (argc == 4)
-        ifd = pm_openr(argv[3]);
-    else
-        ifd = stdin ;
+        if (argc-1 >= 3)
+            cmdlineP->inputFileName = argv[3];
+        else {
+            cmdlineP->inputFileName = "-";
 
-    inbits = pbm_readpbm(ifd, &cols, &rows) ;
+            if (argc-1 > 3)
+                pm_error("Too many arguments (%d).  The most possible are "
+                         "convolution kernel width and height "
+                         "and input file name", argc-1);
+        }
+    }
+}
 
-    if (width > cols)
-        pm_error("You specified a sample width (%u columns) which is greater "
-                 "than the image width (%u columns)", height, rows);
-    if (height > rows)
-        pm_error("You specified a sample height (%u rows) which is greater "
-                 "than the image height (%u rows)", height, rows);
-    if (width > INT_MAX / height)
-        /* prevent overflow of "value" below */
-        pm_error("sample area (%u columns %u rows) too large",
-                 width, height);
 
-    left = width  / 2;  right = width  - left;
-    up   = height / 2;  down  = height - up;
 
+int
+main(int argc, const char ** argv) {
+
+    struct CmdlineInfo cmdline;
+    gray * outrow;
+    gray maxval;
+    unsigned int right, left, down, up;
+    bit ** inbits;
+    int rows, cols;
+    FILE * ifP;
+    unsigned int row;
 
+    pm_proginit(&argc, argv);
+
+    parseCommandLine(argc, argv, &cmdline);
+
+    ifP = pm_openr(cmdline.inputFileName);
+
+    inbits = pbm_readpbm(ifP, &cols, &rows);
+
+    if (cmdline.convCols > cols)
+        pm_error("You specified a convolution kernel width (%u columns) "
+                 "which is greater than the image width (%u columns)",
+                 cmdline.convCols, cols);
+    if (cmdline.convRows > rows)
+        pm_error("You specified a convolution kernel height (%u rows) "
+                 "which is greater than the image height (%u rows)",
+                 cmdline.convRows, rows);
+
+    left = cmdline.convCols / 2;  right = cmdline.convCols - left;
+    up   = cmdline.convRows / 2;  down  = cmdline.convRows - up;
 
     outrow = pgm_allocrow(cols) ;
-    maxval = MIN(PGM_OVERALLMAXVAL, width*height);
+    maxval = MIN(PGM_OVERALLMAXVAL, cmdline.convCols * cmdline.convRows);
     pgm_writepgminit(stdout, cols, rows, maxval, 0) ;
 
-    for (row = 0; row < rows; row++) {
-        int const t = (row > up) ? (row-up) : 0;
-        int const b = (row+down < rows) ? (row+down) : rows;
-        int const onv = height - (t-row+up) - (row+down-b);
+    for (row = 0; row < rows; ++row) {
+        unsigned int const t = (row > up) ? (row - up) : 0;
+        unsigned int const b = (row + down < rows) ? (row + down) : rows;
+        unsigned int const actualConvRows =
+            cmdline.convRows - (t - row + up) - (row + down - b);
         unsigned int col;
-        for (col = 0; col < cols; col++) {
-            int const l = (col > left) ? (col-left) : 0;
-            int const r = (col+right < cols) ? (col+right) : cols;
-            int const onh = width - (l-col+left) - (col+right-r);
-            int value;  /* See above */
-            int x;
-
-            value = 0;  /* initial value */
-
-            for (x = l; x < r; ++x) {
-                int y;
+        for (col = 0; col < cols; ++col) {
+            unsigned int const l = (col > left) ? (col - left) : 0;
+            unsigned int const r = (col + right < cols) ? (col + right) : cols;
+            unsigned int const actualConvCols =
+                cmdline.convCols - (l - col + left) - (col + right - r);
+            unsigned int value;
+            unsigned int x;
+
+            for (x = l, value = 0; x < r; ++x) {
+                unsigned int y;
                 for (y = t; y < b; ++y)
                     if (inbits[y][x] == PBM_WHITE)
                         ++value;
             }
-            outrow[col] = (gray) ((double) maxval*value/(onh*onv));
+            {
+                unsigned int const convKernelArea =
+                    actualConvRows * actualConvCols;
+                outrow[col] = (gray) (((double) value/convKernelArea)*maxval);
+            }
         }
         pgm_writepgmrow(stdout, outrow, cols, maxval, 0) ;
     }
-    pm_close(ifd);
+    pbm_freearray(inbits, rows);
+    pm_close(ifP);
 
     return 0;
 }
+
+
+
diff --git a/converter/other/pdbimgtopam.c b/converter/other/pdbimgtopam.c
index 67044109..55a2ec70 100644
--- a/converter/other/pdbimgtopam.c
+++ b/converter/other/pdbimgtopam.c
@@ -56,7 +56,7 @@ parseCommandLine(int argc, const char ** argv,
                  struct cmdlineInfo * const cmdlineP) {
 /*----------------------------------------------------------------------------
    parse program command line described in Unix standard form by argc
-   and argv.  Return the information in the options as *cmdlineP.  
+   and argv.  Return the information in the options as *cmdlineP.
 
    If command line is internally inconsistent (invalid options, etc.),
    issue error message to stderr and abort program.
@@ -64,9 +64,7 @@ parseCommandLine(int argc, const char ** argv,
    Note that the strings we return are stored in the storage that
    was passed to us as the argv array.  We also trash *argv.
 -----------------------------------------------------------------------------*/
-    optEntry *option_def;
-        /* Instructions to pm_optParseOptions3 on how to parse our options.
-         */
+    optEntry * option_def;   /* Used by OPTENT3 */
     optStruct3 opt;
 
     unsigned int option_def_index;
@@ -85,12 +83,12 @@ parseCommandLine(int argc, const char ** argv,
     opt.short_allowed = false;  /* We have no short (old-fashioned) options */
     opt.allowNegNum = false;  /* We have no parms that are negative numbers */
 
-    pm_optParseOptions3(&argc, (char **)argv, opt, sizeof(opt), 0);
+    pm_optParseOptions4(&argc, argv, opt, sizeof(opt), 0);
         /* Uses and sets argc, argv, and some of *cmdlineP and others. */
 
     if (!notefileSpec)
         cmdlineP->notefile = NULL;
-    
+
     if (argc-1 < 1)
         cmdlineP->inputFileName = "-";
     else if (argc-1 == 1)
@@ -152,7 +150,7 @@ decompress(const uint8_t * const compressed,
         const uint8_t * inP;
         uint8_t *       outP;
         size_t          bytesLeft;
-        
+
         for (bytesLeft = imageSize,
                  inP  = &compressed[0], outP = &uncompressed[0];
              bytesLeft > 0;
@@ -224,7 +222,7 @@ readCompressed(IMAGE *    const imgP,
          * this extra byte and ignore it by paying attention to
          * the image dimensions.
          */
-       size_t const maxCompressedSizeWithBloat = ipdb_img_size(imgP) * 2;
+       size_t const maxCompressedSizeWithBloat = ipdb_imgSize(imgP) * 2;
          /*
           * Provide a buffer large enough for the worst case.
           * See note in lib/util/runlength.c .
@@ -251,7 +249,7 @@ readCompressed(IMAGE *    const imgP,
          * Read to the indicated offset.
          */
         dataSize = end_offset - ftell(fP) + 1;
-        
+
         MALLOCARRAY(buffer, dataSize);
 
         if (buffer == NULL)
@@ -306,19 +304,20 @@ imageReadHeader(FILE *  const fileP,
         pm_message("  Y_anchor: %u", imgP->y_anchor);
         pm_message("  Width: %u", imgP->width);
         pm_message("  Height: %u", imgP->height);
-        pm_message("Pixels per byte: %u", ipdb_img_ppb(imgP));
+        pm_message("Pixels per byte: %u", ipdb_imgPpb(imgP));
         pm_message("Image size: %lu bytes",
-                   (unsigned long)ipdb_img_size(imgP));
+                   (unsigned long)ipdb_imgSize(imgP));
     }
 }
 
 
+
 static int
 imageReadData(FILE *   const fileP,
               IMAGE *  const imgP,
               uint32_t const end_offset) {
 
-    size_t const imageSize = ipdb_img_size(imgP);  
+    size_t const imageSize = ipdb_imgSize(imgP);
 
     int retval;
     size_t dataSize;
@@ -390,7 +389,7 @@ textRead(TEXT * const textP,
         return 0;
 
     textP->r->offset = (uint32_t)ftell(fileP);
-    
+
     /*
      * What a pain in the ass!  Why the hell isn't there a length
      * attached to the text record?  I suppose the designer wasn't
@@ -453,7 +452,7 @@ pdbheadRead(PDBHEAD * const pdbHeadP,
     pm_readbiglongu2(fileP, &pdbHeadP->next_rec);
     pm_readbigshortu(fileP, &pdbHeadP->num_recs);
 
-    if (!memeq(pdbHeadP->type, IPDB_vIMG, 4) 
+    if (!memeq(pdbHeadP->type, IPDB_vIMG, 4)
         || !memeq(pdbHeadP->id, IPDB_View, 4))
         retval = E_NOTIMAGE;
     else
@@ -531,62 +530,54 @@ ipdbRead(IPDB * const pdbP,
 
     int retval;
 
-    ipdb_clear(pdbP);
+    int status;
 
-    pdbP->p = ipdb_pdbhead_alloc(NULL);
+    status = pdbheadRead(pdbP->p, fileP);
 
-    if (pdbP->p == NULL)
-        retval = ENOMEM;
+    if (status != 0)
+        retval = status;
     else {
-        int status;
-
-        status = pdbheadRead(pdbP->p, fileP);
-
-        if (status != 0)
-            retval = status;
+        pdbP->i = ipdb_imageCreate(pdbP->p->name, IMG_GRAY, 0, 0);
+        if (pdbP->i == NULL)
+            retval = ENOMEM;
         else {
-            pdbP->i = ipdb_image_alloc(pdbP->p->name, IMG_GRAY, 0, 0);
-            if (pdbP->i == NULL)
-                retval = ENOMEM;
+            int status;
+            status = rechdrRead(pdbP->i->r, fileP);
+            if (status != 0)
+                retval = status;
             else {
-                int status;
-                status = rechdrRead(pdbP->i->r, fileP);
-                if (status != 0)
-                    retval = status;
-                else {
-                    if (pdbP->p->num_recs > 1) {
-                        pdbP->t = ipdb_text_alloc(NULL);
-                        if (pdbP->t == NULL)
-                            retval = ENOMEM;
-                        else {
-                            int status;
-                            status = rechdrRead(pdbP->t->r, fileP);
-                            if (status != 0)
-                                retval = status;
-                            else
-                                retval = 0;
-                        }
-                    } else
-                        retval = 0;
-                    
-                    if (retval == 0) {
-                        uint32_t const offset =
-                            pdbP->t == NULL ?
-                            UNKNOWN_OFFSET : pdbP->t->r->offset - 1;
-
+                if (pdbP->p->num_recs > 1) {
+                    pdbP->t = ipdb_textAlloc();
+                    if (pdbP->t == NULL)
+                        retval = ENOMEM;
+                    else {
                         int status;
-
-                        status = imageRead(pdbP->i, offset, fileP, verbose);
+                        status = rechdrRead(pdbP->t->r, fileP);
                         if (status != 0)
                             retval = status;
-                        else {
-                            if (pdbP->t != NULL) {
-                                int status;
-                                
-                                status = textRead(pdbP->t, fileP);
-                                if (status != 0)
-                                    retval = status;
-                            }
+                        else
+                            retval = 0;
+                    }
+                } else
+                    retval = 0;
+
+                if (retval == 0) {
+                    uint32_t const offset =
+                        pdbP->t == NULL ?
+                        UNKNOWN_OFFSET : pdbP->t->r->offset - 1;
+
+                    int status;
+
+                    status = imageRead(pdbP->i, offset, fileP, verbose);
+                    if (status != 0)
+                        retval = status;
+                    else {
+                        if (pdbP->t != NULL) {
+                            int status;
+
+                            status = textRead(pdbP->t, fileP);
+                            if (status != 0)
+                                retval = status;
                         }
                     }
                 }
@@ -663,8 +654,8 @@ static void
 g16row(IPDB *       const pdbP,
        unsigned int const row,
        uint8_t *    const buffer) {
-    
-    g16unpack(ipdb_img_row(pdbP->i, row), buffer, ipdb_width(pdbP));
+
+    g16unpack(ipdb_imgRow(pdbP->i, row), buffer, ipdb_width(pdbP));
 }
 
 
@@ -674,7 +665,7 @@ grow(IPDB *       const pdbP,
      unsigned int const row,
      uint8_t *    const buffer) {
 
-    gunpack(ipdb_img_row(pdbP->i, row), buffer, ipdb_width(pdbP));
+    gunpack(ipdb_imgRow(pdbP->i, row), buffer, ipdb_width(pdbP));
 }
 
 
@@ -684,7 +675,7 @@ mrow(IPDB *       const pdbP,
      unsigned int const row,
      uint8_t *    const buffer) {
 
-    munpack(ipdb_img_row(pdbP->i, row), buffer, ipdb_width(pdbP));
+    munpack(ipdb_imgRow(pdbP->i, row), buffer, ipdb_width(pdbP));
 }
 
 
@@ -715,7 +706,7 @@ writeImgPam(IPDB * const pdbP,
            PAM_PBM_TUPLETYPE : PAM_PGM_TUPLETYPE);
 
     pnm_writepaminit(&pam);
-    
+
     tupleRow = pnm_allocpamrow(&pam);
 
     for (row = 0; row < pam.height; ++row) {
@@ -731,7 +722,7 @@ writeImgPam(IPDB * const pdbP,
 
         for (col = 0; col < pam.width; ++col)
             tupleRow[col][0] = imgRow[col];
-        
+
         pnm_writepamrow(&pam, tupleRow);
     }
     pnm_freepamrow(tupleRow);
@@ -754,7 +745,7 @@ writeText(IPDB *       const pdbP,
         fP = pm_openw(name);
         if (fP == NULL)
             pm_error("Could not open note file '%s' for output", name);
-        
+
         fprintf(fP, "%s\n", note);
 
         pm_close(fP);
@@ -777,7 +768,7 @@ main(int argc, const char ** argv) {
 
     ifP = pm_openr(cmdline.inputFileName);
 
-    pdbP = ipdb_alloc(NULL);
+    pdbP = ipdb_alloc();
     if (pdbP == NULL)
         pm_error("Could not allocate IPDB structure.");
 
@@ -795,3 +786,6 @@ main(int argc, const char ** argv) {
 
     return EXIT_SUCCESS;
 }
+
+
+
diff --git a/converter/other/pfmtopam.c b/converter/other/pfmtopam.c
index 080ec7ff..7e26d9c2 100644
--- a/converter/other/pfmtopam.c
+++ b/converter/other/pfmtopam.c
@@ -2,7 +2,7 @@
                                   pfmtopam
 ******************************************************************************
   This program converts a PFM (Portable Float Map) image to PAM.
-  
+
   By Bryan Henderson, San Jose, CA April 2004.
 
   Contributed to the public domain by its author.
@@ -30,13 +30,13 @@ struct cmdlineInfo {
 
 
 
-static void 
-parseCommandLine(int argc, 
-                 char ** argv, 
+static void
+parseCommandLine(int argc,
+                 char ** argv,
                  struct cmdlineInfo  * const cmdlineP) {
 /* --------------------------------------------------------------------------
    Parse program command line described in Unix standard form by argc
-   and argv.  Return the information in the options as *cmdlineP.  
+   and argv.  Return the information in the options as *cmdlineP.
 
    If command line is internally inconsistent (invalid options, etc.),
    issue error message to stderr and abort program.
@@ -47,14 +47,14 @@ parseCommandLine(int argc,
     optEntry *option_def = malloc( 100*sizeof( optEntry ) );
     /* Instructions to pm_optParseOptions3 on how to parse our options. */
     optStruct3 opt;
-  
+
     unsigned int option_def_index;
     unsigned int maxvalSpec;
 
     option_def_index = 0;   /* incremented by OPTENTRY */
     OPTENT3(0, "maxval",   OPT_UINT, &cmdlineP->maxval, &maxvalSpec,        0);
     OPTENT3(0, "verbose",  OPT_FLAG, NULL,             &cmdlineP->verbose, 0);
-  
+
     opt.opt_table = option_def;
     opt.short_allowed = FALSE;  /* We have no short (old-fashioned) options */
     opt.allowNegNum = FALSE;   /* We have no parms that are negative numbers */
@@ -77,13 +77,14 @@ parseCommandLine(int argc,
         cmdlineP->inputFilespec = argv[1];
     else
         cmdlineP->inputFilespec = "-";
-    
+
     if (argc-1 > 1)
         pm_error("Program takes at most one argument:  the file name.  "
                  "You specified %d", argc-1);
 }
 
 
+
 enum endian {ENDIAN_BIG, ENDIAN_LITTLE};
 
 
@@ -99,7 +100,7 @@ thisMachineEndianness(void) {
    that varies among typical machines.
 
    Big endianness is the natural format.  In this format, if an integer is
-   4 bytes, to be stored at memory address 100-103, the most significant 
+   4 bytes, to be stored at memory address 100-103, the most significant
    byte goes at 100, the next most significant at 101, and the least
    significant byte at 103.  This is natural because it matches the way
    humans read and write numbers.  I.e. 258 is stored as 0x00000102.
@@ -115,7 +116,7 @@ thisMachineEndianness(void) {
 
     unsigned char * const storedNumber = (unsigned char *)&testNumber;
     enum endian endianness;
-    
+
     if (storedNumber[0] == 0x01)
         endianness = ENDIAN_LITTLE;
     else
@@ -137,7 +138,7 @@ typedef union {
 
 
 static float
-floatFromPfmSample(pfmSample   const sample, 
+floatFromPfmSample(pfmSample   const sample,
                    enum endian const pfmEndianness) {
 /*----------------------------------------------------------------------------
    Type converter
@@ -147,11 +148,11 @@ floatFromPfmSample(pfmSample   const sample,
     } else {
         pfmSample rightEndianSample;
         unsigned int i, j;
-        
-        for (i = 0, j = sizeof(sample.bytes)-1; 
-             i < sizeof(sample.bytes); 
+
+        for (i = 0, j = sizeof(sample.bytes)-1;
+             i < sizeof(sample.bytes);
              ++i, --j)
-            
+
             rightEndianSample.bytes[i] = sample.bytes[j];
 
         return rightEndianSample.value;
@@ -203,7 +204,7 @@ readPfmHeader(FILE *             const ifP,
         int rc;
         char whitespace;
 
-        rc = fscanf(ifP, "%u %u%c", 
+        rc = fscanf(ifP, "%u %u%c",
                     &pfmHeaderP->width, &pfmHeaderP->height, &whitespace);
 
         if (rc == EOF)
@@ -213,7 +214,7 @@ readPfmHeader(FILE *             const ifP,
                      "are supposed to be (should be two positive decimal "
                      "integers separated by a space and followed by "
                      "white space)");
-        
+
         if (!isspace(whitespace))
             pm_error("Invalid input file format -- '%c' instead of "
                      "white space after height", whitespace);
@@ -235,13 +236,13 @@ readPfmHeader(FILE *             const ifP,
             pm_error("Invalid input file format where scale factor "
                      "is supposed to be (should be a floating point decimal "
                      "number followed by white space");
-        
+
         if (!isspace(whitespace))
             pm_error("Invalid input file format -- '%c' instead of "
                      "white space after scale factor", whitespace);
     }
 
-    pfmHeaderP->color = (secondChar == 'F');  
+    pfmHeaderP->color = (secondChar == 'F');
         /* 'PF' = RGB, 'Pf' = monochrome */
 
     if (scaleFactorEndian > 0.0) {
@@ -255,12 +256,13 @@ readPfmHeader(FILE *             const ifP,
 }
 
 
+
 static void
 dumpPfmHeader(struct pfmHeader const pfmHeader) {
 
     pm_message("width: %u, height: %u", pfmHeader.width, pfmHeader.height);
     pm_message("color: %s", pfmHeader.color ? "YES" : "NO");
-    pm_message("endian: %s", 
+    pm_message("endian: %s",
                pfmHeader.endian == ENDIAN_BIG ? "BIG" : "LITTLE");
     pm_message("scale factor: %f", pfmHeader.scaleFactor);
 }
@@ -268,9 +270,9 @@ dumpPfmHeader(struct pfmHeader const pfmHeader) {
 
 
 static void
-initPam(struct pam * const pamP, 
-        int          const width, 
-        int          const height, 
+initPam(struct pam * const pamP,
+        int          const width,
+        int          const height,
         bool         const color,
         sample       const maxval) {
 
@@ -306,7 +308,7 @@ makePamRow(struct pam * const pamP,
    Make a PAM (tuple) row of the form described by *pamP, from the next
    row in the PFM file identified by 'ifP'.  Place it in the proper location
    in the tuple array 'tuplenArray'.
-  
+
    'endian' is the endianness of the samples in the PFM file.
 
    'pfmRowNum' is the sequence number (starting at 0, which is the
@@ -333,7 +335,7 @@ makePamRow(struct pam * const pamP,
         /* The order of planes (R, G, B) is the same in PFM as in PAM. */
         unsigned int plane;
         for (plane = 0; plane < pamP->depth; ++plane) {
-            float const val = 
+            float const val =
                 floatFromPfmSample(pfmRowBuffer[pfmCursor++], endian);
             tuplenRow[col][plane] = val / scaleFactor;
         }
@@ -368,14 +370,14 @@ main(int argc, char **argv ) {
     if (cmdline.verbose)
         dumpPfmHeader(pfmHeader);
 
-    initPam(&pam, 
+    initPam(&pam,
             pfmHeader.width, pfmHeader.height, pfmHeader.color,
             cmdline.maxval);
 
     tuplenArray = pnm_allocpamarrayn(&pam);
 
     pfmSamplesPerRow = pam.width * pam.depth;
-    
+
     MALLOCARRAY_NOFAIL(pfmRowBuffer, pfmSamplesPerRow);
 
     /* PFMs are upside down like BMPs */
@@ -388,9 +390,12 @@ main(int argc, char **argv ) {
 
     pnm_freepamarrayn(tuplenArray, &pam);
     free(pfmRowBuffer);
-    
+
     pm_close(ifP);
     pm_close(pam.file);
 
     return 0;
 }
+
+
+
diff --git a/converter/other/pgmtopbm.c b/converter/other/pgmtopbm.c
index 64dc814b..b71904d8 100644
--- a/converter/other/pgmtopbm.c
+++ b/converter/other/pgmtopbm.c
@@ -17,6 +17,7 @@
 #include "pgm.h"
 #include "dithers.h"
 #include "mallocvar.h"
+#include "rand.h"
 
 enum halftone {QT_FS, QT_THRESH, QT_DITHER8, QT_CLUSTER, QT_HILBERT};
 
@@ -46,9 +47,7 @@ parseCommandLine(int argc, const char ** argv,
    Note that the file spec array we return is stored in the storage that
    was passed to us as the argv array.
 -----------------------------------------------------------------------------*/
-    optEntry *option_def;
-        /* Instructions to pm_optParseOptions3 on how to parse our options.
-         */
+    optEntry * option_def;   /* Used by OPTENT3 */
     optStruct3 opt;
 
     unsigned int option_def_index;
@@ -82,7 +81,7 @@ parseCommandLine(int argc, const char ** argv,
     opt.short_allowed = FALSE;  /* We have no short (old-fashioned) options */
     opt.allowNegNum = FALSE;  /* We may have parms that are negative numbers */
 
-    pm_optParseOptions3(&argc, (char **)argv, opt, sizeof(opt), 0);
+    pm_optParseOptions4(&argc, argv, opt, sizeof(opt), 0);
         /* Uses and sets argc, argv, and some of *cmdlineP and others. */
 
     if (floydOpt + thresholdOpt + hilbertOpt + dither8Opt +
@@ -462,14 +461,19 @@ createFsConverter(unsigned int const cols,
     /* Initialize Floyd-Steinberg error vectors. */
     MALLOCARRAY_NOFAIL(stateP->thiserr, cols + 2);
     MALLOCARRAY_NOFAIL(stateP->nexterr, cols + 2);
-    srand(randomSeedSpec ? randomSeed : pm_randseed());
 
     {
         /* (random errors in [-fs_scale/8 .. fs_scale/8]) */
         unsigned int col;
+        struct pm_randSt randSt;
+        pm_randinit(&randSt);
+        pm_srand2(&randSt, randomSeedSpec, randomSeed);
+
         for (col = 0; col < cols + 2; ++col)
             stateP->thiserr[col] =
-                (long)(rand() % fs_scale - half_fs_scale) / 4;
+                (long)(pm_rand(&randSt) % fs_scale - half_fs_scale) / 4;
+
+        pm_randterm(&randSt);
     }
 
     stateP->fs_forward = TRUE;
diff --git a/converter/other/pgmtoppm.c b/converter/other/pgmtoppm.c
index c3a26594..822ddac7 100644
--- a/converter/other/pgmtoppm.c
+++ b/converter/other/pgmtoppm.c
@@ -17,27 +17,30 @@
 
 #include "pm_c_util.h"
 #include "mallocvar.h"
+#include "nstring.h"
 #include "shhopt.h"
 #include "ppm.h"
 
-struct cmdlineInfo {
+struct CmdlineInfo {
     /* All the information the user supplied in the command line,
        in a form easy for the program to use.
     */
     const char * inputFilename;  /* '-' if stdin */
     const char * map;
-    const char * colorBlack;
-    const char * colorWhite;
+    const char * colorBlack;  /* malloc'ed */
+        /* The color to which the user says to map black */
+    const char * colorWhite;  /* malloc'ed */
+        /* The color to which the user says to map white */
 };
 
 
 
 static void
-parseCommandLine(int argc, char ** argv,
-                 struct cmdlineInfo * const cmdlineP) {
+parseCommandLine(int argc, const char ** argv,
+                 struct CmdlineInfo * const cmdlineP) {
 /*----------------------------------------------------------------------------
    parse program command line described in Unix standard form by argc
-   and argv.  Return the information in the options as *cmdlineP.  
+   and argv.  Return the information in the options as *cmdlineP.
 
    If command line is internally inconsistent (invalid options, etc.),
    issue error message to stderr and abort program.
@@ -45,18 +48,23 @@ parseCommandLine(int argc, char ** argv,
    Note that the strings we return are stored in the storage that
    was passed to us as the argv array.  We also trash *argv.
 -----------------------------------------------------------------------------*/
-    optEntry *option_def;
-        /* Instructions to pm_optParseOptions3 on how to parse our options.
-         */
+    optEntry * option_def;   /* Used by OPTENT3 */
     optStruct3 opt;
 
     unsigned int option_def_index;
 
-    unsigned int mapSpec;
+    unsigned int blackSpec, whiteSpec, mapSpec;
+
+    const char * blackOpt;
+    const char * whiteOpt;
 
     MALLOCARRAY_NOFAIL(option_def, 100);
 
     option_def_index = 0;   /* incremented by OPTENT3 */
+    OPTENT3(0, "black",          OPT_STRING,    &blackOpt,
+            &blackSpec,          0);
+    OPTENT3(0, "white",          OPT_STRING,    &whiteOpt,
+            &whiteSpec,          0);
     OPTENT3(0, "map",            OPT_STRING,    &cmdlineP->map,
             &mapSpec,            0);
 
@@ -64,13 +72,19 @@ parseCommandLine(int argc, char ** argv,
     opt.short_allowed = FALSE;  /* We have no short (old-fashioned) options */
     opt.allowNegNum = FALSE;  /* We have no parms that are negative numbers */
 
-    pm_optParseOptions3(&argc, argv, opt, sizeof(opt), 0);
-        /* Uses and sets argc, argv, and some of *cmdlineP and others. */
+    pm_optParseOptions4(&argc, argv, opt, sizeof(opt), 0);
 
     if (!mapSpec)
         cmdlineP->map = NULL;
 
     if (mapSpec) {
+        if (blackSpec || whiteSpec)
+            pm_error("You may not specify -black or -white "
+                     "together with -map");
+
+        cmdlineP->colorBlack = NULL;
+        cmdlineP->colorWhite = NULL;
+
         /* No color argument; only argument is file name */
         if (argc-1 < 1)
             cmdlineP->inputFilename = "-";
@@ -81,37 +95,77 @@ parseCommandLine(int argc, char ** argv,
                          "the file name.  You specified %u", argc-1);
         }
     } else {
-        /* Arguments are color or color range and file name */
-        if (argc-1 < 1) {
-            cmdlineP->colorBlack = "black";
-            cmdlineP->colorWhite = "white";
+        /* For default colors, we use "rgbi:..." instead of the simpler
+           "black" and "white" so that we don't have an unnecessary dependency
+           on a color dictionary being available.
+        */
+        if (blackSpec || whiteSpec) {
+            cmdlineP->colorBlack =
+                pm_strdup(blackSpec ? blackOpt : "rgbi:0/0/0");
+            cmdlineP->colorWhite =
+                pm_strdup(whiteSpec ? whiteOpt : "rgbi:1/1/1");
+
+            /* The only possibly argument is input file name */
+            if (argc-1 < 1)
+                cmdlineP->inputFilename = "-";
+            else {
+                cmdlineP->inputFilename = argv[1];
+                if (argc-1 > 1)
+                    pm_error("Whten you specify -black or -white, "
+                             "there can be at most one non-option arguments:  "
+                             "the file name.  "
+                             "You specified %u", argc-1);
+            }
         } else {
-            char * buffer = strdup(argv[1]);
-            char * hyphenPos = strchr(buffer, '-');
-            if (hyphenPos) {
-                *hyphenPos = '\0';
-                cmdlineP->colorBlack = buffer;
-                cmdlineP->colorWhite = hyphenPos+1;
+            /* Arguments are color or color range and optional file name */
+
+            if (argc-1 < 1) {
+                cmdlineP->colorBlack = pm_strdup("rgbi:0/0/0");
+                cmdlineP->colorWhite = pm_strdup("rgbi:1/1/1");
             } else {
-                cmdlineP->colorBlack = "black";
-                cmdlineP->colorWhite = buffer;
+                char * buffer = strdup(argv[1]);
+                if (!buffer)
+                    pm_error("Out of memory allocating tiny buffer");
+                char * hyphenPos = strchr(buffer, '-');
+                if (hyphenPos) {
+                    *hyphenPos = '\0';
+                    cmdlineP->colorBlack = pm_strdup(buffer);
+                    cmdlineP->colorWhite = pm_strdup(hyphenPos+1);
+                } else {
+                    cmdlineP->colorBlack = pm_strdup("rgbi:0/0/0");
+                    cmdlineP->colorWhite = pm_strdup(buffer);
+                }
+                free(buffer);
+            }
+
+            if (argc-1 < 2)
+                cmdlineP->inputFilename = "-";
+            else {
+                cmdlineP->inputFilename = argv[2];
+
+                if (argc-1 > 2)
+                    pm_error("Program takes at most 2 arguments:  "
+                             "color name/range and input file name.  "
+                             "You specified %u", argc-1);
             }
         }
-        if (argc-1 < 2)
-            cmdlineP->inputFilename = "-";
-        else
-            cmdlineP->inputFilename = argv[2];
-        
-        if (argc-1 > 2)
-            pm_error("Program takes at most 2 arguments:  "
-                     "color name/range and input file name.  "
-                     "You specified %u", argc-1);
     }
 }
 
 
 
 static void
+freeCommandLine(struct CmdlineInfo const cmdline) {
+
+    if (cmdline.colorBlack)
+        pm_strfree(cmdline.colorBlack);
+    if (cmdline.colorWhite)
+        pm_strfree(cmdline.colorWhite);
+}
+
+
+
+static void
 convertWithMap(FILE * const ifP,
                unsigned int const cols,
                unsigned int const rows,
@@ -128,7 +182,7 @@ convertWithMap(FILE * const ifP,
     pixval mapmaxval;
     pixel ** mappixels;
     unsigned int mapmaxcolor;
-    
+
     mapFileP = pm_openr(mapFileName);
     mappixels = ppm_readppm(mapFileP, &mapcols, &maprows, &mapmaxval);
     pm_close(mapFileP);
@@ -138,7 +192,7 @@ convertWithMap(FILE * const ifP,
 
     for (row = 0; row < rows; ++row) {
         unsigned int col;
-            
+
         pgm_readpgmrow(ifP, grayrow, cols, maxval, format);
 
         for (col = 0; col < cols; ++col) {
@@ -168,22 +222,20 @@ convertLinear(FILE * const ifP,
               gray *       const grayrow,
               pixel *      const pixelrow) {
 
-    pixel colorBlack, colorWhite;
-    pixval red0, grn0, blu0, red1, grn1, blu1;
+    pixel const colorBlack = ppm_parsecolor(colorNameBlack, maxval);
+    pixel const colorWhite = ppm_parsecolor(colorNameWhite, maxval);
+
+    pixval const red0 = PPM_GETR(colorBlack);
+    pixval const grn0 = PPM_GETG(colorBlack);
+    pixval const blu0 = PPM_GETB(colorBlack);
+    pixval const red1 = PPM_GETR(colorWhite);
+    pixval const grn1 = PPM_GETG(colorWhite);
+    pixval const blu1 = PPM_GETB(colorWhite);
+
     unsigned int row;
 
     ppm_writeppminit(ofP, cols, rows, maxval, 0);
 
-    colorBlack = ppm_parsecolor(colorNameBlack, maxval);
-    colorWhite = ppm_parsecolor(colorNameWhite, maxval);
- 
-    red0 = PPM_GETR(colorBlack);
-    grn0 = PPM_GETG(colorBlack);
-    blu0 = PPM_GETB(colorBlack);
-    red1 = PPM_GETR(colorWhite);
-    grn1 = PPM_GETG(colorWhite);
-    blu1 = PPM_GETB(colorWhite);
-
     for (row = 0; row < rows; ++row) {
         unsigned int col;
 
@@ -204,17 +256,17 @@ convertLinear(FILE * const ifP,
 
 
 int
-main(int    argc,
-     char * argv[]) {
+main(int          argc,
+     const char * argv[]) {
 
     FILE * ifP;
-    struct cmdlineInfo cmdline;
+    struct CmdlineInfo cmdline;
     gray * grayrow;
     pixel * pixelrow;
     int rows, cols, format;
     gray maxval;
 
-    ppm_init(&argc, argv);
+    pm_proginit(&argc, argv);
 
     parseCommandLine(argc, argv, &cmdline);
 
@@ -228,7 +280,7 @@ main(int    argc,
         convertWithMap(ifP, cols, rows, maxval, format, cmdline.map,
                        stdout, grayrow, pixelrow);
     else
-        convertLinear(ifP, cols, rows, maxval, format, 
+        convertLinear(ifP, cols, rows, maxval, format,
                       cmdline.colorBlack, cmdline.colorWhite, stdout,
                       grayrow, pixelrow);
 
@@ -236,8 +288,13 @@ main(int    argc,
     pgm_freerow(grayrow);
     pm_close(ifP);
 
+    freeCommandLine(cmdline);
+
     /* If the program failed, it previously aborted with nonzero completion
        code, via various function calls.
     */
     return 0;
 }
+
+
+
diff --git a/converter/other/pm_tiff.h b/converter/other/pm_tiff.h
index f98110e3..f6fb8403 100644
--- a/converter/other/pm_tiff.h
+++ b/converter/other/pm_tiff.h
@@ -18,7 +18,7 @@ typedef struct tagDefinition {
    This is the definition of a type of tag, e.g. ORIENTATION.
 -----------------------------------------------------------------------------*/
     const char * name;
-        /* The name by which our user knows the tag type, e.g. 
+        /* The name by which our user knows the tag type, e.g.
            "ORIENTATION"
         */
     unsigned int tagnum;
diff --git a/converter/other/pngtopam.c b/converter/other/pngtopam.c
index 9098154a..acb04599 100644
--- a/converter/other/pngtopam.c
+++ b/converter/other/pngtopam.c
@@ -22,10 +22,6 @@
 #include <math.h>
 #include <float.h>
 #include <png.h>
-/* Because of a design error in png.h, you must not #include <setjmp.h> before
-   <png.h>.  If you do, png.h won't compile.
-*/
-#include <setjmp.h>
 #include <zlib.h>
 
 
@@ -77,9 +73,7 @@ parseCommandLine(int                  argc,
    Note that the strings we return are stored in the storage that
    was passed to us as the argv array.  We also trash *argv.
 -----------------------------------------------------------------------------*/
-    optEntry * option_def;
-        /* Instructions to pm_optParseOptions3 on how to parse our options.
-         */
+    optEntry * option_def;   /* Used by OPTENT3 */
     optStruct3 opt;
 
     unsigned int option_def_index;
@@ -113,7 +107,7 @@ parseCommandLine(int                  argc,
     opt.short_allowed = FALSE;  /* We have no short (old-fashioned) options */
     opt.allowNegNum = FALSE;  /* We have no parms that are negative numbers */
 
-    pm_optParseOptions3(&argc, (char **)argv, opt, sizeof(opt), 0);
+    pm_optParseOptions4(&argc, argv, opt, sizeof(opt), 0);
         /* Uses and sets argc, argv, and some of *cmdlineP and others. */
 
 
@@ -668,10 +662,16 @@ dumpPngInfo(struct pngx * const pngxP) {
                    background.blue);
     }
 
-    if (pngx_chunkIsPresent(pngxP, PNG_INFO_tRNS))
-        pm_message("tRNS chunk (transparency): %u entries",
-                   pngx_trns(pngxP).numTrans);
-    else
+    if (pngx_chunkIsPresent(pngxP, PNG_INFO_tRNS)) {
+        struct pngx_trns const trns = pngx_trns(pngxP);
+
+        pm_message("tRNS chunk (transparency):");
+        pm_message("  %u palette entries", trns.numTrans);
+        pm_message("  transparent color = (%u,%u,%u)",
+                   trns.transColor.red,
+                   trns.transColor.green,
+                   trns.transColor.blue);
+    } else
         pm_message("tRNS chunk (transparency): not present");
 
     if (pngx_chunkIsPresent(pngxP, PNG_INFO_gAMA))
@@ -868,17 +868,17 @@ paletteHasPartialTransparency(struct pngx * const pngxP) {
         if (pngx_chunkIsPresent(pngxP, PNG_INFO_tRNS)) {
             struct pngx_trns const trans = pngx_trns(pngxP);
 
-            bool foundGray;
+            bool foundPartial;
             unsigned int i;
 
-            for (i = 0, foundGray = FALSE;
-                 i < trans.numTrans && !foundGray;
+            for (i = 0, foundPartial = FALSE;
+                 i < trans.numTrans && !foundPartial;
                  ++i) {
                 if (trans.trans[i] != 0 && trans.trans[i] != pngxP->maxval) {
-                    foundGray = TRUE;
+                    foundPartial = TRUE;
                 }
             }
-            retval = foundGray;
+            retval = foundPartial;
         } else
             retval = FALSE;
     } else
@@ -1459,15 +1459,11 @@ convertpng(FILE *             const ifP,
     pngcolor bgColor;
     GammaCorrection gamma;
     struct pam pam;
-    jmp_buf jmpbuf;
     struct pngx * pngxP;
 
     *errorLevelP = 0;
 
-    if (setjmp(jmpbuf))
-        pm_error ("setjmp returns error condition");
-
-    pngx_create(&pngxP, PNGX_READ, &jmpbuf);
+    pngx_create(&pngxP, PNGX_READ, NULL);
 
     pngx_readStart(pngxP, ifP);
 
diff --git a/converter/other/pngtxt.c b/converter/other/pngtxt.c
index e02ee227..cf331bd9 100644
--- a/converter/other/pngtxt.c
+++ b/converter/other/pngtxt.c
@@ -32,15 +32,15 @@ readToken(char           const textline[],
     unsigned int cursor;
 
     cursor = *cursorP;
-    
+
     MALLOCARRAY(tokenBuffer, lineLength + 1);
     /* leave room for terminating NUL */
-    if (tokenBuffer == NULL) 
+    if (tokenBuffer == NULL)
         pm_error("Unable to allocate memory for a %u-character "
                  "text string file line", lineLength);
 
     cp = &tokenBuffer[0];  /* initial value */
-    
+
     if (textline[0] == '"') {
         ++cursor;  /* skip past opening quotation mark */
         while (textline[cursor] != '"') {
@@ -56,9 +56,9 @@ readToken(char           const textline[],
         }
         ++cursor;  /* skip past closing quotation mark */
     } else {
-        while ((cursor < lineLength) && 
+        while ((cursor < lineLength) &&
                (textline[cursor] != ' ') && (textline[cursor] != '\t')) {
-            
+
             if (textline[cursor] == '\0')
                 pm_error("Invalid text string file format:  Token contains "
                          "a NUL character.  Text leading up to the NUL "
@@ -75,7 +75,6 @@ readToken(char           const textline[],
 
 
 
-
 static void
 skipWhiteSpace(char           const textline[],
                unsigned int   const lineLength,
@@ -88,7 +87,7 @@ skipWhiteSpace(char           const textline[],
 
     cursor = *cursorP;  /* initial value */
 
-    while (cursor < lineLength && 
+    while (cursor < lineLength &&
            (textline[cursor] == ' ' || textline[cursor] == '\t' ||
             textline[cursor] == '\0'))
         ++cursor;
@@ -113,7 +112,7 @@ readTextString(char          const textline[],
     char * cp;
 
     MALLOCARRAY(cp, lineLength + 1);  /* incl '\0' */
-    if (!cp) 
+    if (!cp)
         pm_error("Unable to allocate memory for text chunks");
 
     memcpy(cp, textline + startPos, lineLength - startPos);
@@ -125,7 +124,7 @@ readTextString(char          const textline[],
 
 
 static void
-startTextChunkEngl(png_text *   const textChunkP, 
+startTextChunkEngl(png_text *   const textChunkP,
                    char         const textline[],
                    unsigned int const lineLength,
                    bool         const isCompressed,
@@ -169,7 +168,7 @@ startTextChunkEngl(png_text *   const textChunkP,
 
 
 static void
-startTextChunkIntl(png_text *   const textChunkP, 
+startTextChunkIntl(png_text *   const textChunkP,
                    char         const textline[],
                    unsigned int const lineLength,
                    bool         const isCompressed,
@@ -219,7 +218,7 @@ startTextChunkIntl(png_text *   const textChunkP,
 
     {
         const char * langKey;
-    
+
         readToken(textline, lineLength, &cursor, &langKey);
 
         pngx_setTextLangKey(textChunkP, langKey);
@@ -233,14 +232,14 @@ startTextChunkIntl(png_text *   const textChunkP,
     readTextString(textline, lineLength, cursor, &textChunkP->text,
                    &textChunkP->text_length);
 
-    textChunkP->compression = 
+    textChunkP->compression =
         isCompressed ? PNG_ITXT_COMPRESSION_zTXt :PNG_ITXT_COMPRESSION_NONE;
 }
 
 
 
 static void
-continueTextString(png_text *   const textChunkP, 
+continueTextString(png_text *   const textChunkP,
                    char         const textline[],
                    unsigned int const lineLength) {
 /*----------------------------------------------------------------------------
@@ -264,7 +263,7 @@ continueTextString(png_text *   const textChunkP,
 
     textChunkP->text[textChunkP->text_length++] = '\n';
 
-    cursor = 0; 
+    cursor = 0;
 
     skipWhiteSpace(textline, lineLength, &cursor);
 
@@ -280,12 +279,12 @@ continueTextString(png_text *   const textChunkP,
 
 
 static void
-getFileLine(FILE *         const fileP, 
-            const char **  const textP, 
+getFileLine(FILE *         const fileP,
+            const char **  const textP,
             unsigned int * const lengthP) {
 /*----------------------------------------------------------------------------
    Read the next line (characters from current position through the first
-   newline character) and return it.  Put the text in newly malloc'ed 
+   newline character) and return it.  Put the text in newly malloc'ed
    storage.
 
    Do not include the newline.
@@ -300,7 +299,7 @@ getFileLine(FILE *         const fileP,
     unsigned int cursor;  /* cursor into textline[] */
     unsigned int allocatedSz;
         /* The number of characters of space that are allocated for
-           'textline' 
+           'textline'
         */
     bool eol;
     bool gotSomething;
@@ -310,14 +309,14 @@ getFileLine(FILE *         const fileP,
     MALLOCARRAY(textline, allocatedSz);
     if (textline == NULL)
         pm_error("Unable to allocate buffer to read a line of a file.");
-    
+
     cursor = 0;
     eol = FALSE;
     gotSomething = FALSE;
 
     while (!eol) {
         int const c = getc(fileP);
-        
+
         if (c != EOF)
             gotSomething = TRUE;
 
@@ -356,7 +355,7 @@ handleArrayAllocation(png_text **    const arrayP,
     if (chunkIdx >= *allocatedChunkCtP) {
         *allocatedChunkCtP *= 2;
         REALLOCARRAY(*arrayP, *allocatedChunkCtP);
-        if (*arrayP == NULL) 
+        if (*arrayP == NULL)
             pm_error("unable to allocate memory for %u text chunks",
                 *allocatedChunkCtP);
     }
@@ -404,9 +403,9 @@ reportChunkCt(bool         const ztxt,
 ******************************************************************************/
 
 
-void 
+void
 pngtxt_addChunk(struct pngx * const pngxP,
-                FILE *        const tfP, 
+                FILE *        const tfP,
                 bool          const ztxt,
                 bool          const itxt,
                 bool          const verbose) {
@@ -436,7 +435,7 @@ pngtxt_addChunk(struct pngx * const pngxP,
     allocatedChunkCt = 256;  /* initial value */
 
     MALLOCARRAY(text, allocatedChunkCt);
-    if (text == NULL) 
+    if (text == NULL)
         pm_error("unable to allocate memory for text chunk array");
 
     for (chunkCt = 0, noChunksYet = true, eof = false; !eof; ) {
@@ -460,15 +459,15 @@ pngtxt_addChunk(struct pngx * const pngxP,
                     } else
                         ++chunkCt;
                     noChunksYet = false;
-                    
+
                     textChunkP = &text[chunkCt];
-                
+
                     if (itxt)
-                        startTextChunkIntl(textChunkP, 
+                        startTextChunkIntl(textChunkP,
                                            textline, lineLength, ztxt,
                                            verbose);
                     else
-                        startTextChunkEngl(textChunkP, 
+                        startTextChunkEngl(textChunkP,
                                            textline, lineLength, ztxt,
                                            verbose);
                 } else {
diff --git a/converter/other/pngtxt.h b/converter/other/pngtxt.h
index 3e6ff2af..30fba1fc 100644
--- a/converter/other/pngtxt.h
+++ b/converter/other/pngtxt.h
@@ -7,9 +7,9 @@
 
 struct pngx;
 
-void 
+void
 pngtxt_addChunk(struct pngx * const pngxP,
-                FILE *        const tfp, 
+                FILE *        const tfp,
                 bool          const ztxt,
                 bool          const itxt,
                 bool          const verbose);
diff --git a/converter/other/pngx.c b/converter/other/pngx.c
index 8295b979..d360e554 100644
--- a/converter/other/pngx.c
+++ b/converter/other/pngx.c
@@ -1,6 +1,10 @@
 #include <stdbool.h>
 #include <assert.h>
 #include <png.h>
+/* Because of a design error in png.h, you must not #include <setjmp.h> before
+   <png.h>.  If you do, png.h won't compile.
+*/
+#include <setjmp.h>
 #include "pm_c_util.h"
 #include "mallocvar.h"
 #include "nstring.h"
@@ -24,7 +28,7 @@ errorHandler(png_structp     const png_ptr,
 
     jmp_buf * jmpbufP;
 
-    /* this function, aside from the extra step of retrieving the "error
+    /* This function, aside from the extra step of retrieving the "error
        pointer" (below) and the fact that it exists within the application
        rather than within libpng, is essentially identical to libpng's
        default error handler.  The second point is critical:  since both
@@ -34,16 +38,14 @@ errorHandler(png_structp     const png_ptr,
        been defined.
     */
 
-    pm_message("fatal libpng error: %s", msg);
+    pm_errormsg("fatal libpng error: %s", msg);
 
     jmpbufP = png_get_error_ptr(png_ptr);
 
-    if (!jmpbufP) {
-        /* we are completely hosed now */
-        pm_error("EXTREMELY fatal error: jmpbuf unrecoverable; terminating.");
-    }
-
-    longjmp(*jmpbufP, 1);
+    if (!jmpbufP)
+        pm_longjmp();
+    else
+        longjmp(*jmpbufP, 1);
 }
 
 
@@ -651,6 +653,7 @@ pngx_setTextLangKey(png_text *   const textP,
 }
 
 
+
 void
 pngx_termText(png_text * const textP) {
 
diff --git a/converter/other/pnmtoddif.c b/converter/other/pnmtoddif.c
index b7b942b3..868ece92 100644
--- a/converter/other/pnmtoddif.c
+++ b/converter/other/pnmtoddif.c
@@ -1,7 +1,7 @@
 /*
  * Author:      Burkhard Neidecker-Lutz
  *              Digital CEC Karlsruhe
- *      neideck@nestvx.enet.dec.com 
+ *      neideck@nestvx.enet.dec.com
 
  Copyright (c) Digital Equipment Corporation, 1992
 
@@ -75,7 +75,7 @@ static void tag(unsigned char ** buffer, int cl, int constructed,
         *p++ = tag_first | 31;
         sp = 0;
         while (t > 0) {
-            stack[sp++] = t & 0x7f; 
+            stack[sp++] = t & 0x7f;
             t >>= 7;
         }
         while (--sp > 0) {  /* Tag values with continuation bits */
@@ -89,7 +89,7 @@ static void tag(unsigned char ** buffer, int cl, int constructed,
 
 
 /* Emit indefinite length encoding */
-static void 
+static void
 ind(unsigned char **buffer)
 {
     unsigned char *p = *buffer;
@@ -101,7 +101,7 @@ ind(unsigned char **buffer)
 
 
 /* Emit ASN.1 NULL */
-static void 
+static void
 wr_null(unsigned char **buffer)
 {
     unsigned char *p = *buffer;
@@ -113,7 +113,7 @@ wr_null(unsigned char **buffer)
 
 
 /* Emit ASN.1 length only into buffer, no data */
-static void 
+static void
 wr_length(unsigned char ** buffer, int amount)
 {
     int length;
@@ -144,7 +144,7 @@ wr_length(unsigned char ** buffer, int amount)
 
 
 /* BER encode an integer and write it's length and value */
-static void 
+static void
 wr_int(unsigned char ** buffer, int val)
 {
     int length;
@@ -178,7 +178,7 @@ wr_int(unsigned char ** buffer, int val)
 
 
 /* Emit and End Of Coding sequence  */
-static void 
+static void
 eoc(unsigned char ** buffer)
 {
     unsigned char *p = *buffer;
@@ -191,13 +191,13 @@ eoc(unsigned char ** buffer)
 
 
 /* Emit a simple string */
-static 
+static
 void wr_string(unsigned char ** const buffer, const char * const val)
 {
     int length;
     unsigned char *p = *buffer;
 
-    length  = strlen(val);        
+    length  = strlen(val);
     if (length > 127) {
         fprintf(stderr,"Can't encode length > 127 yet (%d)\n",length);
         exit(1);
@@ -214,7 +214,7 @@ void wr_string(unsigned char ** const buffer, const char * const val)
 
 
 /* Emit a ISOLATIN-1 string */
-static void 
+static void
 emit_isolatin1(unsigned char ** const buffer, const char * const val)
 {
     int length;
@@ -242,7 +242,7 @@ emit_isolatin1(unsigned char ** const buffer, const char * const val)
 /* values. A lot of the values here are hardcoded to be just right for   */
 /* the bit grammars that the PBMPLUS formats want.           */
 
-static int 
+static int
 write_header(FILE *file, imageparams *ip)
 {
     unsigned char buffer[300];            /* Be careful with the size ! */
@@ -287,7 +287,7 @@ write_header(FILE *file, imageparams *ip)
     tag(&p,CONTEXT,PRIM, 0); wr_int(&p,1); /* PP Pixel Dist */
     tag(&p,CONTEXT,PRIM, 1); wr_int(&p,1); /* LP Pixel Dist */
     eoc(&p);                /* Pixel Aspect Ratio */
-    tag(&p,CONTEXT,PRIM, 4); wr_int(&p,ip->polarity);  
+    tag(&p,CONTEXT,PRIM, 4); wr_int(&p,ip->polarity);
         /* Brightness Polarity */
     tag(&p,CONTEXT,PRIM, 5); wr_int(&p,1);  /* Grid Type    */
     tag(&p,CONTEXT,PRIM, 7); wr_int(&p,ip->spectral);  /* Spectral Mapping */
@@ -300,7 +300,7 @@ write_header(FILE *file, imageparams *ip)
     tag(&p,CONTEXT,PRIM, 0); wr_int(&p,1);  /* Component Space Organization */
     tag(&p,CONTEXT,PRIM, 1); wr_int(&p,1);  /* Planes per Pixel */
     tag(&p,CONTEXT,PRIM, 2); wr_int(&p,1);  /* Plane Significance   */
-    tag(&p,CONTEXT,PRIM, 3); wr_int(&p,ip->components);  
+    tag(&p,CONTEXT,PRIM, 3); wr_int(&p,ip->components);
         /* Number of Components    */
     tag(&p,CONTEXT,CONS, 4); ind(&p);   /* Bits per Component   */
     for (i = 0; i < ip->components; i++) {
@@ -355,7 +355,7 @@ write_header(FILE *file, imageparams *ip)
     tag(&p,CONTEXT,PRIM, 7); wr_int(&p,ip->bytes_per_line * 8);
         /* Scanline Stride    */
     tag(&p,CONTEXT,PRIM, 8); wr_int(&p,1);   /* Bit Order        */
-    tag(&p,CONTEXT,PRIM, 9); wr_int(&p,ip->bits_per_pixel);  
+    tag(&p,CONTEXT,PRIM, 9); wr_int(&p,ip->bits_per_pixel);
         /* Planebits per Pixel */
     tag(&p,CONTEXT,CONS,10); ind(&p);    /* Byteorder Info   */
     tag(&p,CONTEXT,PRIM, 0); wr_int(&p,1);  /* Byte Unit        */
@@ -363,7 +363,7 @@ write_header(FILE *file, imageparams *ip)
     eoc(&p);                 /* Byteorder Info   */
     tag(&p,CONTEXT,PRIM,11); wr_int(&p,3);   /* Data Type        */
     eoc(&p);                              /* Image Coding Attributes */
-    tag(&p,CONTEXT,PRIM, 1); wr_length(&p,ip->bytes_per_line*ip->height);  
+    tag(&p,CONTEXT,PRIM, 1); wr_length(&p,ip->bytes_per_line*ip->height);
         /* Component Plane Data */
     /* End of DDIF document Indentation */
     headersize = p - buffer;
@@ -380,7 +380,7 @@ write_header(FILE *file, imageparams *ip)
 /* Write all the closing brackets of the DDIF grammar that are missing */
 /* The strange indentation reflects exactly the same indentation that  */
 /* we left off in the write_header procedure.                  */
-static int 
+static int
 write_trailer(FILE * file)
 {
     unsigned char buffer[30];
@@ -406,7 +406,6 @@ write_trailer(FILE * file)
 
 
 
-
 static void
 convertPbmRaster(FILE *          const ifP,
                  int             const format,
@@ -415,7 +414,7 @@ convertPbmRaster(FILE *          const ifP,
                  FILE *          const ofP,
                  unsigned int    const bytesPerLine,
                  unsigned char * const data) {
-                 
+
     bit * const pixels = pbm_allocrow(cols);
 
     unsigned int row;
@@ -490,7 +489,6 @@ convertPgmRaster(FILE *          const ifP,
 
 
 
-
 static void
 convertPpmRaster(FILE *          const ifP,
                  int             const format,
@@ -677,3 +675,6 @@ main(int argc, char *argv[]) {
 
     return(0);
 }
+
+
+
diff --git a/converter/other/pnmtojpeg.c b/converter/other/pnmtojpeg.c
index e3458319..b80860e7 100644
--- a/converter/other/pnmtojpeg.c
+++ b/converter/other/pnmtojpeg.c
@@ -20,7 +20,8 @@
 #define _BSD_SOURCE 1      /* Make sure strdup() is in string.h */
 #define _XOPEN_SOURCE 500  /* Make sure strdup() is in string.h */
 
-#include <ctype.h>		/* to declare isdigit(), etc. */
+#include <ctype.h>              /* to declare isdigit(), etc. */
+#include <stdbool.h>
 #include <stdlib.h>
 #include <string.h>
 #include <errno.h>
@@ -39,11 +40,11 @@
 
 #define EXIT_WARNING 2   /* Goes with EXIT_SUCCESS, EXIT_FAILURE in stdlib.h */
 
-enum restart_unit {RESTART_MCU, RESTART_ROW, RESTART_NONE};
-enum density_unit {DEN_UNSPECIFIED, DEN_DOTS_PER_INCH, DEN_DOTS_PER_CM};
+enum RestartUnit {RESTART_MCU, RESTART_ROW, RESTART_NONE};
+enum DensityUnit {DEN_UNSPECIFIED, DEN_DOTS_PER_INCH, DEN_DOTS_PER_CM};
 
-struct density {
-    enum density_unit unit;
+struct Density {
+    enum DensityUnit unit;
         /* The units of density for 'horiz', 'vert' */
     unsigned short horiz;  /* Not 0 */
         /* Horizontal density, in units specified by 'unit' */
@@ -51,92 +52,93 @@ struct density {
         /* Same as 'horiz', but vertical */
 };
 
-struct cmdlineInfo {
+struct CmdlineInfo {
     /* All the information the user supplied in the command line,
        in a form easy for the program to use.
      */
-    char *input_filespec;
-    unsigned int verbose;
-    unsigned int quality;
-    unsigned int force_baseline;
-    unsigned int progressive;
-    unsigned int arith_code;
-    J_DCT_METHOD dct_method;
-    unsigned int grayscale;
-    unsigned int rgb;
-    long int max_memory_to_use;
-    unsigned int trace_level;
-    char *qslots;
-    char *qtablefile;
-    char *sample;
-    char *scans;
-    int smoothing_factor;
-    unsigned int optimize;
-    unsigned int restart_value;
-    enum restart_unit restart_unit;
-    char *restart;
-    char *comment;              /* NULL if none */
-    const char *exif_filespec;  /* NULL if none */
-    unsigned int density_spec;
+    char *           inputFileNm;
+    unsigned int     verbose;
+    unsigned int     quality;
+    unsigned int     baseline;
+    unsigned int     progressive;
+    unsigned int     arithmetic;
+    J_DCT_METHOD     dctMethod;
+    unsigned int     grayscale;
+    unsigned int     rgb;
+    long int         maxMemoryToUse;
+    unsigned int     tracelevel;
+    char *           qslots;
+    char *           qtablefile;
+    char *           sample;
+    char *           scans;
+    int              smooth;
+    unsigned int     optimize;
+    unsigned int     restartValue;
+    enum RestartUnit restartUnit;
+    char *           restart;
+    char *           comment;            /* NULL if none */
+    const char *     exif;               /* NULL if none */
+    unsigned int     densitySpec;
         /* boolean: JFIF should specify a density.  If false, 'density'
            is undefined.
         */
-    struct density density;
+    struct Density density;
 };
 
 static void
-interpret_maxmemory (const char * const maxmemory,
-                     long int * const max_memory_to_use_p) {
+interpretMaxmemory (const char * const maxmemory,
+                    long int *   const maxMemoryToUseP) {
     long int lval;
     char ch;
 
     if (maxmemory == NULL) {
-        *max_memory_to_use_p = -1;  /* unspecified */
+        *maxMemoryToUseP = -1;  /* unspecified */
     } else if (sscanf(maxmemory, "%ld%c", &lval, &ch) < 1) {
         pm_error("Invalid value for --maxmemory option: '%s'.", maxmemory);
         exit(EXIT_FAILURE);
     } else {
         if (ch == 'm' || ch == 'M') lval *= 1000L;
-        *max_memory_to_use_p = lval * 1000L;
+        *maxMemoryToUseP = lval * 1000L;
     }
 }
 
 
 
 static void
-interpret_restart(const char * const restart,
-                  unsigned int * const restart_value_p,
-                  enum restart_unit * const restart_unit_p) {
+interpretRestart(const char *       const restartOpt,
+                 unsigned int *     const restartValueP,
+                 enum RestartUnit * const restartUnitP) {
 /*----------------------------------------------------------------------------
    Interpret the restart command line option.  Return values suitable
    for plugging into a jpeg_compress_struct to control compression.
 -----------------------------------------------------------------------------*/
-    if (restart == NULL) {
+    if (restartOpt == NULL) {
         /* No --restart option.  Set default */
-        *restart_unit_p = RESTART_NONE;
+        *restartUnitP = RESTART_NONE;
     } else {
         /* Restart interval in MCU rows (or in MCUs with 'b'). */
         long lval;
         char ch;
         unsigned int matches;
 
-        matches= sscanf(restart, "%ld%c", &lval, &ch);
+        matches= sscanf(restartOpt, "%ld%c", &lval, &ch);
         if (matches == 0)
             pm_error("Invalid value for the --restart option : '%s'.",
-                     restart);
+                     restartOpt);
         else {
             if (lval < 0 || lval > 65535L) {
                 pm_error("--restart value %ld is out of range.", lval);
                 exit(EXIT_FAILURE);
             } else {
                 if (matches == 1) {
-                    *restart_value_p = lval;
-                    *restart_unit_p = RESTART_ROW;
+                    *restartValueP = lval;
+                    *restartUnitP  = RESTART_ROW;
                 } else {
                     if (ch == 'b' || ch == 'B') {
-                        *restart_value_p = lval;
-                        *restart_unit_p = RESTART_MCU;
-                    } else pm_error("Invalid --restart value '%s'.", restart);
+                        *restartValueP = lval;
+                        *restartUnitP  = RESTART_MCU;
+                    } else
+                        pm_error("Invalid --restart value '%s'.", restartOpt);
                 }
             }
         }
@@ -145,10 +147,9 @@ interpret_restart(const char * const restart,
 
 
 
-
 static void
-interpret_density(const char *        const densityString,
-                  struct density *    const densityP) {
+interpretDensity(const char *     const densityString,
+                 struct Density * const densityP) {
 /*----------------------------------------------------------------------------
    Interpret the value of the "-density" option.
 -----------------------------------------------------------------------------*/
@@ -200,8 +201,8 @@ interpret_density(const char *        const densityString,
 
 
 static void
-parseCommandLine(const int argc, char ** argv,
-                   struct cmdlineInfo *cmdlineP) {
+parseCommandLine(const int argc, const char ** argv,
+                 struct CmdlineInfo * const cmdlineP) {
 /*----------------------------------------------------------------------------
    Note that many of the strings that this function returns in the
    *cmdlineP structure are actually in the supplied argv array.  And
@@ -211,140 +212,141 @@ parseCommandLine(const int argc, char ** argv,
    On the other hand, unlike other option processing functions, we do
    not change argv at all.
 -----------------------------------------------------------------------------*/
-    optEntry *option_def = malloc(100*sizeof(optEntry));
-        /* Instructions to OptParseOptions3 on how to parse our options.
-         */
+    optEntry * option_def;   /* Used by OPTENT3 */
     optStruct3 opt;
 
     int i;  /* local loop variable */
 
-    const char *dctval;
-    const char *maxmemory;
-    const char *restart;
-    const char *density;
+    const char * dctval;
+    const char * maxmemory;
+    const char * restart;
+    const char * density;
 
     unsigned int qualitySpec, smoothSpec;
 
     unsigned int option_def_index;
 
-    int argc_parse;       /* argc, except we modify it as we parse */
-    char ** argv_parse;
+    int argcParse;       /* argc, except we modify it as we parse */
+    const char ** argvParse;
         /* argv, except we modify it as we parse */
 
-    MALLOCARRAY(argv_parse, argc + 1);  /* +1 for the terminating null ptr */
+    MALLOCARRAY_NOFAIL(option_def, 100);
+
+    MALLOCARRAY(argvParse, argc + 1);  /* +1 for the terminating null ptr */
 
     option_def_index = 0;   /* incremented by OPTENTRY */
     OPTENT3(0, "verbose",     OPT_FLAG,   NULL, &cmdlineP->verbose,        0);
     OPTENT3(0, "quality",     OPT_UINT,   &cmdlineP->quality,
             &qualitySpec,        0);
-    OPTENT3(0, "baseline",    OPT_FLAG,   NULL, &cmdlineP->force_baseline, 0);
+    OPTENT3(0, "baseline",    OPT_FLAG,   NULL, &cmdlineP->baseline,       0);
     OPTENT3(0, "progressive", OPT_FLAG,   NULL, &cmdlineP->progressive,    0);
-    OPTENT3(0, "arithmetic",  OPT_FLAG,   NULL, &cmdlineP->arith_code,     0);
-    OPTENT3(0, "dct",         OPT_STRING, &dctval, NULL,                    0);
+    OPTENT3(0, "arithmetic",  OPT_FLAG,   NULL, &cmdlineP->arithmetic,     0);
+    OPTENT3(0, "dct",         OPT_STRING, &dctval, NULL,                   0);
     OPTENT3(0, "grayscale",   OPT_FLAG,   NULL, &cmdlineP->grayscale,      0);
     OPTENT3(0, "greyscale",   OPT_FLAG,   NULL, &cmdlineP->grayscale,      0);
     OPTENT3(0, "rgb",         OPT_FLAG,   NULL, &cmdlineP->rgb,            0);
-    OPTENT3(0, "maxmemory",   OPT_STRING, &maxmemory, NULL,                 0);
-    OPTENT3(0, "tracelevel",  OPT_UINT,   &cmdlineP->trace_level, NULL,    0);
+    OPTENT3(0, "maxmemory",   OPT_STRING, &maxmemory, NULL,                0);
+    OPTENT3(0, "tracelevel",  OPT_UINT,   &cmdlineP->tracelevel, NULL,    0);
     OPTENT3(0, "qslots",      OPT_STRING, &cmdlineP->qslots,      NULL,    0);
     OPTENT3(0, "qtables",     OPT_STRING, &cmdlineP->qtablefile,  NULL,    0);
     OPTENT3(0, "sample",      OPT_STRING, &cmdlineP->sample,      NULL,    0);
     OPTENT3(0, "scans",       OPT_STRING, &cmdlineP->scans,       NULL,    0);
-    OPTENT3(0, "smooth",      OPT_UINT,   &cmdlineP->smoothing_factor,
+    OPTENT3(0, "smooth",      OPT_UINT,   &cmdlineP->smooth,
             &smoothSpec,  0);
     OPTENT3(0, "optimize",    OPT_FLAG,   NULL, &cmdlineP->optimize,       0);
     OPTENT3(0, "optimise",    OPT_FLAG,   NULL, &cmdlineP->optimize,       0);
     OPTENT3(0, "restart",     OPT_STRING, &restart, NULL,                   0);
     OPTENT3(0, "comment",     OPT_STRING, &cmdlineP->comment, NULL,        0);
-    OPTENT3(0, "exif",        OPT_STRING, &cmdlineP->exif_filespec, NULL,  0);
+    OPTENT3(0, "exif",        OPT_STRING, &cmdlineP->exif, NULL,  0);
     OPTENT3(0, "density",     OPT_STRING, &density,
-            &cmdlineP->density_spec, 0);
+            &cmdlineP->densitySpec, 0);
+
 
     /* Set the defaults */
     dctval = NULL;
     maxmemory = NULL;
-    cmdlineP->trace_level = 0;
+    cmdlineP->tracelevel = 0;
     cmdlineP->qslots = NULL;
     cmdlineP->qtablefile = NULL;
     cmdlineP->sample = NULL;
     cmdlineP->scans = NULL;
     restart = NULL;
     cmdlineP->comment = NULL;
-    cmdlineP->exif_filespec = NULL;
+    cmdlineP->exif = NULL;
 
     /* Make private copy of arguments for pm_optParseOptions to corrupt */
-    argc_parse = argc;
-    for (i=0; i < argc+1; i++) argv_parse[i] = argv[i];
+    argcParse = argc;
+    for (i = 0; i < argc+1; ++i)
+        argvParse[i] = argv[i];
 
     opt.opt_table = option_def;
     opt.short_allowed = FALSE;  /* We have no short (old-fashioned) options */
     opt.allowNegNum = FALSE;  /* We have no parms that are negative numbers */
 
-    pm_optParseOptions3(&argc_parse, argv_parse, opt, sizeof(opt), 0);
+    pm_optParseOptions4(&argcParse, argvParse, opt, sizeof(opt), 0);
 
     if (!qualitySpec)
         cmdlineP->quality = -1;  /* unspecified */
 
     if (!smoothSpec)
-        cmdlineP->smoothing_factor = -1;
+        cmdlineP->smooth = -1;
 
     if (cmdlineP->rgb && cmdlineP->grayscale)
         pm_error("You can't specify both -rgb and -grayscale");
 
-    if (argc_parse - 1 == 0)
-        cmdlineP->input_filespec = strdup("-");  /* he wants stdin */
-    else if (argc_parse - 1 == 1)
-        cmdlineP->input_filespec = strdup(argv_parse[1]);
+    if (argcParse - 1 == 0)
+        cmdlineP->inputFileNm = strdup("-");  /* he wants stdin */
+    else if (argcParse - 1 == 1)
+        cmdlineP->inputFileNm = strdup(argvParse[1]);
     else
         pm_error("Too many arguments.  The only argument accepted "
                  "is the input file specification.");
     if (dctval == NULL)
-        cmdlineP->dct_method = JDCT_DEFAULT;
+        cmdlineP->dctMethod = JDCT_DEFAULT;
     else {
         if (streq(dctval, "int"))
-            cmdlineP->dct_method = JDCT_ISLOW;
+            cmdlineP->dctMethod = JDCT_ISLOW;
         else if (streq(dctval, "fast"))
-            cmdlineP->dct_method = JDCT_IFAST;
+            cmdlineP->dctMethod = JDCT_IFAST;
         else if (streq(dctval, "float"))
-            cmdlineP->dct_method = JDCT_FLOAT;
+            cmdlineP->dctMethod = JDCT_FLOAT;
         else
             pm_error("Invalid value for the --dct option: '%s'.", dctval);
     }
 
-    interpret_maxmemory(maxmemory, &cmdlineP->max_memory_to_use);
-    interpret_restart(restart, &cmdlineP->restart_value,
-                      &cmdlineP->restart_unit);
-    if (cmdlineP->density_spec)
-        interpret_density(density, &cmdlineP->density);
+    interpretMaxmemory(maxmemory, &cmdlineP->maxMemoryToUse);
+    interpretRestart(restart, &cmdlineP->restartValue,
+                      &cmdlineP->restartUnit);
+    if (cmdlineP->densitySpec)
+        interpretDensity(density, &cmdlineP->density);
 
-    if (cmdlineP->smoothing_factor > 100)
+    if (cmdlineP->smooth > 100)
         pm_error("Smoothing factor %d is greater than 100 (%%).",
-                 cmdlineP->smoothing_factor);
+                 cmdlineP->smooth);
 
-    if (streq(cmdlineP->input_filespec, "=") &&
-        cmdlineP->exif_filespec &&
-        streq(cmdlineP->exif_filespec, "-"))
+    if (streq(cmdlineP->inputFileNm, "=") &&
+        cmdlineP->exif && streq(cmdlineP->exif, "-"))
 
         pm_error("Cannot have both input image and exif header be from "
                  "Standard Input.");
 
 
-    free(argv_parse);
+    free(argvParse);
 }
 
 
 
 static void
-report_compressor(const struct jpeg_compress_struct cinfo) {
+reportCompressor(const struct jpeg_compress_struct cinfo) {
 
     if (cinfo.scan_info == NULL)
         pm_message("No scan script is being used");
     else {
-        int i;
+        unsigned int i;
         pm_message("A scan script with %d entries is being used:",
                    cinfo.num_scans);
-        for (i = 0; i < cinfo.num_scans; i++) {
-            int j;
+        for (i = 0; i < cinfo.num_scans; ++i) {
+            unsigned int j;
             pm_message("    Scan %2d: Ss=%2d Se=%2d Ah=%2d Al=%2d  "
                        "%d components",
                        i,
@@ -354,7 +356,7 @@ report_compressor(const struct jpeg_compress_struct cinfo) {
                        cinfo.scan_info[i].Al,
                        cinfo.scan_info[i].comps_in_scan
                        );
-            for (j = 0; j < cinfo.scan_info[i].comps_in_scan; j++)
+            for (j = 0; j < cinfo.scan_info[i].comps_in_scan; ++j)
                 pm_message("        Color component %d index: %d", j,
                            cinfo.scan_info[i].component_index[j]);
         }
@@ -364,14 +366,14 @@ report_compressor(const struct jpeg_compress_struct cinfo) {
 
 
 static void
-setup_jpeg_source_parameters(struct jpeg_compress_struct * const cinfoP,
-                             int const width, int const height,
-                             int const format) {
+setupJpegSourceParameters(struct jpeg_compress_struct * const cinfoP,
+                          unsigned int                  const width,
+                          unsigned int                  const height,
+                          int                           const format) {
 /*----------------------------------------------------------------------------
    Set up in the compressor descriptor *cinfoP the description of the
    source image as required by the compressor.
 -----------------------------------------------------------------------------*/
-
     switch PNM_FORMAT_TYPE(format) {
     case PBM_TYPE:
     case PGM_TYPE:
@@ -391,8 +393,8 @@ setup_jpeg_source_parameters(struct jpeg_compress_struct * const cinfoP,
 
 
 static void
-setup_jpeg_density(struct jpeg_compress_struct * const cinfoP,
-                   struct density                const density) {
+setupJpegDensity(struct jpeg_compress_struct * const cinfoP,
+                 struct Density                const density) {
 /*----------------------------------------------------------------------------
    Set up in the compressor descriptor *cinfoP the density information
    'density'.
@@ -421,24 +423,28 @@ setup_jpeg_density(struct jpeg_compress_struct * const cinfoP,
 -----------------------------------------------------------------------------*/
 
 static int
-text_getc (FILE * file)
-/* Read next char, skipping over any comments (# to end of line) */
-/* A comment/newline sequence is returned as a newline */
-{
-    register int ch;
+textGetc (FILE * fileP) {
+/*----------------------------------------------------------------------------
+  Read next char, skipping over any comments (# to end of line).
 
-    ch = getc(file);
+  Return a comment/newline sequence as a newline.
+-----------------------------------------------------------------------------*/
+    int ch;
+
+    ch = getc(fileP);
     if (ch == '#') {
         do {
-            ch = getc(file);
+            ch = getc(fileP);
         } while (ch != '\n' && ch != EOF);
     }
     return ch;
 }
 
 
-static boolean
+
+static void
 readTextInteger(FILE * const fileP,
+                bool * const gotOneP,
                 long * const resultP,
                 int *  const termcharP) {
 /*----------------------------------------------------------------------------
@@ -450,234 +456,335 @@ readTextInteger(FILE * const fileP,
    If there is no character after the integer, return *termcharP == EOF.
 
    Iff the next thing in the file is not a valid unsigned decimal integer,
-   return FALSE.
+   return *gotOneP false.
 -----------------------------------------------------------------------------*/
     int ch;
-    boolean retval;
 
     /* Skip any leading whitespace, detect EOF */
     do {
-        ch = text_getc(fileP);
+        ch = textGetc(fileP);
     } while (isspace(ch));
 
     if (!isdigit(ch))
-        retval = FALSE;
+        *gotOneP = false;
     else {
         long val;
         val = ch - '0';  /* initial value */
-        while ((ch = text_getc(fileP)) != EOF) {
+        while ((ch = textGetc(fileP)) != EOF) {
             if (! isdigit(ch))
                 break;
             val *= 10;
             val += ch - '0';
         }
         *resultP = val;
-        retval = TRUE;
+        *gotOneP = true;
     }
     *termcharP = ch;
-    return retval;
 }
 
 
-static boolean
-read_scan_integer (FILE * file, long * result, int * termchar)
-/* Variant of readTextInteger that always looks for a non-space termchar;
- * this simplifies parsing of punctuation in scan scripts.
- */
-{
-    register int ch;
-
-    if (! readTextInteger(file, result, termchar))
-        return FALSE;
-    ch = *termchar;
-    while (ch != EOF && isspace(ch))
-        ch = text_getc(file);
-    if (isdigit(ch)) {		/* oops, put it back */
-        if (ungetc(ch, file) == EOF)
-            return FALSE;
-        ch = ' ';
-    } else {
-        /* Any separators other than ';' and ':' are ignored;
-         * this allows user to insert commas, etc, if desired.
-         */
-        if (ch != EOF && ch != ';' && ch != ':')
+
+static void
+readScanInteger(FILE * const fileP,
+                bool * const gotOneP,
+                long * const resultP,
+                int *  const termcharP) {
+/*----------------------------------------------------------------------------
+  Variant of readTextInteger that always looks for a non-space termchar.
+  this simplifies parsing of punctuation in scan scripts.
+-----------------------------------------------------------------------------*/
+    readTextInteger(fileP, gotOneP, resultP, termcharP);
+
+    if (*gotOneP) {
+        int ch;
+
+        ch = *termcharP;  /* initial value */
+
+        while (ch != EOF && isspace(ch))
+            ch = textGetc(fileP);
+
+        if (isdigit(ch)) {              /* oops, put it back */
+            if (ungetc(ch, fileP) == EOF)
+                pm_error("Unexpected failure of ungetc");
             ch = ' ';
+        } else {
+            /* Any separators other than ';' and ':' are ignored;
+             * this allows user to insert commas, etc, if desired.
+             */
+            if (ch != EOF && ch != ';' && ch != ':')
+                ch = ' ';
+        }
+        *termcharP = ch;
     }
-    *termchar = ch;
-    return TRUE;
 }
 
 
 
-static boolean
-read_scan_script(j_compress_ptr const cinfo,
-                 const char *   const filename) {
+static void
+readScanScriptComponents(FILE *           const fP,
+                         jpeg_scan_info * const scanP,
+                         int *            const termcharP,
+                         long *           const valP,
+                         const char **    const errorP) {
+/*----------------------------------------------------------------------------
+   Set component table in *scanP, i.e. scanP->component_index and
+   scanP->comps_in_scan.
+
+   *termcharP and *valP at entry are for the value we already read from the
+   file; at exit, they are the value beyond the component table.
+-----------------------------------------------------------------------------*/
+    unsigned int compCt;
+
+    *errorP = NULL;  /* initial value */
+
+    /* First component is value we already read: */
+    scanP->component_index[0] = (int) *valP;
+    compCt = 1;
+
+    /* Rest of components follow, until termchar other than ' ': */
+    while (*termcharP == ' ' && !*errorP) {
+        bool gotOne;
+        if (compCt >= MAX_COMPS_IN_SCAN) {
+            pm_asprintf(errorP, "Too many components in one scan "
+                        "(Max allowed is %u)", MAX_COMPS_IN_SCAN);
+        }
+        readScanInteger(fP, &gotOne, valP, termcharP);
+        if (!gotOne)
+            pm_asprintf(errorP, "Invalid scan entry format");
+        else
+            scanP->component_index[compCt++] = (int) *valP;
+    }
+    scanP->comps_in_scan = compCt;
+}
+
+
+
+static void
+readScanScriptProg(FILE *           const fP,
+                   jpeg_scan_info * const scanP,
+                   int *            const termcharP,
+                   long *           const valP,
+                   const char **    const errorP) {
+
+    bool gotOne;
+    readScanInteger(fP, &gotOne, valP, termcharP);
+    if (!gotOne || *termcharP != ' ')
+        pm_asprintf(errorP, "Error in Ss");
+    else {
+        bool gotOne;
+        scanP->Ss = (int) *valP;
+        readScanInteger(fP, &gotOne, valP, termcharP);
+        if (!gotOne || *termcharP != ' ')
+            pm_asprintf(errorP, "Error in Se");
+        else {
+            bool gotOne;
+            scanP->Se = (int) *valP;
+            readScanInteger(fP, &gotOne, valP, termcharP);
+            if (!gotOne || *termcharP != ' ')
+                pm_asprintf(errorP, "Error in Ah");
+            else {
+                bool gotOne;
+                scanP->Ah = (int) *valP;
+                readScanInteger(fP, &gotOne, valP, termcharP);
+                if (!gotOne)
+                    pm_asprintf(errorP, "Error in Al");
+                else {
+                    scanP->Al = (int) *valP;
+                    *errorP = NULL;
+                }
+            }
+        }
+    }
+}
+
+
+
+static void
+setScanScriptNonProgressive(jpeg_scan_info * const scanP) {
+
+    scanP->Ss = 0;
+    scanP->Se = DCTSIZE2-1;
+    scanP->Ah = 0;
+    scanP->Al = 0;
+}
+
+
+
+static void
+readScanScript1(FILE *           const fP,
+                jpeg_scan_info * const scanP,
+                int *            const termcharP,
+                long *           const valP,
+                const char **    const errorP) {
+
+    const char * error;
+
+    readScanScriptComponents(fP, scanP, termcharP, valP, &error);
+
+    if (error) {
+        pm_asprintf(errorP, "Error in component table.  %s", error);
+        pm_strfree(error);
+    } else {
+        if (*termcharP == ':') {
+            const char * error;
+
+            readScanScriptProg(fP, scanP, termcharP, valP, &error);
+
+            if (error) {
+                pm_asprintf(errorP, "Invalid progressive parameters.  %s",
+                            error);
+                pm_strfree(error);
+            }
+        } else
+            setScanScriptNonProgressive(scanP);
+
+        if (*termcharP != ';' && *termcharP != EOF) {
+            pm_asprintf(errorP, "Expected ';' or EOF");
+        }
+    }
+}
+
+
+
+static void
+readScanScript(j_compress_ptr const cinfoP,
+               const char *   const fileNm,
+               const char **  const errorP) {
 /*----------------------------------------------------------------------------
   Read a scan script from the specified text file.
+
   Each entry in the file defines one scan to be emitted.
+
   Entries are separated by semicolons ';'.
-  An entry contains one to four component indexes,
-  optionally followed by a colon ':' and four progressive-JPEG parameters.
-  The component indexes denote which component(s) are to be transmitted
-  in the current scan.  The first component has index 0.
+
+  An entry contains one to four component indexes, optionally followed by a
+  colon ':' and four progressive-JPEG parameters.  The indexes and parameters
+  are separated by spaces.
+
+  The component indexes identify the color components to be transmitted in the
+  current scan.  The first component has index 0.
+
   Sequential JPEG is used if the progressive-JPEG parameters are omitted.
-  The file is free format text: any whitespace may appear between numbers
-  and the ':' and ';' punctuation marks.  Also, other punctuation (such
-  as commas or dashes) can be placed between numbers if desired.
+
+  Any whitespace may appear between numbers and the ':' and ';' punctuation
+  marks.  Also, other punctuation (such as commas or dashes) may be placed
+  between numbers.
+
   Comments preceded by '#' may be included in the file.
-  Note: we do very little validity checking here;
-  jcmaster.c will validate the script parameters.
+
+  Note: we do very little validity checking here; libjpeg will validate the
+  script parameters.
+
+  The data goes into newly malloc'ed memory pointed to by cinfo->scan_info,
+  with its size as cinfo->num_scans.  If there isn't any scan script,
+  cinfo->scan_info is null.
 -----------------------------------------------------------------------------*/
-    FILE * fp;
-    unsigned int nscans;
-    unsigned int ncomps;
-    int termchar;
-    long val;
-#define MAX_SCANS  100      /* quite arbitrary limit */
-    jpeg_scan_info scans[MAX_SCANS];
+    FILE * fP;
 
-    fp = fopen(filename, "r");
-    if (fp == NULL) {
-        pm_message("Can't open scan definition file %s", filename);
-        return FALSE;
-    }
-    nscans = 0;
-
-    while (read_scan_integer(fp, &val, &termchar)) {
-        ++nscans;  /* We got another scan */
-        if (nscans > MAX_SCANS) {
-            pm_message("Too many scans defined in file %s", filename);
-            fclose(fp);
-            return FALSE;
-        }
-        scans[nscans-1].component_index[0] = (int) val;
-        ncomps = 1;
-        while (termchar == ' ') {
-            if (ncomps >= MAX_COMPS_IN_SCAN) {
-                pm_message("Too many components in one scan in file %s",
-                           filename);
-                fclose(fp);
-                return FALSE;
+    fP = fopen(fileNm, "r");
+    if (!fP)
+        pm_asprintf(errorP, "Can't open file");
+    else {
+        bool notEof;
+        unsigned int scanCt;
+        int termchar;
+        long val;
+        jpeg_scan_info * scan;  /* malloc'ed array */
+            /* Index 0 in this array is called "Entry 1" by libjpeg messages */
+
+        for (notEof = true, *errorP = NULL, scanCt = 0, scan = NULL;
+             notEof && !*errorP;
+            ) {
+            readScanInteger(fP, &notEof, &val, &termchar);
+            if (notEof && !*errorP) {
+                ++scanCt;  /* We got another scan */
+
+                REALLOCARRAY(scan, scanCt);
+
+                if (!scan)
+                    pm_error("Unable to allocate memory for scan table");
+
+                readScanScript1(fP, &scan[scanCt-1], &termchar, &val, errorP);
             }
-            if (! read_scan_integer(fp, &val, &termchar))
-                goto bogus;
-            scans[nscans-1].component_index[ncomps] = (int) val;
-            ++ncomps;
         }
-        scans[nscans-1].comps_in_scan = ncomps;
-        if (termchar == ':') {
-            if (! read_scan_integer(fp, &val, &termchar) || termchar != ' ')
-                goto bogus;
-            scans[nscans-1].Ss = (int) val;
-            if (! read_scan_integer(fp, &val, &termchar) || termchar != ' ')
-                goto bogus;
-            scans[nscans-1].Se = (int) val;
-            if (! read_scan_integer(fp, &val, &termchar) || termchar != ' ')
-                goto bogus;
-            scans[nscans-1].Ah = (int) val;
-            if (! read_scan_integer(fp, &val, &termchar))
-                goto bogus;
-            scans[nscans-1].Al = (int) val;
+        if (!*errorP && termchar != EOF)
+            pm_asprintf(errorP, "Non-numeric data in file '%s'", fileNm);
+
+        if (*errorP) {
+            if (scan)
+                free(scan);
+            cinfoP->scan_info = NULL;
         } else {
-            /* set non-progressive parameters */
-            scans[nscans-1].Ss = 0;
-            scans[nscans-1].Se = DCTSIZE2-1;
-            scans[nscans-1].Ah = 0;
-            scans[nscans-1].Al = 0;
-        }
-        if (termchar != ';' && termchar != EOF) {
-        bogus:
-            pm_message("Invalid scan entry format in file %s", filename);
-            fclose(fp);
-            return FALSE;
+            cinfoP->scan_info = scanCt > 0 ? scan : NULL;
+            cinfoP->num_scans = scanCt;
         }
+        fclose(fP);
     }
-
-    if (termchar != EOF) {
-        pm_message("Non-numeric data in file %s", filename);
-        fclose(fp);
-        return FALSE;
-    }
-
-    if (nscans > 0) {
-        /* Stash completed scan list in cinfo structure.  NOTE: in
-           this program, JPOOL_IMAGE is the right lifetime for this
-           data, but if you want to compress multiple images you'd
-           want JPOOL_PERMANENT.
-        */
-        const unsigned int scan_info_size = nscans * sizeof(jpeg_scan_info);
-        jpeg_scan_info * const scan_info =
-            (jpeg_scan_info *)
-            (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
-                                        scan_info_size);
-        memcpy(scan_info, scans, scan_info_size);
-        cinfo->scan_info = scan_info;
-        cinfo->num_scans = nscans;
-    }
-
-    fclose(fp);
-    return TRUE;
 }
 
 
 
-static boolean
-read_quant_tables (j_compress_ptr cinfo, char * filename,
-                   int scale_factor, boolean force_baseline)
-/* Read a set of quantization tables from the specified file.
- * The file is plain ASCII text: decimal numbers with whitespace between.
- * Comments preceded by '#' may be included in the file.
- * There may be one to NUM_QUANT_TBLS tables in the file, each of 64 values.
- * The tables are implicitly numbered 0,1,etc.
- * NOTE: does not affect the qslots mapping, which will default to selecting
- * table 0 for luminance (or primary) components, 1 for chrominance components.
- * You must use -qslots if you want a different component->table mapping.
- */
-{
+static bool
+readQuantTables(j_compress_ptr const cinfo,
+                const char *   const fileNm,
+                int            const scaleFactor,
+                bool           const forceBaseline) {
+/*----------------------------------------------------------------------------
+  Read a set of quantization tables from the specified file.
+  The file is plain ASCII text: decimal numbers with whitespace between.
+  Comments preceded by '#' may be included in the file.
+  There may be one to NUM_QUANT_TBLS tables in the file, each of 64 values.
+  The tables are implicitly numbered 0,1,etc.
+  NOTE: does not affect the qslots mapping, which will default to selecting
+  table 0 for luminance (or primary) components, 1 for chrominance components.
+  You must use -qslots if you want a different component->table mapping.
+-----------------------------------------------------------------------------*/
     FILE * fp;
-    boolean retval;
+    bool retval;
 
-    fp = fopen(filename, "rb");
+    fp = fopen(fileNm, "rb");
     if (fp == NULL) {
-        pm_message("Can't open table file %s", filename);
-        retval = FALSE;
+        pm_message("Can't open table file '%s'", fileNm);
+        retval = false;
     } else {
         boolean eof, error;
         unsigned int tblno;
 
-        for (tblno = 0, eof = FALSE, error = FALSE; !eof && !error; ++tblno) {
+        for (tblno = 0, eof = false, error = false; !eof && !error; ++tblno) {
             long val;
             int termchar;
-            boolean gotOne;
+            bool gotOne;
 
-            gotOne = readTextInteger(fp, &val, &termchar);
+            readTextInteger(fp, &gotOne, &val, &termchar);
             if (gotOne) {
                 /* read 1st element of table */
                 if (tblno >= NUM_QUANT_TBLS) {
-                    pm_message("Too many tables in file %s", filename);
-                    error = TRUE;
+                    pm_message("Too many tables in file '%s'", fileNm);
+                    error = true;
                 } else {
                     unsigned int table[DCTSIZE2];
                     unsigned int i;
 
                     table[0] = (unsigned int) val;
                     for (i = 1; i < DCTSIZE2 && !error; ++i) {
-                        if (! readTextInteger(fp, &val, &termchar)) {
-                            pm_message("Invalid table data in file %s",
-                                       filename);
-                            error = TRUE;
+                        bool gotOne;
+                        readTextInteger(fp, &gotOne, &val, &termchar);
+                        if (!gotOne) {
+                            pm_message("Invalid table data in file '%s'",
+                                       fileNm);
+                            error = true;
                         } else
                             table[i] = (unsigned int) val;
                     }
                     if (!error)
                         jpeg_add_quant_table(
-                            cinfo, tblno, table, scale_factor, force_baseline);
+                            cinfo, tblno, table, scaleFactor, forceBaseline);
                 }
             } else {
                 if (termchar == EOF)
                     eof = TRUE;
                 else {
-                    pm_message("Non-numeric data in file %s", filename);
+                    pm_message("Non-numeric data in file '%s'", fileNm);
                     error = TRUE;
                 }
             }
@@ -692,75 +799,88 @@ read_quant_tables (j_compress_ptr cinfo, char * filename,
 
 
 
-static boolean
-set_quant_slots (j_compress_ptr cinfo, char *arg)
-/* Process a quantization-table-selectors parameter string, of the form
- *     N[,N,...]
- * If there are more components than parameters, the last value is replicated.
- */
-{
-    int val = 0;			/* default table # */
+static bool
+setQuantSlots(j_compress_ptr const cinfo,
+              const char *   const arg) {
+/*----------------------------------------------------------------------------
+  Process a quantization-table-selectors parameter string, of the form
+  N[,N,...]
+
+  If there are more components than parameters, the last value is replicated.
+-----------------------------------------------------------------------------*/
+    int val;
     int ci;
     char ch;
+    unsigned int i;
+
+    val = 0; /* initial value - default table */
 
-    for (ci = 0; ci < MAX_COMPONENTS; ci++) {
-        if (*arg) {
-            ch = ',';			/* if not set by sscanf, will be ',' */
-            if (sscanf(arg, "%d%c", &val, &ch) < 1)
-                return FALSE;
-            if (ch != ',')		/* syntax check */
-                return FALSE;
+    for (ci = 0, i = 0; ci < MAX_COMPONENTS; ++ci) {
+        if (arg[i]) {
+            ch = ',';                   /* if not set by sscanf, will be ',' */
+            if (sscanf(&arg[i], "%d%c", &val, &ch) < 1)
+                return false;
+            if (ch != ',')              /* syntax check */
+                return false;
             if (val < 0 || val >= NUM_QUANT_TBLS) {
                 pm_message("Invalid quantization table number: %d.  "
                            "JPEG quantization tables are numbered 0..%d",
                            val, NUM_QUANT_TBLS - 1);
-                return FALSE;
+                return false;
             }
             cinfo->comp_info[ci].quant_tbl_no = val;
-            while (*arg && *arg++ != ',')
+            while (arg[i] && arg[i] != ',') {
+                ++i;
                 /* advance to next segment of arg string */
-                ;
+            }
         } else {
             /* reached end of parameter, set remaining components to last tbl*/
             cinfo->comp_info[ci].quant_tbl_no = val;
         }
     }
-    return TRUE;
+    return true;
 }
 
 
-static boolean
-set_sample_factors (j_compress_ptr cinfo, char *arg)
-/* Process a sample-factors parameter string, of the form
- *     HxV[,HxV,...]
- * If there are more components than parameters, "1x1" is assumed for the rest.
- */
-{
-    int ci, val1, val2;
-    char ch1, ch2;
 
-    for (ci = 0; ci < MAX_COMPONENTS; ci++) {
-        if (*arg) {
-            ch2 = ',';		/* if not set by sscanf, will be ',' */
-            if (sscanf(arg, "%d%c%d%c", &val1, &ch1, &val2, &ch2) < 3)
-                return FALSE;
+static bool
+setSampleFactors (j_compress_ptr const cinfo,
+                  const char *   const arg) {
+/*----------------------------------------------------------------------------
+  Process a sample-factors parameter string, of the form
+  HxV[,HxV,...]
+
+  If there are more components than parameters, "1x1" is assumed for the rest.
+-----------------------------------------------------------------------------*/
+    int val1, val2;
+    char ch1, ch2;
+    unsigned int i;
+    unsigned int ci;
+
+    for (ci = 0, i = 0; ci < MAX_COMPONENTS; ++ci) {
+        if (arg[i]) {
+            ch2 = ',';          /* if not set by sscanf, will be ',' */
+            if (sscanf(&arg[i], "%d%c%d%c", &val1, &ch1, &val2, &ch2) < 3)
+                return false;
             if ((ch1 != 'x' && ch1 != 'X') || ch2 != ',') /* syntax check */
-                return FALSE;
+                return false;
             if (val1 <= 0 || val1 > 4) {
                 pm_message("Invalid sampling factor: %d.  "
                            "JPEG sampling factors must be 1..4", val1);
-                return FALSE;
+                return false;
             }
             if (val2 <= 0 || val2 > 4) {
                 pm_message("Invalid sampling factor: %d.  "
                            "JPEG sampling factors must be 1..4", val2);
-                return FALSE;
+                return false;
             }
             cinfo->comp_info[ci].h_samp_factor = val1;
             cinfo->comp_info[ci].v_samp_factor = val2;
-            while (*arg && *arg++ != ',')
+
+            while (arg[i] && arg[i] != ',') {
                 /* advance to next segment of arg string */
-                ;
+                ++i;
+            }
         } else {
             /* reached end of parameter, set remaining components
                to 1x1 sampling */
@@ -768,42 +888,42 @@ set_sample_factors (j_compress_ptr cinfo, char *arg)
             cinfo->comp_info[ci].v_samp_factor = 1;
         }
     }
-    return TRUE;
+    return true;
 }
 
 
 
 static void
-setup_jpeg(struct jpeg_compress_struct * const cinfoP,
-           struct jpeg_error_mgr       * const jerrP,
-           struct cmdlineInfo            const cmdline,
-           int                           const width,
-           int                           const height,
-           pixval                        const maxval,
-           int                           const input_fmt,
-           FILE *                        const output_file) {
+setupJpeg(struct jpeg_compress_struct * const cinfoP,
+          struct jpeg_error_mgr       * const jerrP,
+          struct CmdlineInfo            const cmdline,
+          unsigned int                  const width,
+          unsigned int                  const height,
+          pixval                        const maxval,
+          int                           const inputFmt,
+          FILE *                        const ofP) {
 
     int quality;
-    int q_scale_factor;
+    int qScaleFactor;
 
     /* Initialize the JPEG compression object with default error handling. */
     cinfoP->err = jpeg_std_error(jerrP);
     jpeg_create_compress(cinfoP);
 
-    setup_jpeg_source_parameters(cinfoP, width, height, input_fmt);
+    setupJpegSourceParameters(cinfoP, width, height, inputFmt);
 
     jpeg_set_defaults(cinfoP);
 
     cinfoP->data_precision = BITS_IN_JSAMPLE;
         /* we always rescale data to this */
-    cinfoP->image_width = (unsigned int) width;
-    cinfoP->image_height = (unsigned int) height;
+    cinfoP->image_width = width;
+    cinfoP->image_height = height;
 
-    cinfoP->arith_code = cmdline.arith_code;
-    cinfoP->dct_method = cmdline.dct_method;
-    if (cmdline.trace_level == 0 && cmdline.verbose)
+    cinfoP->arith_code = cmdline.arithmetic;
+    cinfoP->dct_method = cmdline.dctMethod;
+    if (cmdline.tracelevel == 0 && cmdline.verbose)
         cinfoP->err->trace_level = 1;
-    else cinfoP->err->trace_level = cmdline.trace_level;
+    else cinfoP->err->trace_level = cmdline.tracelevel;
     if (cmdline.grayscale)
         jpeg_set_colorspace(cinfoP, JCS_GRAYSCALE);
     else if (cmdline.rgb)
@@ -812,38 +932,38 @@ setup_jpeg(struct jpeg_compress_struct * const cinfoP,
     else
         /* This default will be based on the in_color_space set above */
         jpeg_default_colorspace(cinfoP);
-    if (cmdline.max_memory_to_use != -1)
-        cinfoP->mem->max_memory_to_use = cmdline.max_memory_to_use;
+    if (cmdline.maxMemoryToUse != -1)
+        cinfoP->mem->max_memory_to_use = cmdline.maxMemoryToUse;
     cinfoP->optimize_coding = cmdline.optimize;
     if (cmdline.quality == -1) {
         quality = 75;
-        q_scale_factor = 100;
+        qScaleFactor = 100;
     } else {
         quality = cmdline.quality;
-        q_scale_factor = jpeg_quality_scaling(cmdline.quality);
+        qScaleFactor = jpeg_quality_scaling(cmdline.quality);
     }
-    if (cmdline.smoothing_factor != -1)
-        cinfoP->smoothing_factor = cmdline.smoothing_factor;
+    if (cmdline.smooth != -1)
+        cinfoP->smoothing_factor = cmdline.smooth;
 
     /* Set quantization tables for selected quality. */
     /* Some or all may be overridden if user specified --qtables. */
-    jpeg_set_quality(cinfoP, quality, cmdline.force_baseline);
+    jpeg_set_quality(cinfoP, quality, cmdline.baseline);
 
     if (cmdline.qtablefile != NULL) {
-        if (! read_quant_tables(cinfoP, cmdline.qtablefile,
-                                q_scale_factor, cmdline.force_baseline))
+        if (! readQuantTables(cinfoP, cmdline.qtablefile,
+                              qScaleFactor, cmdline.baseline))
             pm_error("Can't use quantization table file '%s'.",
                      cmdline.qtablefile);
     }
 
     if (cmdline.qslots != NULL) {
-        if (! set_quant_slots(cinfoP, cmdline.qslots))
+        if (! setQuantSlots(cinfoP, cmdline.qslots))
             pm_error("Bad quantization-table-selectors parameter string '%s'.",
                      cmdline.qslots);
     }
 
     if (cmdline.sample != NULL) {
-        if (! set_sample_factors(cinfoP, cmdline.sample))
+        if (! setSampleFactors(cinfoP, cmdline.sample))
             pm_error("Bad sample-factors parameters string '%s'.",
                      cmdline.sample);
     }
@@ -851,19 +971,24 @@ setup_jpeg(struct jpeg_compress_struct * const cinfoP,
     if (cmdline.progressive)
         jpeg_simple_progression(cinfoP);
 
-    if (cmdline.density_spec)
-        setup_jpeg_density(cinfoP, cmdline.density);
+    if (cmdline.densitySpec)
+        setupJpegDensity(cinfoP, cmdline.density);
 
     if (cmdline.scans != NULL) {
-        if (! read_scan_script(cinfoP, cmdline.scans)) {
-            pm_message("Error in scan script '%s'.", cmdline.scans);
+        const char * error;
+        readScanScript(cinfoP, cmdline.scans, &error);
+        if (error) {
+            pm_message("Error in scan script '%s'.  %s", cmdline.scans, error);
+            pm_strfree(error);
         }
-    }
+    } else
+        cinfoP->scan_info = NULL;
 
     /* Specify data destination for compression */
-    jpeg_stdio_dest(cinfoP, output_file);
+    jpeg_stdio_dest(cinfoP, ofP);
 
-    if (cmdline.verbose) report_compressor(*cinfoP);
+    if (cmdline.verbose)
+        reportCompressor(*cinfoP);
 
     /* Start compressor */
     jpeg_start_compress(cinfoP, TRUE);
@@ -873,115 +998,122 @@ setup_jpeg(struct jpeg_compress_struct * const cinfoP,
 
 
 static void
-write_exif_header(struct jpeg_compress_struct * const cinfoP,
-                  const char * const exif_filespec) {
+writeExifHeader(struct jpeg_compress_struct * const cinfoP,
+                const char *                  const exifFileNm) {
 /*----------------------------------------------------------------------------
    Generate an APP1 marker in the JFIF output that is an Exif header.
 
    The contents of the Exif header are in the file with filespec
-   'exif_filespec' (file spec and contents are not validated).
+   'exifFileNm' (file spec and contents are not validated).
 
-   exif_filespec = "-" means Standard Input.
+   exifFileNm = "-" means Standard Input.
 
    If the file contains just two bytes of zero, don't write any marker
    but don't recognize any error either.
 -----------------------------------------------------------------------------*/
-    FILE * exif_file;
+    FILE * exifFp;
     unsigned short length;
 
-    exif_file = pm_openr(exif_filespec);
+    exifFp = pm_openr(exifFileNm);
 
-    pm_readbigshort(exif_file, (short*)&length);
+    pm_readbigshort(exifFp, (short*)&length);
 
     if (length == 0) {
         /* Special value meaning "no header" */
     } else if (length < 3)
         pm_error("Invalid length %u at start of exif file", length);
     else {
-        unsigned char * exif_data;
-        size_t rc;
-        size_t const data_length = length - 2;
+        unsigned char * exifData;
+        size_t const dataLength = length - 2;
             /* Subtract 2 byte length field*/
+        size_t rc;
 
-        assert(data_length > 0);
+        assert(dataLength > 0);
 
-        exif_data = malloc(data_length);
-        if (exif_data == NULL)
+        MALLOCARRAY(exifData, dataLength);
+        if (!exifData)
             pm_error("Unable to allocate %u bytes for exif header buffer",
-                     (unsigned)data_length);
+                     (unsigned)dataLength);
 
-        rc = fread(exif_data, 1, data_length, exif_file);
+        rc = fread(exifData, 1, dataLength, exifFp);
 
-        if (rc != data_length)
+        if (rc != dataLength)
             pm_error("Premature end of file on exif header file.  Should be "
                      "%u bytes of data, read only %u",
-                     (unsigned)data_length, (unsigned)rc);
+                     (unsigned)dataLength, (unsigned)rc);
 
         jpeg_write_marker(cinfoP, JPEG_APP0+1,
-                          (const JOCTET *) exif_data, data_length);
+                          (const JOCTET *) exifData, dataLength);
 
-        free(exif_data);
+        free(exifData);
     }
 
-    pm_close(exif_file);
+    pm_close(exifFp);
 }
 
 
 
 static void
-compute_rescaling_array(JSAMPLE ** const rescale_p, const pixval maxval,
-                        const struct jpeg_compress_struct cinfo) {
+computeRescalingArray(JSAMPLE **                  const rescaleP,
+                      pixval                      const maxval,
+                      struct jpeg_compress_struct const cinfo) {
 /*----------------------------------------------------------------------------
    Compute the rescaling array for a maximum pixval of 'maxval'.
    Allocate the memory for it too.
 -----------------------------------------------------------------------------*/
-  const long half_maxval = maxval / 2;
-  long val;
-
-  *rescale_p = (JSAMPLE *)
-    (cinfo.mem->alloc_small) ((j_common_ptr) &cinfo, JPOOL_IMAGE,
-                              (size_t) (((long) maxval + 1L) *
-                                        sizeof(JSAMPLE)));
-  for (val = 0; val <= maxval; val++) {
-    /* The multiplication here must be done in 32 bits to avoid overflow */
-    (*rescale_p)[val] = (JSAMPLE) ((val*MAXJSAMPLE + half_maxval)/maxval);
-  }
+    long const halfMaxval = maxval / 2;
+
+    JSAMPLE * rescale;
+    long val;
+
+    MALLOCARRAY(rescale, maxval + 1);
+
+    if (!rescale)
+        pm_error("Failed to get memory for map of %u possible sample values",
+                 maxval + 1);
+
+    for (val = 0; val <= maxval; ++val) {
+        /* The multiplication here must be done in 32 bits to avoid overflow */
+        rescale[val] = (JSAMPLE) ((val*MAXJSAMPLE + halfMaxval)/maxval);
+    }
+
+    *rescaleP = rescale;
 }
 
 
 
 static void
-translate_row(const pixel pnm_buffer[],
-              JSAMPLE jpeg_buffer[],
-              int const width,
-              int const input_components,
-              const JSAMPLE translate[]) {
+translateRow(pixel        const pnm_buffer[],
+             unsigned int const width,
+             unsigned int const inputComponentCt,
+             JSAMPLE      const translate[],
+             JSAMPLE *    const jpegBuffer) {
 /*----------------------------------------------------------------------------
    Convert the input row, in pnm format, to an output row in JPEG compressor
    input format.
 
    This is a byte for byte copy, translated through the array 'translate'.
 -----------------------------------------------------------------------------*/
-  unsigned int column;
+  unsigned int col;
   /* I'm not sure why the JPEG library data structures don't have some kind
      of pixel data structure (such that a row buffer is an array of pixels,
      rather than an array of samples).  But because of this, we have to
      index jpeg_buffer the old fashioned way.
      */
 
-  switch (input_components) {
+  switch (inputComponentCt) {
   case 1:
-      for (column = 0; column < width; column++)
-          jpeg_buffer[column] = translate[(int)PNM_GET1(pnm_buffer[column])];
+      for (col = 0; col < width; ++col)
+          jpegBuffer[col] = translate[(int)PNM_GET1(pnm_buffer[col])];
       break;
   case 3:
-      for (column = 0; column < width; column++) {
-          jpeg_buffer[column*3+0] =
-              translate[(int)PPM_GETR(pnm_buffer[column])];
-          jpeg_buffer[column*3+1] =
-              translate[(int)PPM_GETG(pnm_buffer[column])];
-          jpeg_buffer[column*3+2] =
-              translate[(int)PPM_GETB(pnm_buffer[column])];
+      for (col = 0; col < width; ++col) {
+          jpegBuffer[col * 3 + 0] =
+              translate[(int)PPM_GETR(pnm_buffer[col])];
+          jpegBuffer[col * 3 + 1] =
+              translate[(int)PPM_GETG(pnm_buffer[col])];
+          jpegBuffer[col * 3 + 2] =
+              translate[(int)PPM_GETB(pnm_buffer[col])];
       }
       break;
   default:
@@ -994,72 +1126,69 @@ translate_row(const pixel pnm_buffer[],
 
 
 static void
-convert_scanlines(struct jpeg_compress_struct * const cinfo_p,
-                  FILE *                        const input_file,
-                  pixval                        const maxval,
-                  int                           const input_fmt,
-                  JSAMPLE                             xlate_table[]){
+convertScanLines(struct jpeg_compress_struct * const cinfoP,
+                 FILE *                        const inputFileNm,
+                 pixval                        const maxval,
+                 int                           const inputFmt,
+                 const JSAMPLE *               const xlateTable){
 /*----------------------------------------------------------------------------
-   Read scan lines from the input file, which is already opened in the
-   netpbm library sense and ready for reading, and write them to the
-   output JPEG object.  Translate the pnm sample values to JPEG sample
-   values through the thable xlate_table[].
+  Read scan lines from the input file, which is already opened in the
+  netpbm library sense and ready for reading, and write them to the
+  output JPEG object.  Translate the pnm sample values to JPEG sample
+  values through the table xlateTable[].
 -----------------------------------------------------------------------------*/
-  xel * pnm_buffer;
-    /* contains the row of the input image currently being processed,
-       in pnm_readpnmrow format
-    */
-  JSAMPARRAY buffer;
-    /* Row 0 of this array contains the row of the output image currently
-       being processed, in JPEG compressor input format.  The array only
-       has that one row.
-    */
+    xel * pnmBuffer;
+        /* This malloc'ed array contains the row of the input image currently
+           being processed, in pnm_readpnmrow format.
+        */
+    JSAMPLE * jpegBuffer;
+        /* This malloc'ed array contains the row of the output image currently
+           being processed, in JPEG compressor input format.
+        */
 
-  /* Allocate the libpnm output and compressor input buffers */
-  buffer = (*cinfo_p->mem->alloc_sarray)
-    ((j_common_ptr) cinfo_p, JPOOL_IMAGE,
-     (unsigned int) cinfo_p->image_width * cinfo_p->input_components,
-     (unsigned int) 1);
-
-  pnm_buffer = pnm_allocrow(cinfo_p->image_width);
-
-  while (cinfo_p->next_scanline < cinfo_p->image_height) {
-    if (cinfo_p->err->trace_level > 1)
-        pm_message("Converting Row %d...", cinfo_p->next_scanline);
-    pnm_readpnmrow(input_file, pnm_buffer, cinfo_p->image_width,
-                   maxval, input_fmt);
-    translate_row(pnm_buffer, buffer[0],
-                  cinfo_p->image_width, cinfo_p->input_components,
-                  xlate_table);
-    jpeg_write_scanlines(cinfo_p, buffer, 1);
-    if (cinfo_p->err->trace_level > 1)
-        pm_message("Done.");
-  }
+    MALLOCARRAY(jpegBuffer, cinfoP->image_width * cinfoP->input_components);
+    if (!jpegBuffer)
+        pm_error("Unable to allocate buffer for a row of %u pixels, "
+                 "%u samples each",
+                 cinfoP->image_width, cinfoP->input_components);
+
+    pnmBuffer = pnm_allocrow(cinfoP->image_width);
+
+    while (cinfoP->next_scanline < cinfoP->image_height) {
+        if (cinfoP->err->trace_level > 1)
+            pm_message("Converting Row %d...", cinfoP->next_scanline);
+        pnm_readpnmrow(inputFileNm, pnmBuffer, cinfoP->image_width,
+                       maxval, inputFmt);
+        translateRow(pnmBuffer,
+                     cinfoP->image_width, cinfoP->input_components,
+                     xlateTable,  jpegBuffer);
+        jpeg_write_scanlines(cinfoP, &jpegBuffer, 1);
+        if (cinfoP->err->trace_level > 1)
+            pm_message("Done.");
+    }
 
-  pnm_freerow(pnm_buffer);
-  /* Don't worry about the compressor input buffer; it gets freed
-     automatically
-  */
+    pnm_freerow(pnmBuffer);
+    free(jpegBuffer);
 }
 
 
 
 int
-main(int     argc,
-     char ** argv) {
+main(int           argc,
+     const char ** argv) {
 
-    struct cmdlineInfo cmdline;
+    struct CmdlineInfo cmdline;
     struct jpeg_compress_struct cinfo;
     struct jpeg_error_mgr jerr;
-    FILE * input_file;
-    FILE * output_file;
+    FILE * ifP;
+    FILE * ofP;
     int height;
         /* height of the input image in rows, as specified by its header */
     int width;
         /* width of the input image in columns, as specified by its header */
     pixval maxval;
         /* maximum value of an input pixel component, as specified by header */
-    int input_fmt;
+    int inputFmt;
         /* The input format, as determined by its header.  */
     JSAMPLE *rescale;         /* => maxval-remapping array, or NULL */
         /* This is an array that maps each possible pixval in the input to
@@ -1067,48 +1196,53 @@ main(int     argc,
            0 .. maxval, the range of the output values is 0 .. MAXJSAMPLE.
         */
 
-    pnm_init(&argc, argv);
+    pm_proginit(&argc, argv);
 
     parseCommandLine(argc, argv, &cmdline);
 
-    input_file = pm_openr(cmdline.input_filespec);
-    free(cmdline.input_filespec);
+    ifP = pm_openr(cmdline.inputFileNm);
 
-    output_file = stdout;
+    ofP = stdout;
 
     /* Open the pnm input */
-    pnm_readpnminit(input_file, &width, &height, &maxval, &input_fmt);
+    pnm_readpnminit(ifP, &width, &height, &maxval, &inputFmt);
     if (cmdline.verbose) {
         pm_message("Input file has format %c%c.\n"
                    "It has %d rows of %d columns of pixels "
                    "with max sample value of %d.",
-                   (char) (input_fmt/256), (char) (input_fmt % 256),
+                   (char) (inputFmt/256), (char) (inputFmt % 256),
                    height, width, maxval);
     }
 
-    setup_jpeg(&cinfo, &jerr, cmdline, width, height, maxval, input_fmt,
-               output_file);
+    setupJpeg(&cinfo, &jerr, cmdline, width, height, maxval, inputFmt, ofP);
 
-    compute_rescaling_array(&rescale, maxval, cinfo);
+    computeRescalingArray(&rescale, maxval, cinfo);
 
     if (cmdline.comment)
         jpeg_write_marker(&cinfo, JPEG_COM, (const JOCTET *) cmdline.comment,
                           strlen(cmdline.comment));
 
-    if (cmdline.exif_filespec)
-        write_exif_header(&cinfo, cmdline.exif_filespec);
+    if (cmdline.exif)
+        writeExifHeader(&cinfo, cmdline.exif);
 
     /* Translate and copy over the actual scanlines */
-    convert_scanlines(&cinfo, input_file, maxval, input_fmt, rescale);
+    convertScanLines(&cinfo, ifP, maxval, inputFmt, rescale);
 
     /* Finish compression and release memory */
     jpeg_finish_compress(&cinfo);
     jpeg_destroy_compress(&cinfo);
 
+    if (cinfo.scan_info) {
+        free((void*)cinfo.scan_info);
+        cinfo.scan_info = NULL;
+    }
+    free(rescale);
+
     /* Close files, if we opened them */
-    if (input_file != stdin)
-        pm_close(input_file);
+    if (ifP != stdin)
+        pm_close(ifP);
 
+    free(cmdline.inputFileNm);
     /* Program may have exited with non-zero completion code via
        various function calls above.
     */
diff --git a/converter/other/pnmtopalm/gen_palm_colormap.c b/converter/other/pnmtopalm/gen_palm_colormap.c
index 0f3f8a5f..04555221 100644
--- a/converter/other/pnmtopalm/gen_palm_colormap.c
+++ b/converter/other/pnmtopalm/gen_palm_colormap.c
@@ -15,7 +15,7 @@ main(int     argc,
     Colormap defaultMap;
     unsigned int i;
     pixel pix;
-    
+
     defaultMap = palmcolor_build_default_8bit_colormap();
     qsort (defaultMap->color_entries, defaultMap->ncolors,
            sizeof(Color_s), palmcolor_compare_indices);
@@ -44,3 +44,5 @@ main(int     argc,
     return 0;
 }
 
+
+
diff --git a/converter/other/pnmtopalm/palm.h b/converter/other/pnmtopalm/palm.h
index 0edf9a28..0a2a7cfc 100644
--- a/converter/other/pnmtopalm/palm.h
+++ b/converter/other/pnmtopalm/palm.h
@@ -7,7 +7,7 @@
 #define PALM_INDIRECT_BITMAP        0x1000  /* Palm says internal use only */
 #define PALM_FOR_SCREEN             0x0800  /* Palm says internal use only */
 #define PALM_DIRECT_COLOR_FLAG      0x0400
-#define PALM_INDIRECT_COLORMAP      0x0200  /* Palm says internal use only */ 
+#define PALM_INDIRECT_COLORMAP      0x0200  /* Palm says internal use only */
 #define PALM_NO_DITHER_FLAG         0x0100  /* rather mysterious */
 
 #define PALM_COMPRESSION_SCANLINE   0x00
diff --git a/converter/other/pnmtopalm/palmcolormap.c b/converter/other/pnmtopalm/palmcolormap.c
index 1341ca2b..de3def22 100644
--- a/converter/other/pnmtopalm/palmcolormap.c
+++ b/converter/other/pnmtopalm/palmcolormap.c
@@ -28,7 +28,7 @@ palmcolor_mapEntryColorFmPixel(pixel  const color,
 
     return
         0
-        | (scaleSample(PPM_GETR(color), maxval, newMaxval) << 16) 
+        | (scaleSample(PPM_GETR(color), maxval, newMaxval) << 16)
         | (scaleSample(PPM_GETG(color), maxval, newMaxval) <<  8)
         | (scaleSample(PPM_GETB(color), maxval, newMaxval) <<  0);
 }
@@ -68,6 +68,8 @@ palmcolor_compare_colors(const void * const p1,
         return 0;
 }
 
+
+
 /***********************************************************************
  ***********************************************************************
  ***********************************************************************
@@ -81,7 +83,7 @@ palmcolor_compare_colors(const void * const p1,
 /*
  * The 1bit-2 color system palette for Palm Computing Devices.
  */
-static int PalmPalette1bpp[2][3] = 
+static int PalmPalette1bpp[2][3] =
 {
   { 255, 255, 255}, {   0,   0,   0 }
 };
@@ -89,7 +91,7 @@ static int PalmPalette1bpp[2][3] =
 /*
  * The 2bit-4 color system palette for Palm Computing Devices.
  */
-static int PalmPalette2bpp[4][3] = 
+static int PalmPalette2bpp[4][3] =
 {
   { 255, 255, 255}, { 192, 192, 192}, { 128, 128, 128 }, {   0,   0,   0 }
 };
@@ -97,7 +99,7 @@ static int PalmPalette2bpp[4][3] =
 /*
  * The 4bit-16 color system palette for Palm Computing Devices.
  */
-static int PalmPalette4bpp[16][3] = 
+static int PalmPalette4bpp[16][3] =
 {
   { 255, 255, 255}, { 238, 238, 238 }, { 221, 221, 221 }, { 204, 204, 204 },
   { 187, 187, 187}, { 170, 170, 170 }, { 153, 153, 153 }, { 136, 136, 136 },
@@ -108,7 +110,7 @@ static int PalmPalette4bpp[16][3] =
 /*
  * The 4bit-16 color system palette for Palm Computing Devices.
  */
-static int PalmPalette4bppColor[16][3] = 
+static int PalmPalette4bppColor[16][3] =
 {
   { 255, 255, 255}, { 128, 128, 128 }, { 128,   0,   0 }, { 128, 128,   0 },
   {   0, 128,   0}, {   0, 128, 128 }, {   0,   0, 128 }, { 128,   0, 128 },
@@ -123,12 +125,12 @@ static int PalmPalette4bppColor[16][3] =
  *
  * NOTE:  only the first 231, plus the last one, are valid.
  */
-static int PalmPalette8bpp[256][3] = 
+static int PalmPalette8bpp[256][3] =
 {
-  { 255, 255, 255 }, { 255, 204, 255 }, { 255, 153, 255 }, { 255, 102, 255 }, 
-  { 255,  51, 255 }, { 255,   0, 255 }, { 255, 255, 204 }, { 255, 204, 204 }, 
-  { 255, 153, 204 }, { 255, 102, 204 }, { 255,  51, 204 }, { 255,   0, 204 }, 
-  { 255, 255, 153 }, { 255, 204, 153 }, { 255, 153, 153 }, { 255, 102, 153 }, 
+  { 255, 255, 255 }, { 255, 204, 255 }, { 255, 153, 255 }, { 255, 102, 255 },
+  { 255,  51, 255 }, { 255,   0, 255 }, { 255, 255, 204 }, { 255, 204, 204 },
+  { 255, 153, 204 }, { 255, 102, 204 }, { 255,  51, 204 }, { 255,   0, 204 },
+  { 255, 255, 153 }, { 255, 204, 153 }, { 255, 153, 153 }, { 255, 102, 153 },
   { 255,  51, 153 }, { 255,   0, 153 }, { 204, 255, 255 }, { 204, 204, 255 },
   { 204, 153, 255 }, { 204, 102, 255 }, { 204,  51, 255 }, { 204,   0, 255 },
   { 204, 255, 204 }, { 204, 204, 204 }, { 204, 153, 204 }, { 204, 102, 204 },
@@ -215,7 +217,7 @@ palmcolor_build_default_8bit_colormap(void) {
     cmP->ncolors = 232;
 
     /* now sort the table */
-    qsort(cmP->color_entries, cmP->ncolors, sizeof(ColormapEntry), 
+    qsort(cmP->color_entries, cmP->ncolors, sizeof(ColormapEntry),
           palmcolor_compare_colors);
     return cmP;
 }
@@ -235,7 +237,7 @@ palmcolor_build_custom_8bit_colormap(pixel **     const pixels,
     colormapP->nentries = 256;
     MALLOCARRAY_NOFAIL(colormapP->color_entries, colormapP->nentries);
     colormapP->ncolors = 0;  /* initial value */
-    
+
     for (row = 0; row < rows; ++row) {
         unsigned int col;
         for (col = 0; col < cols; ++col) {
@@ -259,7 +261,7 @@ palmcolor_build_custom_8bit_colormap(pixel **     const pixels,
                     ColormapEntry const newEntry =
                         searchTarget | (colorIndex << 24);
                     colormapP->color_entries[colorIndex] = newEntry;
-                    qsort(colormapP->color_entries, colormapP->ncolors, 
+                    qsort(colormapP->color_entries, colormapP->ncolors,
                           sizeof(ColormapEntry), palmcolor_compare_colors);
                 }
             }
@@ -276,7 +278,7 @@ palmcolor_read_colormap (FILE * const ifP) {
     unsigned short ncolors;
     Colormap * retval;
     int rc;
-    
+
     rc = pm_readbigshort(ifP, (short *) &ncolors);
     if (rc != 0)
         retval = NULL;
@@ -289,7 +291,7 @@ palmcolor_read_colormap (FILE * const ifP) {
         MALLOCVAR_NOFAIL(colormapP);
         colormapP->nentries = ncolors;
         MALLOCARRAY_NOFAIL(colormapP->color_entries, colormapP->nentries);
-        
+
         for (i = 0, error = FALSE;  i < ncolors && !error;  ++i) {
             int rc;
             rc = pm_readbiglong(ifP, &colorentry);
@@ -309,3 +311,6 @@ palmcolor_read_colormap (FILE * const ifP) {
     }
     return retval;
 }
+
+
+
diff --git a/converter/other/pnmtopalm/palmtopnm.c b/converter/other/pnmtopalm/palmtopnm.c
index 445f7839..0e83f5e0 100644
--- a/converter/other/pnmtopalm/palmtopnm.c
+++ b/converter/other/pnmtopalm/palmtopnm.c
@@ -445,6 +445,7 @@ yesno(bool const arg) {
 }
 
 
+
 static void
 reportPalmHeader(struct PalmHeader      const palmHeader,
                  struct DirectColorInfo const directColorInfo) {
@@ -821,27 +822,46 @@ readPackBitsRow16(FILE *          const ifP,
 
         Although the [...] spec is byte-oriented, the 16-bit algorithm is
         identical [to the 8-bit algorithm]: just substitute "word" for "byte".
+
+        A note about the 0x80 control byte value: There are some sources that
+        suggest that 1) no Palm file ever uses that value; and 2) a Palm
+        decoder should treat it as a no-op and other decoders do.  We don't
+        treat it as a no-op because we believe it is far more likely that if
+        someone _does_ put that value in a file, he means "repeat the next
+        word 129 times" than "do nothing."  Plus, it's just simpler and
+        cleaner.  Because of the ambiguity, though, anyone creating a Palm
+        file should avoid 0x80.
     */
     unsigned int j;
 
     for (j = 0;  j < bytesPerRow; ) {
-        char incount;
-        pm_readchar(ifP, &incount);
-        if (incount < 0) {
-            /* How do we handle incount == -128 ? */
-            unsigned int const runlength = (-incount + 1) * 2;
-            unsigned int k;
+        unsigned char controlByte;
+        unsigned int  controlNum;
+
+        pm_readcharu(ifP, &controlByte);
+        controlNum = (unsigned int)controlByte;
+
+        if (controlNum >= 128) {
+            /* It's a run - output multiple copies of the next input word */
+            unsigned int const runlength = (257 - controlNum) * 2;
+
             unsigned short inval;
+
             pm_readlittleshortu(ifP, &inval);
+
             if (j + runlength <= bytesPerRow) {
+                unsigned int k;
                 for (k = 0; k < runlength; k += 2)
                     memcpy(palmrow + j + k, &inval, 2);
             }
             j += runlength;
         } else {
+            /* It's a nonrun - output the next words literally */
             /* We just read the stream of shorts as a stream of chars */
-            unsigned int const nonrunlength = (incount + 1) * 2;
+            unsigned int const nonrunlength = (controlNum + 1) * 2;
+
             unsigned int k;
+
             for (k = 0; (k < nonrunlength) && (j + k <= bytesPerRow); ++k) {
                 unsigned char inval;
                 pm_readcharu(ifP, &inval);
@@ -865,22 +885,32 @@ readPackBitsRow(FILE *          const ifP,
                 unsigned char * const palmrow,
                 unsigned int    const bytesPerRow) {
 
+    /* See comments in 'readPackbitsRow16.  Everything here is the same
+       except with 1-byte words instead of 2-byte words.
+    */
     unsigned int j;
 
     for (j = 0;  j < bytesPerRow; ) {
-        char incount;
-        pm_readchar(ifP, &incount);
-        if (incount < 0) {
-            /* How do we handle incount == -128 ? */
-            unsigned int const runlength = -incount + 1;
+        unsigned char controlByte;
+        unsigned int  controlNum;
+
+        pm_readcharu(ifP, &controlByte);
+        controlNum = controlByte;
+
+        if (controlNum >= 128) {
+            unsigned int const runlength = 257 - controlNum;
+
             unsigned char inval;
+
             pm_readcharu(ifP, &inval);
             if (j + runlength <= bytesPerRow)
                 memset(palmrow + j, inval, runlength);
             j += runlength;
         } else {
-            unsigned int const nonrunlength = incount + 1;
+            unsigned int const nonrunlength = controlNum + 1;
+
             unsigned int k;
+
             for (k = 0; k < nonrunlength && j + k <= bytesPerRow; ++k) {
                 unsigned char inval;
                 pm_readcharu(ifP, &inval);
@@ -1221,3 +1251,6 @@ main(int argc, const char **argv) {
 
     return 0;
 }
+
+
+
diff --git a/converter/other/pnmtopalm/pnmtopalm.c b/converter/other/pnmtopalm/pnmtopalm.c
index 9fc92790..ab82996e 100644
--- a/converter/other/pnmtopalm/pnmtopalm.c
+++ b/converter/other/pnmtopalm/pnmtopalm.c
@@ -816,6 +816,7 @@ computeRawRowNonDirect(const xel *     const xelrow,
 }
 
 
+
 typedef struct {
 /*----------------------------------------------------------------------------
    A buffer to which one can write bytes sequentially.
@@ -1352,3 +1353,6 @@ main( int argc, const char **argv ) {
 
     return 0;
 }
+
+
+
diff --git a/converter/other/pnmtopclxl.c b/converter/other/pnmtopclxl.c
index f7db62ee..c7d0642c 100644
--- a/converter/other/pnmtopclxl.c
+++ b/converter/other/pnmtopclxl.c
@@ -456,7 +456,6 @@ createPclGenerator(struct pam *        const pamP,
 
 
 
-
 struct tPrinter {
     const char *name;
     float topmargin;
@@ -1136,3 +1135,6 @@ main(int argc, char *argv[]) {
 
     return 0;
 }
+
+
+
diff --git a/converter/other/pnmtopng.c b/converter/other/pnmtopng.c
index b7bd6d07..10b586b0 100644
--- a/converter/other/pnmtopng.c
+++ b/converter/other/pnmtopng.c
@@ -56,13 +56,10 @@
 #endif                               /*  2 for warnings (1 == error) */
 
 #include <assert.h>
+#include <stdbool.h>
 #include <string.h> /* strcat() */
 #include <limits.h>
 #include <png.h>
-/* Because of a design error in png.h, you must not #include <setjmp.h> before
-   <png.h>.  If you do, png.h won't compile.
-*/
-#include <setjmp.h>
 #include <zlib.h>
 
 #include "pm_c_util.h"
@@ -136,16 +133,6 @@ struct cmdlineInfo {
 
 
 
-typedef struct _jmpbuf_wrapper {
-  jmp_buf jmpbuf;
-} jmpbuf_wrapper;
-
-#ifndef TRUE
-#  define TRUE 1
-#endif
-#ifndef FALSE
-#  define FALSE 0
-#endif
 #ifndef NONE
 #  define NONE 0
 #endif
@@ -160,7 +147,6 @@ typedef struct _jmpbuf_wrapper {
 
 static bool verbose;
 
-static jmpbuf_wrapper pnmtopng_jmpbuf_struct;
 static int errorlevel;
 
 
@@ -192,9 +178,9 @@ parseRgbOpt(const char *         const rgbOpt,
                    &rgbP->gx, &rgbP->gy,
                    &rgbP->bx, &rgbP->by);
 
-    if (count != 6)
+    if (count != 8)
         pm_error("Invalid syntax for the -rgb option value '%s'.  "
-                 "Should be 6 floating point number: "
+                 "Should be 8 floating point numbers: "
                  "x and y for each of white, red, green, and blue",
                  rgbOpt);
 }
@@ -298,9 +284,7 @@ parseCommandLine(int argc, const char ** argv,
    Note that the strings we return are stored in the storage that
    was passed to us as the argv array.  We also trash *argv.
 -----------------------------------------------------------------------------*/
-    optEntry *option_def;
-        /* Instructions to pm_optParseOptions3 on how to parse our options.
-         */
+    optEntry * option_def;   /* Used by OPTENT3 */
     optStruct3 opt;
 
     unsigned int option_def_index;
@@ -394,10 +378,10 @@ parseCommandLine(int argc, const char ** argv,
 
 
     opt.opt_table = option_def;
-    opt.short_allowed = FALSE;  /* We have no short (old-fashioned) options */
-    opt.allowNegNum = FALSE;  /* We have no parms that are negative numbers */
+    opt.short_allowed = false;  /* We have no short (old-fashioned) options */
+    opt.allowNegNum = false;  /* We have no parms that are negative numbers */
 
-    pm_optParseOptions3(&argc, (char **)argv, opt, sizeof(opt), 0);
+    pm_optParseOptions4(&argc, argv, opt, sizeof(opt), 0);
         /* Uses and sets argc, argv, and some of *cmdlineP and others. */
 
 
@@ -511,6 +495,8 @@ parseCommandLine(int argc, const char ** argv,
         cmdlineP->inputFileName = argv[1];
     else
         pm_error("Program takes at most one argument:  input file name");
+
+    free(option_def);
 }
 
 
@@ -613,6 +599,7 @@ alloccoloralphahash(void)  {
 }
 
 
+
 static void
 freecoloralphahash(coloralphahash_table const caht) {
     int i;
@@ -671,7 +658,7 @@ lookupColorAlpha(coloralphahash_table const caht,
 
 
 /* The following variables belong to getChv() and freeChv() */
-static bool getChv_computed = FALSE;
+static bool getChv_computed = false;
 static colorhist_vector getChv_chv;
 
 
@@ -722,7 +709,7 @@ getChv(FILE *             const ifP,
             else
                 pm_message("Too many colors (more than %u) found", maxColors);
         }
-        getChv_computed = TRUE;
+        getChv_computed = true;
     }
     *chvP = getChv_chv;
     *colorsP = getChv_colors;
@@ -736,7 +723,7 @@ static void freeChv(void) {
         if (getChv_chv)
             ppm_freecolorhist(getChv_chv);
 
-    getChv_computed = FALSE;
+    getChv_computed = false;
 }
 
 
@@ -750,7 +737,7 @@ pgmBitsAreRepeated(unsigned int const repeatedSize,
                    xelval       const maxval,
                    int          const format) {
 /*----------------------------------------------------------------------------
-   Return TRUE iff all the samples in the image in file 'ifP',
+   Return true iff all the samples in the image in file 'ifP',
    described by 'cols', 'rows', 'maxval', and 'format', consist in the
    rightmost 'repeatedSize' * 2 bits of two identical sets of
    'repeatedSize' bits.
@@ -774,7 +761,7 @@ pgmBitsAreRepeated(unsigned int const repeatedSize,
 
     pm_seek2(ifP, &rasterPos, sizeof(rasterPos));
 
-    mayscale = TRUE;  /* initial assumption */
+    mayscale = true;  /* initial assumption */
 
     for (row = 0; row < rows && mayscale; ++row) {
         unsigned int col;
@@ -785,7 +772,7 @@ pgmBitsAreRepeated(unsigned int const repeatedSize,
             xelval const testbits1 = testbits2 & mask1;
                 /* The lower half of the bits of interest in the sample */
             if (((testbits1 << repeatedSize) | testbits1) != testbits2)
-                mayscale = FALSE;
+                mayscale = false;
         }
     }
     pnm_freerow(xelrow);
@@ -878,7 +865,7 @@ meaningful_bits_ppm(FILE *         const ifp,
     maxMeaningfulBits = pm_maxvaltobits(maxval);
 
     if (maxval == 65535) {
-        mayscale = TRUE;   /* initial assumption */
+        mayscale = true;   /* initial assumption */
         pm_seek2(ifp, &rasterPos, sizeof(rasterPos));
         for (row = 0; row < rows && mayscale; ++row) {
             unsigned int col;
@@ -888,7 +875,7 @@ meaningful_bits_ppm(FILE *         const ifp,
                 if ((PPM_GETR(p) & 0xff) * 0x101 != PPM_GETR(p) ||
                     (PPM_GETG(p) & 0xff) * 0x101 != PPM_GETG(p) ||
                     (PPM_GETB(p) & 0xff) * 0x101 != PPM_GETB(p))
-                    mayscale = FALSE;
+                    mayscale = false;
             }
         }
         if (mayscale)
@@ -902,7 +889,7 @@ meaningful_bits_ppm(FILE *         const ifp,
 
 
 static void
-tryTransparentColor(FILE *     const ifp,
+tryTransparentColor(FILE *     const ifP,
                     pm_filepos const rasterPos,
                     int        const cols,
                     int        const rows,
@@ -912,7 +899,14 @@ tryTransparentColor(FILE *     const ifp,
                     gray       const alphaMaxval,
                     pixel      const transcolor,
                     bool *     const singleColorIsTransP) {
+/*----------------------------------------------------------------------------
+   Find out if the transparent pixels identified by alpha mask 'alphaMask'
+   (whose maxval is 'alphaMaxval') are exactly the pixels of color
+   'transcolor'.  Return answer as *singleColorIsTransP.
 
+   The image we analyze is that on input stream *ifP, starting at position
+   'rasterPos', and we leave that stream positioned arbitrarily.
+-----------------------------------------------------------------------------*/
     int const pnmType = PNM_FORMAT_TYPE(format);
 
     xel * xelrow;
@@ -922,13 +916,13 @@ tryTransparentColor(FILE *     const ifp,
 
     xelrow = pnm_allocrow(cols);
 
-    pm_seek2(ifp, &rasterPos, sizeof(rasterPos));
+    pm_seek2(ifP, &rasterPos, sizeof(rasterPos));
 
-    singleColorIsTrans = TRUE;  /* initial assumption */
+    singleColorIsTrans = true;  /* initial assumption */
 
     for (row = 0; row < rows && singleColorIsTrans; ++row) {
         int col;
-        pnm_readpnmrow(ifp, xelrow, cols, maxval, format);
+        pnm_readpnmrow(ifP, xelrow, cols, maxval, format);
         for (col = 0 ; col < cols && singleColorIsTrans; ++col) {
             if (alphaMask[row][col] == 0) { /* transparent */
                 /* If we have a second transparent color, we're
@@ -936,16 +930,16 @@ tryTransparentColor(FILE *     const ifp,
                 */
                 if (pnmType == PPM_TYPE) {
                     if (!PPM_EQUAL(xelrow[col], transcolor))
-                        singleColorIsTrans = FALSE;
+                        singleColorIsTrans = false;
                 } else {
                     if (PNM_GET1(xelrow[col]) != PNM_GET1(transcolor))
-                        singleColorIsTrans = FALSE;
+                        singleColorIsTrans = false;
                 }
             } else if (alphaMask[row][col] != alphaMaxval) {
                 /* Here's an area of the mask that is translucent.  That
                    disqualified us.
                 */
-                singleColorIsTrans = FALSE;
+                singleColorIsTrans = false;
             } else {
                 /* Here's an area of the mask that is opaque.  If it's
                    the same color as our candidate transparent color,
@@ -953,14 +947,16 @@ tryTransparentColor(FILE *     const ifp,
                 */
                 if (pnmType == PPM_TYPE) {
                     if (PPM_EQUAL(xelrow[col], transcolor))
-                        singleColorIsTrans = FALSE;
+                        singleColorIsTrans = false;
                 } else {
                     if (PNM_GET1(xelrow[col]) == PNM_GET1(transcolor))
-                        singleColorIsTrans = FALSE;
+                        singleColorIsTrans = false;
                 }
             }
         }
     }
+    *singleColorIsTransP = singleColorIsTrans;
+
     pnm_freerow(xelrow);
 }
 
@@ -988,8 +984,8 @@ analyzeAlpha(FILE *       const ifP,
   of a certain color fully transparent and every other pixel opaque,
   we can simply identify that color in the PNG.
 
-  We have to do this before any scaling occurs, since alpha is only
-  possible with 8 and 16-bit.
+  We have to do this before any scaling occurs, since alpha is possible
+  only with 8 and 16-bit.
 -----------------------------------------------------------------------------*/
     xel * xelrow;
     bool foundTransparentPixel;
@@ -1032,7 +1028,7 @@ analyzeAlpha(FILE *       const ifP,
             pnm_readpnmrow(ifP, xelrow, cols, maxval, format);
             for (col = 0; col < cols && !foundTransparentPixel; ++col) {
                 if (alphaMask[row][col] == 0) {
-                    foundTransparentPixel = TRUE;
+                    foundTransparentPixel = true;
                     transcolor = pnm_xeltopixel(xelrow[col], format);
                 }
             }
@@ -1113,16 +1109,16 @@ determineTransparency(struct cmdlineInfo const cmdline,
         if (alphaCanBeTransparencyIndex && !cmdline.force) {
             if (verbose)
                 pm_message("converting alpha mask to transparency index");
-            *alphaP       = FALSE;
+            *alphaP       = false;
             *transparentP = 2;
             *transColorP  = alphaTranscolor;
         } else if (allOpaque) {
             if (verbose)
                 pm_message("Skipping alpha because mask is all opaque");
-            *alphaP       = FALSE;
+            *alphaP       = false;
             *transparentP = -1;
         } else {
-            *alphaP       = TRUE;
+            *alphaP       = true;
             *transparentP = -1;
         }
         *alphaMaxvalP = alphaMaxval;
@@ -1132,17 +1128,17 @@ determineTransparency(struct cmdlineInfo const cmdline,
            use with trans[], which can have stuff in it if the user specified
            a transparent color.
         */
-        *alphaP       = FALSE;
+        *alphaP       = false;
         *alphaMaxvalP = 255;
 
         if (cmdline.transparent) {
             const char * transstring2;
             /* The -transparent value, but with possible leading '=' removed */
             if (cmdline.transparent[0] == '=') {
-                *transExactP = TRUE;
+                *transExactP = true;
                 transstring2 = &cmdline.transparent[1];
             } else {
-                *transExactP = FALSE;
+                *transExactP = false;
                 transstring2 = cmdline.transparent;
             }
             /* We do this funny PPM_DEPTH thing instead of just passing 'maxval'
@@ -1204,7 +1200,7 @@ hasColor(FILE *       const ifP,
             for (col = 0; col < cols && isGray; ++col) {
                     xel const p = xelrow[col];
                 if (PPM_GETR(p) != PPM_GETG(p) || PPM_GETG(p) != PPM_GETB(p))
-                    isGray = FALSE;
+                    isGray = false;
             }
         }
 
@@ -1333,10 +1329,10 @@ compute_nonalpha_palette(colorhist_vector const chv,
             int j;
             bool found;
 
-            found = FALSE;
+            found = false;
             for (j = 0; j < ordered_palette_size && !found; ++j) {
                 if (PNM_EQUAL(ordered_palette[j], chv[colorIndex].color))
-                    found = TRUE;
+                    found = true;
             }
             if (!found)
                 pm_error("failed to find color (%d, %d, %d), which is in the "
@@ -1468,9 +1464,14 @@ computeUnsortedAlphaPalette(FILE *           const ifP,
     int row;
     xel * xelrow;
     unsigned int alphaColorPairCnt;
+        /* Number of different alpha/color pairs we've seen so far as we
+           iterate through the image.
+        */
 
     cht = ppm_colorhisttocolorhash(chv, colors);
 
+    /* We have not seen any alphas of any color yet. */
+    alphaColorPairCnt = 0;
     for (colorIndex = 0; colorIndex < colors; ++colorIndex) {
         alphasOfColor[colorIndex] = NULL;
         alphasOfColorCnt[colorIndex] = 0;
@@ -1629,7 +1630,7 @@ compute_alpha_palette(FILE *         const ifP,
    MAXPALETTEENTRIES elements.
 
    If there are more than MAXPALETTEENTRIES color/alpha pairs in the image,
-   don't return any palette information -- just return *tooBigP == TRUE.
+   don't return any palette information -- just return *tooBigP == true.
 -----------------------------------------------------------------------------*/
     colorhist_vector chv;
     unsigned int colors;
@@ -1707,9 +1708,9 @@ makeOneColorTransparentInPalette(xel            const transColor,
    can do a better job when the opaque entries are all last in the
    color/alpha palette).
 
-   If the specified color is not there and exact == TRUE, return
+   If the specified color is not there and exact == true, return
    without changing anything, but issue a warning message.  If it's
-   not there and exact == FALSE, just find the closest color.
+   not there and exact == false, just find the closest color.
 
    We assume every entry in the palette is opaque upon entry.
 
@@ -2208,6 +2209,7 @@ computeRasterWidth(bool           const colorMapped,
 }
 
 
+
 static void
 createPngPalette(pixel              palette_pnm[],
                  unsigned int const paletteSize,
@@ -2362,7 +2364,8 @@ writeRaster(struct pngx *        const pngxP,
     /* max: 3 color channels, one alpha channel, 16-bit */
     MALLOCARRAY(line, cols * 8);
     if (line == NULL)
-        pm_error("out of memory allocating PNG row buffer");
+        pm_error("out of memory allocating PNG row buffer for %u columns",
+                 cols);
 
     for (pass = 0; pass < pngxP->numPassesRequired; ++pass) {
         unsigned int row;
@@ -2379,6 +2382,7 @@ writeRaster(struct pngx *        const pngxP,
             pngx_writeRow(pngxP, line);
         }
     }
+    free(line);
     pnm_freerow(xelrow);
 }
 
@@ -2552,6 +2556,7 @@ reportTrans(struct pngx * const pngxP) {
 }
 
 
+
 static void
 doTrnsChunk(struct pngx * const pngxP,
             png_byte      const transPalette[],
@@ -2719,7 +2724,6 @@ convertpnm(struct cmdlineInfo const cmdline,
         /* The background color, with maxval equal to that of the input
            image.
         */
-    jmp_buf jmpbuf;
     struct pngx * pngxP;
 
     bool colorMapped;
@@ -2774,10 +2778,7 @@ convertpnm(struct cmdlineInfo const cmdline,
 
     errorlevel = 0;
 
-    if (setjmp(jmpbuf))
-        pm_error ("setjmp returns error condition");
-
-    pngx_create(&pngxP, PNGX_WRITE, &jmpbuf);
+    pngx_create(&pngxP, PNGX_WRITE, NULL);
 
     pnm_readpnminit(ifP, &cols, &rows, &maxval, &format);
     pm_tell2(ifP, &rasterPos, sizeof(rasterPos));
@@ -2830,9 +2831,9 @@ convertpnm(struct cmdlineInfo const cmdline,
         if (verbose)
             pm_message("Not using color map.  %s", noColormapReason);
         pm_strfree(noColormapReason);
-        colorMapped = FALSE;
+        colorMapped = false;
     } else
-        colorMapped = TRUE;
+        colorMapped = true;
 
     computeColorMapLookupTable(colorMapped, palettePnm, paletteSize,
                                transPnm, transSize, alpha, alphaMaxval,
@@ -2853,10 +2854,6 @@ convertpnm(struct cmdlineInfo const cmdline,
 
     pngMaxval = pm_bitstomaxval(depth);
 
-    if (setjmp (pnmtopng_jmpbuf_struct.jmpbuf)) {
-        pm_error ("setjmp returns error condition (2)");
-    }
-
     doIhdrChunk(pngxP, cols, rows, depth, colorMapped, colorPng, alpha,
                 cmdline.interlace);
 
diff --git a/converter/other/pnmtops.c b/converter/other/pnmtops.c
index 45d856d0..3dd0be79 100644
--- a/converter/other/pnmtops.c
+++ b/converter/other/pnmtops.c
@@ -9,7 +9,7 @@
 
          We use methods we learned from Dirk Krause's program Bmeps.
          Previous versions used raster encoding code based on Bmeps
-         code.  This program does not used any code from Bmeps.
+         code.  This program does not use any code from Bmeps.
 
       2) Use our own filters and redefine /readstring .  This is aboriginal
          Netpbm code, from when Postscript was young.  The filters are
@@ -58,6 +58,10 @@
 
 
 
+unsigned int const psScaleFactor = 72;
+
+
+
 static void
 setSignals() {
 /*----------------------------------------------------------------------------
@@ -260,7 +264,7 @@ parseCommandLine(int argc, const char ** argv,
     opt.short_allowed = FALSE;
     opt.allowNegNum = FALSE;
 
-    pm_optParseOptions3(&argc, (char **)argv, opt, sizeof(opt), 0);
+    pm_optParseOptions4(&argc, argv, opt, sizeof(opt), 0);
 
     if (cmdlineP->mustturn && noturn)
         pm_error("You cannot specify both -turn and -noturn");
@@ -291,21 +295,21 @@ parseCommandLine(int argc, const char ** argv,
     cmdlineP->canturn =  !noturn;
     cmdlineP->showpage = !noshowpage;
 
-    validateCompDimension(width, 72, "-width value");
-    validateCompDimension(height, 72, "-height value");
+    validateCompDimension(width,  psScaleFactor, "-width value");
+    validateCompDimension(height, psScaleFactor, "-height value");
 
-    cmdlineP->width  = width * 72;
-    cmdlineP->height = height * 72;
+    cmdlineP->width  = width  * psScaleFactor;
+    cmdlineP->height = height * psScaleFactor;
 
     if (imagewidthSpec) {
-        validateCompDimension(imagewidth, 72, "-imagewidth value");
-        cmdlineP->imagewidth = imagewidth * 72;
+        validateCompDimension(imagewidth, psScaleFactor, "-imagewidth value");
+        cmdlineP->imagewidth = imagewidth * psScaleFactor;
     }
     else
         cmdlineP->imagewidth = 0;
     if (imageheightSpec) {
-        validateCompDimension(imagewidth, 72, "-imageheight value");
-        cmdlineP->imageheight = imageheight * 72;
+        validateCompDimension(imagewidth, psScaleFactor, "-imageheight value");
+        cmdlineP->imageheight = imageheight * psScaleFactor;
     }
     else
         cmdlineP->imageheight = 0;
@@ -1012,8 +1016,8 @@ validateComputableBoundingBox(float const scols,
     float const bbWidth  = llx + scols + 0.5;
     float const bbHeight = lly + srows + 0.5;
 
-    if (bbHeight < INT_MIN || bbHeight > INT_MAX ||
-        bbWidth  < INT_MIN || bbWidth  > INT_MAX)
+    if ((double)bbHeight < INT_MIN || (double)bbHeight > INT_MAX ||
+        (double)bbWidth  < INT_MIN || (double)bbWidth  > INT_MAX)
         pm_error("Bounding box dimensions %.1f x %.1f are too large "
                  "for computations.  "
                  "This probably means input image width, height, "
@@ -1268,7 +1272,7 @@ putFilters(unsigned int const postscriptLevel,
     assert(postscriptLevel > 1);
 
     /* We say to decode flate, then rle, so Caller must ensure it encodes
-       rel, then flate.
+       rle, then flate.
     */
 
     if (ascii85)
diff --git a/converter/other/pnmtorast.c b/converter/other/pnmtorast.c
index e11d3cb7..14c0be0a 100644
--- a/converter/other/pnmtorast.c
+++ b/converter/other/pnmtorast.c
@@ -31,7 +31,7 @@ allocPrColormap(void) {
     MALLOCARRAY(prColormapP->map[0], MAXCOLORS);
     MALLOCARRAY(prColormapP->map[1], MAXCOLORS);
     MALLOCARRAY(prColormapP->map[2], MAXCOLORS);
-    if (prColormapP->map[0] == NULL || 
+    if (prColormapP->map[0] == NULL ||
         prColormapP->map[1] == NULL ||
         prColormapP->map[2] == NULL)
         pm_error("out of memory");
@@ -92,7 +92,7 @@ doRowDepth1(const xel *     const xelrow,
             xelval          const maxval,
             colorhash_table const cht,
             unsigned int *  const lenP) {
-                
+
     unsigned int col;
     int bitcount;
     unsigned int cursor;
@@ -191,7 +191,6 @@ doRowDepth8(const xel *     const xelrow,
 
 
 
-
 static void
 doRowDepth24(const xel *     const xelrow,
              unsigned char * const rastRow,
@@ -232,7 +231,7 @@ computeRaster(unsigned char * const rastRaster,
               xelval          const maxval,
               xel **          const xels,
               colorhash_table const cht) {
-                  
+
     unsigned int row;
     unsigned char * rastRow;
 
@@ -375,7 +374,7 @@ main(int argc, const char ** argv) {
     if (maxval > 255 && depth != 1)
         pm_message(
             "maxval is not 255 - automatically rescaling colors");
-    
+
     /* Allocate space for the Sun-format image. */
     prP = mem_create(cols, rows, depth);
     if (!prP)
@@ -398,3 +397,5 @@ main(int argc, const char ** argv) {
     return 0;
 }
 
+
+
diff --git a/converter/other/pnmtorle.c b/converter/other/pnmtorle.c
index 1882fe5d..e8a37d9b 100644
--- a/converter/other/pnmtorle.c
+++ b/converter/other/pnmtorle.c
@@ -33,71 +33,155 @@
  * 2000.04.13 adapted for Netpbm by Bryan Henderson.  Quieted compiler
  *            warnings.
  *
+ * 2022.03.06 revision by Akira F Urushibata
+ *            use shhopt instead of scanargs
+ *            proper handling of multiple image files with -h
+ *
  */
 /*-----------------------------------------------------
  * System includes.
  */
 #include <string.h>
 #include <stdio.h>
+#include <assert.h>
 #include "pnm.h"
 #include "mallocvar.h"
 #include "rle.h"
+#include "shhopt.h"
+#include "pm_c_util.h"
+
+
+struct CmdlineInfo {
+    /* All the information the user supplied in the command line,
+       in a form easy for the program to use.
+    */
+    const char * inFileName;
+    const char * outfile;
+    unsigned int verbose;
+    unsigned int header;
+    unsigned int alpha;
+};
+
+
+
+static void
+parseCommandLine(int argc, const char ** argv,
+                 struct CmdlineInfo * const cmdlineP) {
+/*----------------------------------------------------------------------------
+   Note that the file spec array we return is stored in the storage that
+   was passed to us as the argv array.
+-----------------------------------------------------------------------------*/
+    optEntry * option_def;   /* Used by OPTENT3 */
+    optStruct3 opt;
+
+    unsigned int option_def_index;
+    unsigned int outfileSpec;
+
+    MALLOCARRAY_NOFAIL(option_def, 100);
+
+    option_def_index = 0;   /* incremented by OPTENTRY */
+    OPTENT3(0, "alpha",    OPT_FLAG,   NULL,  &cmdlineP->alpha,     0);
+    OPTENT3(0, "header",   OPT_FLAG,   NULL,  &cmdlineP->header,    0);
+    OPTENT3(0, "verbose",  OPT_FLAG,   NULL,  &cmdlineP->verbose,   0);
+    OPTENT3(0, "outfile",  OPT_STRING, &cmdlineP->outfile,
+                                              &outfileSpec,         0);
+
+    opt.opt_table = option_def;
+    opt.short_allowed = false;  /* We have no short (old-fashioned) options */
+    opt.allowNegNum = false;  /* We have no parms that are negative numbers */
+
+    pm_optParseOptions4(&argc, argv, opt, sizeof(opt), 0);
+        /* Uses and sets argc, argv, and some of *cmdlineP and others. */
+
+    free(option_def);
+
+    if (argc-1 == 0)
+        cmdlineP->inFileName = "-";
+    else if (argc-1 != 1) {
+        pm_error("Program takes zero or one argument (filename).  You "
+                 "specified %d", argc-1);
+    }
+    else
+        cmdlineP->inFileName = argv[1];
+
+    if (!outfileSpec)
+        cmdlineP->outfile = "-";
+}
+
 
-#define VPRINTF if (verbose || header) fprintf
 
-typedef unsigned char U_CHAR;
-/*
- * Global variables.
- */
-static FILE    *fp;
-static rle_hdr hdr;
-static int  format;
-static int width, height;
-static int verbose = 0, header = 0, do_alpha = 0;
-static gray    maxval;
-/*-----------------------------------------------------------------------------
- *                                        Read the pnm image file header.
- */
 static void
-read_pnm_header(void) {
+readPnmHeader(bool      const verbose,
+              bool      const wantAlpha,
+              FILE    * const ifP,
+              int     * const widthP,
+              int     * const heightP,
+              gray    * const maxvalP,
+              int     * const formatP) {
+/*-----------------------------------------------------------------------------
+  Read the pnm image file header.
+---------------------------------------------------------------------------- */
+    int   width;
+    int   height;
+    gray  maxval;
+    int   format;
+    const char * type;
+
+    pnm_readpnminit(ifP, &width, &height, &maxval, &format);
 
-    pnm_readpnminit(fp, &width, &height, &maxval, &format);
     switch (format) {
     case PBM_FORMAT:
-        VPRINTF(stderr, "Image type: plain pbm format\n");
+        type="plain pbm";
         break;
     case RPBM_FORMAT:
-        VPRINTF(stderr, "Image type: raw pbm format\n");
+        type="raw pbm";
         break;
     case PGM_FORMAT:
-        VPRINTF(stderr, "Image type: plain pgm format\n");
+        type="plain pgm";
         break;
     case RPGM_FORMAT:
-        VPRINTF(stderr, "Image type: raw pgm format\n");
+        type="raw pgm";
         break;
     case PPM_FORMAT:
-        VPRINTF(stderr, "Image type: plain ppm format\n");
+        type="plain ppm";
         break;
     case RPPM_FORMAT:
-        VPRINTF(stderr, "Image type: raw ppm format\n");
+        type="raw ppm";
         break;
     }
-    VPRINTF(stderr, "Full image: %dx%d\n", width, height);
-    VPRINTF(stderr, "Maxval:     %d\n", maxval);
-    if (do_alpha)
-        VPRINTF(stderr, "Computing alpha channel...\n");
+    if (verbose) {
+        pm_message("Image type: %s format", type);
+        pm_message("Full image: %dx%d", width, height);
+        pm_message("Maxval:     %d", maxval);
+
+        if (wantAlpha)
+            pm_message("Computing alpha channel...");
+    }
+    *widthP  = width;
+    *heightP = height;
+    *maxvalP = maxval;
+    *formatP = format;
 }
 
 
 
 static void
-write_rle_header(void) {
+writeRleHeader(bool         const wantAlpha,
+               int          const format,
+               unsigned int const width,
+               unsigned int const height,
+               rle_hdr *    const hdrP) {
+
+    rle_hdr hdr;
+
+    hdr = *hdrP;  /* initial value */
 
     hdr.xmin    = 0;
     hdr.xmax    = width-1;
     hdr.ymin    = 0;
     hdr.ymax    = height-1;
     hdr.background = 0;
+
     switch (format) {
     case PBM_FORMAT:
     case RPBM_FORMAT:
@@ -114,31 +198,42 @@ write_rle_header(void) {
         RLE_SET_BIT(hdr, RLE_BLUE);
         break;
     }
-    if (do_alpha) {
+    if (wantAlpha) {
         hdr.alpha = 1;
         RLE_SET_BIT(hdr, RLE_ALPHA);
     }
     rle_put_setup(&hdr);
+
+    *hdrP = hdr;
 }
 
 
 
 static void
-write_rle_data(void) {
+writeRleData(bool         const verbose,
+             bool         const wantAlpha,
+             FILE      *  const ifP,
+             rle_hdr   *  const hdrP,
+             unsigned int const width,
+             unsigned int const height,
+             gray         const maxval,
+             int          const format) {
 
     unsigned int scan;
     xel * xelrow;
     rle_pixel *** scanlines;
 
     MALLOCARRAY(xelrow, width);
-    MALLOCARRAY(scanlines, height);
+    if (xelrow == NULL)
+        pm_error("Failed to allocate memory for row of %u pixels", width);
 
-    if (!scanlines)
+    MALLOCARRAY(scanlines, height);
+    if (scanlines == NULL)
         pm_error("Failed to allocate memory for %u scanline pointers", height);
 
     for (scan = 0; scan < height; ++scan) {
         int rc;
-        rc = rle_row_alloc(&hdr, &scanlines[scan]);
+        rc = rle_row_alloc(hdrP, &scanlines[scan]);
         if (rc < 0)
             pm_error("Failed to allocate memory for a scanline");
     }
@@ -151,10 +246,10 @@ write_rle_data(void) {
         for (scan = 0; scan < height; ++scan) {
             rle_pixel ** const scanline = scanlines[height - scan - 1];
             unsigned int col;
-            pnm_readpnmrow(fp, xelrow, width, maxval, format);
+            pnm_readpnmrow(ifP, xelrow, width, maxval, format);
             for (col = 0; col < width; ++col) {
                 scanline[RLE_RED][col] = PNM_GET1(xelrow[col]) ? 255 : 0;
-                if (do_alpha)
+                if (wantAlpha)
                     scanline[RLE_ALPHA][col] = scanline[RLE_RED][col];
             }
         }
@@ -165,10 +260,10 @@ write_rle_data(void) {
         for (scan = 0; scan < height; ++scan) {
             rle_pixel ** const scanline = scanlines[height - scan - 1];
             unsigned int col;
-            pnm_readpnmrow(fp, xelrow, width, maxval, format);
+            pnm_readpnmrow(ifP, xelrow, width, maxval, format);
             for (col = 0; col < width; ++col) {
                 scanline[RLE_RED][col] = PNM_GET1(xelrow[col]);
-                if (do_alpha)
+                if (wantAlpha)
                     scanline[RLE_ALPHA][col] =
                         scanline[RLE_RED][col] ? 255 : 0;
             }
@@ -179,13 +274,16 @@ write_rle_data(void) {
         unsigned int scan;
         for (scan = 0; scan < height; scan++) {
             rle_pixel ** const scanline = scanlines[height - scan - 1];
+
             unsigned int col;
-            pnm_readpnmrow(fp, xelrow, width, maxval, format);
+
+            pnm_readpnmrow(ifP, xelrow, width, maxval, format);
+
             for (col = 0; col < width; ++col) {
                 scanline[RLE_RED][col]   = PPM_GETR(xelrow[col]);
                 scanline[RLE_GREEN][col] = PPM_GETG(xelrow[col]);
                 scanline[RLE_BLUE][col]  = PPM_GETB(xelrow[col]);
-                if (do_alpha)
+                if (wantAlpha)
                     scanline[RLE_ALPHA][col] =
                         (scanline[RLE_RED][col] ||
                          scanline[RLE_GREEN][col] ||
@@ -196,71 +294,98 @@ write_rle_data(void) {
     }
     /* Write out data in URT order (bottom to top). */
     for (scan = 0; scan < height; ++scan)
-        rle_putrow(scanlines[scan], width, &hdr);
+        rle_putrow(scanlines[scan], width, hdrP);
 
     for (scan = 0; scan < height; ++scan)
-        rle_row_free(&hdr, scanlines[scan]);
+        rle_row_free(hdrP, scanlines[scan]);
     free(scanlines);
     free(xelrow);
 
-    VPRINTF(stderr, "Done -- write eof to RLE data.\n");
-    rle_puteof(&hdr);
+    if (verbose)
+        pm_message("Done -- write eof to RLE data.");
+
+    rle_puteof(hdrP);
+}
+
+
+
+static void
+skipData(FILE      *  const ifP,
+         unsigned int const width,
+         unsigned int const height,
+         gray         const maxval,
+         int          const format) {
+
+    xel * xelrow;
+    unsigned int scan;
+
+    MALLOCARRAY(xelrow, width);
+    if (xelrow == NULL)
+        pm_error("Failed to allocate memory for row of %u pixels", width);
+
+    for (scan=0; scan < height; ++scan)
+        pnm_readpnmrow(ifP, xelrow, width, maxval, format);
+
+    free(xelrow);
 }
 
 
 
 int
-main(int argc, char **  argv) {
-
-    const char * pnmname;
-    const char * outname;
-    int oflag;
-
-    pnm_init(&argc, argv);
-
-    pnmname = NULL;  /* initial value */
-    outname = NULL;  /* initial value */
-
-    /* Get those options. */
-    if (!scanargs(argc,argv,
-                  "% v%- h%- a%- o%-outfile!s pnmfile%s\n(\
-\tConvert a PNM file to URT RLE format.\n\
-\t-a\tFake an alpha channel.  Alpha=0 when input=0, 255 otherwise.\n\
-\t-h\tPrint header of PNM file and exit.\n\
-\t-v\tVerbose mode.)",
-                  &verbose,
-                  &header,
-                  &do_alpha,
-                  &oflag, &outname,
-                  &pnmname))
-        exit(-1);
+main(int argc, const char ** argv) {
+
+    struct CmdlineInfo cmdline;
+
+    FILE   * ifP;
+    rle_hdr hdr;
+    int  format;
+    int  width, height;
+    gray maxval;
+    bool verbose;
+    const char ** argvWork;
+    unsigned int i;
+    int eof;
+
+    MALLOCARRAY_NOFAIL(argvWork, argc + 1);
+
+    for (i = 0; i < argc; ++i)  /* Make a copy of argv */
+        argvWork[i] = argv[i];
+
+    pm_proginit(&argc, argvWork);
+
+    parseCommandLine(argc, argvWork, &cmdline);
+
+    verbose = cmdline.verbose || cmdline.header;
 
     hdr = *rle_hdr_init(NULL);
-    rle_names(&hdr, cmd_name(argv), outname, 0);
+
+    rle_names(&hdr, "pnmtorle", cmdline.outfile, 0);
 
     /* Open the file. */
-    if (pnmname == NULL) {
-        fp = pm_openr("-");
-    } else {
-        fp = pm_openr(pnmname);
-    }
+    assert(cmdline.inFileName != NULL);
+    ifP = pm_openr(cmdline.inFileName);
 
-    hdr.rle_file = rle_open_f( hdr.cmd, outname, "wb" );
+    hdr.rle_file = rle_open_f(hdr.cmd, cmdline.outfile, "wb");
 
-    if (header)
-        read_pnm_header();
-    else {
-        int eof;
-        for (eof = 0; !eof; ) {
-            read_pnm_header();
-            rle_addhist(argv, NULL, &hdr);
-            write_rle_header();
-            write_rle_data();
+    for (eof = 0; !eof; ) {
+        readPnmHeader(verbose, cmdline.alpha, ifP,
+                      &width, &height, &maxval, &format);
 
-            pnm_nextimage(fp, &eof);
+        if (cmdline.header) {
+            skipData(ifP, width, height, maxval, format);
+        } else {
+            rle_addhist(argv, NULL, &hdr);
+            writeRleHeader(cmdline.alpha, format, width, height, &hdr);
+            writeRleData(verbose, cmdline.alpha, ifP, &hdr,
+                         width, height, maxval, format);
         }
+        pnm_nextimage(ifP, &eof);
     }
-    pm_close(fp);
+
+    pm_close(ifP);
 
     return 0;
 }
+
+
+
diff --git a/converter/other/pnmtosgi.c b/converter/other/pnmtosgi.c
index cc57349f..adf89bce 100644
--- a/converter/other/pnmtosgi.c
+++ b/converter/other/pnmtosgi.c
@@ -225,12 +225,12 @@ buildChannels(FILE *       const ifP,
 
 
 static void
-writeHeader(unsigned int const cols, 
-            unsigned int const rows, 
-            xelval       const maxval, 
-            unsigned int const bpc, 
-            unsigned int const dimensions, 
-            unsigned int const channels, 
+writeHeader(unsigned int const cols,
+            unsigned int const rows,
+            xelval       const maxval,
+            unsigned int const bpc,
+            unsigned int const dimensions,
+            unsigned int const channels,
             const char * const imagename) {
 
     unsigned int i;
@@ -314,7 +314,7 @@ main(int argc,char * argv[]) {
         pm_error ("Input image is too large.");
 
     pnmrow = pnm_allocrow(cols);
-    
+
     switch (PNM_FORMAT_TYPE(format)) {
         case PBM_TYPE:
             pm_message("promoting PBM to PGM");
@@ -359,3 +359,4 @@ main(int argc,char * argv[]) {
 }
 
 
+
diff --git a/converter/other/pnmtosir.c b/converter/other/pnmtosir.c
index 20bb6178..7b7650fe 100644
--- a/converter/other/pnmtosir.c
+++ b/converter/other/pnmtosir.c
@@ -20,16 +20,16 @@
 
 int
 main(int argc, const char * argv[]) {
-    
+
     FILE * ifP;
     xel ** xels;
     int rows, cols, format;
     unsigned int n;
     bool isGrayscale;
     xelval maxval;
-    unsigned short Header[16];
-    unsigned short LutHeader[16];
-    unsigned short Lut[2048];
+    unsigned short Header[10];
+    unsigned short LutHeader[5];
+    unsigned short Lut[1024];
 
     pm_proginit(&argc, argv);
 
@@ -43,9 +43,9 @@ main(int argc, const char * argv[]) {
     }  else {
         ifP = stdin;
     }
-    
+
     xels = pnm_readpnm(ifP, &cols, &rows, &maxval, &format);
-    
+
     /* Figure out the colormap. */
     switch (PNM_FORMAT_TYPE(format) ) {
     case PPM_TYPE:
@@ -93,15 +93,19 @@ main(int argc, const char * argv[]) {
         pm_writelittleshort(stdout,LutHeader[n]);
     for (n = 5; n < 256; ++n)
         pm_writelittleshort(stdout,0);
- 
-    for (n = 0; n < 3; ++n) {
+
+    for (n = 0; n < 256; ++n) {
         unsigned int m;
-        for (m = 0; m < 256; ++m)
-            Lut[m * 4 + n] = m << 8;
+        for (m = 0; m < 3; ++m)
+            Lut[n * 4 + m] = n << 8;
+
+        Lut[n * 4 + 3] = 0;
+            /* Clear to ensure repeatable output, suppress Valgrind error */
     }
+
     for (n = 0; n < 1024; ++n)
         pm_writelittleshort(stdout,Lut[n]);
- 
+
     /* Finally, write out the data. */
     switch (PNM_FORMAT_TYPE(format)) {
     case PPM_TYPE: {
@@ -110,13 +114,13 @@ main(int argc, const char * argv[]) {
             unsigned int col;
             for (col = 0; col < cols; ++col) {
                 unsigned char const ub =
-                    (char) (PPM_GETR(xels[row][col]) * (255 / maxval)); 
+                    (char) (PPM_GETR(xels[row][col]) * (255 / maxval));
                 fputc(ub, stdout);
             }
         }
         for (row = 0; row < rows; ++row) {
             unsigned int col;
-            for (col = 0; col < cols; ++col) {  
+            for (col = 0; col < cols; ++col) {
                 unsigned const char ub =
                     (char) (PPM_GETG(xels[row][col]) * (255 / maxval));
                 fputc(ub, stdout);
@@ -124,7 +128,7 @@ main(int argc, const char * argv[]) {
         }
         for (row = 0; row < rows; ++row) {
             unsigned int col;
-            for (col = 0; col < cols; ++col) {  
+            for (col = 0; col < cols; ++col) {
                 unsigned const char ub =
                     (char) (PPM_GETB(xels[row][col]) * (255 / maxval));
                 fputc(ub, stdout);
@@ -144,10 +148,11 @@ main(int argc, const char * argv[]) {
         }
     } break;
     }
-    
+
     pm_close(ifP);
 
     return 0;
 }
 
 
+
diff --git a/converter/other/pnmtotiffcmyk.c b/converter/other/pnmtotiffcmyk.c
index b7e3228e..a2fa0a4c 100644
--- a/converter/other/pnmtotiffcmyk.c
+++ b/converter/other/pnmtotiffcmyk.c
@@ -79,7 +79,7 @@ Software copyrights will soon need family trees... :-)
 
 /* only support 8 bit values */
 #define MAXTIFFBITS 8
-#define MAXTIFFVAL 255 
+#define MAXTIFFVAL 255
 
 
 /* definitions for error values */
@@ -111,9 +111,9 @@ typedef int Err ;
 #ifndef PI
 #define PI 3.1415926
 #endif
-#define ONETWENTY ( 2.0 * PI / 3.0 ) 
+#define ONETWENTY ( 2.0 * PI / 3.0 )
 #define TWOFORTY ( 4.0 * PI / 3.0 )
-#define THREESIXTY ( 2.0 * PI ) 
+#define THREESIXTY ( 2.0 * PI )
 /* expand from 0-90 to 0-120 degrees */
 #define EXPAND(x) ( 4.0 * ( x ) / 3.0 )
 /* contract from 0-120 to 0-90 degrees */
@@ -144,7 +144,7 @@ typedef struct {
 
 /* parse an arg with a float value.  name should be the full key name,
    preceded by '-' */
-static Err 
+static Err
 floatArg( float *arg, const char *name, int size, float lo, float hi,
           int *argn, int argc, char **argv ) {
 
@@ -165,7 +165,7 @@ floatArg( float *arg, const char *name, int size, float lo, float hi,
                extra, name ) ;
     }
     if ( *arg > hi || *arg < lo ) {
-      fprintf( stderr, "%s (%f) must be in range %f to %f\n", 
+      fprintf( stderr, "%s (%f) must be in range %f to %f\n",
                name, *arg, lo, hi ) ;
       return ERR_ARG ;
     }
@@ -176,9 +176,10 @@ floatArg( float *arg, const char *name, int size, float lo, float hi,
 }
 
 
+
 /* parse an arg with a long value.  name should be the full key name,
    preceded by '-' */
-static Err 
+static Err
 longArg( long *arg, const char *name, int size, long lo, long hi,
          int *argn, int argc, char **argv ) {
 
@@ -199,7 +200,7 @@ longArg( long *arg, const char *name, int size, long lo, long hi,
                extra, name ) ;
     }
     if ( *arg > hi || *arg < lo ) {
-      fprintf( stderr, "%s (%ld) must be in range %ld to %ld\n", 
+      fprintf( stderr, "%s (%ld) must be in range %ld to %ld\n",
                name, *arg, lo, hi ) ;
       return ERR_ARG ;
     }
@@ -210,13 +211,14 @@ longArg( long *arg, const char *name, int size, long lo, long hi,
 }
 
 
+
 /* print usage.  for simplicity this routine is *not* split amongst
    the various components - when you add a component (eg a new
    conversion algorithm, or maybe new input or output code), you must
    also change this routine.  by keeping all the options in one place
    it is also easier to calculate the minimum key name length (passed
    to pnm_keymatch) */
-static void 
+static void
 printUsage( ) {
   fprintf( stderr, "\nusage: pnmtocmyk [Compargs] [Tiffargs] [Convargs] [pnmfile]\n" ) ;
   fprintf( stderr, " Compargs: [-none|-packbits|-lzw [-predictor 1|-predictor 2]]\n" ) ;
@@ -233,6 +235,8 @@ printUsage( ) {
   fprintf( stderr, "No warranty.\n\n" ) ;
 }
 
+
+
 /* list of key args and number of significant letters required
 -default      2
 -gamma        6
@@ -261,11 +265,11 @@ printUsage( ) {
 /* encapsulate the file reader - uses pnm library at the moment, but
    could be changed if we move to libtiff */
 
-typedef Err OptIn( struct tagIn *conv, Root *r, 
+typedef Err OptIn( struct tagIn *conv, Root *r,
                    int *argn, int argc, char **argv ) ;
 typedef int HasMore( struct tagIn *in ) ;
 typedef Err Next( struct tagIn *in, float *r, float *g, float *b ) ;
-typedef Err OpenIn( struct tagIn *in, Root *r ) ; 
+typedef Err OpenIn( struct tagIn *in, Root *r ) ;
 typedef void CloseIn( struct tagIn *in ) ;
 
 typedef struct tagIn {
@@ -294,7 +298,7 @@ typedef struct {
 
 /* the only output option is the filename, which will be the last
    argument, if it doesn't start with '-' */
-static Err 
+static Err
 pnmOpt( In *in, Root *r, int *argn, int argc, char **argv ) {
   PnmIn *p = (PnmIn*)in->private ;
   if ( *argn + 1 == argc && argv[*argn][0] != '\0' &&
@@ -306,8 +310,9 @@ pnmOpt( In *in, Root *r, int *argn, int argc, char **argv ) {
 }
 
 
+
 /* free the row buffer when closing the input */
-static void 
+static void
 pnmClose( In *in ) {
   if ( in ) {
     PnmIn *p = (PnmIn*)in->private ;
@@ -320,16 +325,17 @@ pnmClose( In *in ) {
 }
 
 
+
 /* open the file, storing dimensions both locally and in the global
    root structure */
-static Err 
+static Err
 pnmOpen( In *in, Root *r ) {
 
   PnmIn *p = (PnmIn*)in->private ;
 
   if ( ! p->in ) p->in = stdin ;
 
-  pnm_readpnminit( p->in, &(r->nCols), &(r->nRows), &(p->maxVal), 
+  pnm_readpnminit( p->in, &(r->nCols), &(r->nRows), &(p->maxVal),
                    &(p->type) ) ;
   p->maxPix = r->nCols * r->nRows ;
   p->iPix = 0 ;
@@ -341,16 +347,18 @@ pnmOpen( In *in, Root *r ) {
 }
 
 
+
 /* more data available? */
-static int 
+static int
 pnmHasMore( In *in ) {
   PnmIn *p = (PnmIn*)in->private ;
   return p->iPix < p->maxPix ;
 }
 
 
+
 /* read next pixel - buffered by row.  return values in range 0 to 1 */
-static Err 
+static Err
 pnmNext( In *in, float *r, float *g, float *b ) {
 
   PnmIn *p = (PnmIn*)in->private ;
@@ -374,8 +382,9 @@ pnmNext( In *in, float *r, float *g, float *b ) {
 }
 
 
+
 /* build the input struct */
-static Err 
+static Err
 newPnmInput( In **in ) {
   if ( ! (*in = (In*)calloc( 1, sizeof( In ) )) ) {
     fprintf( stderr, "cannot allocate memory\n" ) ;
@@ -433,7 +442,7 @@ typedef struct {
 
 /* these options come from either the tiff 6.0 spec or the pnmtotiff
    code */
-static Err 
+static Err
 tiffOpt( Out *out, Root* rt, int *argn, int argc, char **argv ) {
 
   Err err ;
@@ -478,14 +487,14 @@ tiffOpt( Out *out, Root* rt, int *argn, int argc, char **argv ) {
     if ( oldn != *argn ) {
       t->rowsperstrip = (uint32)lVal ;
     } else {
-      if ( (err = longArg( &lVal, "-lowdotrange", 3, 0, 
+      if ( (err = longArg( &lVal, "-lowdotrange", 3, 0,
                            (int)(t->highdotrange - 1),
                            argn, argc, argv )) ) return err ;
     }
     if ( oldn != *argn ) {
       t->lowdotrange = (uint16)lVal ;
     } else {
-      if ( (err = longArg( &lVal, "-highdotrange", 2, 
+      if ( (err = longArg( &lVal, "-highdotrange", 2,
                            (int)(t->lowdotrange + 1), MAXTIFFVAL,
                            argn, argc, argv )) ) return err ;
     }
@@ -498,8 +507,9 @@ tiffOpt( Out *out, Root* rt, int *argn, int argc, char **argv ) {
 }
 
 
+
 /* helper routine - writes individual bytes */
-static Err 
+static Err
 tiffWriteByte( TiffOut *t, int b ) {
   ((unsigned char*)(t->buffer))[t->iBuffer] = (unsigned char)b ;
   if ( ++(t->iBuffer) == t->maxBuffer ) {
@@ -513,8 +523,9 @@ tiffWriteByte( TiffOut *t, int b ) {
 }
 
 
+
 /* write the pixel to the tiff file */
-static Err 
+static Err
 tiffWrite( Out *out, int c, int m, int y, int k ) {
   Err err ;
   TiffOut *t = (TiffOut*)out->private ;
@@ -531,8 +542,9 @@ tiffWrite( Out *out, int c, int m, int y, int k ) {
 }
 
 
+
 /* open output to stdout - see warning below */
-static Err 
+static Err
 tiffOpen( Out* out, Root *r ) {
 
   TiffOut *t = (TiffOut*)out->private ;
@@ -554,7 +566,7 @@ tiffOpen( Out* out, Root *r ) {
   TIFFSetField( t->tiff, TIFFTAG_ORIENTATION, ORIENTATION_TOPLEFT ) ;
   TIFFSetField( t->tiff, TIFFTAG_COMPRESSION, t->compression ) ;
   if ( t->compression == COMPRESSION_LZW && t->predictor ) {
-	TIFFSetField( t->tiff, TIFFTAG_PREDICTOR, t->predictor ) ;
+        TIFFSetField( t->tiff, TIFFTAG_PREDICTOR, t->predictor ) ;
   }
   TIFFSetField( t->tiff, TIFFTAG_PHOTOMETRIC, photometric ) ;
   TIFFSetField( t->tiff, TIFFTAG_FILLORDER, t->fillorder ) ;
@@ -575,13 +587,14 @@ tiffOpen( Out* out, Root *r ) {
     fprintf( stderr, "cannot allocate memory\n" ) ;
     return ERR_MEMORY ;
   }
-  
+
   return ERR_OK ;
 }
 
 
+
 /* close file and tidy memory */
-static void 
+static void
 tiffClose( Out *out ) {
   if ( out ) {
     TiffOut *t = (TiffOut*)out->private ;
@@ -595,8 +608,9 @@ tiffClose( Out *out ) {
 }
 
 
+
 /* assemble the routines above into a single struct/object */
-static Err 
+static Err
 newTiffOutput( Out **out ) {
 
   TiffOut *t ;
@@ -635,7 +649,7 @@ newTiffOutput( Out **out ) {
 typedef Err Opt( struct tagConv *conv, Root *r,
                  int *argn, int argc, char **argv ) ;
 typedef Err Convert( struct tagConv *conv, Root *rt,
-                     float r, float g, float b, 
+                     float r, float g, float b,
                      int *c, int *m, int *y, int *k ) ;
 typedef void Close( struct tagConv *conv ) ;
 
@@ -649,7 +663,7 @@ typedef struct tagConv {
 
 /* include two conversion routines to show how the code can be
    extended.  first, the standard converter, as outlined in the
-   proposal, then a simple replacement that produces colour 
+   proposal, then a simple replacement that produces colour
    negatives */
 
 
@@ -667,8 +681,8 @@ typedef struct {
 
 /* represent an rgb colour as a hue (angle), white level and colour
    strength */
-static void 
-rgbToHueWhiteColour( float r, float g, float b, 
+static void
+rgbToHueWhiteColour( float r, float g, float b,
                      double *phi, float *white, float *colour ) {
   *white = MIN( r, MIN( g, b ) ) ;
   r -= *white ;
@@ -676,19 +690,20 @@ rgbToHueWhiteColour( float r, float g, float b,
   b -= *white ;
   *colour = sqrt( r * r + g * g + b * b ) ;
   if ( r > TINY || g > TINY || b > TINY ) {
-    if ( b < r && b <= g ) { 
+    if ( b < r && b <= g ) {
       *phi = EXPAND( atan2( g, r ) ) ;
     } else if ( r < g && r <= b ) {
       *phi = ONETWENTY + EXPAND( atan2( b, g ) ) ;
     } else {
       *phi = TWOFORTY + EXPAND( atan2( r, b ) ) ;
     }
-  } 
+  }
 }
 
 
+
 /* represent hue, white and colour values as rgb */
-static void 
+static void
 hueWhiteColourToRgb( double phi, float white, float colour,
                      float *r, float *g, float *b ) {
   while ( phi < 0 ) { phi += THREESIXTY ; }
@@ -715,10 +730,11 @@ hueWhiteColourToRgb( double phi, float white, float colour,
 }
 
 
+
 /* for details, see the proposal.  it's pretty simple - a rotation
    before conversion, with colour removal */
-static Err 
-standardConvert( Conv *conv, Root *rt, float r, float g, float b, 
+static Err
+standardConvert( Conv *conv, Root *rt, float r, float g, float b,
                  int *c, int *m, int *y, int *k ) {
 
   float c0, m0, y0, k0 ; /* CMYK before colour removal */
@@ -767,9 +783,10 @@ standardConvert( Conv *conv, Root *rt, float r, float g, float b,
 }
 
 
+
 /* parse options for this conversion - note the ugly use of -1 for
    gammap to indicate no removal of cmy under k */
-static Err 
+static Err
 standardOpt( Conv *conv, Root *r, int *argn, int argc, char **argv ) {
 
   Err err ;
@@ -790,7 +807,7 @@ standardOpt( Conv *conv, Root *r, int *argn, int argc, char **argv ) {
        *argn + 1 < argc && streq(argv[*argn + 1], "-1") ) {
     p->remove = 0 ;
     *argn = (*argn) + 2 ;
-  } 
+  }
   if ( oldn == *argn ) {
     if ( (err = floatArg( &(p->gammap), "-gammap", 7, 0.1, 10.0,
                                argn, argc, argv )) ) return err ;
@@ -801,18 +818,20 @@ standardOpt( Conv *conv, Root *r, int *argn, int argc, char **argv ) {
 }
 
 
+
 /* free conversion structure */
-static void 
+static void
 standardClose( Conv *conv ) {
   if ( conv ) {
     if ( conv->private ) { free( conv->private ) ; }
-    free( conv ) ; 
+    free( conv ) ;
   }
 }
 
 
+
 /* build new conversion structure */
-static Err 
+static Err
 newStandardMap( Conv **conv ) {
 
   Standard *s ;
@@ -842,7 +861,7 @@ newStandardMap( Conv **conv ) {
 
 
 /* the conversion routine must match the Convert typedef */
-static Err 
+static Err
 negativeConvert( Conv *conv, Root *rt, float r, float g, float b,
                  int *c, int *m, int *y, int *k ) {
 
@@ -858,24 +877,26 @@ negativeConvert( Conv *conv, Root *rt, float r, float g, float b,
 }
 
 
+
 /* since this simple conversion takes no parameters, we don't need to
    parse them - this routine must match the Opt typedef */
-static Err 
+static Err
 negativeOpt( Conv *conv, Root *r, int *argn, int argc, char **argv ) {
   return ERR_OK ;
 }
 
 
+
 /* with no parameters we haven't needed the private data structure, so
    closing is trivial - this routine must match the Close typedef */
-static void 
+static void
 negativeClose( Conv *conv ) { }
 
 
 /* and that's it, apart from assembling the routines above into a
    single struct/object (and adding code in parseOpts to select the
    algorithm and printUsage to help the user) */
-static Err 
+static Err
 newNegativeMap( Conv **conv ) {
 
   if ( ! (*conv = (Conv*)calloc( 1, sizeof( Conv ) )) ) goto error ;
@@ -896,7 +917,7 @@ newNegativeMap( Conv **conv ) {
 
 
 /* run through args, passing to sub components */
-static Err 
+static Err
 parseOpts( int argc, char **argv, Root *r ) {
 
   int argn = 1 ;
@@ -947,6 +968,7 @@ parseOpts( int argc, char **argv, Root *r ) {
 }
 
 
+
 /* drive the reading, conversion, and writing */
 int main( int argc, char **argv ) {
 
@@ -966,7 +988,7 @@ int main( int argc, char **argv ) {
   rt->maxOut = MAXTIFFVAL ;
 
   if ( (err = parseOpts( argc, argv, rt )) ) goto exit ;
-  
+
   if ( (err = rt->in->open( rt->in, rt )) ) goto exit ;
   if ( (err = rt->out->open( rt->out, rt )) ) goto exit ;
 
diff --git a/converter/other/pnmtoxwd.c b/converter/other/pnmtoxwd.c
index eda2ee8f..6a008610 100644
--- a/converter/other/pnmtoxwd.c
+++ b/converter/other/pnmtoxwd.c
@@ -31,13 +31,13 @@ struct CmdlineInfo {
 
 
 
-static void 
-parseCommandLine(int argc, 
-                 char ** argv, 
+static void
+parseCommandLine(int argc,
+                 char ** argv,
                  struct CmdlineInfo  * const cmdlineP) {
 /* --------------------------------------------------------------------------
    Parse program command line described in Unix standard form by argc
-   and argv.  Return the information in the options as *cmdlineP.  
+   and argv.  Return the information in the options as *cmdlineP.
 
    If command line is internally inconsistent (invalid options, etc.),
    issue error message to stderr and abort program.
@@ -53,12 +53,12 @@ parseCommandLine(int argc,
     unsigned int depthSpec;
 
     MALLOCARRAY_NOFAIL(option_def, 100);
-  
+
     option_def_index = 0;   /* incremented by OPTENT3 */
     OPTENT3(0, "directcolor", OPT_FLAG,    NULL,   &cmdlineP->directcolor,  0);
-    OPTENT3(0, "pseudodepth",    OPT_UINT,  &cmdlineP->pseudodepth,    
+    OPTENT3(0, "pseudodepth",    OPT_UINT,  &cmdlineP->pseudodepth,
             &depthSpec,          0);
-  
+
     opt.opt_table = option_def;
     opt.short_allowed = FALSE;  /* We have no short (old-fashioned) options */
     opt.allowNegNum = FALSE;   /* We have no parms that are negative numbers */
@@ -77,7 +77,7 @@ parseCommandLine(int argc,
                      "You specified %u", cmdlineP->pseudodepth);
     }
 
-    if (argc-1 == 0) 
+    if (argc-1 == 0)
         cmdlineP->inputFilename = "-";
     else if (argc-1 != 1)
         pm_error("Program takes zero or one argument (filename).  You "
@@ -165,7 +165,6 @@ setupX11Header(X11WDFileHeader * const h11P,
 
 
 
-
 static void
 writeX11Header(X11WDFileHeader const h11,
                FILE *          const ofP) {
@@ -209,7 +208,7 @@ writePseudoColormap(FILE *           const ofP,
                     bool             const backwardMap,
                     xelval           const maxval) {
     /* Write out the colormap, big-endian order. */
-    
+
     X11XColor color;
     unsigned int i;
 
@@ -219,13 +218,13 @@ writePseudoColormap(FILE *           const ofP,
         color.num = i;
         if (grayscale) {
             /* Stupid hack because xloadimage and xwud disagree on
-               how to interpret bitmaps. 
+               how to interpret bitmaps.
             */
             if (backwardMap)
                 color.red = (long) (colors-1-i) * 65535L / (colors - 1);
             else
                 color.red = (long) i * 65535L / (colors - 1);
-            
+
             color.green = color.red;
             color.blue = color.red;
         } else {
@@ -269,7 +268,7 @@ writeDirectColormap(FILE * const ofP) {
         color.green = (short)(i << 8 | i);
         color.blue  = (short)(i << 8 | i);
         color.num   = i << 16 | i << 8 | i;
-        
+
         pm_writebiglong( ofP, color.num);
         pm_writebigshort(ofP, color.red);
         pm_writebigshort(ofP, color.green);
@@ -288,12 +287,12 @@ writeRowDirect(FILE *       const ofP,
                int          const format,
                long         const xmaxval,
                xelval       const maxval) {
-    
+
     switch (PNM_FORMAT_TYPE(format)) {
     case PPM_TYPE: {
         unsigned int col;
         for (col = 0; col < cols; ++col) {
-            unsigned long const ul = 
+            unsigned long const ul =
                 ((PPM_GETR(xelrow[col]) * xmaxval / maxval) << 16) |
                 ((PPM_GETG(xelrow[col]) * xmaxval / maxval) << 8) |
                 (PPM_GETB(xelrow[col]) * xmaxval / maxval);
@@ -331,7 +330,7 @@ writeRowGrayscale(FILE *       const ofP,
     int bitshift;
     unsigned char byte;
     unsigned int col;
-    
+
     bigger_maxval = pm_bitstomaxval(bitsPerPixel);
     bitshift = 8 - bitsPerPixel;
     byte = 0;
@@ -340,7 +339,7 @@ writeRowGrayscale(FILE *       const ofP,
         s = PNM_GET1(xelrow[col]);
         if (backwardMap)
             s = 1 - s;
-        
+
         if (maxval != bigger_maxval)
             s = (long) s * bigger_maxval / maxval;
         byte |= s << bitshift;
@@ -362,7 +361,7 @@ writeRowPseudoColor(FILE *          const ofP,
                     xel *           const xelrow,
                     unsigned int    const cols,
                     colorhash_table const cht) {
-                       
+
     unsigned int col;
 
     for (col = 0; col < cols; ++col)
@@ -391,7 +390,7 @@ writeRaster(FILE *           const ofP,
 
     if (chv)
         cht = ppm_colorhisttocolorhash(chv, colors);
-            
+
     for (row = 0; row < rows; ++row) {
         if (direct)
             writeRowDirect(ofP, xels[row], cols, format, xmaxval, maxval);
@@ -431,7 +430,7 @@ main(int argc, char * argv[]) {
     xels = pnm_readpnm(ifP, &cols, &rows, &maxval, &format);
     xmaxval = (1 << cmdline.pseudodepth) - 1;
     pm_close(ifP);
-    
+
     if (cmdline.directcolor) {
         direct = TRUE;
         grayscale = FALSE;
@@ -482,7 +481,7 @@ main(int argc, char * argv[]) {
             dumpname = cmdline.inputFilename;
     }
 
-    setupX11Header(&h11, dumpname, cols, rows, format, 
+    setupX11Header(&h11, dumpname, cols, rows, format,
                    direct, grayscale, colors,
                    cmdline.pseudodepth);
 
@@ -496,12 +495,15 @@ main(int argc, char * argv[]) {
     if (direct)
         writeDirectColormap(stdout);
     else
-        writePseudoColormap(stdout, chv, colors, 
+        writePseudoColormap(stdout, chv, colors,
                             grayscale, backwardMap, maxval);
-    
-    writeRaster(stdout, xels, cols, rows, format, maxval, xmaxval, 
+
+    writeRaster(stdout, xels, cols, rows, format, maxval, xmaxval,
                 chv, colors, direct, grayscale,
                 backwardMap, h11.bits_per_pixel);
 
     return 0;
 }
+
+
+
diff --git a/converter/other/ppmtopgm.c b/converter/other/ppmtopgm.c
index e20c5660..40df422e 100644
--- a/converter/other/ppmtopgm.c
+++ b/converter/other/ppmtopgm.c
@@ -20,9 +20,9 @@ convertRaster(FILE *       const ifP,
               unsigned int const cols,
               unsigned int const rows,
               pixval       const maxval,
-              int          const format, 
+              int          const format,
               pixel *      const inputRow,
-              gray *       const outputRow, 
+              gray *       const outputRow,
               FILE *       const ofP) {
 
     unsigned int row;
@@ -37,7 +37,7 @@ convertRaster(FILE *       const ifP,
         } else {
             /* Can't use fast approximation, so fall back on floats. */
             unsigned int col;
-            for (col = 0; col < cols; ++col) 
+            for (col = 0; col < cols; ++col)
                 outputRow[col] = ppm_luminosity(inputRow[col]);
         }
         pgm_writepgmrow(ofP, outputRow, cols, maxval, 0);
@@ -52,7 +52,7 @@ main(int argc, char *argv[]) {
     FILE* ifP;
     const char * inputFilespec;
     int eof;
-    
+
     ppm_init( &argc, argv );
 
     if (argc-1 > 1)
@@ -62,7 +62,7 @@ main(int argc, char *argv[]) {
         inputFilespec = argv[1];
     else
         inputFilespec = "-";
-    
+
     ifP = pm_openr(inputFilespec);
 
     eof = FALSE;  /* initial assumption */
@@ -81,7 +81,7 @@ main(int argc, char *argv[]) {
             inputRow = ppm_allocrow(cols);
             outputRow = pgm_allocrow(cols);
 
-            convertRaster(ifP, cols, rows, maxval, format, 
+            convertRaster(ifP, cols, rows, maxval, format,
                           inputRow, outputRow, stdout);
 
             ppm_freerow(inputRow);
@@ -93,3 +93,6 @@ main(int argc, char *argv[]) {
 
     return 0;
 }
+
+
+
diff --git a/converter/other/pstopnm.c b/converter/other/pstopnm.c
index 25f2c429..dfc1b1b8 100644
--- a/converter/other/pstopnm.c
+++ b/converter/other/pstopnm.c
@@ -899,8 +899,8 @@ execGhostscript(int               const inputPipeFd,
                    "-dSAFER", "-");
     }
 
-    execl(ghostscriptProg, arg0, deviceopt, outfileopt, gopt, ropt, 
-	  textalphabitsopt, "-q", "-dNOPAUSE", "-dSAFER", "-", NULL);
+    execl(ghostscriptProg, arg0, deviceopt, outfileopt, gopt, ropt,
+          textalphabitsopt, "-q", "-dNOPAUSE", "-dSAFER", "-", NULL);
 
     pm_error("execl() of Ghostscript ('%s') failed, errno=%d (%s)",
              ghostscriptProg, errno, strerror(errno));
@@ -1161,3 +1161,4 @@ main(int argc, char ** argv) {
 }
 
 
+
diff --git a/converter/other/qoi.h b/converter/other/qoi.h
new file mode 100644
index 00000000..4bd7c024
--- /dev/null
+++ b/converter/other/qoi.h
@@ -0,0 +1,105 @@
+#ifndef QOI_H_INCLUDED
+#define QOI_H_INCLUDED
+/*
+
+QOI - The "Quite OK Image" format for fast, lossless image compression
+
+Dominic Szablewski - https://phoboslab.org
+
+
+-- LICENSE: The MIT License(MIT)
+
+Copyright(c) 2021 Dominic Szablewski
+
+Permission is hereby granted, free of charge, to any person obtaining a copy of
+this software and associated documentation files(the "Software"), to deal in
+the Software without restriction, including without limitation the rights to
+use, copy, modify, merge, publish, distribute, sublicense, and / or sell copies
+of the Software, and to permit persons to whom the Software is furnished to do
+so, subject to the following conditions :
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
+
+*/
+
+
+typedef enum {
+    QOI_SRGB = 0,
+    QOI_LINEAR = 1
+} qoi_Colorspace;
+
+
+typedef struct {
+    unsigned int   width;
+    unsigned int   height;
+    unsigned int   channelCt;
+    qoi_Colorspace colorspace;
+} qoi_Desc;
+
+
+
+#define QOI_OP_INDEX  0x00 /* 00xxxxxx */
+#define QOI_OP_DIFF   0x40 /* 01xxxxxx */
+#define QOI_OP_LUMA   0x80 /* 10xxxxxx */
+#define QOI_OP_RUN    0xc0 /* 11xxxxxx */
+#define QOI_OP_RGB    0xfe /* 11111110 */
+#define QOI_OP_RGBA   0xff /* 11111111 */
+
+#define QOI_MASK_2    0xc0 /* 11000000 */
+
+#define QOI_HEADER_SIZE 14
+
+/* 2GB is the max file size that this implementation can safely handle. We
+   guard against anything larger than that, assuming the worst case with 5
+   bytes per pixel, rounded down to a nice clean value. 400 million pixels
+   ought to be enough for anybody.
+ */
+#define QOI_PIXELS_MAX 400000000
+
+static unsigned int const qoi_pixels_max = (unsigned int) QOI_PIXELS_MAX;
+
+#define QOI_MAXVAL 255
+
+#define QOI_INDEX_SIZE 64
+
+
+typedef union {
+    struct { unsigned char r, g, b, a; } rgba;
+    unsigned int v;
+} qoi_Rgba;
+
+static __inline__ unsigned int
+qoi_colorHash(qoi_Rgba const x) {
+
+    return
+        (x.rgba.r*3 + x.rgba.g*5 + x.rgba.b*7 + x.rgba.a*11) % QOI_INDEX_SIZE;
+}
+
+
+
+static __inline__ void
+qoi_clearQoiIndex(qoi_Rgba * index) {
+
+    memset(index, 0, QOI_INDEX_SIZE * sizeof(qoi_Rgba));
+
+}
+
+
+
+#define QOI_MAGIC_SIZE 4
+
+static char const qoi_magic[QOI_MAGIC_SIZE + 1] = {'q','o','i','f','\0'};
+
+#define QOI_PADDING_SIZE 8
+
+static unsigned char const qoi_padding[QOI_PADDING_SIZE] = {0,0,0,0,0,0,0,1};
+
+
+#endif
diff --git a/converter/other/qoitopam.c b/converter/other/qoitopam.c
new file mode 100644
index 00000000..68182aa3
--- /dev/null
+++ b/converter/other/qoitopam.c
@@ -0,0 +1,323 @@
+/*
+  qoitopam -  Converts from a QOI - The "Quite OK Image" format file to PAM
+
+  This program is part of Netpbm.
+
+  ---------------------------------------------------------------------
+
+
+  QOI - The "Quite OK Image" format for fast, lossless image compression
+
+  Decoder by Dominic Szablewski - https://phoboslab.org
+
+  -- LICENSE: The MIT License(MIT)
+
+  Copyright(c) 2021 Dominic Szablewski
+
+  Permission is hereby granted, free of charge, to any person obtaining a copy
+  of this software and associated documentation files(the "Software"), to deal
+  in the Software without restriction, including without limitation the rights
+  to use, copy, modify, merge, publish, distribute, sublicense, and / or sell
+  copies of the Software, and to permit persons to whom the Software is
+  furnished to do so, subject to the following conditions :
+
+  The above copyright notice and this permission notice shall be included in
+  all copies or substantial portions of the Software.
+
+  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE
+  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+  SOFTWARE.
+
+  For more information on the format visit: https//qoiformat.org/ .
+
+  Modifications for Netpbm & PAM write routines by Akira F. Urushibata.
+*/
+
+#include <stdio.h>
+#include <string.h>
+#include <assert.h>
+
+#include "pm.h"
+#include "pam.h"
+#include "mallocvar.h"
+#include "nstring.h"
+#include "shhopt.h"
+
+#include "qoi.h"
+
+
+
+struct CmdlineInfo {
+    /* All the information the user supplied in the command line,
+       in a form easy for the program to use.
+    */
+    const char * inputFileName;  /* '-' if stdin */
+};
+
+
+
+static void
+parseCommandLine(int                  argc,
+                 const char **        argv,
+                 struct CmdlineInfo * cmdlineP ) {
+/*----------------------------------------------------------------------------
+   Parse program command line described in Unix standard form by argc
+   and argv.  Return the information in the options as *cmdlineP.
+
+   If command line is internally inconsistent (invalid options, etc.),
+   issue error message to stderr and abort program.
+
+   Note that the strings we return are stored in the storage that
+   was passed to us as the argv array.  We also trash *argv.
+-----------------------------------------------------------------------------*/
+    optEntry * option_def;   /* Used by OPTENT3 */
+    optStruct3 opt;
+
+    unsigned int option_def_index;
+
+    MALLOCARRAY(option_def, 100);
+
+    OPTENTINIT;
+
+    opt.opt_table = option_def;
+    opt.short_allowed = FALSE;  /* We have no short (old-fashioned) options */
+    opt.allowNegNum = FALSE;  /* We have no parms that are negative numbers */
+
+    pm_optParseOptions4(&argc, argv, opt, sizeof(opt), 0);
+        /* Uses and sets argc, argv, and some of *cmdlineP and others. */
+
+    if (argc-1 < 1)
+        cmdlineP->inputFileName = "-";
+    else if (argc-1 == 1)
+        cmdlineP->inputFileName = argv[1];
+    else
+        pm_error("Program takes at most one argument: input file name.  "
+            "you specified %d", argc-1);
+}
+
+
+
+static void
+readAndValidateMagic(FILE * const ifP){
+
+    char magicBuff[QOI_MAGIC_SIZE];
+    size_t charsReadCt;
+
+    charsReadCt = fread(magicBuff, 1, QOI_MAGIC_SIZE, ifP);
+
+    if (charsReadCt == 0)
+        pm_error("Input file is empty.");
+    else if (charsReadCt < QOI_MAGIC_SIZE || !MEMSEQ(&magicBuff, &qoi_magic)) {
+        assert(QOI_MAGIC_SIZE == 4);
+        pm_error("Invalid QOI image: does not start with magic number "
+                 "'%c%c%c%c'",
+                 qoi_magic[0], qoi_magic[1], qoi_magic[2], qoi_magic[3]);
+    }
+}
+
+
+
+/* The following two functions are from lib/pmfileio.c */
+
+static void
+abortWithReadError(FILE * const ifP) {
+
+    if (feof(ifP))
+        pm_error("Unexpected end of input file");
+    else
+        pm_error("Error (not EOF) reading file.");
+}
+
+
+
+static unsigned char
+getcNofail(FILE * const ifP) {
+
+    int c;
+
+    c = getc(ifP);
+
+    if (c == EOF)
+        abortWithReadError(ifP);
+
+    return (unsigned char) c;
+}
+
+
+
+static void
+decodeQoiHeader(FILE *     const ifP,
+                qoi_Desc * const qoiDescP) {
+
+    unsigned long int width, height;
+
+    readAndValidateMagic(ifP);
+
+    pm_readbiglongu(ifP, &width);
+    if (width == 0)
+        pm_error("Invalid QOI image: width is zero");
+    else
+        qoiDescP->width = width;
+
+    pm_readbiglongu(ifP, &height);
+    if (height == 0)
+        pm_error("Invalid QOI image: height is zero");
+    else if (height > QOI_PIXELS_MAX / width)
+        pm_error ("Invalid QOI image: %u x %u is more than %u pixels",
+                  (unsigned int) width, (unsigned int) height, QOI_PIXELS_MAX);
+    else
+        qoiDescP->height = height;
+
+    qoiDescP->channelCt = getcNofail(ifP);
+    if (qoiDescP->channelCt != 3 && qoiDescP->channelCt != 4)
+        pm_error("Invalid QOI image: channel count is %u.  "
+                 "Only 3 and 4 are valid", qoiDescP->channelCt);
+
+    qoiDescP->colorspace = getcNofail(ifP);
+    if (qoiDescP->colorspace != QOI_SRGB && qoiDescP->colorspace != QOI_LINEAR)
+        pm_error("Invalid QOI image: colorspace code is %u.  "
+                 "Only %u (SRGB) and %u (LINEAR) are valid",
+                 qoiDescP->colorspace, QOI_SRGB, QOI_LINEAR);
+}
+
+
+
+static void
+qoiDecode(FILE *       const ifP,
+          qoi_Desc *   const qoiDescP,
+          struct pam * const outpamP) {
+
+    qoi_Rgba index[QOI_INDEX_SIZE];
+    unsigned int row;
+    qoi_Rgba px;
+    unsigned int run;
+    tuple * tuplerow;
+
+    assert(qoiDescP);
+    tuplerow = pnm_allocpamrow(outpamP);
+
+    qoi_clearQoiIndex(index);
+    px.rgba.r = px.rgba.g = px.rgba.b = 0;
+    px.rgba.a = 255;
+
+    for (row = 0, run = 0; row < outpamP->height; ++row) {
+        unsigned int col;
+
+        for (col = 0; col < outpamP->width; ++col) {
+            if (run > 0) {
+                 --run;
+            } else {
+                unsigned char const b1 = getcNofail(ifP);
+
+                if (b1 == QOI_OP_RGB) {
+                    px.rgba.r = getcNofail(ifP);
+                    px.rgba.g = getcNofail(ifP);
+                    px.rgba.b = getcNofail(ifP);
+                } else if (b1 == QOI_OP_RGBA) {
+                    px.rgba.r = getcNofail(ifP);
+                    px.rgba.g = getcNofail(ifP);
+                    px.rgba.b = getcNofail(ifP);
+                    px.rgba.a = getcNofail(ifP);
+                } else if ((b1 & QOI_MASK_2) == QOI_OP_INDEX) {
+                  /* Official spec says 2 or more consecutive instances of
+                     QOI_OP_INDEX are not allowed, but we don't check */
+                    px = index[b1];
+                } else if ((b1 & QOI_MASK_2) == QOI_OP_DIFF) {
+                    px.rgba.r += ((b1 >> 4) & 0x03) - 2;
+                    px.rgba.g += ((b1 >> 2) & 0x03) - 2;
+                    px.rgba.b += ( b1       & 0x03) - 2;
+                } else if ((b1 & QOI_MASK_2) == QOI_OP_LUMA) {
+                    unsigned char const b2 = getcNofail(ifP);
+                    unsigned char const vg = (b1 & 0x3f) - 32;
+                    px.rgba.r += vg - 8 + ((b2 >> 4) & 0x0f);
+                    px.rgba.g += vg;
+                    px.rgba.b += vg - 8 +  (b2       & 0x0f);
+                } else if ((b1 & QOI_MASK_2) == QOI_OP_RUN) {
+                    run = (b1 & 0x3f);
+                }
+                /* register pixel in hash lookup array */
+                index[qoi_colorHash(px)] = px;
+            }
+            tuplerow[col][PAM_RED_PLANE] = px.rgba.r;
+            tuplerow[col][PAM_GRN_PLANE] = px.rgba.g;
+            tuplerow[col][PAM_BLU_PLANE] = px.rgba.b;
+            if (qoiDescP->channelCt == 4)
+                tuplerow[col][PAM_TRN_PLANE] = px.rgba.a;
+        }
+        pnm_writepamrow(outpamP, tuplerow);
+    }
+    if (run > 0)
+        pm_error("Invalid QOI image: %u (or more) extra pixels "
+                 "beyond end of image.", run);
+
+    pnm_freepamrow(tuplerow);
+}
+
+
+
+static void
+readAndValidatePadding(FILE * const ifP){
+
+    unsigned char padBuff[QOI_PADDING_SIZE];
+    size_t charsReadCt;
+
+    charsReadCt = fread(padBuff, 1, QOI_PADDING_SIZE, ifP);
+
+    if(charsReadCt < QOI_PADDING_SIZE) {
+        pm_error("Invalid QOI image.  Error reading final 8-byte padding.  "
+                 "Premature end of file.");
+    } else if (!MEMSEQ(&padBuff, &qoi_padding))
+        pm_error("Invalid QOI image.  Final 8-byte padding incorrect.");
+    else if (fgetc(ifP) != EOF)
+        pm_error("Invalid QOI image.  "
+                 "Extraneous bytes after final 8-byte padding.");
+}
+
+
+
+int
+main(int argc, const char **argv) {
+
+    struct CmdlineInfo cmdline;
+    qoi_Desc qoiDesc;
+    struct pam outpam;
+    FILE * ifP;
+
+    pm_proginit(&argc, argv);
+
+    parseCommandLine(argc, argv, &cmdline);
+
+    ifP = pm_openr(cmdline.inputFileName);
+
+    outpam.size        = sizeof(struct pam);
+    outpam.len         = PAM_STRUCT_SIZE(tuple_type);
+    outpam.maxval      = QOI_MAXVAL;
+    outpam.plainformat = 0;
+
+    decodeQoiHeader(ifP, &qoiDesc);
+
+    outpam.depth  = qoiDesc.channelCt == 3 ? 3 : 4;
+    outpam.width  = qoiDesc.width;
+    outpam.height = qoiDesc.height;
+    outpam.format = PAM_FORMAT;
+    outpam.file   = stdout;
+
+    if (qoiDesc.channelCt == 3)
+        strcpy(outpam.tuple_type, PAM_PPM_TUPLETYPE);
+    else
+        strcpy(outpam.tuple_type, PAM_PPM_ALPHA_TUPLETYPE);
+
+    pnm_writepaminit(&outpam);
+    qoiDecode(ifP, &qoiDesc, &outpam);
+
+    readAndValidatePadding(ifP);
+
+    return 0;
+}
+
+
+
diff --git a/converter/other/rast.c b/converter/other/rast.c
index 1c787089..1a64f7e5 100644
--- a/converter/other/rast.c
+++ b/converter/other/rast.c
@@ -61,6 +61,8 @@ mem_create( w, h, depth )
     return p;
 }
 
+
+
 void
 mem_free( p )
     struct pixrect* p;
@@ -70,6 +72,8 @@ mem_free( p )
     free( p );
 }
 
+
+
 int
 pr_dump( p, out, colormap, type, copy_flag )
     struct pixrect* p;
@@ -371,11 +375,11 @@ pr_load_colormap( in, hP, colormap )
                 free( colormap->map[1] );
                 return PIX_ERR;
             }
-            if ( fread( colormap->map[0], 1, colormap->length, in ) != 
+            if ( fread( colormap->map[0], 1, colormap->length, in ) !=
                  colormap->length ||
-                 fread( colormap->map[1], 1, colormap->length, in ) != 
+                 fread( colormap->map[1], 1, colormap->length, in ) !=
                  colormap->length ||
-                 fread( colormap->map[2], 1, colormap->length, in ) != 
+                 fread( colormap->map[2], 1, colormap->length, in ) !=
                  colormap->length )
             {
                 free( colormap->map[0] );
@@ -409,6 +413,8 @@ pr_load_colormap( in, hP, colormap )
     return 0;
 }
 
+
+
 struct pixrect*
 pr_load_image( in, hP, colormap )
     FILE* in;
@@ -502,3 +508,6 @@ pr_load_image( in, hP, colormap )
 
     return p;
 }
+
+
+
diff --git a/converter/other/rast.h b/converter/other/rast.h
index eb6f4ec4..2a6b0126 100644
--- a/converter/other/rast.h
+++ b/converter/other/rast.h
@@ -27,44 +27,44 @@
 #ifndef RAST_H_INCLUDED
 #define RAST_H_INCLUDED
 
-#define PIX_ERR		-1
+#define PIX_ERR         -1
 
 struct rasterfile {
     long ras_magic;
-#define	RAS_MAGIC	0x59a66a95
+#define RAS_MAGIC       0x59a66a95
     long ras_width;
     long ras_height;
     long ras_depth;
     long ras_length;
     long ras_type;
-#define RT_OLD		0	/* Raw pixrect image in 68000 byte order */
-#define RT_STANDARD	1	/* Raw pixrect image in 68000 byte order */
-#define RT_BYTE_ENCODED	2	/* Run-length compression of bytes */
-#define RT_FORMAT_RGB	3	/* XRGB or RGB instead of XBGR or BGR */
-#define RT_FORMAT_TIFF	4	/* tiff <-> standard rasterfile */
-#define RT_FORMAT_IFF	5	/* iff (TAAC format) <-> standard rasterfile */
-#define RT_EXPERIMENTAL 0xffff	/* Reserved for testing */
+#define RT_OLD          0       /* Raw pixrect image in 68000 byte order */
+#define RT_STANDARD     1       /* Raw pixrect image in 68000 byte order */
+#define RT_BYTE_ENCODED 2       /* Run-length compression of bytes */
+#define RT_FORMAT_RGB   3       /* XRGB or RGB instead of XBGR or BGR */
+#define RT_FORMAT_TIFF  4       /* tiff <-> standard rasterfile */
+#define RT_FORMAT_IFF   5       /* iff (TAAC format) <-> standard rasterfile */
+#define RT_EXPERIMENTAL 0xffff  /* Reserved for testing */
     long ras_maptype;
-#define RMT_NONE	0
-#define RMT_EQUAL_RGB	1
-#define RMT_RAW		2
+#define RMT_NONE        0
+#define RMT_EQUAL_RGB   1
+#define RMT_RAW         2
     long ras_maplength;
 };
 
 struct pixrectops {
-    int	(*pro_rop)();
-    int	(*pro_stencil)();
-    int	(*pro_batchrop)();
-    int	(*pro_nop)();
-    int	(*pro_destroy)();
-    int	(*pro_get)();
-    int	(*pro_put)();
-    int	(*pro_vector)();
+    int (*pro_rop)();
+    int (*pro_stencil)();
+    int (*pro_batchrop)();
+    int (*pro_nop)();
+    int (*pro_destroy)();
+    int (*pro_get)();
+    int (*pro_put)();
+    int (*pro_vector)();
     struct pixrect* (*pro_region)();
-    int	(*pro_putcolormap)();
-    int	(*pro_getcolormap)();
-    int	(*pro_putattributes)();
-    int	(*pro_getattributes)();
+    int (*pro_putcolormap)();
+    int (*pro_getcolormap)();
+    int (*pro_putattributes)();
+    int (*pro_getattributes)();
 };
 
 struct pr_size {
@@ -79,12 +79,12 @@ struct pixrect {
     struct pixrectops* pr_ops;
     struct pr_size pr_size;
     int pr_depth;
-    struct mpr_data* pr_data;	/* work-alike only handles memory pixrects */
+    struct mpr_data* pr_data;   /* work-alike only handles memory pixrects */
 };
 
 struct mpr_data {
     int md_linebytes;
-    unsigned char* md_image;	/* note, byte not short -- avoid pr_flip() */
+    unsigned char* md_image;    /* note, byte not short -- avoid pr_flip() */
     struct pr_pos md_offset;
     short md_primary;
     short md_flags;
diff --git a/converter/other/rasttopnm.c b/converter/other/rasttopnm.c
index 285fc5e0..bc199ef7 100644
--- a/converter/other/rasttopnm.c
+++ b/converter/other/rasttopnm.c
@@ -37,9 +37,7 @@ parseCommandLine(int argc, const char ** argv,
    Note that the file spec array we return is stored in the storage that
    was passed to us as the argv array.
 -----------------------------------------------------------------------------*/
-    optEntry * option_def;
-        /* Instructions to OptParseOptions2 on how to parse our options.
-         */
+    optEntry * option_def;   /* Used by OPTENT3 */
     optStruct3 opt;
 
     unsigned int option_def_index;
@@ -47,7 +45,7 @@ parseCommandLine(int argc, const char ** argv,
     MALLOCARRAY_NOFAIL(option_def, 100);
 
     option_def_index = 0;   /* incremented by OPTENT3 */
- 
+
     opt.opt_table = option_def;
     opt.short_allowed = false;  /* We have no short (old-fashioned) options */
     opt.allowNegNum = false;  /* We have no parms that are negative numbers */
@@ -59,10 +57,10 @@ parseCommandLine(int argc, const char ** argv,
     OPTENT3(0,   "dumpcolormap", OPT_FLAG,   NULL,
             &cmdlineP->dumpcolormap,   0);
 
-    pm_optParseOptions3(&argc, (char **)argv, opt, sizeof(opt), 0);
+    pm_optParseOptions4(&argc, argv, opt, sizeof(opt), 0);
         /* Uses and sets argc, argv, and some of *cmdlineP and others. */
 
-    if (argc-1 == 0) 
+    if (argc-1 == 0)
         cmdlineP->inputFileName = "-";
     else if (argc-1 != 1)
         pm_error("Program takes zero or one argument (filename).  You "
@@ -258,7 +256,7 @@ convertRowDepth8(const unsigned char * const lineStart,
 
         ++byteP;
     }
-} 
+}
 
 
 
@@ -299,7 +297,7 @@ convertRowRgb(const unsigned char * const lineStart,
         else
             PPM_ASSIGN(xelrow[col], r, g, b);
     }
-} 
+}
 
 
 
@@ -387,9 +385,9 @@ dumpHeader(struct rasterfile const header) {
 
 
 static void
-dumpHeaderAnalysis(bool         const grayscale, 
+dumpHeaderAnalysis(bool         const grayscale,
                    unsigned int const depth,
-                   xel          const zero, 
+                   xel          const zero,
                    xel          const one) {
 
     pm_message("grayscale: %s", grayscale ? "YES" : "NO");
@@ -464,9 +462,9 @@ main(int argc, const char ** const argv) {
 
     if (header.ras_maplength != 0) {
         int rc;
-        
+
         rc = pr_load_colormap(ifP, &header, &colorMap);
-        
+
         if (rc != 0 )
             pm_error("unable to read colormap from RAST file");
 
@@ -488,7 +486,7 @@ main(int argc, const char ** const argv) {
                  "but this is not a color mapped image");
 
     writePnm(stdout, pr, header.ras_width, header.ras_height, maxval, format,
-             header.ras_depth, header.ras_type, grayscale, 
+             header.ras_depth, header.ras_type, grayscale,
              header.ras_maplength > 0, colorMap, zero, one, cmdline.index);
 
     pm_close(ifP);
@@ -496,3 +494,6 @@ main(int argc, const char ** const argv) {
 
     return 0;
 }
+
+
+
diff --git a/converter/other/rla.h b/converter/other/rla.h
index 875cbfc6..e8bb6da1 100644
--- a/converter/other/rla.h
+++ b/converter/other/rla.h
@@ -8,9 +8,9 @@ typedef struct
 
 typedef struct
 {
-    window_s	window;
-    window_s	active_window;
-    short	    frame;
+    window_s    window;
+    window_s    active_window;
+    short           frame;
     short       storage_type;
     short       num_chan;
     short       num_matte;
diff --git a/converter/other/rletopnm.c b/converter/other/rletopnm.c
index 97f271dc..2edad50b 100644
--- a/converter/other/rletopnm.c
+++ b/converter/other/rletopnm.c
@@ -503,3 +503,6 @@ main(int argc, char ** argv) {
 
     return 0;
 }
+
+
+
diff --git a/converter/other/sgitopnm.c b/converter/other/sgitopnm.c
index 6fd4efcf..09bdc669 100644
--- a/converter/other/sgitopnm.c
+++ b/converter/other/sgitopnm.c
@@ -56,9 +56,7 @@ parseCommandLine(int argc, const char ** argv,
    Note that the strings we return are stored in the storage that
    was passed to us as the argv array.  We also trash *argv.
 -----------------------------------------------------------------------------*/
-    optEntry * option_def;
-        /* Instructions to pm_optParseOptions3 on how to parse our options.
-         */
+    optEntry * option_def;   /* Used by OPTENT3 */
     optStruct3 opt;
 
     unsigned int option_def_index;
@@ -78,7 +76,7 @@ parseCommandLine(int argc, const char ** argv,
     opt.short_allowed = FALSE;  /* We have no short (old-fashioned) options */
     opt.allowNegNum = FALSE;  /* We have no parms that are negative numbers */
 
-    pm_optParseOptions3(&argc, (char **)argv, opt, sizeof(opt), 0);
+    pm_optParseOptions4(&argc, argv, opt, sizeof(opt), 0);
         /* Uses and sets argc, argv, and some of *cmdlineP and others. */
 
     free(option_def);
@@ -522,3 +520,4 @@ main(int argc, const char * argv[]) {
 }
 
 
+
diff --git a/converter/other/sirtopnm.c b/converter/other/sirtopnm.c
index fafcc913..8bdeb6b5 100644
--- a/converter/other/sirtopnm.c
+++ b/converter/other/sirtopnm.c
@@ -10,86 +10,155 @@
 ** implied warranty.
 */
 
+#include <stdbool.h>
+#include <assert.h>
+
+#include "mallocvar.h"
 #include "pnm.h"
 
-int main( argc, argv )
-int argc;
-char* argv[];
-{
-    FILE *ifp;
-    xel *xelrow, *xP;
-    unsigned char *sirarray;
-    int rows, cols, row, format, picsize, planesize;
-    register int col, i;
+
+
+static void
+readSirHeader(FILE *         const ifP,
+              int *          const formatP,
+              unsigned int * const rowsP,
+              unsigned int * const colsP) {
+
     short info;
 
-    pnm_init( &argc, argv );
+    pm_readlittleshort(ifP, &info);
+    if (info != 0x3a4f)
+        pm_error( "Input file is not a Solitaire file");
 
-    if ( argc > 2 )
-	pm_usage( "[sirfile]" );
+    pm_readlittleshort(ifP, &info);
 
-    if ( argc == 2 )
-	ifp = pm_openr( argv[1] );
+    pm_readlittleshort(ifP, &info);
+    if (info == 17)
+        *formatP = PGM_TYPE;
+    else if (info == 11)
+        *formatP = PPM_TYPE;
     else
-	ifp = stdin;
-
-    pm_readlittleshort( ifp, &info );
-    if ( info != 0x3a4f)
-	pm_error( "Input file is not a Solitaire file" );
-    pm_readlittleshort( ifp, &info );
-    pm_readlittleshort( ifp, &info );
-    if ( info == 17 )
+        pm_error( "Input is not MGI TYPE 11 or MGI TYPE 17" );
+
+    pm_readlittleshort(ifP, &info);
+    *colsP = info;
+
+    pm_readlittleshort(ifP, &info);
+    *rowsP = info;
+
     {
-	format = PGM_TYPE;
+        unsigned int i;
+        for (i = 1; i < 1531; ++i)
+            pm_readlittleshort(ifP, &info);
     }
-    else if ( info == 11 )
-    {
-	format = PPM_TYPE;
+}
+
+
+
+static void
+convertPgm(FILE *       const ifP,
+           FILE *       const ofP,
+           unsigned int const rows,
+           unsigned int const cols,
+           xel *        const xelrow) {
+
+    unsigned int row;
+
+    pm_message("Writing a PGM file");
+
+    for (row = 0; row < rows; ++row) {
+        unsigned int col;
+        for (col = 0; col < cols; ++col)
+            PNM_ASSIGN1(xelrow[col], fgetc(ifP));
+
+        pnm_writepnmrow(ofP, xelrow, cols, 255, PGM_TYPE, 0);
     }
+}
+
+
+
+static void
+convertPpm(FILE *       const ifP,
+           FILE *       const ofP,
+           unsigned int const rows,
+           unsigned int const cols,
+           xel *        const xelrow) {
+
+    unsigned int const picsize = cols * rows * 3;
+    unsigned int const planesize = cols * rows;
+
+    unsigned char * sirarray;  /* malloc'ed array */
+    unsigned int row;
+
+    if (UINT_MAX/cols/rows < 3)
+        pm_error("Image is too large (%u x %u x %u) for computation",
+                 cols, rows, 3);
+
+    MALLOCARRAY(sirarray, picsize);
+
+    if (!sirarray)
+        pm_error( "Not enough memory to load %u x %u x %u SIR file",
+                  cols, rows, 3);
+
+    if (fread(sirarray, 1, picsize, ifP) != picsize)
+        pm_error("Error reading SIR file");
+
+    pm_message("Writing a PPM file");
+    for (row = 0; row < rows; ++row) {
+        unsigned int col;
+
+        for (col = 0; col < cols; col++)
+            PPM_ASSIGN(xelrow[col], sirarray[row*cols+col],
+                       sirarray[planesize + (row*cols+col)],
+                       sirarray[2*planesize + (row*cols+col)]);
+
+        pnm_writepnmrow(ofP, xelrow, cols, 255, PPM_TYPE, 0);
+    }
+    free(sirarray);
+}
+
+
+
+int
+main(int argc, const char ** argv) {
+
+    FILE * ifP;
+    xel * xelrow;
+    unsigned int rows, cols;
+    int format;
+
+    pm_proginit(&argc, argv);
+
+    if (argc-1 > 1)
+        pm_error ("Too many arguments.  The only possible argument is "
+                  "the input file name");
+    else if (argc-1 >= 1)
+        ifP = pm_openr(argv[1]);
     else
-	pm_error( "Input is not MGI TYPE 11 or MGI TYPE 17" );
-    pm_readlittleshort( ifp, &info );
-    cols = (int) ( info );
-    pm_readlittleshort( ifp, &info );
-    rows = (int) ( info );
-    for ( i = 1; i < 1531; i++ )
-	pm_readlittleshort( ifp, &info );
-
-    pnm_writepnminit( stdout, cols, rows, 255, format, 0 );
-    xelrow = pnm_allocrow( cols );
-    switch ( PNM_FORMAT_TYPE(format) )
-    {
-	case PGM_TYPE:
-            pm_message( "Writing a PGM file" );
-	    for ( row = 0; row < rows; ++row )
-	    {
-	        for ( col = 0, xP = xelrow; col < cols; col++, xP++ )
-	        	PNM_ASSIGN1( *xP, fgetc( ifp ) );
-	        pnm_writepnmrow( stdout, xelrow, cols, 255, format, 0 );
-	    }
-	    break;
-	case PPM_TYPE:
-	    picsize = cols * rows * 3;
-	    planesize = cols * rows;
-            if ( !( sirarray = (unsigned char*) malloc( picsize ) ) ) 
-	        pm_error( "Not enough memory to load SIR file" );
-	    if ( fread( sirarray, 1, picsize, ifp ) != picsize )
-	        pm_error( "Error reading SIR file" );
-            pm_message( "Writing a PPM file" );
-            for ( row = 0; row < rows; row++ )
-	    {
-	        for ( col = 0, xP = xelrow; col < cols; col++, xP++ )
-        	    PPM_ASSIGN( *xP, sirarray[row*cols+col],
-				 sirarray[planesize + (row*cols+col)],
-				 sirarray[2*planesize + (row*cols+col)] );
-                pnm_writepnmrow( stdout, xelrow, cols, 255, format, 0 );
-	    }
-	    break;
-	default:
-	    pm_error( "Shouldn't happen" );
+        ifP = stdin;
+
+    readSirHeader(ifP, &format, &rows, &cols);
+
+    pnm_writepnminit(stdout, cols, rows, 255, format, 0);
+
+    xelrow = pnm_allocrow(cols);
+
+    switch (PNM_FORMAT_TYPE(format)) {
+    case PGM_TYPE:
+        convertPgm(ifP, stdout, rows, cols, xelrow);
+        break;
+    case PPM_TYPE:
+        convertPpm(ifP, stdout, rows, cols, xelrow);
+        break;
+    default:
+        assert(false);
     }
+    pnm_freerow(xelrow);
 
-    pm_close( ifp );
+    pm_close(ifP);
 
-    exit( 0 );
+    exit(0);
 }
+
+
+
diff --git a/converter/other/srf.c b/converter/other/srf.c
index b0f97242..a6d51a5d 100644
--- a/converter/other/srf.c
+++ b/converter/other/srf.c
@@ -24,7 +24,7 @@ csumRaw(void * const p,
 
     for (i = 0, retval = 0, c = p; i < len; ++i)
         retval += *c++;
-    
+
     return retval;
 }
 
@@ -419,10 +419,10 @@ csum(struct srf * const srfP,
 
     for (i = 0; i < srfP->header.img_cnt; ++i)
         retval += csumImg(&srfP->imgs[i]);
-    
+
     for (i = 0; i < padLen; ++i)
         retval += 0xff;
-    
+
     return retval;
 }
 
@@ -540,7 +540,7 @@ void
 srf_term(struct srf * const srfP) {
 
     unsigned int i;
-    
+
     free(srfP->header.s578.val);
     free(srfP->header.ver.val);
     free(srfP->header.prod.val);
@@ -634,12 +634,12 @@ srf_create_img(struct srf * const srfP,
                uint16_t     const width,
                uint16_t     const height) {
 /*----------------------------------------------------------------------------
-   Add an "image" to the SRF.  An image is a horizontal series of 36 
+   Add an "image" to the SRF.  An image is a horizontal series of 36
    square frames, each showing a different angle view of an object, 10
    degrees about.  At least that's what it's supposed to be.  We don't
    really care -- it's just an arbitrary rectangular raster image to us.
 -----------------------------------------------------------------------------*/
-    
+
     ++srfP->header.img_cnt;
 
     REALLOCARRAY(srfP->imgs, srfP->header.img_cnt);
@@ -650,4 +650,6 @@ srf_create_img(struct srf * const srfP,
 
     srf_img_init(&srfP->imgs[srfP->header.img_cnt-1], width, height);
 }
-                 
+
+
+
diff --git a/converter/other/srftopam.c b/converter/other/srftopam.c
index efe55253..857d6d92 100644
--- a/converter/other/srftopam.c
+++ b/converter/other/srftopam.c
@@ -46,9 +46,7 @@ parseCommandLine(int argc, const char ** argv,
    Note that the strings we return are stored in the storage that
    was passed to us as the argv array.  We also trash *argv.
 -----------------------------------------------------------------------------*/
-    optEntry *option_def;
-    /* Instructions to pm_optParseOptions3 on how to parse our options.
-     */
+    optEntry * option_def;   /* Used by OPTENT3 */
     optStruct3 opt;
 
     unsigned int option_def_index;
@@ -63,7 +61,7 @@ parseCommandLine(int argc, const char ** argv,
     opt.short_allowed = FALSE;  /* We have no short (old-fashioned) options */
     opt.allowNegNum = FALSE;  /* We have no parms that are negative numbers */
 
-    pm_optParseOptions3(&argc, (char **)argv, opt, sizeof(opt), 0);
+    pm_optParseOptions4(&argc, argv, opt, sizeof(opt), 0);
     /* Uses and sets argc, argv, and some of *cmdlineP and others. */
 
     if (argc-1 < 1)
@@ -82,18 +80,21 @@ srfRed(uint16_t const pixel) {
 }
 
 
+
 static unsigned int
 srfGrn(uint16_t const pixel) {
     return ((pixel >>  6) & 0x1f) << 3;
 }
 
 
+
 static unsigned int
 srfBlu(uint16_t const pixel) {
     return ((pixel >>  0) & 0x1f) << 3;
 }
 
 
+
 static uint8_t
 srfAlpha(uint8_t const d) {
 
@@ -130,7 +131,7 @@ writeRaster(struct pam *     const pamP,
             uint16_t const alpha = imgP->alpha.data[rowStart + col];
 
             assert(col < pamP->width);
-            
+
             tuplerow[col][PAM_RED_PLANE] = srfRed(data);
             tuplerow[col][PAM_GRN_PLANE] = srfGrn(data);
             tuplerow[col][PAM_BLU_PLANE] = srfBlu(data);
@@ -142,7 +143,7 @@ writeRaster(struct pam *     const pamP,
             tuplerow[col][PAM_GRN_PLANE] = 0;
             tuplerow[col][PAM_BLU_PLANE] = 0;
             tuplerow[col][PAM_TRN_PLANE] = 0;
-        }            
+        }
 
         pnm_writepamrow(pamP, tuplerow);
     }
diff --git a/converter/other/sunicontopnm.c b/converter/other/sunicontopnm.c
index eff1be58..8d67179a 100644
--- a/converter/other/sunicontopnm.c
+++ b/converter/other/sunicontopnm.c
@@ -12,10 +12,12 @@
 
 /*
   Most icon images are monochrome: Depth=1
+
   Depth=8 images are extremely rare.  At least some of these are color
-  images but we can't tell the palette color order.
+  images but we haven't found information on the palette color order.
   Output will be in pgm.  Convert to ppm with pgmtoppm or pamlookup
-  if necessary.
+  if necessary.  It is up to the user to provide the color palette in
+  a form acceptable by the above conversion utilities.
 */
 
 #include <assert.h>
@@ -28,9 +30,9 @@
 
 
 static void
-ReadIconFileHeader(FILE * const file, 
-                   int *  const widthP, 
-                   int *  const heightP, 
+ReadIconFileHeader(FILE * const file,
+                   int *  const widthP,
+                   int *  const heightP,
                    int *  const depthP,
                    int *  const bitsPerItemP) {
 
@@ -49,7 +51,7 @@ ReadIconFileHeader(FILE * const file,
                 ch == ' ')
             ;
         for (i = 0;
-             ch != '=' && ch != ',' && ch != '\n' && ch != '\t' && 
+             ch != '=' && ch != ',' && ch != '\n' && ch != '\t' &&
                  ch != ' ' && (i < (sizeof(variable) - 1));
              ++i) {
             variable[i] = ch;
@@ -82,7 +84,7 @@ ReadIconFileHeader(FILE * const file,
         } else if (streq(variable, "Valid_bits_per_item")) {
             if (value != 16 && value !=32)
                 pm_error("invalid Valid_bits_per_item");
-            *bitsPerItemP = value; 
+            *bitsPerItemP = value;
             ++fieldCt;
         }
     }
@@ -93,12 +95,19 @@ ReadIconFileHeader(FILE * const file,
 
     if (*widthP <= 0)
         pm_error("invalid width (must be positive): %d", *widthP);
+    else if (*widthP % 8 > 0)
+        pm_message("warning: width not a multiple of 8: %d", *widthP);
+        /* We don't know whether widths which are not a multiple of 8
+           are allowed.   The program must gracefully handle this case
+           because sun icon files are easy to edit by hand.
+        */
     if (*heightP <= 0)
         pm_error("invalid height (must be positive): %d", *heightP);
 
 }
 
 
+
 int
 main(int argc, const char ** argv) {
 
@@ -125,7 +134,7 @@ main(int argc, const char ** argv) {
         maxval = 1;
         pbm_writepbminit(stdout, cols, rows, 0);
         bitrow = pbm_allocrow_packed(cols);
-        colChars = cols / 8;
+        colChars = pbm_packed_bytes(cols);
     } else {
         assert(depth == 8);
         format = PGM_TYPE;
@@ -156,7 +165,7 @@ main(int argc, const char ** argv) {
                 else
                     grayrow[colChar] = data;
             } else
-                pm_error("error scanning bits item %u" , colChar);
+                pm_error("error scanning bits item %u", colChar);
         }
 
         /* output row */
@@ -166,7 +175,15 @@ main(int argc, const char ** argv) {
             pgm_writepgmrow(stdout, grayrow, cols, maxval, 0);
     }
 
+    if (format == PBM_TYPE)
+        pbm_freerow_packed(bitrow);
+    else
+        pgm_freerow(grayrow);
+
     pm_close(ifP);
     pm_close(stdout);
     return 0;
 }
+
+
+
diff --git a/converter/other/svgtopam.c b/converter/other/svgtopam.c
index ca6f4dc7..060d8cde 100644
--- a/converter/other/svgtopam.c
+++ b/converter/other/svgtopam.c
@@ -23,7 +23,7 @@
    10.3.9 user reports in April 2007 that he has 2.6.16 installed and it
    doesn't have xmlReaderTypes.  Another MacOS user reported that in December
    2008.  Apparently that OS has a broken libxml2 installation.
-   
+
 ============================================================================*/
 
 #define _DEFAULT_SOURCE /* New name for SVID & BSD source defines */
@@ -54,13 +54,13 @@ struct cmdlineInfo {
 
 
 
-static void 
-parseCommandLine(int argc, 
-                 char ** argv, 
+static void
+parseCommandLine(int argc,
+                 char ** argv,
                  struct cmdlineInfo  * const cmdlineP) {
 /* --------------------------------------------------------------------------
    Parse program command line described in Unix standard form by argc
-   and argv.  Return the information in the options as *cmdlineP.  
+   and argv.  Return the information in the options as *cmdlineP.
 
    If command line is internally inconsistent (invalid options, etc.),
    issue error message to stderr and abort program.
@@ -77,7 +77,7 @@ parseCommandLine(int argc,
     MALLOCARRAY_NOFAIL(option_def, 100);
 
     option_def_index = 0;   /* incremented by OPTENT3 */
-    OPTENT3(0, "trace",     OPT_FLAG,   NULL,                  
+    OPTENT3(0, "trace",     OPT_FLAG,   NULL,
             &cmdlineP->trace,       0);
 
     opt.opt_table = option_def;
@@ -91,7 +91,7 @@ parseCommandLine(int argc,
         cmdlineP->inputFileName = "-";
     else {
         cmdlineP->inputFileName = argv[1];
-        
+
         if (argc-1 > 1)
             pm_error("Too many arguments (%u).  The only non-option argument "
                      "is the input file name.", argc-1);
@@ -177,7 +177,7 @@ createPath(const char * const pathText,
 -----------------------------------------------------------------------------*/
     bool error;
     Path * pathP;
-    
+
     MALLOCVAR(pathP);
     if (pathP == NULL)
         error = TRUE;
@@ -205,7 +205,7 @@ createPath(const char * const pathText,
 
 static void
 destroyPath(Path * const pathP) {
-    
+
     assert(pathP->pathTextLength == strlen(pathP->pathText));
 
     pm_strfree(pathP->pathText);
@@ -225,13 +225,15 @@ makePoint(unsigned int const x,
           unsigned int const y) {
 
     Point p;
-    
+
     p.x = x;
     p.y = y;
-    
+
     return p;
 }
 
+
+
 static ppmd_point
 makePpmdPoint(Point const arg) {
 
@@ -243,6 +245,8 @@ makePpmdPoint(Point const arg) {
     return p;
 }
 
+
+
 typedef enum {
     PATH_MOVETO,
     PATH_LINETO,
@@ -310,6 +314,8 @@ pathReader_create(Path *        const pathP,
     *pathReaderPP = pathReaderP;
 }
 
+
+
 static void
 pathReader_destroy(PathReader * const pathReaderP) {
     free(pathReaderP);
@@ -432,7 +438,7 @@ pathReader_getNextCommand(PathReader *  const pathReaderP,
             break;
         default: {
             const char * const context = pathReader_context(pathReaderP);
-            
+
             pm_errormsg("Unrecognized command in <path>: '%c'.  %s",
                         pathText[pathReaderP->cursor++], context);
 
@@ -544,7 +550,7 @@ drawPath(Canvas * const canvasP,
 
     ppmd_fill(canvasP->pixels, canvasP->width, canvasP->height,
               canvasP->maxval,
-              fillObjP, 
+              fillObjP,
               PPMD_NULLDRAWPROC, &pathP->style.fillColor);
 
     ppmd_fill_destroy(fillObjP);
@@ -574,7 +580,7 @@ interpretStyle(const char * const styleAttr) {
         char * buffer;
 
         for (p = &token[0]; isspace(*p); ++p);
-        
+
         strippedToken = p;
 
         buffer = strdup(strippedToken);
@@ -589,7 +595,7 @@ interpretStyle(const char * const styleAttr) {
             else {
                 const char * const value = colonPos + 1;
                 const char * const name  = &buffer[0];
-                
+
                 *colonPos = '\0';
 
                 if (streq(name, "fill")) {
@@ -614,6 +620,7 @@ interpretStyle(const char * const styleAttr) {
 }
 
 
+
 static void
 getPathAttributes(xmlTextReaderPtr const xmlReaderP,
                   Style *          const styleP,
@@ -652,7 +659,7 @@ processSubPathNode(xmlTextReaderPtr const xmlReaderP,
         } break;
     default:
         /* Just ignore whatever this is.  Contents of <path> are
-           meaningless; all the information is in the attributes 
+           meaningless; all the information is in the attributes
         */
         break;
     }
@@ -687,7 +694,7 @@ processPathElement(xmlTextReaderPtr const xmlReaderP,
         int rc;
 
         rc = xmlTextReaderRead(xmlReaderP);
-        
+
         switch (rc) {
         case 1:
             processSubPathNode(xmlReaderP, &endOfPath);
@@ -736,7 +743,7 @@ processSubSvgElement(xmlTextReaderPtr const xmlReaderP,
     const char * const nodeName = currentNodeName(xmlReaderP);
 
     assert(xmlTextReaderNodeType(xmlReaderP) == XML_READER_TYPE_ELEMENT);
-    
+
     if (streq(nodeName, "path"))
         processPathElement(xmlReaderP, canvasP);
     else
@@ -822,7 +829,7 @@ writePam(FILE *   const ofP,
     pam.depth            = 3;
     pam.maxval           = OUTPUT_MAXVAL;
     strcpy(pam.tuple_type, PAM_PPM_TUPLETYPE);
-    
+
     pnm_writepaminit(&pam);
 
     tuplerow = pnm_allocpamrow(&pam);
@@ -867,7 +874,7 @@ processSvgElement(xmlTextReaderPtr const xmlReaderP,
         int rc;
 
         rc = xmlTextReaderRead(xmlReaderP);
-        
+
         switch (rc) {
         case 1:
             processSubSvgNode(xmlReaderP, canvasP, &endOfSvg);
@@ -938,7 +945,7 @@ processDocument(xmlTextReaderPtr const xmlReaderP,
         int rc;
 
         rc = xmlTextReaderRead(xmlReaderP);
-        
+
         switch (rc) {
         case 1:
             processTopLevelNode(xmlReaderP, ofP);
@@ -968,12 +975,20 @@ main(int argc, char **argv) {
     LIBXML_TEST_VERSION;
 
     parseCommandLine(argc, argv, &cmdline);
-    
+
     traceDraw = cmdline.trace;
 
     ifP = pm_openr(cmdline.inputFileName);
 
     xmlReaderP = xmlReaderForFd(fileno(ifP), "SVG_IMAGE", NULL, 0);
+        /* 'xmlReaderForFd' issues an error message to Standard Error if it
+           cannot interpret the XML document on *ifP; that message identifies
+           the document as "SVG_IMAGE".  It issues the bogus message
+           "Extra content at the end of the document" if the document is
+           empty.  It issues the bogus message "Document is empty" if the
+           file starts with something other than an XML element.
+           libxml2 2.9.10 23.10.09
+        */
 
     if (xmlReaderP) {
         processDocument(xmlReaderP, stdout);
@@ -990,3 +1005,6 @@ main(int argc, char **argv) {
 
     return 0;
 }
+
+
+
diff --git a/converter/other/tiff.c b/converter/other/tiff.c
index 39e3b0ce..62a6dc94 100644
--- a/converter/other/tiff.c
+++ b/converter/other/tiff.c
@@ -24,14 +24,14 @@
 static uint32
 number(const char * const value,
        tagvalmap    const tagvallist[]) {
-    
+
     char * ep;
     long num;
 
     if (strlen(value) == 0)
         pm_error("null string where numeric tag value or enumerated tag "
                  "value name expected");
-    
+
     num = strtol(value, &ep, 10);
     if (*ep != '\0') {
         /* It's not a numeric string, so it must be an enumerated value name */
@@ -53,7 +53,7 @@ dnumber(const char * const value) {
 
     char * ep;
     double num;
-    
+
     num = strtod(value, &ep);
     if (ep == value || *ep != '\0')
         pm_error("Bad floating point number %s", value);
@@ -162,7 +162,7 @@ putCountBytes(TIFF *       const tifP,
 
 #define TV(p,a) { #a, p##a, }
 
-static tagvalmap const 
+static tagvalmap const
 tvm_compression[] = {
     TV(COMPRESSION_,NONE),
     TV(COMPRESSION_,CCITTRLE),
@@ -463,3 +463,6 @@ tagDefFind(const char * const name) {
 
     return NULL;
 }
+
+
+
diff --git a/converter/other/tifftopnm.c b/converter/other/tifftopnm.c
index 0c301a4a..0fbbaad0 100644
--- a/converter/other/tifftopnm.c
+++ b/converter/other/tifftopnm.c
@@ -105,8 +105,8 @@ parseCommandLine(int argc, const char ** const argv,
    sometimes, one of these strings is actually just a suffix of an entry
    in argv!
 -----------------------------------------------------------------------------*/
+    optEntry * option_def;
     optStruct3 opt;
-    optEntry *option_def;
     unsigned int option_def_index;
     unsigned int alphaSpec;
 
@@ -130,7 +130,7 @@ parseCommandLine(int argc, const char ** const argv,
     OPTENT3(0,   "alphaout",
             OPT_STRING, &cmdlineP->alphaFilename, &alphaSpec,  0);
 
-    pm_optParseOptions3(&argc, (char **)argv, opt, sizeof(opt), 0);
+    pm_optParseOptions4(&argc, argv, opt, sizeof(opt), 0);
 
     if (argc - 1 == 0)
         cmdlineP->inputFilename = strdup("-");  /* he wants stdin */
@@ -714,23 +714,6 @@ analyzeImageType(TIFF *             const tiffP,
 
 
 
-static void
-reportOutputFormat(int const format) {
-
-    const char * formatDesc;
-
-    switch (format) {
-    case PBM_TYPE: formatDesc = "PBM"; break;
-    case PGM_TYPE: formatDesc = "PGM"; break;
-    case PPM_TYPE: formatDesc = "PPM"; break;
-    default: assert(false);
-    }
-
-    pm_message("writing %s file", formatDesc);
-}
-
-
-
 typedef struct {
     FILE *       imageoutFileP;
         /* The stream to which we write the PNM image.  Null for none. */
@@ -1372,6 +1355,9 @@ convertRasterByRows(pnmOut *       const pnmOutP,
     if (scanbuf == NULL)
         pm_error("can't allocate memory for scanline buffer");
 
+    if (UINT_MAX/cols < spp)
+        pm_error("Image is too wide/deep (%u x %u) for computations",
+                 cols, spp);
     MALLOCARRAY(samplebuf, cols * spp);
     if (samplebuf == NULL)
         pm_error("can't allocate memory for row buffer");
@@ -1684,7 +1670,7 @@ convertImage(TIFF *             const tifP,
     analyzeImageType(tifP, tiffDir.bps, tiffDir.spp, tiffDir.photomet,
                      &maxval, &format, colormap, cmdline.headerdump, cmdline);
 
-    reportOutputFormat(format);
+    pm_message("writing %s file", pnm_formattypenm(format));
 
     pnmOut_init(imageoutFileP, alphaFileP, tiffDir.width, tiffDir.height,
                 tiffDir.orientation, maxval, format, maxval,
diff --git a/converter/other/winicontopam.c b/converter/other/winicontopam.c
index f6f89e11..b0dbbc07 100644
--- a/converter/other/winicontopam.c
+++ b/converter/other/winicontopam.c
@@ -86,7 +86,7 @@ parseCommandLine(int argc, const char **argv,
     opt3.short_allowed = false;
     opt3.allowNegNum   = false;
 
-    pm_optParseOptions3(&argc, (char **)argv, opt3, sizeof(opt3), 0);
+    pm_optParseOptions4(&argc, argv, opt3, sizeof(opt3), 0);
 
     if (cmdlineP->allimages && cmdlineP->imageSpec)
         pm_error("You cannot specify both -allimages and -image");
@@ -1273,7 +1273,7 @@ convertImage(struct File *         const icoP,
 
     image = readImage(icoP, dirEntryP);
 
-    if (MEMEQ(image, pngSignature, sizeof (pngSignature)))
+    if (memeq(image, pngSignature, sizeof (pngSignature)))
         convertPng(image, ofP, dirEntryP);
     else
         convertBmp(image, ofP, dirEntryP, needHeaderDump, wantAndMaskPlane);
diff --git a/converter/other/x10wd.h b/converter/other/x10wd.h
index 3c4fb8ca..e60e416a 100644
--- a/converter/other/x10wd.h
+++ b/converter/other/x10wd.h
@@ -9,19 +9,19 @@
 
 #define X10WD_FILE_VERSION 6
 typedef struct {
-    int header_size;		/* Size of the entire file header (bytes). */
-    int file_version;		/* X10WD_FILE_VERSION */
-    int display_type;		/* Display type. */
-    int display_planes;		/* Number of display planes. */
-    int pixmap_format;		/* Pixmap format. */
-    int pixmap_width;		/* Pixmap width. */
-    int pixmap_height;		/* Pixmap height. */
-    short window_width;		/* Window width. */
-    short window_height;	/* Window height. */
-    short window_x;		/* Window upper left X coordinate. */
-    short window_y;		/* Window upper left Y coordinate. */
-    short window_bdrwidth;	/* Window border width. */
-    short window_ncolors;	/* number of Color entries in this window */
+    int header_size;            /* Size of the entire file header (bytes). */
+    int file_version;           /* X10WD_FILE_VERSION */
+    int display_type;           /* Display type. */
+    int display_planes;         /* Number of display planes. */
+    int pixmap_format;          /* Pixmap format. */
+    int pixmap_width;           /* Pixmap width. */
+    int pixmap_height;          /* Pixmap height. */
+    short window_width;         /* Window width. */
+    short window_height;        /* Window height. */
+    short window_x;             /* Window upper left X coordinate. */
+    short window_y;             /* Window upper left Y coordinate. */
+    short window_bdrwidth;      /* Window border width. */
+    short window_ncolors;       /* number of Color entries in this window */
     } X10WDFileHeader;
 
 typedef struct {
diff --git a/converter/other/x11wd.h b/converter/other/x11wd.h
index 7161260b..3c1d996d 100644
--- a/converter/other/x11wd.h
+++ b/converter/other/x11wd.h
@@ -55,7 +55,7 @@ typedef struct {
            instead.  That's how Pnmtoxwd sets ncolors, and is how Xwdtopnm
            interprets it.  Xwdtopnm doesn't even look at 'colormap_entries'.
 
-           This could be an old mistake; maybe colormap_entries was 
+           This could be an old mistake; maybe colormap_entries was
            originally the number of entries in the colormap, and ncolors
            was the number of distinct colors in the image (which might be
            less than colormap_entries or, for direct color, could be much
@@ -63,7 +63,7 @@ typedef struct {
         */
     xwdval ncolors;
         /* Number of entries in the color map (for direct color, it's the
-           number of entries in each of them).  See 'colormap_entries'. 
+           number of entries in each of them).  See 'colormap_entries'.
         */
     xwdval window_width;    /* Window width */
     xwdval window_height;   /* Window height */
diff --git a/converter/other/xwdtopnm.c b/converter/other/xwdtopnm.c
index a99768b8..5f8a56c9 100644
--- a/converter/other/xwdtopnm.c
+++ b/converter/other/xwdtopnm.c
@@ -39,14 +39,14 @@
 #include "x10wd.h"
 #include "x11wd.h"
 
-struct compMask {
+struct CompMask {
     unsigned long red;
     unsigned long grn;
     unsigned long blu;
 };
 
 
-struct cmdlineInfo {
+struct CmdlineInfo {
     /* All the information the user supplied in the command line,
        in a form easy for the program to use.
     */
@@ -62,41 +62,40 @@ static bool debug;
 static bool verbose;
 
 #ifdef DEBUG_PIXEL
-static unsigned int pixel_count = 0;
+static unsigned int pixelCount = 0;
 #endif
 
 /* Byte-swapping junk. */
 
 static int
-zero_bits(const unsigned long mask) {
+zeroBits(unsigned long const mask) {
 /*----------------------------------------------------------------------------
    Return the number of consecutive zero bits at the least significant end
    of the binary representation of 'mask'.  E.g. if mask == 0x00fff800,
    we would return 11.
 -----------------------------------------------------------------------------*/
-    int i;
-    unsigned long shifted_mask;
+    unsigned int i;
+    unsigned long shiftedMask;
+
+    for (i = 0, shiftedMask = mask;
+         i < sizeof(mask)*8 && (shiftedMask & 0x00000001) == 0;
+         ++i, shiftedMask >>= 1 );
 
-    for (i=0, shifted_mask = mask;
-         i < sizeof(mask)*8 && (shifted_mask & 0x00000001) == 0;
-         i++, shifted_mask >>= 1 );
-    return(i);
+    return i;
 }
 
 
 
 static void
-parseCommandLine(int argc, char ** argv,
-                 struct cmdlineInfo * const cmdlineP) {
+parseCommandLine(int argc, const char ** argv,
+                 struct CmdlineInfo * const cmdlineP) {
 /*----------------------------------------------------------------------------
    Note that many of the strings that this function returns in the
    *cmdline_p structure are actually in the supplied argv array.  And
    sometimes, one of these strings is actually just a suffix of an entry
    in argv!
 -----------------------------------------------------------------------------*/
-    optEntry * option_def;
-        /* Instructions to OptParseOptions3 on how to parse our options.
-         */
+    optEntry * option_def;   /* Used by OPTENT3 */
     optStruct3 opt;
 
     unsigned int option_def_index;
@@ -114,7 +113,7 @@ parseCommandLine(int argc, char ** argv,
     opt.short_allowed = FALSE;  /* We have no short (old-fashioned) options */
     opt.allowNegNum = FALSE;  /* We may have parms that are negative numbers */
 
-    pm_optParseOptions3(&argc, argv, opt, sizeof(opt), 0);
+    pm_optParseOptions4(&argc, argv, opt, sizeof(opt), 0);
         /* Uses and sets argc, argv, and some of *cmdlineP and others. */
 
     if (argc - 1 == 0)
@@ -125,7 +124,7 @@ parseCommandLine(int argc, char ** argv,
         else
             cmdlineP->inputFilename = strdup(argv[1]);
     } else
-        pm_error("Too many arguments.  The only argument accepted\n"
+        pm_error("Too many arguments.  The only argument accepted "
                  "is the input file specification");
 }
 
@@ -141,19 +140,24 @@ processX10Header(X10WDFileHeader *  const h10P,
                  enum visualclass * const visualclassP,
                  int *              const formatP,
                  xel **             const colorsP,
-                 int *              const bits_per_pixelP,
-                 int *              const bits_per_itemP,
-                 struct compMask *  const compMaskP,
-                 enum byteorder *   const byte_orderP,
-                 enum byteorder *   const bit_orderP) {
-
-    int i;
-    X10Color* x10colors;
+                 int *              const bitsPerPixelP,
+                 int *              const bitsPerItemP,
+                 struct CompMask *  const compMaskP,
+                 enum byteorder *   const byteOrderP,
+                 enum byteorder *   const bitOrderP) {
+/*----------------------------------------------------------------------------
+  *h10P is a mapping of the raw bytes of the header.  Interpret and validate
+  it and return the information as *colsP, etc.
+
+  As a side effect, destroy *h10P.
+-----------------------------------------------------------------------------*/
+    unsigned int i;
+    X10Color * x10colors;
     bool grayscale;
-    bool byte_swap;
+    bool bytesSwapped;
 
     if (h10P->file_version != X10WD_FILE_VERSION) {
-        byte_swap = TRUE;
+        bytesSwapped = true;
         h10P->header_size     = pm_bs_long(h10P->header_size);
         h10P->file_version    = pm_bs_long(h10P->file_version);
         h10P->display_type    = pm_bs_long(h10P->display_type);
@@ -168,7 +172,7 @@ processX10Header(X10WDFileHeader *  const h10P,
         h10P->window_bdrwidth = pm_bs_short(h10P->window_bdrwidth);
         h10P->window_ncolors  = pm_bs_short(h10P->window_ncolors);
     } else
-        byte_swap = FALSE;
+        bytesSwapped = false;
 
     for (i = 0; i < h10P->header_size - sizeof(*h10P); ++i)
         if (getc(file) == EOF)
@@ -192,7 +196,7 @@ processX10Header(X10WDFileHeader *  const h10P,
             bytesRead = fread(&x10colors[i], sizeof(X10Color), 1, file);
             if (bytesRead != 1)
                 pm_error("couldn't read X10 XWD colormap");
-            if (byte_swap) {
+            if (bytesSwapped) {
                 x10colors[i].red   = pm_bs_short(x10colors[i].red);
                 x10colors[i].green = pm_bs_short(x10colors[i].green);
                 x10colors[i].blue  = pm_bs_short(x10colors[i].blue);
@@ -203,6 +207,14 @@ processX10Header(X10WDFileHeader *  const h10P,
         }
     }
 
+    if (h10P->pixmap_width < 0)
+        pm_error("XWD header says pixmap_width is negative: %d",
+                 h10P->pixmap_width);
+    if (h10P->pixmap_width > UINT_MAX/8 - 15)
+        pm_error("XWD header says pixmap_width is %d, "
+                 "which is too large for this program to compute",
+                 h10P->pixmap_width);
+
     if (h10P->display_planes == 1) {
         *formatP = PBM_TYPE;
         *visualclassP = StaticGray;
@@ -212,8 +224,8 @@ processX10Header(X10WDFileHeader *  const h10P,
         PNM_ASSIGN1((*colorsP)[1], *maxvalP);
         *padrightP =
             (((h10P->pixmap_width + 15) / 16) * 16 - h10P->pixmap_width) * 8;
-        *bits_per_itemP = 16;
-        *bits_per_pixelP = 1;
+        *bitsPerItemP = 16;
+        *bitsPerPixelP = 1;
     } else if (h10P->window_ncolors == 0) {
         /* Must be grayscale. */
         unsigned int i;
@@ -233,8 +245,8 @@ processX10Header(X10WDFileHeader *  const h10P,
             PNM_ASSIGN1((*colorsP)[i], i);
         *padrightP =
             (((h10P->pixmap_width + 15) / 16) * 16 - h10P->pixmap_width) * 8;
-        *bits_per_itemP = 16;
-        *bits_per_pixelP = 1;
+        *bitsPerItemP = 16;
+        *bitsPerPixelP = 1;
     } else {
         *maxvalP = 65535;
 
@@ -255,20 +267,20 @@ processX10Header(X10WDFileHeader *  const h10P,
         }
 
         *padrightP = (h10P->pixmap_width & 1) * 8;
-        *bits_per_itemP = 8;
-        *bits_per_pixelP = 8;
+        *bitsPerItemP  = 8;
+        *bitsPerPixelP = 8;
     }
     *colsP = h10P->pixmap_width;
     *rowsP = h10P->pixmap_height;
-    *byte_orderP = MSBFirst;
-    *bit_orderP = LSBFirst;
+    *byteOrderP = MSBFirst;
+    *bitOrderP  = LSBFirst;
 }
 
 
 
 static void
-fixH11ByteOrder(X11WDFileHeader *  const h11P,
-                X11WDFileHeader ** const h11FixedPP) {
+fixH11ByteOrder(const X11WDFileHeader * const h11P,
+                X11WDFileHeader **      const h11FixedPP) {
 
     X11WDFileHeader * h11FixedP;
 
@@ -325,7 +337,7 @@ static void
 readX11Colormap(FILE *       const file,
                 unsigned int const nColors,
                 bool         const byteSwap,
-                bool         const cmapDump,
+                bool         const mustDumpCmap,
                 X11XColor**  const x11colorsP) {
 
     X11XColor * x11colors;
@@ -346,7 +358,7 @@ readX11Colormap(FILE *       const file,
             x11colors[i].blue  = pm_bs_short(x11colors[i].blue);
         }
     }
-    if (cmapDump)
+    if (mustDumpCmap)
         dumpX11Cmap(nColors, x11colors);
 
     *x11colorsP = x11colors;
@@ -467,7 +479,7 @@ reverseBits(unsigned long arg,
 
 static void
 computeComponentMasks(X11WDFileHeader * const h11P,
-                      struct compMask * const compMaskP) {
+                      struct CompMask * const compMaskP) {
 /*----------------------------------------------------------------------------
    You'd think the component (red, green, blue) masks in the header
    would just be right.  But we've seen a direct color image which has
@@ -490,6 +502,7 @@ computeComponentMasks(X11WDFileHeader * const h11P,
 }
 
 
+
 /* About TrueColor maxval:
 
    The X11 spec says that in TrueColor, you use the bits in the raster for a
@@ -517,31 +530,34 @@ computeComponentMasks(X11WDFileHeader * const h11P,
 
 
 static void
-processX11Header(X11WDFileHeader *  const h11P,
-                 FILE *             const fileP,
-                 bool               const cmapDump,
-                 int *              const colsP,
-                 int *              const rowsP,
-                 unsigned int *     const padrightP,
-                 xelval *           const maxvalP,
-                 enum visualclass * const visualclassP,
-                 int *              const formatP,
-                 xel **             const colorsP,
-                 int *              const bits_per_pixelP,
-                 int *              const bits_per_itemP,
-                 struct compMask *  const compMaskP,
-                 enum byteorder *   const byte_orderP,
-                 enum byteorder *   const bit_orderP) {
-
-    int i;
-    X11XColor* x11colors;
+processX11Header(const X11WDFileHeader *  const h11P,
+                 FILE *                   const fileP,
+                 bool                     const mustDumpCmap,
+                 int *                    const colsP,
+                 int *                    const rowsP,
+                 unsigned int *           const padrightP,
+                 xelval *                 const maxvalP,
+                 enum visualclass *       const visualclassP,
+                 int *                    const formatP,
+                 xel **                   const colorsP,
+                 int *                    const bitsPerPixelP,
+                 int *                    const bitsPerItemP,
+                 struct CompMask *        const compMaskP,
+                 enum byteorder *         const byteOrderP,
+                 enum byteorder *         const bitOrderP) {
+/*----------------------------------------------------------------------------
+  *h11P is a mapping of the raw bytes of the header.  Interpret and validate
+   it and return the information as *colsP, etc.
+-----------------------------------------------------------------------------*/
+    unsigned int i;
+    X11XColor * x11colors;
     bool grayscale;
-    bool const byte_swap = (h11P->file_version != X11WD_FILE_VERSION);
+    bool const bytesSwapped = (h11P->file_version != X11WD_FILE_VERSION);
     X11WDFileHeader * h11FixedP;
 
     fixH11ByteOrder(h11P, &h11FixedP);
 
-    if (byte_swap && verbose)
+    if (bytesSwapped && verbose)
         pm_message("Header is different endianness from this machine.");
 
     for (i = 0; i < h11FixedP->header_size - sizeof(*h11FixedP); ++i)
@@ -549,10 +565,10 @@ processX11Header(X11WDFileHeader *  const h11P,
             pm_error("couldn't read rest of X11 XWD file header");
 
     /* Check whether we can handle this dump. */
-    if (h11FixedP->pixmap_depth > 24)
-        pm_error( "can't handle X11 pixmap_depth > 24");
-    if (h11FixedP->bits_per_rgb > 24)
-        pm_error("can't handle X11 bits_per_rgb > 24");
+    if (h11FixedP->pixmap_depth > 32)
+        pm_error( "can't handle X11 pixmap_depth > 32");
+    if (h11FixedP->bits_per_rgb > 32)
+        pm_error("can't handle X11 bits_per_rgb > 32");
     if (h11FixedP->pixmap_format != ZPixmap && h11FixedP->pixmap_depth != 1)
         pm_error("can't handle X11 pixmap_format %d with depth != 1",
                  h11FixedP->pixmap_format);
@@ -567,11 +583,11 @@ processX11Header(X11WDFileHeader *  const h11P,
                  h11FixedP->bitmap_unit);
 
     if (h11FixedP->ncolors > 0) {
-        readX11Colormap(fileP, h11FixedP->ncolors, byte_swap, cmapDump,
+        readX11Colormap(fileP, h11FixedP->ncolors, bytesSwapped, mustDumpCmap,
                         &x11colors);
         grayscale = colormapAllGray(x11colors, h11FixedP->ncolors);
     } else
-        grayscale = TRUE;
+        grayscale = true;
 
     *visualclassP = (enum visualclass) h11FixedP->visual_class;
     if (*visualclassP == DirectColor) {
@@ -593,11 +609,14 @@ processX11Header(X11WDFileHeader *  const h11P,
         *formatP = PPM_TYPE;
 
         /* See discussion above about this maxval */
+        if (h11FixedP->bits_per_rgb > 16)
+            pm_error("Invalid bits_per_rgb for TrueColor image: %u. "
+                     "Maximum possible is 16", h11FixedP->bits_per_rgb);
         *maxvalP = pm_bitstomaxval(h11FixedP->bits_per_rgb);
     } else if (*visualclassP == StaticGray && h11FixedP->bits_per_pixel == 1) {
         *formatP = PBM_TYPE;
         *maxvalP = 1;
-        *colorsP = pnm_allocrow( 2 );
+        *colorsP = pnm_allocrow(2);
         PNM_ASSIGN1((*colorsP)[0], *maxvalP);
         PNM_ASSIGN1((*colorsP)[1], 0);
     } else if (*visualclassP == StaticGray) {
@@ -633,8 +652,25 @@ processX11Header(X11WDFileHeader *  const h11P,
         *maxvalP = 65535;
     }
 
+    if (h11FixedP->pixmap_width < 1)
+        pm_error("XWD header states zero width");
+
     *colsP = h11FixedP->pixmap_width;
+
+    if (h11FixedP->pixmap_height < 1)
+        pm_error("XWD header states zero height");
+
     *rowsP = h11FixedP->pixmap_height;
+
+    if (h11FixedP->bytes_per_line > UINT_MAX/8)
+        pm_error("XWD header says bytes per line is %u, "
+                 "which is too large for this program to compute",
+                 h11FixedP->bytes_per_line);
+    if (h11FixedP->pixmap_width > UINT_MAX/h11FixedP->bits_per_pixel)
+        pm_error("XWD header says there are %u pixels per row and "
+                 "%u bits per pixel, which is too many for this program "
+                 "to compute",
+                 h11FixedP->pixmap_width, h11FixedP->bits_per_pixel);
     *padrightP =
         h11FixedP->bytes_per_line * 8 -
         h11FixedP->pixmap_width * h11FixedP->bits_per_pixel;
@@ -671,18 +707,18 @@ processX11Header(X11WDFileHeader *  const h11P,
        We still don't see any logic in these fields at all, but we
        figure whichever one is greater (assuming both are meaningful)
        has to be the item size.  */
-    *bits_per_itemP  = MAX(h11FixedP->bitmap_pad, h11FixedP->bitmap_unit);
-    *bits_per_pixelP = h11FixedP->bits_per_pixel;
+    *bitsPerItemP  = MAX(h11FixedP->bitmap_pad, h11FixedP->bitmap_unit);
+    *bitsPerPixelP = h11FixedP->bits_per_pixel;
 
     if (*visualclassP == DirectColor) {
         /* Strange, but we've seen a Direct Color 24/32 image that
            says LSBFirst and it's a lie.  And Xwud renders it correctly.
         */
-        *byte_orderP = MSBFirst;
-        *bit_orderP = MSBFirst;
+        *byteOrderP = MSBFirst;
+        *bitOrderP  = MSBFirst;
     } else {
-        *byte_orderP = (enum byteorder) h11FixedP->byte_order;
-        *bit_orderP  = (enum byteorder) h11FixedP->bitmap_bit_order;
+        *byteOrderP = (enum byteorder) h11FixedP->byte_order;
+        *bitOrderP  = (enum byteorder) h11FixedP->bitmap_bit_order;
     }
     computeComponentMasks(h11FixedP, compMaskP);
 
@@ -692,21 +728,21 @@ processX11Header(X11WDFileHeader *  const h11P,
 
 
 static void
-getinit(FILE *             const ifP,
-        int *              const colsP,
-        int *              const rowsP,
-        unsigned int *     const padrightP,
-        xelval *           const maxvalP,
-        enum visualclass * const visualclassP,
-        int *              const formatP,
-        xel **             const colorsP,
-        int *              const bits_per_pixelP,
-        int *              const bits_per_itemP,
-        struct compMask *  const compMaskP,
-        enum byteorder *   const byte_orderP,
-        enum byteorder *   const bit_orderP,
-        bool               const headerDump,
-        bool               const cmapDump) {
+readXwdHeader(FILE *             const ifP,
+              int *              const colsP,
+              int *              const rowsP,
+              unsigned int *     const padrightP,
+              xelval *           const maxvalP,
+              enum visualclass * const visualclassP,
+              int *              const formatP,
+              xel **             const colorsP,
+              int *              const bitsPerPixelP,
+              int *              const bitsPerItemP,
+              struct CompMask *  const compMaskP,
+              enum byteorder *   const byteOrderP,
+              enum byteorder *   const bitOrderP,
+              bool               const headerDump,
+              bool               const mustDumpCmap) {
 /*----------------------------------------------------------------------------
    Read the header from the XWD image in input stream 'ifP'.  Leave
    the stream positioned to the beginning of the raster.
@@ -715,20 +751,20 @@ getinit(FILE *             const ifP,
 
    Return as *padrightP the number of additional bits of padding are
    at the end of each line of input.  This says the input stream
-   contains *colsP pixels of image data (at *bits_per_pixelP bits each)
+   contains *colsP pixels of image data (at *bitsPerPixelP bits each)
    plus *padrightP bits of padding.
 -----------------------------------------------------------------------------*/
     /* Assume X11 headers are larger than X10 ones. */
     unsigned char header[sizeof(X11WDFileHeader)];
-    X10WDFileHeader* h10P;
-    X11WDFileHeader* h11P;
+    X10WDFileHeader * h10P;
+    X11WDFileHeader * h11P;
     int rc;
 
     h10P = (X10WDFileHeader*) header;
     h11P = (X11WDFileHeader*) header;
     if ( sizeof(*h10P) > sizeof(*h11P) )
         pm_error("ARGH!  On this machine, X10 headers are larger than "
-                 "X11 headers!\n    You will have to re-write xwdtopnm." );
+                 "X11 headers!  You will have to re-write xwdtopnm." );
 
     /* We read an X10 header's worth of data from the file, then look
        at it to see if it looks like an X10 header.  If so we process
@@ -749,8 +785,8 @@ getinit(FILE *             const ifP,
             pm_message("Input is X10");
         processX10Header(h10P, ifP, colsP, rowsP, padrightP, maxvalP,
                          visualclassP, formatP,
-                         colorsP, bits_per_pixelP, bits_per_itemP,
-                         compMaskP, byte_orderP, bit_orderP);
+                         colorsP, bitsPerPixelP, bitsPerItemP,
+                         compMaskP, byteOrderP, bitOrderP);
     } else if (h11P->file_version == X11WD_FILE_VERSION ||
                pm_bs_long(h11P->file_version) == X11WD_FILE_VERSION) {
 
@@ -768,13 +804,14 @@ getinit(FILE *             const ifP,
         if (headerDump)
             dumpX11Header(h11P);
 
-        processX11Header(h11P, ifP, cmapDump,
+        processX11Header(h11P, ifP, mustDumpCmap,
                          colsP, rowsP, padrightP, maxvalP,
                          visualclassP, formatP,
-                         colorsP, bits_per_pixelP, bits_per_itemP,
-                         compMaskP, byte_orderP, bit_orderP);
+                         colorsP, bitsPerPixelP, bitsPerItemP,
+                         compMaskP, byteOrderP, bitOrderP);
     } else
-        pm_error("unknown XWD file version: %u", h11P->file_version);
+        pm_error("unknown XWD file version: %u.  "
+                 "Probably not an XWD file", h11P->file_version);
 }
 
 
@@ -967,7 +1004,7 @@ readItem(pixelReader * const rdrP) {
     }
         break;
     default:
-        pm_error("INTERNAL ERROR: impossible bits_per_item");
+        pm_error("INTERNAL ERROR: impossible bitsPerItem");
     }
 }
 
@@ -1066,21 +1103,21 @@ pixelReader_getpix(pixelReader * const rdrP) {
    pure binary cipher, with the first bit the most significant bit.
 
    The basic unit of storage in the input file is an "item."  An item
-   can be 1, 2, or 4 bytes, and 'bits_per_item' tells us which.  Each
+   can be 1, 2, or 4 bytes, and 'bitsPerItem' tells us which.  Each
    item can have its bytes stored in forward or reverse order, and
-   'byte_order' tells us which.  We have seen a Direct Color 24 bpp/32 bpi
-   image which said 'byte_order' == LSBFirst, but the byte order is
+   'byteOrder' tells us which.  We have seen a Direct Color 24 bpp/32 bpi
+   image which said 'byteOrder' == LSBFirst, but the byte order is
    nonetheless MSB first.
 
    Each item can contain one or more pixels, and may contain
-   fractional pixels.  'bits_per_pixel' tells us how many bits each
-   pixel has, and 'bits_per_pixel' is always less than or equal to
-   'bits_per_item', but not necessarily a factor of it.  Within an item,
+   fractional pixels.  'bitsPerPixel' tells us how many bits each
+   pixel has, and 'bitsPerPixel' is always less than or equal to
+   'bitsPerItem', but not necessarily a factor of it.  Within an item,
    after taking care of the endianness of its storage format, the pixels
-   may be arranged from left to right or right to left.  'bit_order' tells
+   may be arranged from left to right or right to left.  'bitOrder' tells
    us which.  We have also seen images in which the pixels are arranged
    from left to right within the items, but the RGB components within
-   each pixel are right to left and 'bit_order' is LSBFirst.
+   each pixel are right to left and 'bitOrder' is LSBFirst.
 
    But it's not that simple.  Sometimes dummy bits are added to the
    right edge of the image in order to make an integral number of
@@ -1109,15 +1146,15 @@ reportInfo(int              const cols,
            xelval           const maxval,
            enum visualclass const visualclass,
            int              const format,
-           int              const bits_per_pixel,
-           int              const bits_per_item,
-           struct compMask  const compMask,
-           enum byteorder   const byte_order,
-           enum byteorder   const bit_order) {
+           int              const bitsPerPixel,
+           int              const bitsPerItem,
+           struct CompMask  const compMask,
+           enum byteorder   const byteOrder,
+           enum byteorder   const bitOrder) {
 
     const char *visualclass_name;
-    const char *byte_order_name;
-    const char *bit_order_name;
+    const char *byteOrder_name;
+    const char *bitOrder_name;
     switch (visualclass) {
     case StaticGray:  visualclass_name="StaticGray";  break;
     case GrayScale:   visualclass_name="Grayscale";   break;
@@ -1127,25 +1164,25 @@ reportInfo(int              const cols,
     case DirectColor: visualclass_name="DirectColor"; break;
     default:          visualclass_name="(invalid)";    break;
     }
-    switch (byte_order) {
-    case MSBFirst: byte_order_name = "MSBFirst";  break;
-    case LSBFirst: byte_order_name = "LSBFirst";  break;
-    default:       byte_order_name = "(invalid)"; break;
+    switch (byteOrder) {
+    case MSBFirst: byteOrder_name = "MSBFirst";  break;
+    case LSBFirst: byteOrder_name = "LSBFirst";  break;
+    default:       byteOrder_name = "(invalid)"; break;
     }
-    switch (bit_order) {
-    case MSBFirst: bit_order_name = "MSBFirst";  break;
-    case LSBFirst: bit_order_name = "LSBFirst";  break;
-    default:       bit_order_name = "(invalid)"; break;
+    switch (bitOrder) {
+    case MSBFirst: bitOrder_name = "MSBFirst";  break;
+    case LSBFirst: bitOrder_name = "LSBFirst";  break;
+    default:       bitOrder_name = "(invalid)"; break;
     }
     pm_message("%d rows of %d columns with maxval %d",
                rows, cols, maxval);
     pm_message("padright=%u bits.  visualclass = %s.  format=%d (%c%c)",
                padright, visualclass_name,
                format, format/256, format%256);
-    pm_message("bits_per_pixel=%d; bits_per_item=%d",
-               bits_per_pixel, bits_per_item);
-    pm_message("byte_order=%s; bit_order=%s",
-               byte_order_name, bit_order_name);
+    pm_message("bitsPerPixel=%d; bitsPerItem=%d",
+               bitsPerPixel, bitsPerItem);
+    pm_message("byteOrder=%s; bitOrder=%s",
+               byteOrder_name, bitOrder_name);
     pm_message("component mask: red=0x%.8lx; grn=0x%.8lx; blu=0x%.8lx",
                compMask.red, compMask.grn, compMask.blu);
 }
@@ -1191,7 +1228,7 @@ static void
 convertRowDirect(pixelReader *   const pixelReaderP,
                  int             const cols,
                  const xel *     const colors,
-                 struct compMask const compMask,
+                 struct CompMask const compMask,
                  xel *           const xelrow) {
 
     unsigned int col;
@@ -1201,20 +1238,20 @@ convertRowDirect(pixelReader *   const pixelReaderP,
             /* This is a triplet of indices into the color map, packed
                into this bit string according to compMask
             */
-        unsigned int red_index, grn_index, blu_index;
+        unsigned int redIndex, grnIndex, bluIndex;
             /* These are indices into the color map, unpacked from 'pixel'.
              */
 
         pixel = pixelReader_getpix(pixelReaderP);
 
-        red_index = (pixel & compMask.red) >> zero_bits(compMask.red);
-        grn_index = (pixel & compMask.grn) >> zero_bits(compMask.grn);
-        blu_index = (pixel & compMask.blu) >> zero_bits(compMask.blu);
+        redIndex = (pixel & compMask.red) >> zeroBits(compMask.red);
+        grnIndex = (pixel & compMask.grn) >> zeroBits(compMask.grn);
+        bluIndex = (pixel & compMask.blu) >> zeroBits(compMask.blu);
 
         PPM_ASSIGN(xelrow[col],
-                   PPM_GETR(colors[red_index]),
-                   PPM_GETG(colors[grn_index]),
-                   PPM_GETB(colors[blu_index])
+                   PPM_GETR(colors[redIndex]),
+                   PPM_GETG(colors[grnIndex]),
+                   PPM_GETB(colors[bluIndex])
             );
     }
 }
@@ -1226,16 +1263,16 @@ convertRowTrueColor(pixelReader *   const pixelReaderP,
                     int             const cols,
                     pixval          const maxval,
                     const xel *     const colors,
-                    struct compMask const compMask,
+                    struct CompMask const compMask,
                     xel *           const xelrow) {
 
     unsigned int col;
     unsigned int red_shift, grn_shift, blu_shift;
     unsigned int red_maxval, grn_maxval, blu_maxval;
 
-    red_shift = zero_bits(compMask.red);
-    grn_shift = zero_bits(compMask.grn);
-    blu_shift = zero_bits(compMask.blu);
+    red_shift = zeroBits(compMask.red);
+    grn_shift = zeroBits(compMask.grn);
+    blu_shift = zeroBits(compMask.blu);
 
     red_maxval = compMask.red >> red_shift;
     grn_maxval = compMask.grn >> grn_shift;
@@ -1267,7 +1304,7 @@ convertRow(pixelReader *    const pixelReaderP,
            int              const cols,
            xelval           const maxval,
            int              const format,
-           struct compMask  const compMask,
+           struct CompMask  const compMask,
            const xel*       const colors,
            enum visualclass const visualclass) {
 /*----------------------------------------------------------------------------
@@ -1334,9 +1371,9 @@ reportOutputType(int const format) {
 
 
 int
-main(int argc, char *argv[]) {
+main(int argc, const char ** argv) {
 
-    struct cmdlineInfo cmdline;
+    struct CmdlineInfo cmdline;
     FILE * ifP;
     int rows, cols, format;
     unsigned int padright;
@@ -1344,14 +1381,14 @@ main(int argc, char *argv[]) {
     unsigned int row;
     int bitsPerPixel;
     int bitsPerItem;
-    struct compMask compMask;
+    struct CompMask compMask;
     xelval maxval;
     enum visualclass visualclass;
     enum byteorder byteOrder, bitOrder;
     xel * colors;  /* the color map */
     pixelReader pixelReader;
 
-    pnm_init(&argc, argv);
+    pm_proginit(&argc, argv);
 
     parseCommandLine(argc, argv, &cmdline);
 
@@ -1363,10 +1400,10 @@ main(int argc, char *argv[]) {
     else
         ifP = stdin;
 
-    getinit(ifP, &cols, &rows, &padright, &maxval, &visualclass, &format,
-            &colors, &bitsPerPixel, &bitsPerItem,
-            &compMask, &byteOrder, &bitOrder,
-            cmdline.headerdump, cmdline.cmapdump);
+    readXwdHeader(ifP, &cols, &rows, &padright, &maxval, &visualclass, &format,
+                  &colors, &bitsPerPixel, &bitsPerItem,
+                  &compMask, &byteOrder, &bitOrder,
+                  cmdline.headerdump, cmdline.cmapdump);
 
     warn16Bit(maxval);
 
@@ -1410,7 +1447,7 @@ main(int argc, char *argv[]) {
    doesn't match these hard-coded shift amounts, so we have replaced
    this whole switch thing.  -Bryan 00.03.01
 
-   switch (bits_per_pixel) {
+   switch (bitsPerPixel) {
 
    case 16:
        PPM_ASSIGN( *xP,
diff --git a/converter/other/yuy2topam.c b/converter/other/yuy2topam.c
index 40ab98b3..8416d393 100644
--- a/converter/other/yuy2topam.c
+++ b/converter/other/yuy2topam.c
@@ -31,12 +31,12 @@ struct CmdlineInfo {
 
 
 
-static void 
-parseCommandLine(int argc, const char ** argv, 
+static void
+parseCommandLine(int argc, const char ** argv,
                  struct CmdlineInfo * const cmdlineP) {
 /* --------------------------------------------------------------------------
    Parse program command line described in Unix standard form by argc
-   and argv.  Return the information in the options as *cmdlineP.  
+   and argv.  Return the information in the options as *cmdlineP
 
    If command line is internally inconsistent (invalid options, etc.),
    issue error message to stderr and abort program.
@@ -44,8 +44,7 @@ parseCommandLine(int argc, const char ** argv,
    Note that the strings we return are stored in the storage that
    was passed to us as the argv array.  We also trash *argv.
 --------------------------------------------------------------------------*/
-    optEntry * option_def;
-        /* Instructions to pm_optParseOptions3 on how to parse our options. */
+    optEntry * option_def; /* Used by OPTENT3 */
     optStruct3 opt;
 
     unsigned int widthSpec, heightSpec;
@@ -63,7 +62,7 @@ parseCommandLine(int argc, const char ** argv,
     opt.short_allowed = false;  /* We have no short (old-fashioned) options */
     opt.allowNegNum = false;   /* We have no parms that are negative numbers */
 
-    pm_optParseOptions3(&argc, (char **)argv, opt, sizeof(opt), 0);
+    pm_optParseOptions4(&argc, argv, opt, sizeof(opt), 0);
         /* Uses and sets argc, argv, and some of *cmdlineP and others. */
 
     if (!widthSpec)
@@ -84,7 +83,7 @@ parseCommandLine(int argc, const char ** argv,
         cmdlineP->inputFileName = "-";
     else {
         cmdlineP->inputFileName = argv[1];
-        
+
         if (argc-1 > 1)
             pm_error("Too many arguments (%u).  The only non-option argument "
                      "is the input file name.", argc-1);
@@ -264,3 +263,6 @@ main(int argc, const char *argv[]) {
 
     return 0;
 }
+
+
+
diff --git a/converter/other/zeisstopnm.c b/converter/other/zeisstopnm.c
index e94d9b44..5f1e97ec 100644
--- a/converter/other/zeisstopnm.c
+++ b/converter/other/zeisstopnm.c
@@ -75,34 +75,34 @@ main( argc, argv )
     argn = 1;
 
     while ( argn < argc && argv[argn][0] == '-' && argv[argn][1] != '\0' )
-	{
-	if ( pm_keymatch( argv[argn], "-pgm", 3 ) )
-	    {
-	    if ( argn >= argc )
-		pm_usage( usage );
-	    format = PGM_TYPE;
-	    }
-	else if ( pm_keymatch( argv[argn], "-ppm", 3 ) )
-	    {
-	    if ( argn >= argc )
-		pm_usage( usage );
-	    format = PPM_TYPE;
-	    }
-	else
-	    pm_usage( usage );
-	++argn;
-	}
+        {
+        if ( pm_keymatch( argv[argn], "-pgm", 3 ) )
+            {
+            if ( argn >= argc )
+                pm_usage( usage );
+            format = PGM_TYPE;
+            }
+        else if ( pm_keymatch( argv[argn], "-ppm", 3 ) )
+            {
+            if ( argn >= argc )
+                pm_usage( usage );
+            format = PPM_TYPE;
+            }
+        else
+            pm_usage( usage );
+        ++argn;
+        }
 
     if ( argn < argc )
-	{
-	ifp = pm_openr( argv[argn] );
-	++argn;
-	}
+        {
+        ifp = pm_openr( argv[argn] );
+        ++argn;
+        }
     else
-	ifp = stdin;
+        ifp = stdin;
 
     if ( argn != argc )
-	pm_usage( usage );
+        pm_usage( usage );
 
     /* Read the image to a buffer */
 
@@ -111,35 +111,35 @@ main( argc, argv )
     /* Check the format of the file */
 
     if (nread <=1024)
-	pm_error( "Input file not in Zeiss format (too small)" );
+        pm_error( "Input file not in Zeiss format (too small)" );
 
     lutg = (unsigned char *)buf+(nread-1024+512);
     lutr = (unsigned char *)buf+(nread-1024+256);
     lutb = (unsigned char *)buf+(nread-1024);
 
     cols = ((unsigned char) buf[nread-1024+768+8]) +
-	(((unsigned char) buf[nread-1024+768+9]) << 8);
+        (((unsigned char) buf[nread-1024+768+9]) << 8);
     rows = ((unsigned char) buf[nread-1024+768+10]) +
-	(((unsigned char) buf[nread-1024+768+11]) << 8);
+        (((unsigned char) buf[nread-1024+768+11]) << 8);
 
     if ( cols <= 0 )
-	pm_error( "invalid cols: %d", cols );
+        pm_error( "invalid cols: %d", cols );
     if ( rows <= 0 )
-	pm_error( "invalid rows: %d", rows );
+        pm_error( "invalid rows: %d", rows );
 
     if (cols*rows != nread-1024)
-	pm_error( "Hmm, %d rows, %d cols, %ld total image size",
-		 rows, cols, nread-1024);
+        pm_error( "Hmm, %d rows, %d cols, %ld total image size",
+                 rows, cols, nread-1024);
 
     /* Choose pgm or ppm */
     /* If the LUTs all contain 0,1,2,3,4..255, it is a pgm file */
 
     for (i=0; i<256 && format==0; i++)
-	if (lutr[i] != i || lutg[i] != i || lutb[i] != i)
-	    format = PPM_TYPE;
+        if (lutr[i] != i || lutg[i] != i || lutb[i] != i)
+            format = PPM_TYPE;
 
     if (format == 0)
-	format = PGM_TYPE;
+        format = PGM_TYPE;
 
     pnm_writepnminit( stdout, cols, rows, 255, format, 0 );
     xelrow = pnm_allocrow( cols );
@@ -161,23 +161,23 @@ main( argc, argv )
 
     for ( row = 0; row < rows; ++row )
     {
-	switch ( PNM_FORMAT_TYPE(format) )
-	{
-	case PGM_TYPE:
-	    for ( col = 0, xP = xelrow; col < cols; ++col, ++xP, ++byteP )
-		PNM_ASSIGN1( *xP, *byteP );
-	    break;
-
-	case PPM_TYPE:
-	    for ( col = 0, xP = xelrow; col < cols; ++col, ++xP, ++byteP )
-		PPM_ASSIGN( *xP, lutr[*byteP], lutg[*byteP], lutb[*byteP] );
-	    break;
+        switch ( PNM_FORMAT_TYPE(format) )
+        {
+        case PGM_TYPE:
+            for ( col = 0, xP = xelrow; col < cols; ++col, ++xP, ++byteP )
+                PNM_ASSIGN1( *xP, *byteP );
+            break;
+
+        case PPM_TYPE:
+            for ( col = 0, xP = xelrow; col < cols; ++col, ++xP, ++byteP )
+                PPM_ASSIGN( *xP, lutr[*byteP], lutg[*byteP], lutb[*byteP] );
+            break;
 
         default:
-	    pm_error( "shouldn't happen" );
+            pm_error( "shouldn't happen" );
         }
 
-	pnm_writepnmrow( stdout, xelrow, cols, 255, format, 0 );
+        pnm_writepnmrow( stdout, xelrow, cols, 255, format, 0 );
     }
 
     free( buf );
@@ -185,3 +185,6 @@ main( argc, argv )
 
     exit( 0 );
 }
+
+
+
diff --git a/converter/pbm/atktopbm.c b/converter/pbm/atktopbm.c
index 807e4f4a..eb3c071a 100644
--- a/converter/pbm/atktopbm.c
+++ b/converter/pbm/atktopbm.c
@@ -44,7 +44,7 @@
 #define dataobject_OBJECTCREATIONFAILED 4
 #define dataobject_BADFORMAT 5
 
-/* ReadRow(file, row, length) 
+/* ReadRow(file, row, length)
 ** Reads from 'file' the encoding of bytes to fill in 'row'.  Row will be
 ** truncated or padded (with WHITE) to exactly 'length' bytes.
 **
@@ -52,7 +52,7 @@
 **      '|'     correct end of line
 **      '\0'    if the length was satisfied (before a terminator)
 **      EOF     if the file ended
-**      '\'  '{'    other recognized ends. 
+**      '\'  '{'    other recognized ends.
 ** The '|' is the expected end and pads the row with WHITE.
 ** The '\' and '{' are error conditions and may indicate the
 ** beginning of some other portion of the data stream.
@@ -76,11 +76,11 @@ ReadRow(FILE *          const file,
   'file' is where to get them from.
   'row' is where to put bytes.
   'length' is how many bytes in row must be filled.
-  
+
   Return the delimiter that marks the end of the row, or EOF if EOF marks
   the end of the row, or NUL in some cases.
 -----------------------------------------------------------------------------*/
-    /* Each input character is processed by the central loop.  There are 
+    /* Each input character is processed by the central loop.  There are
     ** some input codes which require two or three characters for
     ** completion; these are handled by advancing the state machine.
     ** Errors are not processed; instead the state machine is reset
@@ -98,7 +98,7 @@ ReadRow(FILE *          const file,
         RepeatAndDigit
             /* have seen repeat code and its first following digit */
     };
-    
+
     enum StateCode InputState;  /* current state */
     int c;     /* the current input character */
     long repeatcount;  /* current repeat value */
@@ -106,8 +106,8 @@ ReadRow(FILE *          const file,
     long pendinghex;    /* the first of a pair of hex characters */
     int lengthRemaining;
     unsigned char * cursor;
-    
-    /* We cannot exit when length becomes zero because we need to check 
+
+    /* We cannot exit when length becomes zero because we need to check
     ** to see if a row ending character follows.  Thus length is checked
     ** only when we get a data generating byte.  If length then is
     ** zero, we ungetc the byte.
@@ -148,7 +148,7 @@ ReadRow(FILE *          const file,
             while (lengthRemaining-- > 0)
                 *cursor++ = WHITEBYTE;
             return c;
-    
+
         CASE1(0x21):
         CASE6(0x22):
         CASE8(0x28):
@@ -227,9 +227,9 @@ ReadRow(FILE *          const file,
             break;
 
         store:
-            /* generate byte(s) into the output row 
+            /* generate byte(s) into the output row
                Use repeatcount, depending on state.  */
-            if (lengthRemaining < repeatcount) 
+            if (lengthRemaining < repeatcount)
                 /* reduce repeat count if it would exceed
                    available space */
                 repeatcount = lengthRemaining;
@@ -269,7 +269,7 @@ ReadATKRaster(FILE * const ifP) {
         pm_error ("input file not Andrew raster object");
 
     fscanf(ifP, " %d ", &version);
-    if (version < 2) 
+    if (version < 2)
         pm_error ("version too old to parse");
 
     {
@@ -277,8 +277,8 @@ ReadATKRaster(FILE * const ifP) {
         long xscale, yscale;
         long xoffset, yoffset, subwidth, subheight;
         /* ignore all these features: */
-        fscanf(ifP, " %u %ld %ld %ld %ld %ld %ld",  
-               &options, &xscale, &yscale, &xoffset, 
+        fscanf(ifP, " %u %ld %ld %ld %ld %ld %ld",
+               &options, &xscale, &yscale, &xoffset,
                &yoffset, &subwidth, &subheight);
     }
     /* scan to end of line in case this is actually something beyond V2 */
@@ -291,8 +291,12 @@ ReadATKRaster(FILE * const ifP) {
 
     fscanf(ifP, " %d %d %d ", &objectid, &width, &height);
 
-    if (width < 1 || height < 1 || width > 1000000 || height > 1000000) 
+    if (width < 1 || height < 1 || width > 1000000 || height > 1000000)
         pm_error("bad width or height");
+        /* Note: Whether these values are upper limits set by the author of
+           the original version of this program, or come from the official
+           file format specification is unknown.
+        */
 
     pbm_writepbminit(stdout, width, height, 0);
     bitrow = pbm_allocrow_packed(width);
@@ -302,7 +306,7 @@ ReadATKRaster(FILE * const ifP) {
         long const nextChar = ReadRow(ifP, bitrow, rowlen);
 
         switch (nextChar) {
-        case '|': 
+        case '|':
             pbm_writepbmrow_packed(stdout, bitrow, width, 0);
             break;
         case EOF:
@@ -349,3 +353,6 @@ main(int argc, const char ** argv) {
 
     return 0;
 }
+
+
+
diff --git a/converter/pbm/brushtopbm.c b/converter/pbm/brushtopbm.c
index ebd817be..63cd0d04 100644
--- a/converter/pbm/brushtopbm.c
+++ b/converter/pbm/brushtopbm.c
@@ -26,7 +26,7 @@ getinit(FILE *         const ifP,
 
     bytesRead = fread(header, sizeof(header), 1, ifP);
     if (bytesRead !=1)
-        pm_error("Error reading header");   
+        pm_error("Error reading header");
 
     if (header[0] != 1)
         pm_error("bad magic number 1");
@@ -49,6 +49,7 @@ validateEof(FILE * const ifP) {
 }
 
 
+
 /*
    The routine for converting the raster closely resembles the pbm
    case of pnminvert.  Input is padded up to 16 bit border.
@@ -85,7 +86,7 @@ main(int argc, const char ** argv)  {
         unsigned int i;
         size_t bytesRead;
 
-        bytesRead = fread (bitrow, 1, inRowBytes, ifP); 
+        bytesRead = fread (bitrow, 1, inRowBytes, ifP);
         if (bytesRead != inRowBytes)
             pm_error("Error reading a row of data from brushfile");
 
@@ -102,6 +103,9 @@ main(int argc, const char ** argv)  {
 
     pm_close(ifP);
     pm_close(stdout);
-    
+
     return 0;
 }
+
+
+
diff --git a/converter/pbm/cistopbm.c b/converter/pbm/cistopbm.c
index 591e2aa5..b62f6045 100644
--- a/converter/pbm/cistopbm.c
+++ b/converter/pbm/cistopbm.c
@@ -38,6 +38,8 @@ static void syntax(const char *prog)
                  );
 }
 
+
+
 int main(int argc, const char **argv)
 {
     FILE *ifP;
@@ -176,5 +178,8 @@ int main(int argc, const char **argv)
     }
     pbm_writepbm(stdout, bits, width, height, 0);
     pm_close(ifP);
-    return 0;       
+    return 0;
 }
+
+
+
diff --git a/converter/pbm/cmuwmtopbm.c b/converter/pbm/cmuwmtopbm.c
index be8a7fc1..c2e3bde0 100644
--- a/converter/pbm/cmuwmtopbm.c
+++ b/converter/pbm/cmuwmtopbm.c
@@ -87,7 +87,7 @@ main(int           argc,
         inputFileName = argv[1];
     else
         inputFileName = "-";
-    
+
     ifP = pm_openr(inputFileName);
 
     readCmuwmHeader(ifP, &cols, &rows, &depth);
@@ -105,15 +105,15 @@ main(int           argc,
         bytesRead = fread(bitrow, 1, bytesPerRow, ifP);
         if (bytesRead != bytesPerRow)
             pm_error("CWU window manager bitmap EOF / read error");
-            
+
         /* Invert all bits in row - raster formats are similar.
            CMUWM Black:0 White:1  End of row padded with 1
            PBM   Black:1 White:0  End preferably padded with 0
         */
-   
+
         for (byteSeq = 0; byteSeq < bytesPerRow; ++byteSeq)
             bitrow[byteSeq] = ~bitrow[byteSeq];
-                
+
         pbm_writepbmrow_packed(stdout, bitrow, cols, 0);
     }
 
@@ -123,3 +123,6 @@ main(int           argc,
 
     return 0;
 }
+
+
+
diff --git a/converter/pbm/ddbugtopbm.c b/converter/pbm/ddbugtopbm.c
index 8b0a6d0e..75b39b77 100644
--- a/converter/pbm/ddbugtopbm.c
+++ b/converter/pbm/ddbugtopbm.c
@@ -13,15 +13,15 @@
  * it under the terms of the GNU General Public License as published by
  * the Free Software Foundation; either version 2 of the License, or (at
  * your option) any later version.
- * 
+ *
  * This program is distributed in the hope that it will be useful, but
  * WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * General Public License for more details.
- * 
+ *
  * You should have received a copy of the GNU General Public License
  * along with this program; if not, write to the Free Software
- * Foundation, 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.  
+ * Foundation, 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
  *
  * Adapted to Netpbm by Bryan Henderson 2003.08.09.  Bryan got his copy
  * from ftp:ibiblio.com/pub/linux/apps/graphics/convert, dated 2002.08.21.
@@ -37,7 +37,7 @@
 #include "mallocvar.h"
 
 /* this is basically UncompressSketch() from DiddleBug 2.50's diddlebug.c */
-static void 
+static void
 uncompress_sketch(unsigned char * const cPtr,
                   unsigned char * const uPtr,
                   int             const size) {
@@ -79,7 +79,7 @@ make_noname(void) {
 
     do {
         num++;
-        if (out != NULL) 
+        if (out != NULL)
             fclose(out);
         sprintf(name, "sketch-%04d.pbm", num);
     } while (num<10000 && (out = fopen(name, "rb")) != NULL);
@@ -92,7 +92,7 @@ make_noname(void) {
 
 
 
-int 
+int
 main(int argc, char ** argv) {
     FILE * const in=stdin;
 
@@ -147,7 +147,7 @@ main(int argc, char ** argv) {
         for (ptr = nameptr; *ptr; ++ptr) {
             if (!isalnum(*ptr) && strchr("()-_+=[]:;,.<>?",*ptr) == NULL)
                 *ptr='_';
-            if (isupper(*ptr)) 
+            if (isupper(*ptr))
                 *ptr = tolower(*ptr);
         }
 
@@ -161,7 +161,7 @@ main(int argc, char ** argv) {
 
         pm_message("extracting sketch %2d as `%s'", f, outfilename);
         if((out=fopen(outfilename,"wb"))==NULL)
-            pm_message("WARNING: couldn't open file '%s'.  Carrying on...", 
+            pm_message("WARNING: couldn't open file '%s'.  Carrying on...",
                        outfilename);
         else {
             pbm_writepbminit(out, 160, 160, FALSE);
@@ -171,3 +171,6 @@ main(int argc, char ** argv) {
     }
     return 0;
 }
+
+
+
diff --git a/converter/pbm/escp2topbm.c b/converter/pbm/escp2topbm.c
index 632e6345..de3ea931 100644
--- a/converter/pbm/escp2topbm.c
+++ b/converter/pbm/escp2topbm.c
@@ -47,10 +47,17 @@
 
 
 #include <stdbool.h>
+#include <assert.h>
 
 #include "mallocvar.h"
 #include "pbm.h"
 
+static unsigned int widthMax = 127 * 256 + 255;
+    /* Limit in official Epson manual */
+
+static unsigned int const heightMax = 5120 * 200;
+    /* 5120 rows is sufficient for US legal at 360 DPI */
+
 #define ESC 033
 
 
@@ -97,7 +104,7 @@ readChar(FILE * const ifP) {
 
 
 
-static void       
+static void
 readStripeHeader(unsigned int * const widthThisStripeP,
                  unsigned int * const rowsThisStripeP,
                  unsigned int * const compressionP,
@@ -113,13 +120,17 @@ readStripeHeader(unsigned int * const widthThisStripeP,
     compression     = stripeHeader[0];
     /* verticalResolution   = stripeHeader[1]; */
     /* horizontalResolution = stripeHeader[2]; */
-    rowsThisStripe  = stripeHeader[3];  
+    rowsThisStripe  = stripeHeader[3];
     widthThisStripe = stripeHeader[5] * 256 + stripeHeader[4];
 
     if (widthThisStripe == 0 || rowsThisStripe == 0)
         pm_error("Error: Abnormal value in data block header:  "
                  "Says stripe has zero width or height");
 
+    if (widthThisStripe > widthMax)
+        pm_error("Error: Abnormal width value in data block header:  %u",
+                 widthThisStripe);
+
     if (compression != 0 && compression != 1)
         pm_error("Error: Unknown compression mode %u", compression);
 
@@ -132,7 +143,7 @@ readStripeHeader(unsigned int * const widthThisStripeP,
 
 /* RLE decoder */
 static void
-decEpsonRLE(unsigned int    const blockSize, 
+decEpsonRLE(unsigned int    const blockSize,
             unsigned char * const outBuffer,
             FILE *          const ifP) {
 
@@ -163,7 +174,7 @@ decEpsonRLE(unsigned int    const blockSize,
             unsigned int i;
 
             for (i = 0; i < runLength; ++i)
-                outBuffer[dpos + i] = repeatChar;  
+                outBuffer[dpos + i] = repeatChar;
             dpos += runLength;
         }
     }
@@ -180,7 +191,7 @@ processStripeRaster(unsigned char ** const bitarray,
                     unsigned int     const compression,
                     FILE *           const ifP,
                     unsigned int *   const rowIdxP) {
-         
+
     unsigned int const initialRowIdx = *rowIdxP;
     unsigned int const widthInBytes = pbm_packed_bytes(width);
     unsigned int const blockSize = rowsThisStripe * widthInBytes;
@@ -221,14 +232,12 @@ expandBitarray(unsigned char *** const bitarrayP,
                unsigned int   *  const bitarraySizeP) {
 
     unsigned int const heightIncrement = 5120;
-    unsigned int const heightMax = 5120 * 200;
-        /* 5120 rows is sufficient for US legal at 360 DPI */
 
     *bitarraySizeP += heightIncrement;
     if (*bitarraySizeP > heightMax)
-        pm_error("Image too tall");
+        pm_error("Error: Image too tall");
     else
-        REALLOCARRAY_NOFAIL(*bitarrayP, *bitarraySizeP); 
+        REALLOCARRAY_NOFAIL(*bitarrayP, *bitarraySizeP);
 }
 
 
@@ -244,7 +253,7 @@ writePbmImage(unsigned char ** const bitarray,
         pm_error("No image");
 
     pbm_writepbminit(stdout, width, height, 0);
- 
+
     for (row = 0; row < height; ++row) {
         pbm_cleanrowend_packed(bitarray[row], width);
         pbm_writepbmrow_packed(stdout, bitarray[row], width, 0);
@@ -300,7 +309,7 @@ main(int          argc,
                 unsigned int compression;
                 unsigned int rowsThisStripe;
                 unsigned int widthThisStripe;
-            
+
                 readStripeHeader(&widthThisStripe, &rowsThisStripe,
                                  &compression, ifP);
 
@@ -311,7 +320,7 @@ main(int          argc,
                     /* The official Epson manual says valid values are 1, 8,
                        24 but we just print a warning message and continue if
                        other values are detected.
-                    */ 
+                    */
                     pm_message("Abnormal data block height value: %u "
                                "(ignoring)",
                                rowsThisStripe);
@@ -326,6 +335,10 @@ main(int          argc,
                              width, widthThisStripe);
                 }
                 height += rowsThisStripe;
+                assert(height <= INT_MAX - 10);
+                    /* Becuse image height is tested in expandBitarray()
+                       with a more stringent condition.
+                    */
                 if (height > bitarraySize)
                     expandBitarray(&bitarray, &bitarraySize);
 
diff --git a/converter/pbm/g3topbm.c b/converter/pbm/g3topbm.c
index 5d98fcb2..80b7b37d 100644
--- a/converter/pbm/g3topbm.c
+++ b/converter/pbm/g3topbm.c
@@ -21,6 +21,8 @@
 #define _DEFAULT_SOURCE /* New name for SVID & BSD source defines */
 #define _BSD_SOURCE   /* Make nstring.h define strcaseeq() */
 
+#include <assert.h>
+
 #include "pm_c_util.h"
 #include "pbm.h"
 #include "shhopt.h"
@@ -71,10 +73,6 @@ The receiver may be less patient.  It may opt to disconnect if one row
 is not received within 5 seconds.
 */
 
-static G3TableEntry * whash[HASHSIZE];
-static G3TableEntry * bhash[HASHSIZE];
-
-
 struct CmdlineInfo {
     /* All the information the user supplied in the command line,
        in a form easy for the program to use.
@@ -85,6 +83,7 @@ struct CmdlineInfo {
     unsigned int stretch;
     unsigned int stop_error;
     unsigned int expectedLineSize;
+    unsigned int correctlong;
 };
 
 
@@ -97,7 +96,6 @@ parseCommandLine(int argc, const char ** const argv,
    was passed to us as the argv array.
 -----------------------------------------------------------------------------*/
     optEntry * option_def;  /* malloc'ed */
-        /* Instructions to OptParseOptions3 on how to parse our options.  */
     optStruct3 opt;
 
     unsigned int option_def_index;
@@ -120,12 +118,14 @@ parseCommandLine(int argc, const char ** const argv,
             &widthSpec,                0);
     OPTENT3(0, "paper_size",       OPT_STRING, &paperSize,
             &paper_sizeSpec,           0);
+    OPTENT3(0, "correctlong",      OPT_FLAG,  NULL, &cmdlineP->correctlong,
+            0);
 
     opt.opt_table = option_def;
     opt.short_allowed = FALSE;  /* We have no short (old-fashioned) options */
     opt.allowNegNum = FALSE;  /* We may have parms that are negative numbers */
 
-    pm_optParseOptions3(&argc, (char**)argv, opt, sizeof(opt), 0);
+    pm_optParseOptions4(&argc, argv, opt, sizeof(opt), 0);
         /* Uses and sets argc, argv, and some of *cmdlineP and others. */
 
     if (widthSpec && paper_sizeSpec)
@@ -163,6 +163,11 @@ parseCommandLine(int argc, const char ** const argv,
 
 
 
+typedef struct {
+    const G3TableEntry * whash[HASHSIZE];
+    const G3TableEntry * bhash[HASHSIZE];
+} BwHash;
+
 struct BitStream {
 
     FILE * fileP;
@@ -243,6 +248,7 @@ readBitAndDetectEol(struct BitStream * const bitStreamP,
 }
 
 
+
 static void
 initBitStream(struct BitStream * const bitStreamP,
               FILE *             const fileP,
@@ -275,16 +281,16 @@ skipToNextLine(struct BitStream * const bitStreamP) {
 
 
 static void
-addtohash(G3TableEntry *     hash[],
-          G3TableEntry       table[],
-          unsigned int const n,
-          int          const a,
-          int          const b) {
+addtohash(const G3TableEntry ** const hash,
+          const G3TableEntry *  const table,
+          unsigned int          const n,
+          int                   const a,
+          int                   const b) {
 
     unsigned int i;
 
     for (i = 0; i < n; ++i) {
-        G3TableEntry * const teP = &table[i*2];
+        const G3TableEntry * const teP = &table[i*2];
         unsigned int const pos =
             ((teP->length + a) * (teP->code + b)) % HASHSIZE;
         if (hash[pos])
@@ -295,38 +301,51 @@ addtohash(G3TableEntry *     hash[],
 
 
 
-static G3TableEntry *
-hashfind(G3TableEntry *       hash[],
-         int            const length,
-         int            const code,
-         int            const a,
-         int            const b) {
+static const G3TableEntry *
+hashfind(const G3TableEntry * const * const hash,
+         unsigned int                 const length,
+         int                          const code,
+         int                          const a,
+         int                          const b) {
 
-    unsigned int pos;
-    G3TableEntry * te;
+    unsigned int         const pos = ((length + a) * (code + b)) % HASHSIZE;
+    const G3TableEntry * const teP = hash[pos];
 
-    pos = ((length + a) * (code + b)) % HASHSIZE;
-    te = hash[pos];
-    return ((te && te->length == length && te->code == code) ? te : NULL);
+    return ((teP && teP->length == length && teP->code == code) ? teP : NULL);
 }
 
 
 
-static void
-buildHashes(G3TableEntry * (*whashP)[HASHSIZE],
-            G3TableEntry * (*bhashP)[HASHSIZE]) {
+static BwHash *
+newBwHash() {
 
-    unsigned int i;
+    BwHash * bwHashP;
 
-    for (i = 0; i < HASHSIZE; ++i)
-        (*whashP)[i] = (*bhashP)[i] = NULL;
+    MALLOCVAR(bwHashP);
 
-    addtohash(*whashP, &g3ttable_table[0], 64, WHASHA, WHASHB);
-    addtohash(*whashP, &g3ttable_mtable[2], 40, WHASHA, WHASHB);
+    if (!bwHashP)
+        pm_error("Unable to allocate memory for hashes");
+    else {
+        unsigned int i;
+        /* Initialize */
+        for (i = 0; i < HASHSIZE; ++i)
+            bwHashP->whash[i] = bwHashP->bhash[i] = NULL;
 
-    addtohash(*bhashP, &g3ttable_table[1], 64, BHASHA, BHASHB);
-    addtohash(*bhashP, &g3ttable_mtable[3], 40, BHASHA, BHASHB);
+        addtohash(bwHashP->whash, &g3ttable_table [0], 64, WHASHA, WHASHB);
+        addtohash(bwHashP->whash, &g3ttable_mtable[2], 40, WHASHA, WHASHB);
 
+        addtohash(bwHashP->bhash, &g3ttable_table [1], 64, BHASHA, BHASHB);
+        addtohash(bwHashP->bhash, &g3ttable_mtable[3], 40, BHASHA, BHASHB);
+    }
+    return bwHashP;
+}
+
+
+
+static void
+freeBwHash(BwHash * const bwHashP) {
+
+    free(bwHashP);
 }
 
 
@@ -342,10 +361,11 @@ makeRowWhite(unsigned char * const packedBitrow,
 
 
 
-static G3TableEntry *
-g3code(unsigned int const curcode,
-       unsigned int const curlen,
-       bit          const color) {
+static const G3TableEntry *
+g3code(unsigned int   const curcode,
+       unsigned int   const curlen,
+       bit            const color,
+       const BwHash * const bwHashP) {
 /*----------------------------------------------------------------------------
    Return the position in the code tables mtable and ttable of the
    G3 code which is the 'curlen' bits long with value 'curcode'.
@@ -353,20 +373,20 @@ g3code(unsigned int const curcode,
    Note that it is the _position_ in the table that determines the meaning
    of the code.  The contents of the table entry do not.
 -----------------------------------------------------------------------------*/
-    G3TableEntry * retval;
+    const G3TableEntry * retval;
 
     switch (color) {
     case PBM_WHITE:
         if (curlen < 4)
             retval = NULL;
         else
-            retval = hashfind(whash, curlen, curcode, WHASHA, WHASHB);
+            retval = hashfind(bwHashP->whash, curlen, curcode, WHASHA, WHASHB);
         break;
     case PBM_BLACK:
         if (curlen < 2)
             retval = NULL;
         else
-            retval = hashfind(bhash, curlen, curcode, BHASHA, BHASHB);
+            retval = hashfind(bwHashP->bhash, curlen, curcode, BHASHA, BHASHB);
         break;
     default:
         pm_error("INTERNAL ERROR: color is not black or white");
@@ -481,6 +501,7 @@ formatBadCodeException(const char ** const exceptionP,
 static void
 readFaxRow(struct BitStream * const bitStreamP,
            unsigned char *    const packedBitrow,
+           BwHash *           const bwHashP,
            unsigned int *     const lineLengthP,
            const char **      const exceptionP,
            const char **      const errorP) {
@@ -552,17 +573,16 @@ readFaxRow(struct BitStream * const bitStreamP,
                 curcode = (curcode << 1) | bit;
                 ++curlen;
 
-		if (curlen > 11 && curcode == 0x00) {
-		    if (++fillbits > MAXFILLBITS)
-                pm_error("Encountered %u consecutive fill bits.  "
-                       "Aborting", fillbits);
-		}
-		else if (curlen - fillbits > 13) {
+                if (curlen > 11 && curcode == 0x00) {
+                    if (++fillbits > MAXFILLBITS)
+                        pm_error("Encountered %u consecutive fill bits.  "
+                                 "Aborting", fillbits);
+                } else if (curlen - fillbits > 13) {
                     formatBadCodeException(exceptionP, col, curlen, curcode);
                     done = TRUE;
                 } else if (curcode != 0) {
                     const G3TableEntry * const teP =
-                        g3code(curcode, curlen, currentColor);
+                        g3code(curcode, curlen, currentColor, bwHashP);
                         /* Address of structure that describes the
                            current G3 code.  Null means 'curcode' isn't
                            a G3 code yet (probably just the beginning of one)
@@ -645,16 +665,21 @@ typedef struct {
         */
     bool warned;
         /* We have warned the user that he has a line length problem */
+
     bool tolerateErrors;
         /* Try to continue when we detect a line size error, as opposed to
            aborting the program.
         */
-} lineSizeAnalyzer;
+    unsigned int lineSizeCt[MAXCOLS+1];
+        /* Histogram of line sizes in image -- lineSizeCt[i] is the number
+           of lines we've seen of size i.
+        */
+} LineSizeAnalyzer;
 
 
 
 static void
-initializeLineSizeAnalyzer(lineSizeAnalyzer * const analyzerP,
+initializeLineSizeAnalyzer(LineSizeAnalyzer * const analyzerP,
                            unsigned int       const expectedLineSize,
                            bool               const tolerateErrors) {
 
@@ -663,12 +688,19 @@ initializeLineSizeAnalyzer(lineSizeAnalyzer * const analyzerP,
 
     analyzerP->maxLineSize = 0;
     analyzerP->warned      = FALSE;
+
+    {
+        unsigned int i;
+
+        for (i = 0; i < MAXCOLS; ++i)
+            analyzerP->lineSizeCt[i] = 0;
+    }
 }
 
 
 
 static void
-analyzeLineSize(lineSizeAnalyzer * const analyzerP,
+analyzeLineSize(LineSizeAnalyzer * const analyzerP,
                 unsigned int       const thisLineSize) {
 
     const char * error;
@@ -701,6 +733,45 @@ analyzeLineSize(lineSizeAnalyzer * const analyzerP,
         pm_strfree(error);
     }
     analyzerP->maxLineSize = MAX(thisLineSize, analyzerP->maxLineSize);
+
+    assert(thisLineSize <= MAXCOLS);
+    ++analyzerP->lineSizeCt[thisLineSize];
+}
+
+
+
+static unsigned int
+imageLineSize(const LineSizeAnalyzer * const lineSizeAnalyzerP,
+              bool                     const mustCorrectLongLine) {
+/*----------------------------------------------------------------------------
+   The width of the fax in pixels, based on the analysis of the image
+   *lineSizeAnalyzerP.
+
+   Zero if the fax contains no lines.
+-----------------------------------------------------------------------------*/
+    unsigned int retval;
+
+    if (mustCorrectLongLine) {
+        /* Assume that long lines are actually concatenation of two
+           lines because the EOL code that was supposed to separate them
+           got lost.
+
+           Assume the most common line length in the image is the correct line
+           length for the image and that other line lengths are due to
+           corruption
+        */
+        unsigned int modeSoFar;
+        unsigned int i;
+
+        for (i = 0, modeSoFar = 0; i <= MAXCOLS; ++i) {
+            if (lineSizeAnalyzerP->lineSizeCt[i] > modeSoFar)
+                modeSoFar = i;
+        }
+        retval = modeSoFar;
+    } else {
+        retval = lineSizeAnalyzerP->maxLineSize;
+    }
+    return retval;
 }
 
 
@@ -718,12 +789,14 @@ static void
 readFax(struct BitStream * const bitStreamP,
         bool               const stretch,
         unsigned int       const expectedLineSize,
-        bool               const tolerateErrors,
+        bool               const mustTolerateErrors,
+        bool               const mustCorrectLongLine,
+        BwHash *           const bwHashP,
         unsigned char ***  const packedBitsP,
         unsigned int *     const colsP,
         unsigned int *     const rowsP) {
 
-    lineSizeAnalyzer lineSizeAnalyzer;
+    LineSizeAnalyzer lineSizeAnalyzer;
     unsigned char ** packedBits;
     const char * error;
     bool eof;
@@ -732,7 +805,7 @@ readFax(struct BitStream * const bitStreamP,
     MALLOCARRAY_NOFAIL(packedBits, MAXROWS);
 
     initializeLineSizeAnalyzer(&lineSizeAnalyzer,
-                               expectedLineSize, tolerateErrors);
+                               expectedLineSize, mustTolerateErrors);
 
     eof = FALSE;
     error = NULL;
@@ -748,10 +821,10 @@ readFax(struct BitStream * const bitStreamP,
             const char * exception;
 
             packedBits[row] = pbm_allocrow_packed(MAXCOLS);
-            readFaxRow(bitStreamP, packedBits[row],
+            readFaxRow(bitStreamP, packedBits[row], bwHashP,
                        &lineSize, &exception, &error);
 
-            handleRowException(exception, error, row, tolerateErrors);
+            handleRowException(exception, error, row, mustTolerateErrors);
 
             if (!error) {
                 if (lineSize == 0) {
@@ -775,7 +848,8 @@ readFax(struct BitStream * const bitStreamP,
         }
     }
     *rowsP        = row;
-    *colsP        = lineSizeAnalyzer.maxLineSize;
+    *colsP        = imageLineSize(&lineSizeAnalyzer, mustCorrectLongLine);
+
     *packedBitsP  = packedBits;
 }
 
@@ -789,6 +863,7 @@ main(int argc, const char * argv[]) {
     struct BitStream bitStream;
     unsigned int rows, cols;
     unsigned char ** packedBits;
+    BwHash * bwHashP;
 
     pm_proginit(&argc, argv);
 
@@ -806,10 +881,10 @@ main(int argc, const char * argv[]) {
     }
     skipToNextLine(&bitStream);
 
-    buildHashes(&whash, &bhash);
+    bwHashP = newBwHash();
 
     readFax(&bitStream, cmdline.stretch, cmdline.expectedLineSize,
-            !cmdline.stop_error,
+            !cmdline.stop_error, !!cmdline.correctlong, bwHashP,
             &packedBits, &cols, &rows);
 
     pm_close(ifP);
@@ -826,5 +901,10 @@ main(int argc, const char * argv[]) {
 
     freeBits(packedBits, rows, cmdline.stretch);
 
+    freeBwHash(bwHashP);
+
     return 0;
 }
+
+
+
diff --git a/converter/pbm/macp.h b/converter/pbm/macp.h
index d00dc5c9..dcd96af9 100644
--- a/converter/pbm/macp.h
+++ b/converter/pbm/macp.h
@@ -6,11 +6,11 @@
 #ifndef MACP_H_INCLUDED
 #define MACP_H_INCLUDED
 
-#define	MACBIN_HEAD_LEN	128
-#define	MACP_HEAD_LEN	512
-#define	MACP_ROWS	720
-#define	MACP_COLCHARS	72
-#define MACP_COLS	((MACP_COLCHARS) * 8)
-#define MACP_BYTES	((MACP_COLCHARS) * (MACP_ROWS))
+#define MACBIN_HEAD_LEN 128
+#define MACP_HEAD_LEN   512
+#define MACP_ROWS       720
+#define MACP_COLCHARS   72
+#define MACP_COLS       ((MACP_COLCHARS) * 8)
+#define MACP_BYTES      ((MACP_COLCHARS) * (MACP_ROWS))
 
 #endif
diff --git a/converter/pbm/macptopbm.c b/converter/pbm/macptopbm.c
index db628b6c..b5dbcbad 100644
--- a/converter/pbm/macptopbm.c
+++ b/converter/pbm/macptopbm.c
@@ -133,7 +133,6 @@ scanMacBinaryHeader( const unsigned char * rBuff ) {
 
 
 
-
 static void
 skipHeader( FILE * const ifP ) {
 /*--------------------------------------------------------------------------
@@ -227,7 +226,6 @@ readChar( FILE * const ifP ) {
 
 
 
-
 static void
 ReadMacPaintFile( FILE *  const ifP,
                   int  * outOfSyncP,
@@ -291,6 +289,7 @@ ReadMacPaintFile( FILE *  const ifP,
 }
 
 
+
 int
 main( int argc, char * argv[])  {
 
@@ -354,3 +353,6 @@ main( int argc, char * argv[])  {
     pm_close( stdout );
     exit( 0 );
 }
+
+
+
diff --git a/converter/pbm/mdatopbm.c b/converter/pbm/mdatopbm.c
index 461b3f80..670ba8c4 100644
--- a/converter/pbm/mdatopbm.c
+++ b/converter/pbm/mdatopbm.c
@@ -1,4 +1,3 @@
-
 /***************************************************************************
 
     MDATOPBM: Convert Microdesign area to portable bitmap
@@ -30,156 +29,188 @@
 
 typedef unsigned char mdbyte;   /* Must be exactly one byte */
 
-static FILE *infile;            /* Input file */
 static mdbyte header[128];      /* MDA file header */
 static bit **data;          /* PBM image */
 static mdbyte *mdrow;           /* MDA row after decompression (MD3 only) */
 static int bInvert = 0;     /* Invert image? */
 static int bScale  = 0;     /* Scale image? */
 static int bAscii  = 0;     /* Output ASCII PBM? */
-static int nInRows, nInCols;        /* Height, width of input (rows x bytes) */
-static int nOutCols, nOutRows;      /* Height, width of output (rows x bytes) */
 
-static mdbyte 
-getbyte(void) {
+static mdbyte
+getbyte(FILE * const ifP) {
     /* Read a byte from the input stream, with error trapping */
     int b;
 
-    b = fgetc(infile);
+    b = fgetc(ifP);
+
+    if (b == EOF)
+        pm_error("Unexpected end of MDA file");
 
-    if (b == EOF) pm_error("Unexpected end of MDA file\n");
-    
     return (mdbyte)b;
 }
 
 
 
-static void 
-render_byte(int *col, int *xp, int *yp, int b) {
+static void
+renderByte(unsigned int   const nInCols,
+           unsigned int   const nOutRows,
+           unsigned int * const colP,
+           unsigned int * const xP,
+           unsigned int * const yP,
+           int            const b) {
+/*----------------------------------------------------------------------------
+  Convert a byte to 8 cells in the destination bitmap
 
-/* Convert a byte to 8 cells in the destination bitmap 
- *
- * *col = source column
- * *xp  = destination column
- * *yp  = destination row
- *  b   = byte to draw
- *
- * Will update *col, *xp and *yp to point to the next bit of the row.
- */
+  As input
 
-    int mask = 0x80;
-    int n;
-    int y3 = *yp;
+    *colP = source column
+    *xP  = destination column
+    *yP  = destination row
+    b    = byte to draw
 
-    if (bScale) y3 *= 2;
+  As output, update *colP, *xP and *yP to point to the next bit of the row.
+-----------------------------------------------------------------------------*/
+    int const y3 =  bScale ? *yP * 2 : *yP;
 
-    if (y3 >= nOutRows) return;
+    if (y3 < nOutRows) {
+        unsigned int n;
+        int mask;
 
-    for (n = 0; n < 8; ++n) {
-        if (bInvert) data[y3][*xp] = (b & mask) ? PBM_BLACK : PBM_WHITE;
-        else         data[y3][*xp] = (b & mask) ? PBM_WHITE : PBM_BLACK;
-        mask = mask >> 1;
-        if (bScale) data[y3+1][*xp] = data[y3][*xp];
-        ++(*xp);
-    }
-    ++(*col);       /* Next byte */
-    if ((*col) >= nInCols) {
-        /* Onto next line? */
-        *col = 0;
-        *xp = 0;
-        ++(*yp);
+        for (n = 0, mask = 0x80; n < 8; ++n) {
+            if (bInvert) data[y3][*xP] = (b & mask) ? PBM_BLACK : PBM_WHITE;
+            else         data[y3][*xP] = (b & mask) ? PBM_WHITE : PBM_BLACK;
+            mask = mask >> 1;
+            if (bScale)
+                data[y3+1][*xP] = data[y3][*xP];
+            ++(*xP);
+        }
+        ++(*colP);       /* Next byte */
+        if ((*colP) >= nInCols) {
+            /* Onto next line? */
+            *colP = 0;
+            *xP = 0;
+            ++(*yP);
+        }
     }
 }
 
 
-static void 
-md2_trans(void) {
-    /* Convert a MicroDesign 2 area to PBM */
-    /* MD2 has RLE encoding that may go over */
 
-    int x1, y1, col;    /* multiple lines. */
+static void
+md2Trans(FILE *       const ifP,
+         unsigned int const nInRows,
+         unsigned int const nInCols,
+         unsigned int const nOutRows,
+         unsigned int const nOutCols) {
+/*----------------------------------------------------------------------------
+   Convert a MicroDesign 2 area to PBM
+
+   MD2 has RLE encoding that may go over
+-----------------------------------------------------------------------------*/
+    unsigned int x1, y1, col;    /* multiple lines. */
     mdbyte b;
-    int c;
 
     x1 = y1 = col = 0;
 
     while (y1 < nInRows) {
-        b = getbyte();
-    
+        b = getbyte(ifP);
+
         if (b == 0 || b == 0xFF) {
             /* RLE sequence */
-            c = getbyte();
-            if (c == 0) c = 256;
-            while (c > 0) { 
-                render_byte(&col, &x1, &y1, b); 
-                --c; 
+            int c;
+            c = getbyte(ifP);
+            if (c == 0)
+                c = 256;
+            while (c > 0) {
+                renderByte(nInCols, nOutRows, &col, &x1, &y1, b);
+                --c;
             }
-        }
-        else 
-            render_byte(&col, &x1, &y1, b);    /* Not RLE */
+        } else
+            /* Not RLE */
+            renderByte(nInCols, nOutRows, &col, &x1, &y1, b);
     }
 }
 
 
 
-static void 
-md3_trans(void) {
-    /* Convert MD3 file. MD3 are encoded as rows, and 
-       there are three types. 
-    */
-    int x1, y1, col;
-    mdbyte b;
-    int c, d, n;
+static void
+md3Trans(FILE *       const ifP,
+         unsigned int const nInRows,
+         unsigned int const nInCols,
+         unsigned int const nOutRows,
+         unsigned int const nOutCols) {
+/*----------------------------------------------------------------------------
+   Convert MD3 file. MD3 are encoded as rows, and there are three types.
+-----------------------------------------------------------------------------*/
+    unsigned int y1;
 
     for (y1 = 0; y1 < nInRows; ++y1) {
-        b = getbyte();   /* Row type */
+        mdbyte b;
+
+        b = getbyte(ifP);   /* Row type */
         switch(b)  {
-        case 0: /* All the same byte */
-            c = getbyte();
-            for (n = 0; n < nInCols; n++) 
-                mdrow[n] = c;
-            break;
-            
+        case 0: {  /* All the same byte */
+            int c;
+            unsigned int i;
+            c = getbyte(ifP);
+            for (i = 0; i < nInCols; ++i)
+                mdrow[i] = c;
+        } break;
+
         case 1:      /* Encoded data */
-        case 2: col = 0; /* Encoded as XOR with previous row */
+        case 2: {     /* Encoded as XOR with previous row */
+            unsigned int col;
+            col = 0;
             while (col < nInCols) {
-                c = getbyte();
+                int c;
+                c = getbyte(ifP);
                 if (c >= 129) {
                     /* RLE sequence */
+                    unsigned int i;
+                    int d;
                     c = 257 - c;
-                    d = getbyte();
-                    for (n = 0; n < c; ++n) {
-                        if (b == 1) 
+                    d = getbyte(ifP);
+                    for (i = 0; i < c; ++i) {
+                        if (b == 1)
                             mdrow[col++] = d;
-                        else 
+                        else
                             mdrow[col++] ^= d;
-                    }   
+                    }
                 } else {
                     /* not RLE sequence */
-                        ++c;
-                        for (n = 0; n < c; ++n) {
-                            d = getbyte();
-                            if (b == 1) 
-                                mdrow[col++] = d;
-                            else
-                                mdrow[col++] ^= d;
-                        }
-                } 
+                    unsigned int i;
+                    ++c;
+                    for (i = 0; i < c; ++i) {
+                        int d;
+                        d = getbyte(ifP);
+                        if (b == 1)
+                            mdrow[col++] = d;
+                        else
+                            mdrow[col++] ^= d;
+                    }
+                }
             }
+        } break;
         }
-        /* Row loaded. Convert it. */
-        x1 = 0; col = 0; 
-        for (n = 0; n < nInCols; ++n) {
-            d  = y1;
-            render_byte(&col, &x1, &d, mdrow[n]);
+        {
+            /* Row loaded. Convert it. */
+            unsigned int x1;
+            unsigned int col;
+            unsigned int i;
+
+            for (i = 0, x1 = 0, col = 0; i < nInCols; ++i) {
+                unsigned int d;
+                d = y1;
+                renderByte(nInCols, nOutRows, &col, &x1, &d, mdrow[i]);
+            }
         }
     }
 }
 
 
 
-static void 
-usage(char *s) {        
+static void
+usage(const char *s) {
     printf("mdatopbm v1.00, Copyright (C) 1999 "
            "John Elliott <jce@seasip.demon.co.uk>\n"
            "This program is redistributable under the terms of "
@@ -197,17 +228,24 @@ usage(char *s) {
 
 
 
-int 
-main(int argc, char **argv) {
+int
+main(int argc, const char **argv) {
+
+    FILE * ifP;
     int n, optstop = 0;
-    char *fname = NULL;
+    const char * fname;
+    unsigned int nInRows, nInCols;
+        /* Height, width of input (rows x bytes) */
+    unsigned int nOutCols, nOutRows;
+        /* Height, width of output (rows x bytes) */
 
-    pbm_init(&argc, argv);
+    pm_proginit(&argc, argv);
 
     /* Parse options */
 
+    fname = NULL;  /* initial value */
     for (n = 1; n < argc; ++n) {
-        if (argv[n][0] == '-' && !optstop) {   
+        if (argv[n][0] == '-' && !optstop) {
             if (argv[n][1] == 'a' || argv[n][1] == 'A') bAscii = 1;
             if (argv[n][1] == 'd' || argv[n][1] == 'D') bScale = 1;
             if (argv[n][1] == 'i' || argv[n][1] == 'I') bInvert = 1;
@@ -225,47 +263,50 @@ main(int argc, char **argv) {
         }
     }
 
-    if (fname) 
-        infile = pm_openr(fname);
+    if (fname)
+        ifP = pm_openr(fname);
     else
-        infile = stdin;
+        ifP = stdin;
 
     /* Read MDA file header */
 
-    if (fread(header, 1, 128, infile) < 128)
+    if (fread(header, 1, 128, ifP) < 128)
         pm_error("Not a .MDA file\n");
 
-    if (strncmp((char*) header, ".MDA", 4) && 
+    if (strncmp((char*) header, ".MDA", 4) &&
         strncmp((char*) header, ".MDP", 4))
         pm_error("Not a .MDA file\n");
 
     {
         short yy;
-        pm_readlittleshort(infile, &yy); nInRows = yy;
-        pm_readlittleshort(infile, &yy); nInCols = yy;
+        pm_readlittleshort(ifP, &yy); nInRows = yy;
+        pm_readlittleshort(ifP, &yy); nInCols = yy;
     }
-    
+
     nOutCols = 8 * nInCols;
     nOutRows = nInRows;
-    if (bScale) 
+    if (bScale)
         nOutRows *= 2;
 
     data = pbm_allocarray(nOutCols, nOutRows);
-    
+
     MALLOCARRAY_NOFAIL(mdrow, nInCols);
 
-    if (header[21] == '0') 
-        md2_trans();
+    if (header[21] == '0')
+        md2Trans(ifP, nInRows, nInCols, nOutRows, nOutCols);
     else
-        md3_trans();
+        md3Trans(ifP, nInRows, nInCols, nOutRows, nOutCols);
 
-    pbm_writepbm(stdout, data, nInCols*8, nOutRows, bAscii);
+    pbm_writepbm(stdout, data, nOutCols, nOutRows, bAscii);
 
-    if (infile != stdin) 
-        pm_close(infile);
+    if (ifP != stdin)
+        pm_close(ifP);
     fflush(stdout);
     pbm_freearray(data, nOutRows);
     free(mdrow);
 
     return 0;
 }
+
+
+
diff --git a/converter/pbm/mgrtopbm.c b/converter/pbm/mgrtopbm.c
index 9f7004a1..e0a88883 100644
--- a/converter/pbm/mgrtopbm.c
+++ b/converter/pbm/mgrtopbm.c
@@ -16,12 +16,54 @@
 
 
 static void
-readMgrHeader(FILE *          const ifP, 
-              unsigned int *  const colsP, 
-              unsigned int *  const rowsP, 
-              unsigned int *  const depthP, 
+interpHdrWidth(struct b_header const head,
+               unsigned int *  const colsP) {
+
+    if (head.h_wide < ' ' || head.l_wide < ' ')
+        pm_error("Invalid width field in MGR header");
+    else {
+        unsigned int const maxDimension = 4095;
+
+        unsigned int const cols =
+            (((int)head.h_wide - ' ') << 6) + ((int)head.l_wide - ' ');
+
+        if (cols == 0 || cols > maxDimension)
+            pm_error("Invalid width value (%u) in MGR header", cols);
+        else
+            *colsP = cols;
+    }
+}
+
+
+
+static void
+interpHdrHeight(struct b_header const head,
+                unsigned int *  const rowsP) {
+
+    if (head.h_high < ' ' || head.l_high < ' ')
+        pm_error("Invalid height field in MGR header");
+    else {
+        unsigned int const maxDimension = 4095;
+
+        unsigned int const rows =
+            (((int)head.h_high - ' ') << 6) + ((int)head.l_high - ' ');
+
+        if (rows == 0 || rows > maxDimension)
+            pm_error("Invalid height value (%u) in MGR header", rows);
+        else
+            *rowsP = rows;
+    }
+}
+
+
+
+static void
+readMgrHeader(FILE *          const ifP,
+              unsigned int *  const colsP,
+              unsigned int *  const rowsP,
+              unsigned int *  const depthP,
               unsigned int *  const padrightP ) {
-    
+
     struct b_header head;
     unsigned int pad;
     size_t bytesRead;
@@ -31,10 +73,10 @@ readMgrHeader(FILE *          const ifP,
         pm_error("Unable to read 1st byte of file.  "
                  "fread() returns errno %d (%s)",
                  errno, strerror(errno));
-    if (head.magic[0] == 'y' && head.magic[1] == 'z') { 
+    if (head.magic[0] == 'y' && head.magic[1] == 'z') {
         /* new style bitmap */
         size_t bytesRead;
-        bytesRead = fread(&head.depth, 
+        bytesRead = fread(&head.depth,
                           sizeof(head) - sizeof(struct old_b_header), 1, ifP);
         if (bytesRead != 1 )
             pm_error("Unable to read header after 1st byte.  "
@@ -42,11 +84,11 @@ readMgrHeader(FILE *          const ifP,
                      errno, strerror(errno));
         *depthP = (int) head.depth - ' ';
         pad = 8;
-    } else if (head.magic[0] == 'x' && head.magic[1] == 'z') { 
+    } else if (head.magic[0] == 'x' && head.magic[1] == 'z') {
         /* old style bitmap with 32-bit padding */
         *depthP = 1;
         pad = 32;
-    } else if (head.magic[0] == 'z' && head.magic[1] == 'z') { 
+    } else if (head.magic[0] == 'z' && head.magic[1] == 'z') {
         /* old style bitmap with 16-bit padding */
         *depthP = 1;
         pad = 16;
@@ -60,14 +102,10 @@ readMgrHeader(FILE *          const ifP,
         pad = 0;  /* should never reach here */
     }
 
-    if (head.h_wide < ' ' || head.l_wide < ' ')
-        pm_error("Invalid width field in MGR header");
-    if (head.h_high < ' ' || head.l_high < ' ')
-        pm_error("Invalid width field in MGR header");
-    
-    *colsP = (((int)head.h_wide - ' ') << 6) + ((int)head.l_wide - ' ');
-    *rowsP = (((int)head.h_high - ' ') << 6) + ((int) head.l_high - ' ');
-    *padrightP = ( ( *colsP + pad - 1 ) / pad ) * pad - *colsP;
+    interpHdrWidth (head, colsP);
+    interpHdrHeight(head, rowsP);
+
+    *padrightP = ((*colsP + pad - 1) / pad) * pad - *colsP;
 }
 
 
@@ -93,7 +131,7 @@ main(int    argc,
         inputFileName = argv[1];
     else
         inputFileName = "-";
-    
+
     ifP = pm_openr(inputFileName);
 
     readMgrHeader(ifP, &cols, &rows, &depth, &padright);
@@ -103,7 +141,7 @@ main(int    argc,
     pbm_writepbminit(stdout, cols, rows, 0);
 
     bitrow = pbm_allocrow_packed(cols + padright);
-    
+
     itemCount = (cols + padright ) / 8;
 
     for (row = 0; row < rows; ++row) {
@@ -128,9 +166,9 @@ main(int    argc,
    Changed bitrow from plain to raw, read function from getc() to fread(),
    write function from pbm_writepbmrow() to pbm_writepbmrow_packed().
    Retired bitwise transformation functions.
-   
+
    NOT tested for old-style format files.  Only one zz file in mgrsrc-0.69 .
-  
+
 */
 
 
diff --git a/converter/pbm/mrftopbm.c b/converter/pbm/mrftopbm.c
index 32f36ef3..07cf0ed2 100644
--- a/converter/pbm/mrftopbm.c
+++ b/converter/pbm/mrftopbm.c
@@ -20,15 +20,15 @@ static int bitbox;
 static int bitsleft;
 
 
-static void 
+static void
 bit_init(void) {
-    bitbox=0; 
+    bitbox=0;
     bitsleft=0;
 }
 
 
 
-static int 
+static int
 bit_input(FILE * const in) {
     if (bitsleft == 0)   {
         int rc;
@@ -45,7 +45,7 @@ bit_input(FILE * const in) {
 
 
 
-static void 
+static void
 doSquare(FILE *          const ifP,
          unsigned char * const image,
          unsigned int    const ulCol,
@@ -60,7 +60,7 @@ doSquare(FILE *          const ifP,
    image[], which is a concatenation of rows 'imageWidth' pixels wide, one
    byte per pixel.
 -----------------------------------------------------------------------------*/
-    if (size == 1 || bit_input(ifP)) { 
+    if (size == 1 || bit_input(ifP)) {
         /* It's all black or all white.  Next bit says which. */
 
         unsigned int const c = bit_input(ifP);
@@ -100,7 +100,7 @@ writeOutput(FILE *                const ofP,
             int                   const cols,
             int                   const rows,
             const unsigned char * const image) {
-            
+
     /* w64 is units-of-64-bits width */
     unsigned int const w64 = (cols+63)/64;
 
@@ -113,9 +113,9 @@ writeOutput(FILE *                const ofP,
 
     for (row = 0; row < rows; ++row) {
         unsigned int col;
-     
+
         for (col = 0; col < cols; ++col)
-            bitrow[col] = 
+            bitrow[col] =
                 (image[row * (w64*64) + col] == 1) ? PBM_WHITE : PBM_BLACK;
 
         pbm_writepbmrow(ofP, bitrow, cols, FALSE);
@@ -173,7 +173,7 @@ readMrfImage(FILE *           const ifP,
     image = calloc(w64*h64*64*64, 1);
     if (image == NULL)
         pm_error("Unable to get memory for raster");
-                 
+
     /* now recursively input squares. */
 
     bit_init();
@@ -191,7 +191,7 @@ readMrfImage(FILE *           const ifP,
 
 
 
-int 
+int
 main(int argc, char *argv[]) {
 
     FILE *ifP;
@@ -213,7 +213,7 @@ main(int argc, char *argv[]) {
         pm_error("Too many arguments: %d.  Only argument is input file",
                  argc-1);
 
-    if (argc-1 == 1) 
+    if (argc-1 == 1)
         ifP = pm_openr(argv[1]);
     else
         ifP = stdin;
@@ -221,9 +221,9 @@ main(int argc, char *argv[]) {
     ofP = stdout;
 
     readMrfImage(ifP, expandAll, &image, &cols, &rows);
-    
+
     pm_close(ifP);
-    
+
     writeOutput(ofP, cols, rows, image);
 
     free(image);
@@ -233,6 +233,3 @@ main(int argc, char *argv[]) {
 
 
 
-
-
-
diff --git a/converter/pbm/pbmto10x.c b/converter/pbm/pbmto10x.c
index d040b3ed..99f35847 100644
--- a/converter/pbm/pbmto10x.c
+++ b/converter/pbm/pbmto10x.c
@@ -23,8 +23,8 @@
 
 
 static void
-outstripe(char * const stripe, 
-          char * const sP, 
+outstripe(char * const stripe,
+          char * const sP,
           int    const reschar) {
 
     char * p;
@@ -32,7 +32,7 @@ outstripe(char * const stripe,
     p = sP;  /* initial value */
 
     /* scan backwards, removing empty columns */
-    while (p != stripe) 
+    while (p != stripe)
         if (*--p != 0) {
             ++p;
             break;
@@ -199,7 +199,7 @@ main(int argc, const char ** argv) {
         fname = argv[1];
     else
         fname = "-";
-    
+
     ifP = pm_openr(fname);
 
     pbm_readpbminit(ifP, &cols, &rows, &format);
diff --git a/converter/pbm/pbmto4425.c b/converter/pbm/pbmto4425.c
index 1d97ac6a..f18b2e5a 100644
--- a/converter/pbm/pbmto4425.c
+++ b/converter/pbm/pbmto4425.c
@@ -1,178 +1,155 @@
+#include <assert.h>
 #include <string.h>
 
 #include "nstring.h"
+#include "mallocvar.h"
 #include "pbm.h"
 
-static char bit_table[2][3] = {
-{1, 4, 0x10},
-{2, 8, 0x40}
+static char const bit_table[2][3] = {
+    {1, 4, 0x10},
+    {2, 8, 0x40}
 };
 
-static int vmap_width;
-static int vmap_height;
+static unsigned int const vmapWidth  = 132;
+static unsigned int const vmapHeight = 23;
 
-static int xres;
-static int yres;
-
-static char *vmap;
 
 
 static void
-init_map()
-{
-    int x, y;
+initMap(char * const vmap) {
 
+    unsigned int col;
 
-    for(x = 0; x < vmap_width; ++x)
-    {
-        for(y = 0; y < vmap_height; ++y)
-        {
-            vmap[y*(vmap_width) + x] = 0x20;
-        }
+    for (col = 0; col < vmapWidth; ++col) {
+        unsigned int row;
+
+        for (row = 0; row < vmapHeight; ++row)
+            vmap[row * vmapWidth + col] = ' ';
     }
 }
 
 
 
 static void
-set_vmap(x, y)
-    int x, y;
-{
-    int ix, iy;
+setVmap(char *       const vmap,
+        unsigned int const x,
+        unsigned int const y) {
+
+    unsigned int const ix = x/2;
+    unsigned int const iy = y/3;
 
-    ix = x/2;
-    iy = y/3;
+    assert(ix < vmapWidth);
+    assert(iy < vmapHeight);
 
-    vmap[iy*(vmap_width) + ix] |= bit_table[x % 2][y % 3];
+    vmap[iy * vmapWidth + ix] |= bit_table[x % 2][y % 3];
 }
 
 
 
 static void
-fill_map(pbmfp)
-    FILE *pbmfp;
-{
-    bit **pbm_image;
+fillMap(FILE * const pbmFileP,
+        char * const vmap) {
+
+    unsigned int const xres = vmapWidth  * 2;
+    unsigned int const yres = vmapHeight * 3;
+
+    bit ** pbmImage;
     int cols;
     int rows;
-    int x;
-    int y;
-
-    pbm_image = pbm_readpbm(pbmfp, &cols, &rows);
-    for(y = 0; y < rows && y < yres; ++y)
-    {
-        for(x = 0; x < cols && x < xres; ++x)
-        {
-            if(pbm_image[y][x] == PBM_WHITE)
-            {
-                set_vmap(x, y);
-            }
+    unsigned int row;
+
+    pbmImage = pbm_readpbm(pbmFileP, &cols, &rows);
+
+    for (row = 0; row < rows && row < yres; ++row) {
+        unsigned int col;
+
+        for (col = 0; col < cols && col < xres; ++col) {
+            if (pbmImage[row][col] == PBM_WHITE)
+                setVmap(vmap, col, row);
         }
     }
 }
 
 
+
 static void
-print_map()
-{
-    int x, y;
-    int last_byte;
-
-#ifdef BUFFERED
-    char *iobuf;
-    iobuf = (char *)malloc(BUFSIZ);
-    if(iobuf == NULL)
-    {
-        pm_message( "Can't allocate space for I/O buffer.  "
-                    "Using unbuffered I/O...\n" );
-        setbuf(stdout, NULL);
-    }
-    else
-    {
-        setbuf(stdout, iobuf);
-    }
-#endif
-
-    fputs("\033[H\033[J", stdout);	/* clear screen */
-    fputs("\033[?3h", stdout);	/* 132 column mode */
-    fputs("\033)}\016", stdout);	/* mosaic mode */
-
-    for(y = 0; y < vmap_height; ++y)
-    {
-        for(last_byte = vmap_width - 1;
-            last_byte >= 0
-                && vmap[y * vmap_width + last_byte] == 0x20;
-            --last_byte)
+printMap(char * const vmap,
+         FILE * const ofP) {
+
+    unsigned int row;
+
+    fputs("\033[H\033[J", ofP);  /* clear screen */
+    fputs("\033[?3h",     ofP);  /* 132 column mode */
+    fputs("\033)}\016",   ofP);  /* mosaic mode */
+
+    for (row = 0; row < vmapHeight; ++row) {
+        unsigned int endCol;
+            /* Column number just past the non-space data in the row;
+               (i.e. spaces on the right are padding; not data
+            */
+        unsigned int col;
+
+        for (endCol = vmapWidth;
+             endCol > 0 && vmap[row * vmapWidth + (endCol-1)] == ' ';
+             --endCol)
             ;
 
-        for(x = 0; x <= last_byte; ++x)
-        {
-            fputc(vmap[y*(vmap_width) + x], stdout);
-        }
-        fputc('\n', stdout);
+        for (col = 0; col < endCol; ++col)
+            fputc(vmap[row * vmapWidth + col], ofP);
+
+        fputc('\n', ofP);
     }
 
-    fputs("\033(B\017", stdout);
+    fputs("\033(B\017", ofP);
 }
 
 
 
 int
-main(int argc, char * argv[]) {
-    int argn;
-    const char *pbmfile;
-    FILE *pbmfp;
-    const char *usage="[pbmfile]";
-
-    pbm_init( &argc, argv );
-    for(argn = 1;
-        argn < argc && argv[argn][0] == '-' && strlen(argv[argn]) > 1;
-        ++argn)
-    {
-        pm_usage(usage);
-    }
+main(int argc, const char ** argv) {
 
-    if(argn >= argc)
-    {
-        pbmfile = "-";
-    }
-    else if(argc - argn != 1)
-    {
-        pm_usage(usage);
-    }
-    else
-    {
-        pbmfile = argv[argn];
-    }
+    unsigned int argn;
+    const char * inputFileNm;
+    FILE * ifP;
+
+    char * vmap;  /* malloced */
+
+    pm_proginit(&argc, argv);
 
-    if(streq(pbmfile, "-"))
-    {
-        pbmfp = stdin;
+    for (argn = 1;
+         argn < argc && argv[argn][0] == '-' && strlen(argv[argn]) > 1;
+         ++argn) {
+        pm_error("Unrecognized option '%s'", argv[argn]);
     }
-    else
-    {
-        pbmfp = pm_openr( argv[argn] );
+
+    if (argn >= argc) {
+        inputFileNm = "-";
+    } else if(argc - argn != 1) {
+        pm_error("Too many arguments.  At most one argument is allowed: "
+                 "Name of the input file");
+    } else {
+        inputFileNm = argv[argn];
     }
 
-    vmap_width = 132;
-    vmap_height = 23;
+    ifP = pm_openr(inputFileNm);
+
+    assert(vmapWidth < UINT_MAX/vmapHeight);
+
+    MALLOCARRAY(vmap, vmapWidth * vmapHeight);
+    if (!vmap)
+        pm_error("Cannot allocate memory for %u x %u pixels",
+                 vmapWidth, vmapHeight);
 
-    xres = vmap_width * 2;
-    yres = vmap_height * 3;
+    initMap(vmap);
+    fillMap(ifP, vmap);
+    printMap(vmap, stdout);
 
-    vmap = malloc(vmap_width * vmap_height * sizeof(char));
-    if(vmap == NULL)
-	{
-        pm_error( "Cannot allocate memory" );
-	}
+    free(vmap);
 
-    init_map();
-    fill_map(pbmfp);
-    print_map();
     /* If the program failed, it previously aborted with nonzero completion
        code, via various function calls.
     */
-    return 0; 
+    return 0;
 }
 
 
diff --git a/converter/pbm/pbmtoascii.c b/converter/pbm/pbmtoascii.c
index 0305a47b..634bea67 100644
--- a/converter/pbm/pbmtoascii.c
+++ b/converter/pbm/pbmtoascii.c
@@ -272,7 +272,7 @@ main(int argc, const char ** argv) {
     }
     else
         ifP = stdin;
-    
+
     if ( argn != argc )
         pm_usage( usage );
 
@@ -282,3 +282,6 @@ main(int argc, const char ** argv) {
 
     return 0;
 }
+
+
+
diff --git a/converter/pbm/pbmtoatk.c b/converter/pbm/pbmtoatk.c
index ea5b7abe..d58d7c7d 100644
--- a/converter/pbm/pbmtoatk.c
+++ b/converter/pbm/pbmtoatk.c
@@ -22,8 +22,8 @@
 
 
 static void
-write_atk_bytes(FILE *        const file, 
-                unsigned char const curbyte, 
+write_atk_bytes(FILE *        const file,
+                unsigned char const curbyte,
                 unsigned int  const startcount) {
 
     /* codes for data stream */
@@ -37,7 +37,7 @@ write_atk_bytes(FILE *        const file,
     #define BLACKBYTE 0xFF
 
     /* WriteRow table for conversion of a byte value to two character
-       hex representation 
+       hex representation
     */
 
     static unsigned char hex[16] = {
@@ -82,10 +82,10 @@ write_atk_bytes(FILE *        const file,
 
 
 static void
-process_atk_byte(int *           const pcurcount, 
-                 unsigned char * const pcurbyte, 
-                 FILE *          const file, 
-                 unsigned char   const newbyte, 
+process_atk_byte(int *           const pcurcount,
+                 unsigned char * const pcurbyte,
+                 FILE *          const file,
+                 unsigned char   const newbyte,
                  int             const eolflag) {
 
     int curcount;
@@ -93,7 +93,7 @@ process_atk_byte(int *           const pcurcount,
 
     curcount = *pcurcount;  /* initial value */
     curbyte  = *pcurbyte;  /* initial value */
-    
+
     if (curcount < 1) {
         *pcurbyte = curbyte = newbyte;
         *pcurcount = curcount = 1;
@@ -139,6 +139,17 @@ main(int argc, const char ** argv) {
     }
 
     pbm_readpbminit(ifP, &cols, &rows, &format);
+    /* Note: atktopbm imposes limits: cols <= 1000000 rows <= 1000000
+       Whether these values are defined in the official file format
+       specification is unknown.  We issue warning messages when large
+       values are encountered.
+     */
+
+    if (cols > 1000000)
+        pm_message("Proceeding with extremely large width value: %u", cols);
+    if (rows > 1000000)
+        pm_message("Proceeding with extremely large height value: %u", rows);
+
     bitrow = pbm_allocrow_packed(cols);
 
     printf("\\begindata{raster,%d}\n", 1);
@@ -152,7 +163,7 @@ main(int argc, const char ** argv) {
 
         pbm_readpbmrow_packed(ifP, bitrow, cols, format);
         pbm_cleanrowend_packed(bitrow, cols);
-        
+
         for (i = 0, curbyte = 0, curcount = 0; i < byteCt; ++i) {
             process_atk_byte(&curcount, &curbyte, stdout,
                              bitrow[i],
@@ -162,8 +173,11 @@ main(int argc, const char ** argv) {
 
     pbm_freerow_packed(bitrow);
     pm_close(ifP);
-    
+
     printf("\\enddata{raster, %d}\n", 1);
 
     return 0;
 }
+
+
+
diff --git a/converter/pbm/pbmtobbnbg.c b/converter/pbm/pbmtobbnbg.c
index e97ef4f2..f9191a49 100644
--- a/converter/pbm/pbmtobbnbg.c
+++ b/converter/pbm/pbmtobbnbg.c
@@ -9,7 +9,7 @@
 ** documentation.  This software is provided "as is" without express or
 ** implied warranty.
 */
-  
+
 /*
 ** Changed to take advantage of negative Packed Pixed Data values and
 ** supply ANSI-standard string terminator.  Paul Milazzo, 28 May 1990.
@@ -17,7 +17,7 @@
 
 #include "pbm.h"
 
-static void write16 ARGS(( unsigned int	));
+static void write16 ARGS(( unsigned int ));
 
 static int nco;
 
@@ -72,10 +72,10 @@ char **argv;
      { if (bitrow[i]==PBM_BLACK) sixteen |= mask;
        mask >>= 1;
        if (mask == 0)
-	{ mask = 0x8000;
-	  write16(sixteen);
-	  sixteen = 0;
-	}
+        { mask = 0x8000;
+          write16(sixteen);
+          sixteen = 0;
+        }
      }
     if (mask != 0x8000)
      { write16(sixteen);
@@ -85,6 +85,8 @@ char **argv;
  exit(0);
 }
 
+
+
 #ifdef POSITIVE_VALUES_ONLY
 static void
 write16(sixteen)
@@ -113,40 +115,40 @@ unsigned int sixteen;
  */
 static void
 write16 (word)
-unsigned int	word;
+unsigned int    word;
 {
-    int		high;
-    int		mid;
-    int		low;
-    int		signChar;
+    int         high;
+    int         mid;
+    int         low;
+    int         signChar;
 
     if (nco > 75) {
-	putchar ('\n');
-	nco = 0;
+        putchar ('\n');
+        nco = 0;
     }
 
     if (word > 0x7fff) {
-	word = (unsigned int) (0x10000L - (long) word);
-	signChar = ' ';
+        word = (unsigned int) (0x10000L - (long) word);
+        signChar = ' ';
     }
     else
-	signChar = '0';
+        signChar = '0';
 
     high = (word >> 10) + '@';
-    mid	= ((word & 0x3f0) >> 4) + '@';
-    low	= (word & 0xf) + signChar;
+    mid = ((word & 0x3f0) >> 4) + '@';
+    low = (word & 0xf) + signChar;
 
     if (high != '@') {
-	printf ("%c%c%c", high, mid, low);
-	nco += 3;
+        printf ("%c%c%c", high, mid, low);
+        nco += 3;
     }
     else if (mid != '@') {
-	printf ("%c%c", mid, low);
-	nco += 2;
+        printf ("%c%c", mid, low);
+        nco += 2;
     }
     else {
-	putchar (low);
-	nco++;
+        putchar (low);
+        nco++;
     }
 }
 #endif
diff --git a/converter/pbm/pbmtocis.c b/converter/pbm/pbmtocis.c
index 9bb42c56..c7a29055 100644
--- a/converter/pbm/pbmtocis.c
+++ b/converter/pbm/pbmtocis.c
@@ -42,6 +42,8 @@ static void syntax(const char *prog)
          );
 }
 
+
+
 int main(int argc, const char **argv)
 {
     FILE *ofP = stdout;
@@ -86,7 +88,7 @@ int main(int argc, const char **argv)
                 pm_keymatch(argv[n], "-W", 2) ||
                 pm_keymatch(argv[n], "--whitebg", 9))
             {
-                bg = PBM_WHITE; 
+                bg = PBM_WHITE;
                 continue;
             }
             if (argv[n][0] == '-' && argv[n][1] != 0)
@@ -126,7 +128,7 @@ int main(int argc, const char **argv)
     run = 0;
     while (y < outh)
     {
-        if (x < width && y < height)    
+        if (x < width && y < height)
         {
             cell = bits[y][x];
             if (inverse) cell ^= (PBM_BLACK ^ PBM_WHITE);
@@ -137,11 +139,11 @@ int main(int argc, const char **argv)
         {
             ++run;
             if (run > MAXRUNLENGTH)
-            {       
+            {
                 fputc(0x20 + MAXRUNLENGTH, ofP);
                 fputc(0x20, ofP);
                 run -= MAXRUNLENGTH;
-            }   
+            }
         }
         else    /* change */
         {
@@ -166,5 +168,8 @@ int main(int argc, const char **argv)
     fputc(0x47, ofP);
     fputc(0x4E, ofP);
     pm_close(ifP);
-    return 0;   
+    return 0;
 }
+
+
+
diff --git a/converter/pbm/pbmtocmuwm.c b/converter/pbm/pbmtocmuwm.c
index 983ea491..f166b5ba 100644
--- a/converter/pbm/pbmtocmuwm.c
+++ b/converter/pbm/pbmtocmuwm.c
@@ -67,18 +67,18 @@ main(int argc,
         inputFileName = argv[1];
     else
         inputFileName = "-";
-    
+
     ifP = pm_openr(inputFileName);
 
     pbm_readpbminit(ifP, &cols, &rows, &format);
     bitrow = pbm_allocrow_packed(cols);
 
     putinit(rows, cols);
-    
-    /* Convert PBM raster data to CMUWM and write */ 
+
+    /* Convert PBM raster data to CMUWM and write */
     for (row = 0; row < rows; ++row) {
         unsigned int const bytesPerRow = pbm_packed_bytes(cols);
-        unsigned char const padding = 
+        unsigned char const padding =
             (cols % 8 == 0) ? 0x00 : ((unsigned char) ~0 >> (cols % 8));
 
         unsigned int i;
@@ -95,7 +95,7 @@ main(int argc,
             bitrow[i] = ~bitrow[i];
 
         bitrow[bytesPerRow-1] |= padding;  /* Set row end pad bits */
-        
+
         bytesWritten = fwrite(bitrow, 1, bytesPerRow, stdout);
         if (bytesWritten != bytesPerRow)
             pm_error("fwrite() failed to write CMU window manager bitmap");
@@ -104,3 +104,6 @@ main(int argc,
     pm_close(ifP);
     return 0;
 }
+
+
+
diff --git a/converter/pbm/pbmtodjvurle.c b/converter/pbm/pbmtodjvurle.c
index 83e99ec4..598abfbb 100644
--- a/converter/pbm/pbmtodjvurle.c
+++ b/converter/pbm/pbmtodjvurle.c
@@ -1,7 +1,7 @@
 /*
    Convert a PBM image into the DjVu Bitonal RLE format
    described in the csepdjvu(1) documentation
-  
+
    Copyright (c) 2004 Scott Pakin <scott+pbm@pakin.org>
 
    All rights reserved.
@@ -9,7 +9,7 @@
    Redistribution and use in source and binary forms, with or without
    modification, are permitted provided that the following conditions
    are met:
-   
+
    1. Redistributions of source code must retain the above copyright
       notice, this list of conditions and the following disclaimer.
    2. Redistributions in binary form must reproduce the above copyright
@@ -17,7 +17,7 @@
       documentation and/or other materials provided with the distribution.
    3. The name of the author may not be used to endorse or promote products
       derived from this software without specific prior written permission.
-   
+
    THIS SOFTWARE IS PROVIDED BY THE AUTHOR "AS IS" AND ANY EXPRESS OR
    IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
    OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
@@ -48,8 +48,9 @@ writebyte(FILE *        const ofP,
 }
 
 
+
 /* Write a run length to the RLE file. */
-static void 
+static void
 write_rle(FILE *   const rlefile,
           uint32_t const tallyArg) {
 
@@ -83,7 +84,7 @@ write_rle(FILE *   const rlefile,
 
 
 
-int 
+int
 main (int argc, const char * argv[]) {
 
     FILE * const rlefile = stdout; /* Generated Bitonal RLE file */
@@ -144,3 +145,6 @@ main (int argc, const char * argv[]) {
 
     return 0;
 }
+
+
+
diff --git a/converter/pbm/pbmtoepsi.c b/converter/pbm/pbmtoepsi.c
index 87985a1f..bfa87032 100644
--- a/converter/pbm/pbmtoepsi.c
+++ b/converter/pbm/pbmtoepsi.c
@@ -26,14 +26,15 @@
 */
 
 #include "pm_c_util.h"
-#include "pbm.h"
+#include "mallocvar.h"
 #include "shhopt.h"
+#include "pbm.h"
 
-struct cmdlineInfo {
+struct CmdlineInfo {
     /* All the information the user supplied in the command line,
        in a form easy for the program to use.
     */
-    const char *inputFileName;
+    const char * inputFileName;
 
     unsigned int dpiX;     /* horiz component of DPI option */
     unsigned int dpiY;     /* vert component of DPI option */
@@ -45,7 +46,7 @@ struct cmdlineInfo {
 
 
 static void
-parseDpi(char *         const dpiOpt, 
+parseDpi(char *         const dpiOpt,
          unsigned int * const dpiXP,
          unsigned int * const dpiYP) {
 
@@ -53,7 +54,7 @@ parseDpi(char *         const dpiOpt,
     unsigned int dpiX, dpiY;
 
     dpiX = strtol(dpiOpt, &dpistr2, 10);
-    if (dpistr2 == dpiOpt) 
+    if (dpistr2 == dpiOpt)
         pm_error("Invalid value for -dpi: '%s'.  Must be either number "
                  "or NxN ", dpiOpt);
     else {
@@ -64,7 +65,7 @@ parseDpi(char *         const dpiOpt,
             char * dpistr3;
 
             dpistr2++;  /* Move past 'x' */
-            dpiY = strtol(dpistr2, &dpistr3, 10);        
+            dpiY = strtol(dpistr2, &dpistr3, 10);
             if (dpistr3 != dpistr2 && *dpistr3 == '\0') {
                 *dpiXP = dpiX;
                 *dpiYP = dpiY;
@@ -77,23 +78,23 @@ parseDpi(char *         const dpiOpt,
 }
 
 
+
 static void
 parseCommandLine(int argc, const char ** const argv,
-                 struct cmdlineInfo * const cmdlineP) {
+                 struct CmdlineInfo * const cmdlineP) {
 /*----------------------------------------------------------------------------
    Note that the file spec array we return is stored in the storage that
    was passed to us as the argv array.
 -----------------------------------------------------------------------------*/
-    optEntry *option_def = malloc(100*sizeof(optEntry));
-        /* Instructions to OptParseOptions2 on how to parse our options.
-         */
+    optEntry * option_def;
     optStruct3 opt;
-
     unsigned int option_def_index;
 
     char * dpiOpt;
     unsigned int dpiOptSpec;
 
+    MALLOCARRAY_NOFAIL(option_def, 100);
+
     option_def_index = 0;   /* incremented by OPTENTRY */
     OPTENT3(0, "bbonly",     OPT_FLAG,   NULL, &cmdlineP->bbonly,        0);
     OPTENT3(0, "verbose",    OPT_FLAG,   NULL, &cmdlineP->verbose,       0);
@@ -103,19 +104,19 @@ parseCommandLine(int argc, const char ** const argv,
     opt.short_allowed = FALSE;  /* We have no short (old-fashioned) options */
     opt.allowNegNum = FALSE;  /* We have no parms that are negative numbers */
 
-    pm_optParseOptions3(&argc, (char **)argv, opt, sizeof(opt), 0);
+    pm_optParseOptions4(&argc, argv, opt, sizeof(opt), 0);
         /* Uses and sets argc, argv, and some of *cmdlineP and others. */
-    
+
 
     if (dpiOptSpec)
         parseDpi(dpiOpt, &cmdlineP->dpiX, &cmdlineP->dpiY);
     else
         cmdlineP->dpiX = cmdlineP->dpiY = 72;
-    
+
     if ((argc-1) > 1)
         pm_error("Too many arguments (%d).  Only argument is input file name",
                  argc-1);
-    
+
     if (argc-1 == 0)
         cmdlineP->inputFileName = "-";
     else
@@ -125,7 +126,7 @@ parseCommandLine(int argc, const char ** const argv,
 
 
 static void
-findPrincipalImage(bit **         const bits, 
+findPrincipalImage(bit **         const bits,
                    unsigned int   const rows,
                    unsigned int   const cols,
                    unsigned int * const topP,
@@ -151,25 +152,25 @@ findPrincipalImage(bit **         const bits,
     bottom = 0;
     left   = cols;
     right  = 0;
- 
+
     for (row = 0; row < rows; ++row) {
         unsigned int col;
         for (col = 0; col < cols; ++col) {
             if (bits[row][col] == PBM_BLACK) {
-                if (row < top) 
+                if (row < top)
                     top = row;
-                if (row > bottom) 
+                if (row > bottom)
                     bottom = row;
-                if (col < left) 
+                if (col < left)
                     left = col;
-                if (col > right) 
+                if (col > right)
                     right = col;
             }
         }
     }
 
     if (top > bottom) {
-        /* No black pixels encountered */ 
+        /* No black pixels encountered */
         pm_message("Blank page");
         top    = 0;
         left   = 0;
@@ -194,8 +195,8 @@ outputBoundingBox(int const top, int const bottom,
     float const xScale = 72.0 / dpiX;
     float const yScale = 72.0 / dpiY;
 
-    printf("%%%%BoundingBox: %d %d %d %d\n", 
-           ROUND(left*xScale),  ROUND((rows - bottom)*yScale), 
+    printf("%%%%BoundingBox: %d %d %d %d\n",
+           ROUND(left*xScale),  ROUND((rows - bottom)*yScale),
            ROUND(right*xScale), ROUND((rows - top)*yScale));
 }
 
@@ -234,7 +235,7 @@ eightPixels(bit ** const bits,
 int
 main(int argc, const char * argv[]) {
 
-    struct cmdlineInfo cmdline;
+    struct CmdlineInfo cmdline;
     FILE * ifP;
     bit ** bits;
     int rows, cols;
@@ -244,7 +245,7 @@ main(int argc, const char * argv[]) {
         */
 
     pm_proginit(&argc, argv);
-    
+
     parseCommandLine(argc, argv, &cmdline);
 
     ifP = pm_openr(cmdline.inputFileName);
@@ -255,12 +256,12 @@ main(int argc, const char * argv[]) {
 
     printf("%%!PS-Adobe-2.0 EPSF-1.2\n");
 
-    outputBoundingBox(top, bottom, left, right, rows, 
+    outputBoundingBox(top, bottom, left, right, rows,
                       cmdline.dpiX, cmdline.dpiY);
 
     if (!cmdline.bbonly) {
         int row;
-        printf("%%%%BeginPreview: %d %d 1 %d\n", 
+        printf("%%%%BeginPreview: %d %d 1 %d\n",
                right - left + 1, bottom - top + 1, bottom - top + 1);
 
         for (row = top; row <= bottom; row++) {
@@ -274,7 +275,7 @@ main(int argc, const char * argv[]) {
                 if (outChars == 72) {
                     printf("\n%% ");
                     outChars = 2;
-                }  
+                }
 
                 printf("%02x", eightPixels(bits, row, col, cols));
                 outChars += 2;
@@ -287,3 +288,6 @@ main(int argc, const char * argv[]) {
     }
     return 0;
 }
+
+
+
diff --git a/converter/pbm/pbmtoepson.c b/converter/pbm/pbmtoepson.c
index 122a438f..293167ac 100644
--- a/converter/pbm/pbmtoepson.c
+++ b/converter/pbm/pbmtoepson.c
@@ -1,7 +1,7 @@
 /* pbmtoeps.c - read a PBM image and produce Epson graphics
 **
 ** Copyright (C) 1990 by John Tiller (tiller@galois.msfc.nasa.gov)
-**			 and Jef Poskanzer.
+**                       and Jef Poskanzer.
 **
 ** Permission to use, copy, modify, and distribute this software and its
 ** documentation for any purpose and without fee is hereby granted, provided
@@ -42,12 +42,12 @@ struct CmdlineInfo {
 
 
 static void
-parseCommandLine(int                  argc, 
+parseCommandLine(int                  argc,
                  const char **        argv,
                  struct CmdlineInfo * cmdlineP ) {
 /*----------------------------------------------------------------------------
    Parse program command line described in Unix standard form by argc
-   and argv.  Return the information in the options as *cmdlineP.  
+   and argv.  Return the information in the options as *cmdlineP.
 
    If command line is internally inconsistent (invalid options, etc.),
    issue error message to stderr and abort program.
@@ -55,11 +55,8 @@ parseCommandLine(int                  argc,
    Note that the strings we return are stored in the storage that
    was passed to us as the argv array.  We also trash *argv.
 -----------------------------------------------------------------------------*/
-    optEntry *option_def;
-        /* Instructions to pm_optParseOptions3 on how to parse our options.
-         */
+    optEntry * option_def;
     optStruct3 opt;
-
     unsigned int option_def_index;
 
     char * protocol;
@@ -82,7 +79,7 @@ parseCommandLine(int                  argc,
     opt.short_allowed = FALSE;  /* We have no short (old-fashioned) options */
     opt.allowNegNum = FALSE;  /* We have no parms that are negative numbers */
 
-    pm_optParseOptions3( &argc, (char **)argv, opt, sizeof(opt), 0);
+    pm_optParseOptions4( &argc, argv, opt, sizeof(opt), 0);
         /* Uses and sets argc, argv, and some of *cmdlineP and others. */
 
 
@@ -107,7 +104,7 @@ parseCommandLine(int                  argc,
                      "Only recognized values are 'escp9' and 'escp'",
                      protocol);
     }
-    
+
     if (adjacentSpec && nonadjacentSpec)
         pm_error("You can't specify both -adjacent and -nonadjacent");
     else if (adjacentSpec)
@@ -143,7 +140,7 @@ lineWidth(const bit ** const stripeBits,
 -----------------------------------------------------------------------------*/
     unsigned int col;
     unsigned int endSoFar;
-    
+
     endSoFar = 0;
 
     for (col = 0; col < cols; ++ col) {
@@ -177,14 +174,14 @@ printStripe(const bit ** const stripeBits,
 
     /* Print header of Select Bit Image command */
     printf("%c%c%c%c%c", esc, '*', m, cols % 256, cols / 256);
-    
+
     /* Print the data part of the Select Bit Image command */
     for (col = 0; col < cols; ++col) {
         unsigned int stripeRow;
         int val;
-        
+
         val = 0;
-        for (stripeRow = 0; stripeRow < stripeRows; ++stripeRow) 
+        for (stripeRow = 0; stripeRow < stripeRows; ++stripeRow)
             if (stripeBits[stripeRow][col] == PBM_BLACK)
                 val |= (1 << (8-1-stripeRow));
         putchar(val);
@@ -213,7 +210,7 @@ computeM(enum epsonProtocol const protocol,
             }
         }
         break;
-    case 60: 
+    case 60:
         if (adjacence == ADJACENT_NO)
             pm_error("You can't print at %u dpi "
                      "with adjacent dot printing", dpi);
@@ -236,7 +233,7 @@ computeM(enum epsonProtocol const protocol,
         break;
     case 72:
         if (protocol != ESCP9)
-            pm_error("%u dpi is possible only with the ESC/P 9-pin protocol", 
+            pm_error("%u dpi is possible only with the ESC/P 9-pin protocol",
                      dpi);
         if (adjacence == ADJACENT_NO)
             pm_error("You can't print at %u dpi "
@@ -251,7 +248,7 @@ computeM(enum epsonProtocol const protocol,
         break;
     case 144:
         if (protocol != ESCP9)
-            pm_error("%u dpi is possible only with the ESC/P 9-pin protocol", 
+            pm_error("%u dpi is possible only with the ESC/P 9-pin protocol",
                      dpi);
         if (adjacence == ADJACENT_NO)
             pm_error("You can't print at %u dpi "
@@ -273,13 +270,13 @@ convertToEpson(const bit **       const bits,
                enum epsonProtocol const protocol,
                unsigned int       const dpi,
                enum adjacence     const adjacence) {
-    
+
     unsigned int const rowsPerStripe = 8;
     unsigned int const stripeCt = (rows + rowsPerStripe-1) / rowsPerStripe;
 
     unsigned int stripe;
     char m;
-    
+
     computeM(protocol, dpi, adjacence, &m);
 
     /* Change line spacing to 8/72 inches. */
@@ -292,10 +289,10 @@ convertToEpson(const bit **       const bits,
 
     for (stripe = 0; stripe < stripeCt; ++stripe) {
         const bit ** const stripeBits = &bits[stripe*rowsPerStripe];
-        unsigned int const stripeRows = 
+        unsigned int const stripeRows =
             MIN(rowsPerStripe, rows - stripe * rowsPerStripe);
             /* Number of rows in this stripe (8 for all but bottom stripe) */
-        
+
         unsigned int const endcol = lineWidth(stripeBits, cols, stripeRows);
             /* Column where right margin (contiguous white area at right
                end of stripe) begins.  Zero if entire stripe is white.
@@ -332,10 +329,13 @@ main(int argc, const char ** argv) {
 
     pm_close(ifP);
 
-    convertToEpson(bits, cols, rows, 
+    convertToEpson(bits, cols, rows,
                    cmdline.protocol, cmdline.dpi, cmdline.adjacence);
 
     pbm_freearray(bits, rows);
 
     return 0;
 }
+
+
+
diff --git a/converter/pbm/pbmtoescp2.c b/converter/pbm/pbmtoescp2.c
index 6f284f3c..d4d98388 100644
--- a/converter/pbm/pbmtoescp2.c
+++ b/converter/pbm/pbmtoescp2.c
@@ -18,6 +18,7 @@
 *
 *  ESC/P Reference Manual (1997)
 *  ftp://download.epson-europe.com/pub/download/182/epson18162eu.zip
+*  See Part 1 "ESC ." Print Raster Graphics
 */
 
 #include <string.h>
@@ -28,7 +29,7 @@
 #include "runlength.h"
 #include "pbm.h"
 
-
+#define MAXCOLS (127 * 256 + 255)  /* Limit in official Epson manual */
 
 static char const esc = 033;
 
@@ -48,28 +49,31 @@ parseCommandLine(int argc, const char ** argv,
                  struct CmdlineInfo *cmdlineP) {
 
     optStruct3 opt;
-    unsigned int option_def_index = 0;
-    optEntry * option_def = malloc(100*sizeof(optEntry));
+    unsigned int option_def_index;
+    optEntry * option_def;
 
     unsigned int compressSpec, resolutionSpec, stripeHeightSpec,
                  rawSpec, formfeedSpec;
 
+    MALLOCARRAY(option_def, 100);
+
+    option_def_index = 0;
     opt.opt_table = option_def;
     opt.short_allowed = FALSE;
     opt.allowNegNum = FALSE;
-    OPTENT3(0, "compress",     OPT_UINT,    &cmdlineP->compress,    
+    OPTENT3(0, "compress",     OPT_UINT,    &cmdlineP->compress,
             &compressSpec,    0);
-    OPTENT3(0, "resolution",   OPT_UINT,    &cmdlineP->resolution,  
+    OPTENT3(0, "resolution",   OPT_UINT,    &cmdlineP->resolution,
             &resolutionSpec,  0);
-    OPTENT3(0, "stripeheight", OPT_UINT,    &cmdlineP->stripeHeight,  
+    OPTENT3(0, "stripeheight", OPT_UINT,    &cmdlineP->stripeHeight,
             &stripeHeightSpec, 0);
-    OPTENT3(0, "raw",          OPT_FLAG,    NULL,  
+    OPTENT3(0, "raw",          OPT_FLAG,    NULL,
             &rawSpec,    0);
-    OPTENT3(0, "formfeed",     OPT_FLAG,    NULL,  
+    OPTENT3(0, "formfeed",     OPT_FLAG,    NULL,
             &formfeedSpec,    0);
-    
-    pm_optParseOptions3(&argc, (char **)argv, opt, sizeof(opt), 0);
-    
+
+    pm_optParseOptions4(&argc, argv, opt, sizeof(opt), 0);
+
     if (argc-1 > 1)
         pm_error("Too many arguments: %d.  "
                  "Only argument is the filename", argc-1);
@@ -155,7 +159,7 @@ main(int argc, const char * argv[]) {
     unsigned char * bitrow[256];
     unsigned char * compressedData;
     struct CmdlineInfo cmdline;
-    
+
     pm_proginit(&argc, argv);
 
     parseCommandLine(argc, argv, &cmdline);
@@ -164,7 +168,7 @@ main(int argc, const char * argv[]) {
 
     pbm_readpbminit(ifP, &cols, &rows, &format);
 
-    if (cols / 256 > 127)  /* Limit in official Epson manual */
+    if (cols > MAXCOLS)
         pm_error("Image width is too large");
 
     outColByteCt = pbm_packed_bytes(cols);
@@ -229,7 +233,7 @@ main(int argc, const char * argv[]) {
         }
     }
 
-    free(inBuff); 
+    free(inBuff);
     free(compressedData);
     pm_close(ifP);
 
@@ -244,3 +248,6 @@ main(int argc, const char * argv[]) {
 
     return 0;
 }
+
+
+
diff --git a/converter/pbm/pbmtog3.c b/converter/pbm/pbmtog3.c
index f034b466..ac190d22 100644
--- a/converter/pbm/pbmtog3.c
+++ b/converter/pbm/pbmtog3.c
@@ -57,11 +57,11 @@ parseCommandLine(int argc, const char ** const argv,
     optEntry * option_def;
         /* Instructions to OptParseOptions2 on how to parse our options.  */
     optStruct3 opt;
+    unsigned int option_def_index;
+
     unsigned int nofixedwidth;
     unsigned int align8, align16;
 
-    unsigned int option_def_index;
-
     MALLOCARRAY_NOFAIL(option_def, 100);
 
     option_def_index = 0;   /* incremented by OPTENTRY */
@@ -84,7 +84,7 @@ parseCommandLine(int argc, const char ** const argv,
     opt.short_allowed = false;  /* We have no short (old-fashioned) options */
     opt.allowNegNum = true;  /* We may have parms that are negative numbers */
 
-    pm_optParseOptions3(&argc, (char **)argv, opt, sizeof(opt), 0);
+    pm_optParseOptions4(&argc, argv, opt, sizeof(opt), 0);
         /* Uses and sets argc, argv, and some of *cmdlineP and others. */
 
     free(option_def);
@@ -145,7 +145,7 @@ flushBuffer(struct OutStream * const outP) {
         outbytes = pm_bigendFromUint32(
                    buffer.intBuffer << (fullBuffer - buffer.bitCount));
         if (outP->reverseBits)
-    	reversebuffer((unsigned char *)&outbytes, bytesToWrite);
+        reversebuffer((unsigned char *)&outbytes, bytesToWrite);
         rc = fwrite((unsigned char *)&outbytes, 1, bytesToWrite, outP->fp);
         if (rc != bytesToWrite)
             pm_error("Output error");
@@ -153,6 +153,7 @@ flushBuffer(struct OutStream * const outP) {
 }
 
 
+
 #if 1==0
 static void
 putbitsDump(struct OutStream * const outP,
diff --git a/converter/pbm/pbmtogem.c b/converter/pbm/pbmtogem.c
index 4fd30e92..64bcb761 100644
--- a/converter/pbm/pbmtogem.c
+++ b/converter/pbm/pbmtogem.c
@@ -32,7 +32,7 @@
 *
 *  Deficiencies:
 *  Compression of repeated scanlines not added
-*  
+*
 *       Johann Haider (jh@fortec.tuwien.ac.at)
 *
 * 94/01/31 Andreas Schwab (schwab@ls5.informatik.uni-dortmund.de)
@@ -85,6 +85,8 @@ putinit (int const rows, int const cols)
   linerepeat = -1;
 }
 
+
+
 static void
 putitem( )
     {
@@ -119,6 +121,7 @@ putstring ( unsigned char *p, int n)
 }
 
 
+
 static void
 flushrow( )
     {
@@ -173,7 +176,7 @@ flushrow( )
                 p++;
                 col--;
             }
-    }           
+    }
     if (p > outp)
          putstring (outp, p-outp);
     if (ferror (stdout))
@@ -181,6 +184,7 @@ flushrow( )
 }
 
 
+
 static void
 putrow( )
 {
@@ -203,6 +207,7 @@ putrow( )
 }
 
 
+
 int
 main( int argc, char* argv[])
     {
@@ -246,3 +251,6 @@ main( int argc, char* argv[])
 
     exit( 0 );
     }
+
+
+
diff --git a/converter/pbm/pbmtoibm23xx.c b/converter/pbm/pbmtoibm23xx.c
index 3f1f9679..86103ba6 100644
--- a/converter/pbm/pbmtoibm23xx.c
+++ b/converter/pbm/pbmtoibm23xx.c
@@ -120,7 +120,7 @@ parseCommandLine(int argc, char ** const argv,
 
 
 /* Read all pbm images from a filehandle and print them */
-static void 
+static void
 process_handle(FILE *        const fh,
                unsigned char const graph_mode,
                unsigned int  const passes) {
@@ -155,7 +155,7 @@ process_handle(FILE *        const fh,
             for(bitline = 0; bitline < 8; ++bitline)
                 for(pass = 0; pass < passes; ++pass)
                     /* don't read beyond the end of the image if
-                       height is not a multiple of passes 
+                       height is not a multiple of passes
                     */
                     if(y + bitline * passes + pass < rows) {
                         pbm_readpbmrow(fh, row, cols, format);
@@ -188,7 +188,7 @@ process_handle(FILE *        const fh,
 
 
 
-int 
+int
 main(int argc,char **argv) {
 
   struct cmdlineInfo cmdline;
@@ -212,3 +212,6 @@ main(int argc,char **argv) {
 
   return 0;
 }
+
+
+
diff --git a/converter/pbm/pbmtolj.c b/converter/pbm/pbmtolj.c
index 3cd76703..1805206b 100644
--- a/converter/pbm/pbmtolj.c
+++ b/converter/pbm/pbmtolj.c
@@ -27,12 +27,14 @@
 ** implied warranty.
 */
 
+#include <stdbool.h>
+#include <assert.h>
+#include <string.h>
+
 #include "pm_c_util.h"
 #include "pbm.h"
 #include "shhopt.h"
 #include "mallocvar.h"
-#include <string.h>
-#include <assert.h>
 
 static char *rowBuffer, *prevRowBuffer, *packBuffer, *deltaBuffer;
 static int rowBufferSize, rowBufferIndex, prevRowBufferIndex;
@@ -43,7 +45,7 @@ static int item, bitsperitem, bitshift;
 
 
 
-struct cmdlineInfo {
+struct CmdlineInfo {
     /* All the information the user supplied in the command line,
        in a form easy for the program to use.
     */
@@ -58,18 +60,16 @@ struct cmdlineInfo {
 
 
 static void
-parseCommandLine(int argc, char ** argv,
-                 struct cmdlineInfo * const cmdlineP) {
+parseCommandLine(int argc, const char ** argv,
+                 struct CmdlineInfo * const cmdlineP) {
 /*----------------------------------------------------------------------------
    Note that the file spec array we return is stored in the storage that
    was passed to us as the argv array.
 -----------------------------------------------------------------------------*/
     optEntry *option_def;
-        /* Instructions to OptParseOptions3 on how to parse our options.
-         */
     optStruct3 opt;
-
     unsigned int option_def_index;
+
     unsigned int dpiSpec, copiesSpec, compressSpec;
 
     MALLOCARRAY(option_def, 100);
@@ -91,10 +91,10 @@ parseCommandLine(int argc, char ** argv,
             &compressSpec, 0);
 
     opt.opt_table = option_def;
-    opt.short_allowed = FALSE;  /* We have no short (old-fashioned) options */
-    opt.allowNegNum = FALSE;  /* We may have parms that are negative numbers */
+    opt.short_allowed = false;  /* We have no short (old-fashioned) options */
+    opt.allowNegNum = false;  /* We may have parms that are negative numbers */
 
-    pm_optParseOptions3(&argc, argv, opt, sizeof(opt), 0);
+    pm_optParseOptions4(&argc, argv, opt, sizeof(opt), 0);
         /* Uses and sets argc, argv, and some of *cmdlineP and others. */
 
     if (argc-1 == 0)
@@ -144,7 +144,7 @@ freeBuffers(void) {
 
 
 static void
-putinit(struct cmdlineInfo const cmdline) {
+putinit(struct CmdlineInfo const cmdline) {
     if (!cmdline.noreset) {
         /* Printer reset. */
         printf("\033E");
@@ -352,9 +352,9 @@ findRightmostBlackCol(const bit *    const bitrow,
     for (i = cols - 1; i >= 0 && bitrow[i] == PBM_WHITE; --i);
 
     if (i < 0)
-        *allWhiteP = TRUE;
+        *allWhiteP = true;
     else {
-        *allWhiteP = FALSE;
+        *allWhiteP = false;
         *blackColP = i;
     }
 }
@@ -495,7 +495,7 @@ printRow(void) {
 
 static void
 doPage(FILE *             const ifP,
-       struct cmdlineInfo const cmdline) {
+       struct CmdlineInfo const cmdline) {
 
     bit * bitrow;
     int rows, cols, format, row;
@@ -541,19 +541,19 @@ doPage(FILE *             const ifP,
 
 
 int
-main(int argc, char * argv[]) {
+main(int argc, const char ** argv) {
 
-    struct cmdlineInfo cmdline;
+    struct CmdlineInfo cmdline;
     FILE * ifP;
     int eof;
 
-    pbm_init(&argc, argv);
+    pm_proginit(&argc, argv);
 
     parseCommandLine(argc, argv, &cmdline);
 
     ifP = pm_openr(cmdline.inputFilename);
 
-    eof = FALSE;
+    eof = false;
     while (!eof) {
         doPage(ifP, cmdline);
         pbm_nextimage(ifP, &eof);
diff --git a/converter/pbm/pbmtoln03.c b/converter/pbm/pbmtoln03.c
index 235429cd..cf1f7959 100644
--- a/converter/pbm/pbmtoln03.c
+++ b/converter/pbm/pbmtoln03.c
@@ -268,3 +268,4 @@ main (int argc, char **argv) {
 }
 
 
+
diff --git a/converter/pbm/pbmtolps.c b/converter/pbm/pbmtolps.c
index d974fcb2..e1e057f8 100644
--- a/converter/pbm/pbmtolps.c
+++ b/converter/pbm/pbmtolps.c
@@ -69,9 +69,7 @@ parseCommandLine(int                        argc,
    and argv.  Return the information in the options as *cmdlineP.
 -----------------------------------------------------------------------------*/
     optEntry * option_def;  /* malloc'ed */
-        /* Instructions to OptParseOptions3 on how to parse our options.  */
     optStruct3 opt;
-
     unsigned int option_def_index;
 
     MALLOCARRAY_NOFAIL(option_def, 100);
@@ -86,7 +84,7 @@ parseCommandLine(int                        argc,
     opt.short_allowed = FALSE;  /* We have no short (old-fashioned) options */
     opt.allowNegNum = FALSE;  /* We have no parms that are negative numbers */
 
-    pm_optParseOptions3(&argc, (char **)argv, opt, sizeof(opt), 0);
+    pm_optParseOptions4(&argc, argv, opt, sizeof(opt), 0);
         /* Uses and sets argc, argv, and some of *cmdlineP and others. */
 
     if (cmdlineP->dpiSpec)
@@ -251,3 +249,6 @@ main(int argc, const char *argv[]) {
 
     return 0;
 }
+
+
+
diff --git a/converter/pbm/pbmtomacp.c b/converter/pbm/pbmtomacp.c
index 4897e6d0..0a6dcf93 100644
--- a/converter/pbm/pbmtomacp.c
+++ b/converter/pbm/pbmtomacp.c
@@ -73,7 +73,6 @@ parseCommandLine(int                        argc,
    and argv.  Return the information in the options as *cmdlineP.
 -----------------------------------------------------------------------------*/
     optEntry * option_def;  /* malloc'ed */
-        /* Instructions to OptParseOptions3 on how to parse our options.  */
     optStruct3 opt;
 
     unsigned int norleSpec;
@@ -98,7 +97,7 @@ parseCommandLine(int                        argc,
     opt.short_allowed = FALSE;  /* We have no short (old-fashioned) options */
     opt.allowNegNum = FALSE;  /* We have no parms that are negative numbers */
 
-    pm_optParseOptions3(&argc, (char **)argv, opt, sizeof(opt), 0);
+    pm_optParseOptions4(&argc, argv, opt, sizeof(opt), 0);
         /* Uses and sets argc, argv, and some of *cmdlineP and others. */
 
     cmdlineP->norle = norleSpec;
@@ -441,3 +440,5 @@ main(int argc, const char *argv[]) {
     return 0;
 }
 
+
+
diff --git a/converter/pbm/pbmtomatrixorbital.c b/converter/pbm/pbmtomatrixorbital.c
index 41f8e260..f91fd5ff 100644
--- a/converter/pbm/pbmtomatrixorbital.c
+++ b/converter/pbm/pbmtomatrixorbital.c
@@ -14,7 +14,7 @@
 
 
 static void
-generateMo(FILE *       const ofP, 
+generateMo(FILE *       const ofP,
            bit **       const bits,
            unsigned int const cols,
            unsigned int const rows) {
@@ -28,7 +28,7 @@ generateMo(FILE *       const ofP,
         unsigned int row;
         unsigned int outbitpos;
         unsigned char outchar;
-        
+
         outbitpos = 0;  /* Start at 1st bit of 1st output byte */
 
         for (row = 0; row < rows; ++row) {
@@ -38,7 +38,7 @@ generateMo(FILE *       const ofP,
 
             outchar |= bits[row][col] << outbitpos;
 
-            if (outbitpos == 7) 
+            if (outbitpos == 7)
                 /* We filled up a byte.  Output it. */
                 fputc(outchar, ofP);
 
@@ -65,13 +65,13 @@ main(int argc, const char ** argv) {
     if (argc-1 > 1)
         pm_error("Too many arguments (%u).  The only valid argument is an "
                  "input file name.", argc-1);
-    else if (argc-1 == 1) 
+    else if (argc-1 == 1)
         inputFilename = argv[1];
     else
         inputFilename = "-";
 
     ifP = pm_openr(inputFilename);
-    
+
     bits = pbm_readpbm(ifP, &cols, &rows);
 
     if (rows > 255)
@@ -80,7 +80,7 @@ main(int argc, const char ** argv) {
         pm_error("Image is too wide:  %u cols.  Max width: 255 cols", cols);
 
     generateMo(stdout, bits, cols, rows);
-    
+
     pm_close(ifP);
 
     pbm_freearray(bits, rows);
diff --git a/converter/pbm/pbmtomda.c b/converter/pbm/pbmtomda.c
index 3ad51499..f684276f 100644
--- a/converter/pbm/pbmtomda.c
+++ b/converter/pbm/pbmtomda.c
@@ -1,7 +1,6 @@
-
 /***************************************************************************
 
-    PBMTOMDA: Convert portable bitmap to Microdesign area
+    PBMTOMDA: Convert PBM to Microdesign area
     Copyright (C) 1999,2004 John Elliott <jce@seasip.demon.co.uk>
 
     This program is free software; you can redistribute it and/or modify
@@ -20,31 +19,78 @@
 
 ******************************************************************************/
 
+#include <stdbool.h>
+#include <assert.h>
 #include <stdio.h>
 #include <string.h>
 
 #include "pbm.h"
 #include "mallocvar.h"
+#include "shhopt.h"
+
+struct CmdlineInfo {
+    /* All the information the user supplied in the command line,
+       in a form easy for the program to use.
+    */
+    const char * inputFileNm;
+    unsigned int dscale;
+    unsigned int invert;
+};
+
+
+static void
+parseCommandLine(int argc, const char ** argv,
+                 struct CmdlineInfo * const cmdlineP) {
+/*----------------------------------------------------------------------------
+   Note that the file spec array we return is stored in the storage that
+   was passed to as as the argv array.
+-----------------------------------------------------------------------------*/
+    optEntry * option_def;
+    optStruct3 opt;
+
+    unsigned int option_def_index;
+
+    MALLOCARRAY_NOFAIL(option_def, 100);
+
+    option_def_index = 0;   /* incremented by OPTENT3 */
+    OPTENT3(0,   "dscale", OPT_FLAG,  NULL, &cmdlineP->dscale,   0);
+    OPTENT3(0,   "invert", OPT_FLAG,  NULL, &cmdlineP->invert,   0);
+
+    opt.opt_table     = option_def;
+    opt.short_allowed = false; /* We have no short (old-fashioned) options */
+    opt.allowNegNum   = false; /* We have no parms that are negative numbers */
+
+    pm_optParseOptions4(&argc, argv, opt, sizeof(opt), 0);
+        /* Uses and sets argc, argv, and some of *cmdlineP and others */
+
+    if (argc-1 < 1)
+        cmdlineP->inputFileNm = "-";
+    else if (argc-1 == 1)
+        cmdlineP->inputFileNm = argv[1];
+    else
+        pm_error("Program takes at most one argument:  input file name");
+
+    free(option_def);
+}
+
 
-/* I'm being somewhat conservative in the PBM -> MDA translation. I output 
+
+/* I'm being somewhat conservative in the PBM -> MDA translation. I output
  * only the MD2 format and don't allow RLE over the ends of lines.
  */
 
-typedef unsigned char mdbyte;
-
-static FILE *infile;
-static mdbyte header[128];
-static int bInvert = 0;
-static int bScale  = 0;
+typedef unsigned char Mdbyte;
 
 /* Encode 8 pixels as a byte */
 
-static mdbyte 
-encode(bit ** const bits, int const row, int const col)
-{
+static Mdbyte
+encode(bit ** const bits,
+       int    const row,
+       int    const col) {
+
     int n;
     int mask;
-    mdbyte b;
+    Mdbyte b;
 
     mask = 0x80;   /* initial value */
     b = 0;  /* initial value */
@@ -56,131 +102,110 @@ encode(bit ** const bits, int const row, int const col)
     return b;
 }
 
-/* Translate a pbm to MD2 format, one row at a time */
 
-static void 
-do_translation(bit ** const bits, 
-               int    const nOutCols, 
-               int    const nOutRows,
-               int    const nInRows)
-{
-    int row;
-    mdbyte *mdrow;  /* malloc'ed */
 
-    int const step = bScale ? 2 : 1;
+static void
+doTranslation(bit **       const bits,
+              unsigned int const nOutCols,
+              unsigned int const nOutRows,
+              unsigned int const nInRows,
+              bool         const mustInvert,
+              bool         const mustScale) {
+/*----------------------------------------------------------------------------
+  Translate a pbm to MD2 format, one row at a time
+-----------------------------------------------------------------------------*/
+    unsigned int const step = mustScale ? 2 : 1;
+
+    unsigned int row;
+    Mdbyte * mdrow;  /* malloc'ed */
 
     MALLOCARRAY(mdrow, nOutCols);
 
     if (mdrow == NULL)
-        pm_error("Not enough memory for conversion.");
+        pm_error("Unable to allocate memory for %u columns", nOutCols);
 
-    for (row = 0; row < nOutRows; row+=step)
-    {
-        int col;
-        int x1;
+    for (row = 0; row < nOutRows; row += step) {
+        unsigned int col;
 
         /* Encode image into non-compressed bitmap */
         for (col = 0; col < nOutCols; ++col) {
-            mdbyte b;
+            Mdbyte b;
 
             if (row < nInRows)
-                b = encode(bits, row, col*8);
+                b = encode(bits, row, col * 8);
             else
                 b = 0xff;  /* All black */
 
-            mdrow[col] = bInvert ? b : ~b;
+            mdrow[col] = mustInvert ? b : ~b;
         }
 
         /* Encoded. Now RLE it */
-        for (col = 0; col < nOutCols; )
-        {
-            mdbyte const b = mdrow[col];
+        for (col = 0; col < nOutCols; ) {
+            Mdbyte const b = mdrow[col];
 
-            if (b != 0xFF && b != 0) /* Normal byte */
-            {
+            if (b != 0xFF && b != 0) {
+                /* Normal byte */
                 putchar(b);
                 ++col;
-            }
-            else    /* RLE a run of 0s or 0xFFs */
-            {
-                for (x1 = col; x1 < nOutCols; x1++)
-                {
+            } else {
+                /* RLE a run of 0s or 0xFFs */
+
+                unsigned int x1;
+
+                for (x1 = col; x1 < nOutCols; ++x1) {
                     if (mdrow[x1] != b) break;
+                    assert(x1 >= col);
                     if (x1 - col > 256) break;
                 }
+                assert(x1 >= col);
                 x1 -= col;    /* x1 = no. of repeats */
                 if (x1 == 256) x1 = 0;
                 putchar(b);
                 putchar(x1);
-                col += x1;        
-            }   
+                col += x1;
+            }
         }
     }
     free(mdrow);
 }
 
 
-static void usage(char *s)
-{        
-    printf("pbmtomda v1.01, Copyright (C) 1999,2004 John Elliott <jce@seasip.demon.co.uk>\n"
-         "This program is redistributable under the terms of the GNU General Public\n"
-                 "License, version 2 or later.\n\n"
-                 "Usage: %s [ -d ] [ -i ] [ -- ] [ infile ]\n\n"
-                 "-d: Halve height (to compensate for the PCW aspect ratio)\n"
-                 "-i: Invert colors\n"
-                 "--: No more options (use if filename begins with a dash)\n",
-        s);
 
-    exit(0);
-}
+int
+main(int argc, const char ** argv) {
+
+    const char * const headerValue = ".MDAMicroDesignPCWv1.00\r\npbm2mda\r\n";
 
-int main(int argc, char **argv)
-{
-    int nOutRowsUnrounded;  /* Before rounding up to multiple of 4 */
-    int nOutCols, nOutRows;
+    struct CmdlineInfo cmdline;
+    FILE * ifP;
+    unsigned int nOutRowsUnrounded;  /* Before rounding up to multiple of 4 */
+    unsigned int nOutCols, nOutRows;
     int nInCols, nInRows;
-    bit **bits;
+    bit ** bits;
+    Mdbyte header[128];
     int rc;
 
-    int n, optstop = 0;
-    char *fname = NULL;
+    pm_proginit(&argc, argv);
 
-    pbm_init(&argc, argv);
+    parseCommandLine(argc, argv, &cmdline);
 
     /* Output v2-format MDA images. Simulate MDA header...
-     * 2004-01-11: Hmm. Apparently some (but not all) MDA-reading 
-     * programs insist on the program identifier being exactly 
+     * 2004-01-11: Hmm. Apparently some (but not all) MDA-reading
+     * programs insist on the program identifier being exactly
      * 'MicroDesignPCW'. The spec does not make this clear. */
-    strcpy((char*) header, ".MDAMicroDesignPCWv1.00\r\npbm2mda\r\n");
-
-    for (n = 1; n < argc; n++)
-    {
-        if (argv[n][0] == '-' && !optstop)
-        {   
-            if (argv[n][1] == 'd' || argv[n][1] == 'D') bScale = 1;
-            if (argv[n][1] == 'i' || argv[n][1] == 'I') bInvert = 1;
-            if (argv[n][1] == 'h' || argv[n][1] == 'H') usage(argv[0]);
-            if (argv[n][1] == '-' && argv[n][2] == 0 && !fname)     /* "--" */
-            {
-                optstop = 1;
-            }
-            if (argv[n][1] == '-' && (argv[n][2] == 'h' || argv[n][2] == 'H')) usage(argv[0]);
-        }
-        else if (argv[n][0] && !fname)  /* Filename */
-        {
-            fname = argv[n];
-        }
-    }
+    memcpy(header + 0, headerValue, strlen(headerValue));
+    memset(header + strlen(headerValue),
+           0x00,
+           sizeof(header)-strlen(headerValue));
 
-    if (fname) infile = pm_openr(fname);
-    else       infile = stdin;
+    ifP = pm_openr(cmdline.inputFileNm);
 
-    bits = pbm_readpbm(infile, &nInCols, &nInRows);
-    
-    nOutRowsUnrounded = bScale ? nInRows/2 : nInRows;
+    bits = pbm_readpbm(ifP, &nInCols, &nInRows);
+
+    nOutRowsUnrounded = cmdline.dscale ? nInRows/2 : nInRows;
 
     nOutRows = ((nOutRowsUnrounded + 3) / 4) * 4;
-        /* MDA wants rows a multiple of 4 */   
+        /* MDA wants rows a multiple of 4 */
     nOutCols = nInCols / 8;
 
     rc = fwrite(header, 1, 128, stdout);
@@ -191,11 +216,15 @@ int main(int argc, char **argv)
     pm_writelittleshort(stdout, nOutRows);
     pm_writelittleshort(stdout, nOutCols);
 
-    do_translation(bits, nOutCols, nOutRows, nInRows);
+    doTranslation(bits, nOutCols, nOutRows, nInRows,
+                  !!cmdline.invert, !!cmdline.dscale);
 
-    pm_close(infile);
+    pm_close(ifP);
     fflush(stdout);
     pbm_freearray(bits, nInRows);
-    
+
     return 0;
 }
+
+
+
diff --git a/converter/pbm/pbmtomgr.c b/converter/pbm/pbmtomgr.c
index 0e529740..faa56d8f 100644
--- a/converter/pbm/pbmtomgr.c
+++ b/converter/pbm/pbmtomgr.c
@@ -33,7 +33,7 @@ putinit(unsigned int const rows,
     head._reserved = ' ';
     writtenCount = fwrite(&head, sizeof(head), 1, stdout);
     if (writtenCount != 1)
-        pm_error("fwrite() failed to write the MGR header.");    
+        pm_error("fwrite() failed to write the MGR header.");
 }
 
 
@@ -63,7 +63,7 @@ main(int argc,
         inputFileName = argv[1];
     else
         inputFileName = "-";
-    
+
     ifP = pm_openr(inputFileName);
 
     pbm_readpbminit(ifP, &cols, &rows, &format);
@@ -71,14 +71,14 @@ main(int argc,
         pm_error("Image width too large: %u (max: %u)", cols, maxDimension);
     if (rows > maxDimension)
         pm_error("Image height too large: %u (max: %u)", rows, maxDimension);
-    
+
     bitrow = pbm_allocrow_packed(cols);
     bytesPerRow = pbm_packed_bytes(cols);
 
     putinit(rows, cols);
-    
+
     for (row = 0; row < rows; ++row) {
-        /* The raster formats are identical. 
+        /* The raster formats are identical.
            The row end pad bits are set to 0 in mgr.
         */
         size_t bytesWritten;
@@ -89,7 +89,7 @@ main(int argc,
         bytesWritten = fwrite(bitrow, 1, bytesPerRow, stdout);
         if (bytesWritten != bytesPerRow )
             pm_error("fwrite() failed to write MGR bitmap "
-                     "to Standard Output.");    
+                     "to Standard Output.");
     }
     pm_close(ifP);
     return 0;
@@ -102,7 +102,7 @@ main(int argc,
    pbm_readpbmrow_packed(), write function from putc() to fwrite().
 
    Retired bitwise transformation functions.
-   
+
    Produces only new style bitmap (8 bit padding.)  See mgrtopbm.c .
 */
 
diff --git a/converter/pbm/pbmtomrf.c b/converter/pbm/pbmtomrf.c
index e7b7fcc9..a9243561 100644
--- a/converter/pbm/pbmtomrf.c
+++ b/converter/pbm/pbmtomrf.c
@@ -23,18 +23,18 @@ typedef struct bitOut {
 
 
 
-static void 
+static void
 bit_init(struct bitOut * const bitOutP,
          FILE *          const ofP) {
 
-    bitOutP->bitbox = 0; 
+    bitOutP->bitbox = 0;
     bitOutP->bitsleft = 8;
     bitOutP->fileP = ofP;
 }
 
 
 
-static void 
+static void
 bit_output(struct bitOut * const bitOutP,
            int             const bit) {
 
@@ -49,7 +49,7 @@ bit_output(struct bitOut * const bitOutP,
 
 
 
-static void 
+static void
 bit_flush(struct bitOut * const bitOutP) {
     /* there are never 0 bits left outside of bit_output, but
      * if 8 bits are left here there's nothing to flush, so
@@ -86,7 +86,7 @@ determineBlackWhiteOrMix(const unsigned char * const image,
 
             t += image[rowOfImage * imageWidth + colOfImage];
         }
-    }        
+    }
     /* if the total's 0, it's black. if it's size*size, it's white. */
     if (t == 0) {
         *oneColorP = TRUE;
@@ -100,7 +100,7 @@ determineBlackWhiteOrMix(const unsigned char * const image,
 
 
 
-static void 
+static void
 doSquare(bitOut *              const bitOutP,
          const unsigned char * const image,
          unsigned int          const ulCol,
@@ -148,7 +148,7 @@ doSquare(bitOut *              const bitOutP,
         }
     }
 }
-    
+
 
 
 static void
@@ -186,7 +186,7 @@ fiddleBottomEdge(unsigned char * const image,
                  unsigned int    const pw,
                  unsigned int    const ph,
                  bool *          const flippedP) {
-    
+
     unsigned int col;
     unsigned int t;
 
@@ -207,7 +207,6 @@ fiddleBottomEdge(unsigned char * const image,
 
 
 
-
 static void
 fiddleBottomRightCorner(unsigned char * const image,
                         unsigned int    const w,
@@ -218,7 +217,7 @@ fiddleBottomRightCorner(unsigned char * const image,
 
     for (row = h; row < ph; ++row) {
         unsigned int col;
-        
+
         for (col = w; col < pw; ++col)
                     image[row*pw + col] = 1;
     }
@@ -226,7 +225,7 @@ fiddleBottomRightCorner(unsigned char * const image,
 
 
 
-static void 
+static void
 fiddleEdges(unsigned char * const image,
             int             const cols,
             int             const rows) {
@@ -247,9 +246,9 @@ fiddleEdges(unsigned char * const image,
          * So, all we do is flip the runoff area of an edge to white
          * if more than half of the pixels on that edge are
          * white. Then for the bottom-right runoff square (if there is
-         * one), we flip it if we flipped both edges.  
+         * one), we flip it if we flipped both edges.
          */
-        
+
     /* w64 is units-of-64-bits width, h64 same for height */
     unsigned int const w64 = (cols + 63) / 64;
     unsigned int const h64 = (rows + 63) / 64;
@@ -259,28 +258,28 @@ fiddleEdges(unsigned char * const image,
 
     bool flippedRight, flippedBottom;
 
-    if (cols % 64 != 0) 
+    if (cols % 64 != 0)
         fiddleRightEdge(image, cols, rows, pw, &flippedRight);
     else
         flippedRight = FALSE;
 
-    if (rows % 64 != 0) 
+    if (rows % 64 != 0)
         fiddleBottomEdge(image, cols, rows, pw, ph, &flippedBottom);
     else
         flippedBottom = FALSE;
 
-    if (flippedRight && flippedBottom) 
+    if (flippedRight && flippedBottom)
         fiddleBottomRightCorner(image, cols, rows, pw, ph);
 }
 
 
 
 static void
-readPbmImage(FILE *           const ifP, 
+readPbmImage(FILE *           const ifP,
              unsigned char ** const imageP,
              int *            const colsP,
              int *            const rowsP) {
-    
+
 
     /* w64 is units-of-64-bits width, h64 same for height */
     unsigned int w64, h64;
@@ -289,7 +288,7 @@ readPbmImage(FILE *           const ifP,
     int cols, rows, format;
     unsigned int row;
     bit * bitrow;
-    
+
     pbm_readpbminit(ifP, &cols, &rows, &format);
 
     w64 = (cols + 63) / 64;
@@ -302,7 +301,7 @@ readPbmImage(FILE *           const ifP,
     image = calloc(w64*h64*64*64, 1);
     if (image == NULL)
         pm_error("Unable to get memory for raster");
-                 
+
     /* get bytemap image rounded up into mod 64x64 squares */
 
     bitrow = pbm_allocrow(cols);
@@ -324,7 +323,7 @@ readPbmImage(FILE *           const ifP,
 
 
 static void
-outputMrf(FILE *          const ofP, 
+outputMrf(FILE *          const ofP,
           unsigned char * const image,
           unsigned int    const cols,
           unsigned int    const rows) {
@@ -340,7 +339,7 @@ outputMrf(FILE *          const ofP,
     fprintf(ofP, "%c%c%c%c", cols >> 24, cols >> 16, cols >> 8, cols >> 0);
     fprintf(ofP, "%c%c%c%c", rows >> 24, rows >> 16, rows >> 8, rows >> 0);
     fputc(0, ofP);   /* option byte, unused for now */
-    
+
     /* now recursively check squares. */
 
     bit_init(&bitOut, ofP);
@@ -355,18 +354,18 @@ outputMrf(FILE *          const ofP,
 
 
 
-int 
+int
 main(int argc,char *argv[]) {
 
     FILE * ifP;
     FILE * ofP;
     unsigned char *image;
     int rows, cols;
-    
+
     pbm_init(&argc, argv);
 
     if (argc-1 > 1)
-        pm_error("Too many arguments: %d.  Only argument is input file", 
+        pm_error("Too many arguments: %d.  Only argument is input file",
                  argc-1);
 
     if (argc-1 == 1)
@@ -375,7 +374,7 @@ main(int argc,char *argv[]) {
         ifP = stdin;
 
     ofP = stdout;
- 
+
     readPbmImage(ifP, &image, &cols, &rows);
 
     pm_close(ifP);
@@ -395,4 +394,3 @@ main(int argc,char *argv[]) {
 
 
 
-
diff --git a/converter/pbm/pbmtonokia.c b/converter/pbm/pbmtonokia.c
index 4604064a..7bf51368 100644
--- a/converter/pbm/pbmtonokia.c
+++ b/converter/pbm/pbmtonokia.c
@@ -168,7 +168,6 @@ validateSize(unsigned int const cols,
 
 
 
-
 static void
 convertToHexNol(bit **       const image,
                 unsigned int const cols,
@@ -236,7 +235,6 @@ convertToHexNgg(bit **       const image,
 
 
 
-
 static void
 convertToHexNpm(bit **       const image,
                 unsigned int const cols,
@@ -337,7 +335,6 @@ convertToNol(bit **       const image,
 
 
 
-
 static void
 convertToNgg(bit **       const image,
              unsigned int const cols,
diff --git a/converter/pbm/pbmtopi3.c b/converter/pbm/pbmtopi3.c
index 791bcb50..35e73ca3 100644
--- a/converter/pbm/pbmtopi3.c
+++ b/converter/pbm/pbmtopi3.c
@@ -67,7 +67,7 @@ main(int argc, const char ** argv) {
     inColByteCt = pbm_packed_bytes(inCols);
 
     bitrow = pbm_allocrow_packed(MAX(outCols, inCols));
-    
+
     /* Add padding to round cols up to 640 */
     for (i = inColByteCt; i < outColByteCt; ++i)
         bitrow[i] = 0x00;
@@ -96,3 +96,6 @@ main(int argc, const char ** argv) {
 
     return 0;
 }
+
+
+
diff --git a/converter/pbm/pbmtoplot.c b/converter/pbm/pbmtoplot.c
index 8c9075b2..db897bd0 100644
--- a/converter/pbm/pbmtoplot.c
+++ b/converter/pbm/pbmtoplot.c
@@ -30,13 +30,13 @@ main( argc, argv )
     FILE* ifp;
     register bit** bits;
     register int row, col, scol;
-    int	rows, cols;
+    int rows, cols;
 
 
     pbm_init( &argc, argv );
 
     if ( argc > 2 )
-	pm_usage( "[pbmfile]" );
+        pm_usage( "[pbmfile]" );
 
     ifp = (argc == 2) ? pm_openr( argv[1] ) : stdin;
 
@@ -50,27 +50,30 @@ main( argc, argv )
     puttwo( rows - 1 );
     puttwo( cols - 1 );
     for ( row = 0; row < rows; ++row )
-	{
-	for ( col = 0; col < cols; ++col )
-	    {
-	    if ( bits[row][col] == PBM_WHITE )
-		continue;
-	    scol = col;
-	    while ( ++col < cols && bits[row][col] == PBM_BLACK )
-		; /* nothing */
-	    --col;
-	    if ( col == scol )
-		(void) putchar( 'p' );
-	    else
-		{
-		(void) putchar( 'l' );
-		puttwo( scol );
-		puttwo( rows - 1 - row );
-		}
-	    puttwo( col );
-	    puttwo( rows - 1 - row );
-	    }
-	}
+        {
+        for ( col = 0; col < cols; ++col )
+            {
+            if ( bits[row][col] == PBM_WHITE )
+                continue;
+            scol = col;
+            while ( ++col < cols && bits[row][col] == PBM_BLACK )
+                ; /* nothing */
+            --col;
+            if ( col == scol )
+                (void) putchar( 'p' );
+            else
+                {
+                (void) putchar( 'l' );
+                puttwo( scol );
+                puttwo( rows - 1 - row );
+                }
+            puttwo( col );
+            puttwo( rows - 1 - row );
+            }
+        }
 
     exit( 0 );
     }
+
+
+
diff --git a/converter/pbm/pbmtoppa/cutswath.c b/converter/pbm/pbmtoppa/cutswath.c
index d3f15c03..bc7139b9 100644
--- a/converter/pbm/pbmtoppa/cutswath.c
+++ b/converter/pbm/pbmtoppa/cutswath.c
@@ -12,6 +12,9 @@
 #include <stdlib.h>
 #include <string.h>
 
+#include "mallocvar.h"
+#include "pm.h"
+
 #include "ppa.h"
 #include "ppapbm.h"
 #include "cutswath.h"
@@ -20,343 +23,321 @@ extern int Width;
 extern int Height;
 extern int Pwidth;
 
-/* sweep_data->direction must be set already */
-/* Upon successful completion, sweep_data->image_data and
-   sweep_data->nozzle_data have been set to pointers which this routine
-   malloc()'d. */
-/* Upon successful completion, all members of *sweep_data have been set
-   except direction, vertical_pos, and next. */
-/* Returns: 0 if unsuccessful
+
+
+int
+cut_pbm_swath(pbm_stat *       const pbmP,
+              ppa_stat *       const prnP,
+              int              const maxlines,
+              ppa_sweep_data * const sweepDataP) {
+/*----------------------------------------------------------------------------
+   sweepDataP->direction must be set already
+
+   Upon successful completion, sweepDataP->image_data and
+   sweepDataP->nozzle_data have been set to pointers which this routine
+   malloc()'d.
+
+   Upon successful completion, all members of *sweepDataP have been set
+   except direction, vertical_pos, and next.
+
+   Returns: 0 if unsuccessful
             1 if successful, but with non-printing result (end of page)
-            2 if successful, with printing result */
-int 
-cut_pbm_swath(pbm_stat* pbm,ppa_stat* prn,int maxlines,ppa_sweep_data* sweep_data)
-{
-  unsigned char *data, *ppa, *place, *maxplace;
-  int p_width, width8, p_width8;
-  int i, j, left, right, got_nonblank, numlines;
-  int horzpos, hp2;
-  int shift;
-  ppa_nozzle_data nozzles[2];
-
-  ppa = NULL;
-
-  /* shift = 6 if DPI==300  */
-  /* shift = 12 if DPI==600 */ 
-  shift = ( prn->DPI == 300 ? 6:12 ) ;
-  
-  /* safeguard against the user freeing these */
-  sweep_data->image_data  = NULL;
-  sweep_data->nozzle_data = NULL;
-
-  /* read the data from the input file */
-  width8 = (pbm->width + 7) / 8;
- 
-/* 
-  fprintf(stderr,"cutswath(): width=%u\n",pbm->width);
-  fprintf(stderr,"cutswath(): height=%u\n",pbm->height);
-*/
-
-  if ((data=malloc(width8*maxlines)) == NULL)
-  {
-    fprintf(stderr,"cutswath(): could not malloc data storage\n");
-    return 0;
-  }
-
-  /* ignore lines that are above the upper margin */
-  while(pbm->current_line < prn->top_margin)
-    if(!pbm_readline(pbm,data))
-    {
-      fprintf(stderr,"cutswath(): A-could not read top margin\n");
-      free (data); data=NULL;
-      return 0;
+            2 if successful, with printing result
+-----------------------------------------------------------------------------*/
+    int const shift = prnP->DPI == 300 ? 6 : /* DPI=600 */ 12;
+
+    unsigned char *data, *ppa, *place, *maxplace;
+    int pWidth, width8, pWidth8;
+    int i, left, right, gotNonblank, numlines;
+    int horzpos, hp2;
+    ppa_nozzle_data nozzles[2];
+
+    ppa = NULL;
+
+    /* Safeguard against the user freeing these */
+    sweepDataP->image_data  = NULL;
+    sweepDataP->nozzle_data = NULL;
+
+    /* Read the data from the input file */
+    width8 = (pbmP->width + 7) / 8;
+
+    MALLOCARRAY(data, width8 * maxlines);
+    if (!data) {
+        pm_message("could not malloc data storage");
+        return 0;
+    }
+
+    /* Ignore lines that are above the upper margin */
+    while (pbmP->current_line < prnP->top_margin) {
+        if (!pbm_readline(pbmP, data)) {
+            pm_message("could not read top margin");
+            free(data); data=NULL;
+            return 0;
+        }
+    }
+
+    /* Eat all lines that are below the lower margin */
+    if (pbmP->current_line >= Height - prnP->bottom_margin) {
+        while (pbmP->current_line < pbmP->height) {
+            if (!pbm_readline(pbmP, data)) {
+                pm_message("could not clear bottom margin");
+                free(data); data=NULL;
+                return 0;
+            }
+        }
+        free(data); data=NULL;
+        return 1;
     }
 
-  /* eat all lines that are below the lower margin */
-  if(pbm->current_line >= Height - prn->bottom_margin)
-  {
-    while(pbm->current_line < pbm->height)
-      if(!pbm_readline(pbm,data))
-      {
-	fprintf(stderr,"cutswath(): could not clear bottom margin\n");
-	free (data); data=NULL;
-	return 0;
-      }
-    free (data); data=NULL;
-    return 1;
-  }
-
-  left = Pwidth-prn->right_margin/8;
-  right = prn->left_margin/8;
-
-  /* eat all beginning blank lines and then up to maxlines or lower margin */
-  got_nonblank=numlines=0;
-  while( (pbm->current_line < Height-prn->bottom_margin) &&
-	 (numlines < maxlines) )
-  {
-    if(!pbm_readline(pbm,data+width8*numlines))
-    {
-      fprintf(stderr,"cutswath(): B-could not read next line\n");
-      free (data); data=NULL;
-      return 0;
+    left  = Pwidth - prnP->right_margin / 8;
+    right = prnP->left_margin / 8;
+
+    /* Eat all beginning blank lines and then up to maxlines or lower margin */
+    gotNonblank = numlines = 0;
+    while ((pbmP->current_line < Height-prnP->bottom_margin) &&
+           (numlines < maxlines)) {
+        if (!pbm_readline(pbmP, data + width8 * numlines)) {
+            pm_message("could not read next line");
+            free(data); data=NULL;
+            return 0;
+        }
+        if (!gotNonblank) {
+            unsigned int j;
+            for (j = prnP->left_margin / 8; j < left; ++j) {
+                if (data[j]) {
+                  left = j;
+                  gotNonblank=1;
+                  break;
+                }
+            }
+        }
+        if (gotNonblank) {
+            int newleft, newright;
+            unsigned int i;
+
+            /* Find left-most nonblank */
+            for (i = prnP->left_margin / 8, newleft = left; i < left; ++i) {
+                if (data[width8 * numlines + i]) {
+                    newleft = i;
+                    break;
+                }
+            }
+            /* Find right-most nonblank */
+            for (i = Pwidth - prnP->right_margin / 8 - 1, newright = right;
+                 i >= right;
+                 --i) {
+              if (data[width8 * numlines + i]) {
+                  newright = i;
+                  break;
+              }
+            }
+            ++numlines;
+
+            if (newright < newleft) {
+                pm_message("Ack! newleft=%d, newright=%d, left=%d, right=%d",
+                           newleft, newright, left, right);
+                free(data); data=NULL;
+                return 0;
+            }
+
+            /* If the next line might push us over the buffer size, stop here!
+               ignore this test for the 720 right now.  Will add better
+               size-guessing for compressed data in the near future!
+            */
+            if (numlines % 2 == 1 && prnP->version != HP720) {
+                int l = newleft;
+                int r = newright;
+                int w;
+
+                --l;
+                r += 2;
+                l *= 8;
+                r *= 8;
+                w = r-l;
+                w = (w + 7) / 8;
+
+                if ((w + 2 * shift) * numlines > prnP->bufsize) {
+                    --numlines;
+                    pbm_unreadline(pbmP, data + width8 * numlines);
+                    break;
+                } else {
+                    left  = newleft;
+                    right = newright;
+                }
+            } else {
+                left  = newleft;
+                right = newright;
+            }
+        }
     }
-    if(!got_nonblank)
-      for(j=prn->left_margin/8; j<left; j++)
-	if(data[j])
-	{
-	  left = j;
-	  got_nonblank=1;
-	  break;
-	}
-    if(got_nonblank)
-      {
-	int newleft = left, newright = right;
-
-	/* find left-most nonblank */
-	for (i = prn->left_margin/8; i < left; i++)
-	  if (data[width8*numlines+i])
-	    {
-	      newleft = i;
-	      break;
-	    }
-	/* find right-most nonblank */
-	for (i = Pwidth-prn->right_margin/8-1; i >= right; i--)
-	  if (data[width8*numlines+i])
-	    {
-	      newright = i;
-	      break;
-	    }
-	numlines++;
-
-	if (newright < newleft)
-	  {
-	    fprintf (stderr, "Ack! newleft=%d, newright=%d, left=%d, right=%d\n",
-		     newleft, newright, left, right);
-	    free (data); data=NULL;
-	    return 0;
-	  }
-
-	/* if the next line might push us over the buffer size, stop here! */
-	/* ignore this test for the 720 right now.  Will add better */
-	/* size-guessing for compressed data in the near future! */
-	if (numlines % 2 == 1 && prn->version != HP720)
-	  {
-	    int l = newleft, r = newright, w;
-	    
-	    l--;
-	    r+=2;
-	    l*=8;
-	    r*=8;
-	    w = r-l;
-	    w = (w+7)/8;
-	    
-	    if ((w+2*shift)*numlines > prn->bufsize)
-	      {
-		numlines--;
-		pbm_unreadline (pbm, data+width8*numlines);
-		break;
-	      }
-	    else
-	      {
-		left = newleft;
-		right = newright;
-	      }
-	  }
-	else
-	  {
-	    left = newleft;
-	    right = newright;
-	  }
-      }
-  }
-
-  if(!got_nonblank)
-  {
-    /* eat all lines that are below the lower margin */
-    if(pbm->current_line >= Height - prn->bottom_margin)
-    {
-      while(pbm->current_line < pbm->height)
-	if(!pbm_readline(pbm,data))
-	{
-	  fprintf(stderr,"cutswath(): could not clear bottom margin\n");
-	  free (data); data=NULL;
-	  return 0;
-	}
-      free (data); data=NULL;
-      return 1;
+
+    if (!gotNonblank) {
+        /* Eat all lines that are below the lower margin */
+        if (pbmP->current_line >= Height - prnP->bottom_margin) {
+            while (pbmP->current_line < pbmP->height) {
+                if (!pbm_readline(pbmP, data)) {
+                    pm_message("could not clear bottom margin");
+                    free(data); data = NULL;
+                    return 0;
+                }
+            }
+            free(data); data = NULL;
+            return 1;
+        }
+        free(data); data = NULL;
+        return 0; /* error, since didn't get to lower margin, yet blank */
     }
-    free (data); data=NULL;
-    return 0; /* error, since didn't get to lower margin, yet blank */
-  }
-
-  /* make sure numlines is even and >= 2 (b/c we have to pass the printer 
-     HALF of the number of pins used */
-  if (numlines == 1)
-    {
-      /* there's no way that we only have 1 line and not enough memory, so
-	 we're safe to increase numlines here.  Also, the bottom margin should
-	 be > 0 so we have some lines to read */
-      if(!pbm_readline(pbm,data+width8*numlines))
-	{
-	  fprintf(stderr,"cutswath(): C-could not read next line\n");
-	  free (data); data=NULL;
-	  return 0;
-	}
-      numlines++;
+
+    /* Make sure numlines is even and >= 2 (b/c we have to pass the printer
+       HALF of the number of pins used
+    */
+    if (numlines == 1) {
+        /* There's no way that we only have 1 line and not enough memory, so
+           we're safe to increase numlines here.  Also, the bottom margin
+           should be > 0 so we have some lines to read
+        */
+        if (!pbm_readline(pbmP, data + width8 * numlines)) {
+            pm_message("could not read next line");
+            free(data); data = NULL;
+            return 0;
+        }
+        ++numlines;
     }
-  if (numlines % 2 == 1)
-    {
-      /* decrease instead of increasing so we don't max out the buffer */
-      numlines--;
-      pbm_unreadline (pbm, data+width8*numlines);
+    if (numlines % 2 == 1) {
+      /* Decrease instead of increasing so we don't max out the buffer */
+        --numlines;
+        pbm_unreadline(pbmP, data + width8 * numlines);
     }
 
-  /* calculate vertical position */
-  sweep_data->vertical_pos = pbm->current_line;
+    sweepDataP->vertical_pos = pbmP->current_line;
 
-  /* change sweep params */
-  left--;
-  right+=2;
-  left *= 8;
-  right *= 8;
+    /* Change sweep params */
+    left  -= 1;
+    right += 2;
+    left  *= 8;
+    right *= 8;
 
-  /* construct the sweep data */
-  p_width = right - left;
-  p_width8 = (p_width + 7) / 8;
+    /* Construct the sweep data */
+    pWidth = right - left;
+    pWidth8 = (pWidth + 7) / 8;
 
-  if ((ppa = malloc ((p_width8+2*shift) * numlines)) == NULL)
-    {
-      fprintf(stderr,"cutswath(): could not malloc ppa storage\n");
-      free (data); data=NULL;
-      return 0;
+    MALLOCARRAY(ppa, (pWidth8 + 2 * shift) * numlines);
+    if (!ppa) {
+        pm_message("could not malloc ppa storage");
+        free(data); data = NULL;
+        return 0;
     }
 
-  place = ppa;
-
-  /* place 0's in the first 12 columns */
-  memset (place, 0, numlines/2 * shift);
-  place += numlines/2 * shift;
-
-
-  if(sweep_data->direction == right_to_left)  /* right-to-left */
-  {
-    for (i = p_width8+shift-1; i >= 0; i--)
-    {
-      if (i >= shift)
-      {
-	for (j = 0; j < numlines/2; j++)
-	  *place++ = data[j*2*width8 + i + left/8-shift];
-      }
-      else
-      {
-	memset (place, 0, numlines/2);
-	place += numlines/2;
-      }
-
-      if (i < p_width8)
-      {
-	for (j = 0; j < numlines/2; j++)
-	  *place++ = data[(j*2+1)*width8 + i + left/8];
-      }
-      else
-      {
-	memset (place, 0, numlines/2);
-	place += numlines/2;
-      }
-    }
-  }
-  else /* sweep_data->direction == left_to_right */
-  {
-    for (i = 0; i < p_width8+shift; i++)
-    {
-      if (i < p_width8)
-      {
-	for (j = 0; j < numlines/2; j++)
-	  *place++ = data[(j*2+1)*width8 + i + left/8];
-      }
-      else
-      {
-	memset (place, 0, numlines/2);
-	place += numlines/2;
-      }
-
-      if (i >= shift)
-      {
-	for (j = 0; j < numlines/2; j++)
-	  *place++ = data[j*2*width8 + i + left/8 - shift];
-      }
-      else
-      {
-	memset (place, 0, numlines/2);
-	place += numlines/2;
-      }
+    place = ppa;
+
+    /* Place 0's in the first 12 columns */
+    memset(place, 0, numlines/2 * shift);
+    place += numlines/2 * shift;
+
+    if (sweepDataP->direction == right_to_left) { /* right-to-left */
+        int i;
+
+        for (i = pWidth8 + shift - 1; i >= 0; --i) {
+            if (i >= shift) {
+                unsigned int j;
+
+                for (j = 0; j < numlines/2; ++j)
+                    *place++ = data[j * 2 * width8 + i + left / 8 - shift];
+            } else {
+                memset(place, 0, numlines/2);
+                place += numlines/2;
+            }
+
+            if (i < pWidth8) {
+                unsigned int j;
+
+                for (j = 0; j < numlines/2; ++j)
+                    *place++ = data[(j * 2 + 1) * width8 + i + left / 8];
+            } else {
+                memset(place, 0, numlines/2);
+                place += numlines/2;
+            }
+        }
+    } else {
+        /* sweep_data->direction == left_to_right */
+        unsigned int i;
+        for (i = 0; i < pWidth8 + shift; ++i) {
+            if (i < pWidth8) {
+                unsigned int j;
+                for (j = 0; j < numlines/2; ++j)
+                    *place++ = data[(j * 2 + 1) * width8 + i + left / 8];
+            } else {
+                memset(place, 0, numlines/2);
+                place += numlines/2;
+            }
+
+            if (i >= shift) {
+                unsigned int j;
+                for (j = 0; j < numlines/2; ++j)
+                    *place++ = data[j * 2 * width8 + i + left / 8 - shift];
+            } else {
+                memset(place, 0, numlines/2);
+                place += numlines/2;
+            }
+        }
     }
-  }
-
-  /* done with data */
-  free (data); data=NULL;
-
-  /* place 0's in the last 12 columns */
-  memset (place, 0, numlines/2 * shift);
-  place += numlines/2 * shift;
-  maxplace = place;
-
-  /* create sweep data */
-  sweep_data->image_data = ppa;
-  sweep_data->data_size = maxplace-ppa;
-  sweep_data->in_color = False;
-
-  /*
-  horzpos = left*600/prn->DPI + (sweep_data->direction==left_to_right ? 0*600/prn->DPI : 0);
-  */
-  horzpos = left * 600/prn->DPI;
-
-  hp2 = horzpos + ( p_width8 + 2*shift )*8 * 600/prn->DPI;
-  
- 
-  sweep_data->left_margin = horzpos;
-  sweep_data->right_margin = hp2 + prn->marg_diff;
-
-  
-  for (i = 0; i < 2; i++)
-  {
-    nozzles[i].DPI = prn->DPI;
-        
-    nozzles[i].pins_used_d2 = numlines/2;
-    nozzles[i].unused_pins_p1 = 301-numlines;
-    nozzles[i].first_pin = 1;
-    if (i == 0)
-    {
-      nozzles[i].left_margin = horzpos + prn->marg_diff;
-      nozzles[i].right_margin = hp2 + prn->marg_diff;
-      if(sweep_data->direction == right_to_left)
-       /* 0 */
-	nozzles[i].nozzle_delay=prn->right_to_left_delay[0];
-      else
-       /* 6 */
-	nozzles[i].nozzle_delay=prn->left_to_right_delay[0];
-    }
-    else
-    {
-      nozzles[i].left_margin = horzpos;
-      nozzles[i].right_margin = hp2;
-      if(sweep_data->direction == right_to_left)
-       /* 2 */
-	nozzles[i].nozzle_delay=prn->right_to_left_delay[1];
-      else
-       /* 0 */
-	nozzles[i].nozzle_delay=prn->left_to_right_delay[1];
 
+    /* Done with data */
+    free(data); data=NULL;
+
+    /* Place 0's in the last 12 columns */
+    memset(place, 0, numlines/2 * shift);
+    place += numlines/2 * shift;
+    maxplace = place;
+
+    /* Create sweep data */
+    sweepDataP->image_data = ppa;
+    sweepDataP->data_size  = maxplace-ppa;
+    sweepDataP->in_color   = False;
+
+    /*
+      horzpos = left*600/prn->DPI + (sweep_data->direction==left_to_right ? 0*600/prn->DPI : 0);
+    */
+    horzpos = left * 600 / prnP->DPI;
+
+    hp2 = horzpos + (pWidth8 + 2 * shift) * 8 * 600 /prnP->DPI;
+
+    sweepDataP->left_margin  = horzpos;
+    sweepDataP->right_margin = hp2 + prnP->marg_diff;
+
+    for (i = 0; i < 2; ++i) {
+        nozzles[i].DPI = prnP->DPI;
+
+        nozzles[i].pins_used_d2 = numlines/2;
+        nozzles[i].unused_pins_p1 = 301 - numlines;
+        nozzles[i].first_pin = 1;
+
+        if (i == 0) {
+            nozzles[i].left_margin  = horzpos + prnP->marg_diff;
+            nozzles[i].right_margin = hp2 + prnP->marg_diff;
+            if (sweepDataP->direction == right_to_left)  /* 0 */
+
+                nozzles[i].nozzle_delay = prnP->right_to_left_delay[0];
+            else  /* 6 */
+                nozzles[i].nozzle_delay = prnP->left_to_right_delay[0];
+        } else {
+            nozzles[i].left_margin  = horzpos;
+            nozzles[i].right_margin = hp2;
+
+            if (sweepDataP->direction == right_to_left)  /* 2 */
+                nozzles[i].nozzle_delay = prnP->right_to_left_delay[1];
+            else  /* 0 */
+                nozzles[i].nozzle_delay = prnP->left_to_right_delay[1];
+        }
     }
-  }
 
-  sweep_data->nozzle_data_size = 2;
-  sweep_data->nozzle_data = malloc(sizeof(nozzles));
-  if(sweep_data->nozzle_data == NULL)
-    return 0;
-  memcpy(sweep_data->nozzle_data,nozzles,sizeof(nozzles));
+    sweepDataP->nozzle_data_size = 2;
+    MALLOCARRAY_NOFAIL(sweepDataP->nozzle_data, 2);
+    sweepDataP->nozzle_data[0] = nozzles[0];
+    sweepDataP->nozzle_data[1] = nozzles[1];
 
-  return 2;
+    return 2;
 }
 
 
+
diff --git a/converter/pbm/pbmtoppa/cutswath.h b/converter/pbm/pbmtoppa/cutswath.h
index 430558de..347510cf 100644
--- a/converter/pbm/pbmtoppa/cutswath.h
+++ b/converter/pbm/pbmtoppa/cutswath.h
@@ -1,4 +1,4 @@
-int 
+int
 cut_pbm_swath(pbm_stat* pbm,ppa_stat* prn,int maxlines,
               ppa_sweep_data* sweep_data);
 
diff --git a/converter/pbm/pbmtoppa/pbm.c b/converter/pbm/pbmtoppa/pbm.c
index ae36e0d2..403ca95c 100644
--- a/converter/pbm/pbmtoppa/pbm.c
+++ b/converter/pbm/pbmtoppa/pbm.c
@@ -15,8 +15,11 @@
 
 #include "pm.h"
 #include "nstring.h"
+
 #include "ppapbm.h"
 
+
+
 int
 make_pbm_stat(pbm_stat * const pbmStatP,
               FILE *     const ifP) {
@@ -61,15 +64,15 @@ make_pbm_stat(pbm_stat * const pbmStatP,
                     if (pbmStatP->width < 0) {
                         pm_message("Image has negative width");
                         retval = 0;
-                    } else if (pbmStatP->width > INT_MAX/2) {
-                        pm_message("Uncomputeably large width: %d",
+                    } else if (pbmStatP->width > INT_MAX/2 - 10) {
+                        pm_message("Uncomputably large width: %d",
                                    pbmStatP->width);
                         retval = 0;
                     } else if (pbmStatP->height < 0) {
                         pm_message("Image has negative height");
                         retval = 0;
-                    } else if (pbmStatP->height > INT_MAX/2) {
-                        pm_message("Uncomputeably large height: %d",
+                    } else if (pbmStatP->height > INT_MAX/2 - 10) {
+                        pm_message("Uncomputably large height: %d",
                                    pbmStatP->height);
                         retval = 0;
                     } else
@@ -193,3 +196,4 @@ pbm_unreadline(pbm_stat * const pbmStatP,
 }
 
 
+
diff --git a/converter/pbm/pbmtoppa/pbmtoppa.c b/converter/pbm/pbmtoppa/pbmtoppa.c
index ff4a599e..47e64ecc 100644
--- a/converter/pbm/pbmtoppa/pbmtoppa.c
+++ b/converter/pbm/pbmtoppa/pbmtoppa.c
@@ -14,6 +14,8 @@
 #include <unistd.h>
 
 #include "pbm.h"
+#include "nstring.h"
+
 #include "ppa.h"
 #include "ppapbm.h"
 #include "cutswath.h"
@@ -40,8 +42,8 @@ int Pwidth;     /* width in bytes */
 
 ppa_stat printer;
 
-static int 
-print_pbm(FILE * const in) {
+static int
+printPbm(FILE * const ifP) {
 
     char line[1024];
     pbm_stat pbm;
@@ -51,8 +53,8 @@ print_pbm(FILE * const in) {
 
     ppa_init_job(&printer);
 
-    while(make_pbm_stat(&pbm, in)) {
-        if (pbm.width != Width || pbm.height != Height) 
+    while(make_pbm_stat(&pbm, ifP)) {
+        if (pbm.width != Width || pbm.height != Height)
             pm_error("print_pbm(): Input image is not the size "
                     "of a page for Page %d.  "
                     "The input is %dW x %dH, "
@@ -123,7 +125,7 @@ print_pbm(FILE * const in) {
 
         /* eat any remaining whitespace */
         if(pbm.version==P1)
-            fgets (line, 1024, in);
+            fgets (line, 1024, ifP);
 
         ++numpages;
     }
@@ -141,11 +143,13 @@ print_pbm(FILE * const in) {
 
 
 
-static void 
-set_printer_specific_defaults()
-{
-    switch(printer.version)
-    {
+static void
+setPrinterSpecificDefaults() {
+
+    switch(printer.version) {
+    case HP710:
+        pm_error("Don't know how to drive HP 710");
+        break;
     case HP720:
         printer.marg_diff     = HP720_MARG_DIFF;
         printer.bufsize       = HP720_BUFSIZE;
@@ -179,14 +183,12 @@ set_printer_specific_defaults()
         printer.right_margin  = HP1000_RIGHT_MARGIN;
         printer.bottom_margin = HP1000_BOTTOM_MARGIN;
         break;
-    default:
-        pm_error("set_printer_defaults(): unknown printer version");
     }
 }
 
 
 
-static void 
+static void
 show_usage(const char* const prog)
 {
     printf("usage: %s [ options ] [ <infile> [ <outfile> ] ]\n\n",prog);
@@ -220,9 +222,9 @@ show_usage(const char* const prog)
 
 
 
-static void 
-parm_version(char* arg)
-{
+static void
+parmVersion(char * const arg) {
+
     if(!strcasecmp(arg,"hp720") || !strcmp(arg,"720"))
         printer.version=HP720;
     else if(!strcasecmp(arg,"hp820") || !strcmp(arg,"820"))
@@ -231,39 +233,39 @@ parm_version(char* arg)
         printer.version=HP1000;
     else
         pm_error("parm_version(): unknown printer version '%s'",arg);
-    set_printer_specific_defaults();
+    setPrinterSpecificDefaults();
 }
 
 
 
-static void 
-parm_iversion(int arg)
-{
+static void
+parmIversion(int const arg) {
+
     switch(arg)
     {
     case 720:
-        printer.version=HP720;
+        printer.version = HP720;
         break;
     case 820:
-        printer.version=HP820;
+        printer.version = HP820;
         break;
     case 1000:
-        printer.version=HP1000;
+        printer.version = HP1000;
         break;
     default:
-        pm_error("parm_iversion(): unknown printer version '%d'", arg);
+        pm_error("parmIversion(): unknown printer version '%d'", arg);
     }
-    set_printer_specific_defaults();
+    setPrinterSpecificDefaults();
 }
 
 
 
-static void 
-dump_config()
-{
+static void
+dumpConfig() {
+
     printf("version:  ");
-    switch(printer.version)
-    {
+
+    switch(printer.version) {
     case HP710:  printf("HP710\n");  break;
     case HP720:  printf("HP720\n");  break;
     case HP820:  printf("HP820\n");  break;
@@ -278,90 +280,88 @@ dump_config()
 
 
 
-static void 
-read_config_file(const char* const fname)
-{
-    FILE* cfgfile=fopen(fname,"r");
-    char line[1024],key[14],buf[10];
-    int len,value,lineno=1;
+static void
+readConfigFile(const char * const fname) {
+
+    FILE * cfgFileP;
+    char line[1024];
+    char key[14];
+    char buf[10];
+    int len;
+    int value;
+    int lineno;
 
-    if(!cfgfile)
+    cfgFileP = fopen(fname, "r");
+
+    lineno = 1;  /* initial value */
+
+    if (!cfgFileP)
         pm_error("read_config_file(): couldn't open file '%s'", fname);
 
-    while(fgets(line,1024,cfgfile))
-    {
-        if(strchr(line,'#'))
-            *strchr(line,'#')=0;
-        switch(sscanf(line,"%13s%9s",key,buf))
-        {
+    while (fgets(line, 1024, cfgFileP)) {
+        if (strchr(line, '#'))
+            *strchr(line, '#')=0;
+        switch(sscanf(line, "%13s%9s", key, buf)) {
         case 2:
-            value=atoi(buf);
-            len=strlen(key);
-            if(!strncmp(key,"version",len))
-                parm_iversion(value);
-            else if(!strncmp(key,"xoffset",len))
-                printer.x_offset=value;
-            else if(!strncmp(key,"yoffset",len))
-                printer.y_offset=value;
-            else if(!strncmp(key,"topmargin",len))
-                printer.top_margin=value;
-            else if(!strncmp(key,"leftmargin",len))
-                printer.left_margin=value;
-            else if(!strncmp(key,"rightmargin",len))
-                printer.right_margin=value;
-            else if(!strncmp(key,"bottommargin",len))
-                printer.bottom_margin=value;
-            else if(!strncmp(key,"papersize",len))
-            {
-                if(!strcmp(buf,"us"))
-                {
-                    Width = USWIDTH;
+            value = atoi(buf);
+            len   = strlen(key);
+            if (strneq(key, "version",           len))
+                parmIversion(value);
+            else if (strneq(key, "xoffset",      len))
+                printer.x_offset = value;
+            else if (strneq(key, "yoffset",      len))
+                printer.y_offset = value;
+            else if(strneq(key,  "topmargin",    len))
+                printer.top_margin = value;
+            else if(strneq(key,  "leftmargin",   len))
+                printer.left_margin = value;
+            else if(strneq(key,  "rightmargin",  len))
+                printer.right_margin = value;
+            else if(strneq(key,  "bottommargin", len))
+                printer.bottom_margin = value;
+            else if(strneq(key,  "papersize"   , len)) {
+                if(streq(buf, "us")) {
+                    Width  = USWIDTH;
                     Height = USHEIGHT;
-                }
-                else if(!strcmp(buf,"a4"))
-                {
-                    Width = A4WIDTH;
+                } else if (streq(buf, "a4")) {
+                    Width  = A4WIDTH;
                     Height = A4HEIGHT;
-                }
-                else
+                } else
                     pm_error("read_config_file(): unknown paper size %s", buf);
-            }
-            else if(!strcmp(key,"dump"))
-                dump_config();
-            else 
+            } else if(!strcmp(key,"dump"))
+                dumpConfig();
+            else
                 pm_error("read_config_file(): unrecognized parameter '%s' "
                          "(line %d)", key, lineno);
         case EOF:
-        case 0: 
+        case 0:
             break;
         default:
             pm_error("read_config_file(): error parsing config file "
                      "(line %d)", lineno);
         }
-        lineno++;
+        ++lineno;
     }
 
-    if(feof(cfgfile))
-    {
-        fclose(cfgfile);
-        return;
-    }
-
-    pm_error("read_config_file(): error parsing config file");
+    if (feof(cfgFileP)) {
+        fclose(cfgFileP);
+    } else
+        pm_error("read_config_file(): error parsing config file");
 }
 
 
 
-const char* const defaultcfgfile="/etc/pbmtoppa.conf";
+const char * const defaultCfgFileNm = "/etc/pbmtoppa.conf";
 
 
 
-int 
+int
 main(int argc, char *argv[]) {
 
     int argn;
     int got_in=0, got_out=0, do_continue=1;
-    FILE *in=stdin, *out=stdout;
+    FILE * ifP;
+    FILE * ofP;
     struct stat tmpstat;
 
     pbm_init(&argc, argv);
@@ -374,12 +374,15 @@ main(int argc, char *argv[]) {
     printer.right_margin  = DEFAULT_RIGHT_MARGIN;
     printer.bottom_margin = DEFAULT_BOTTOM_MARGIN;
     printer.DPI           = DEFAULT_DPI;
-    Width = USWIDTH;
+    Width  = USWIDTH;
     Height = USHEIGHT;
-    set_printer_specific_defaults();
+    setPrinterSpecificDefaults();
+
+    if (!stat(defaultCfgFileNm, &tmpstat))
+        readConfigFile(defaultCfgFileNm);
 
-    if(!stat(defaultcfgfile,&tmpstat))
-        read_config_file(defaultcfgfile);
+    ifP = stdin;  /* initial value */
+    ofP = stdout;  /* initial value */
 
     for(argn=1; argn<argc; argn++)
     {
@@ -389,12 +392,12 @@ main(int argc, char *argv[]) {
             return 0;
         }
         else if(!strcmp(argv[argn],"-d"))
-            dump_config();
+            dumpConfig();
         else if(argn+1<argc)
         {
             do_continue=1;
             if(!strcmp(argv[argn],"-v"))
-                parm_version(argv[++argn]);
+                parmVersion(argv[++argn]);
             else if(!strcmp(argv[argn],"-x"))
                 printer.x_offset+=atoi(argv[++argn]);
             else if(!strcmp(argv[argn],"-y"))
@@ -426,7 +429,7 @@ main(int argc, char *argv[]) {
                     pm_error("unknown paper size %s",argv[argn]);
             }
             else if(!strcmp(argv[argn],"-f"))
-                read_config_file(argv[++argn]);
+                readConfigFile(argv[++argn]);
             else do_continue=0;
             if(do_continue) continue;
         }
@@ -434,18 +437,18 @@ main(int argc, char *argv[]) {
         if(!got_in)
         {
             if (strcmp (argv[argn], "-") == 0)
-                in = stdin;
-            else if ((in = fopen (argv[argn], "rb")) == NULL)
-                pm_error("main(): couldn't open file '%s'", 
+                ifP = stdin;
+            else if ((ifP = fopen (argv[argn], "rb")) == NULL)
+                pm_error("main(): couldn't open file '%s'",
                          argv[argn]);
             got_in=1;
         }
         else if(!got_out)
         {
             if (strcmp (argv[argn], "-") == 0)
-                out = stdout;
-            else if ((out = fopen (argv[argn], "wb")) == NULL)
-                pm_error("main(): couldn't open file '%s'", 
+                ofP = stdout;
+            else if ((ofP = fopen (argv[argn], "wb")) == NULL)
+                pm_error("main(): couldn't open file '%s'",
                          argv[argn]);
             got_out=1;
         }
@@ -453,9 +456,11 @@ main(int argc, char *argv[]) {
             pm_error("main(): unrecognized parameter '%s'", argv[argn]);
     }
 
-    Pwidth=(Width+7)/8;
-    printer.fptr=out;
+    Pwidth = (Width+7)/8;
+    printer.fptr = ofP;
 
-    return print_pbm (in);
+    return printPbm(ifP);
 }
 
+
+
diff --git a/converter/pbm/pbmtoppa/ppa.c b/converter/pbm/pbmtoppa/ppa.c
index 69e7bb79..0f75aa1e 100644
--- a/converter/pbm/pbmtoppa/ppa.c
+++ b/converter/pbm/pbmtoppa/ppa.c
@@ -31,7 +31,7 @@
   (*): responses, autostatus, and pacing are communicated from the printer to
        the computer, and may be safely ignored.
 */
-static void 
+static void
 vlink_put(FILE *fptr, int channel, int length, void *data)
 {
   fputc ('$', fptr);
@@ -40,6 +40,8 @@ vlink_put(FILE *fptr, int channel, int length, void *data)
   fwrite (data, length, 1, fptr);
 }
 
+
+
 /*
   SCP packet structure:
 
@@ -60,9 +62,9 @@ vlink_put(FILE *fptr, int channel, int length, void *data)
        19       1     Handle Media
        18       1     Print Sweep
 */
-static void 
+static void
 scp_put(FILE *fptr, int comspec, int comref, int priority,
-	     int length, void *data)
+             int length, void *data)
 {
   /* encapsulate the vlink_put call in here, to avoid a memcpy */
   fputc ('$', fptr);
@@ -79,6 +81,7 @@ scp_put(FILE *fptr, int comspec, int comref, int priority,
 }
 
 
+
 /*
   SCP2 packet structure:
 
@@ -101,10 +104,10 @@ scp_put(FILE *fptr, int comspec, int comref, int priority,
      0x181      1     Handle Media
      0x180      1     Print Sweep
 */
-static void 
+static void
 scp2_put(FILE *fptr,unsigned short comspec,unsigned short pkt_len_s16,
-	      unsigned char priority,unsigned short comref,unsigned data_len,
-	      void *data)
+              unsigned char priority,unsigned short comref,unsigned data_len,
+              void *data)
 {
   /* encapsulate the vlink_put call in here, to avoid a memcpy */
   fputc ('$', fptr);
@@ -128,6 +131,7 @@ scp2_put(FILE *fptr,unsigned short comspec,unsigned short pkt_len_s16,
 }
 
 
+
 /*
   SCP3 packet structure:
 
@@ -152,10 +156,10 @@ scp2_put(FILE *fptr,unsigned short comspec,unsigned short pkt_len_s16,
      0x181      1     Handle Media
      0x180      1     Print Sweep
 */
-static void 
+static void
 scp3_put(FILE *fptr,unsigned short comspec,unsigned short pkt_len_s16,
-	      unsigned char priority,unsigned short comref,unsigned data_len,
-	      void *data)
+              unsigned char priority,unsigned short comref,unsigned data_len,
+              void *data)
 {
   /* encapsulate the vlink_put call in here, to avoid a memcpy */
   fputc ('$', fptr);
@@ -179,6 +183,7 @@ scp3_put(FILE *fptr,unsigned short comspec,unsigned short pkt_len_s16,
 }
 
 
+
 void ppa_init_job(ppa_stat* prn)
 {
   unsigned char init1[8] = { 0x00, 0x00, 0x01, 0xf4, 0x01, 0x00, 0x00, 0x00 };
@@ -211,6 +216,8 @@ void ppa_init_job(ppa_stat* prn)
   }
 }
 
+
+
 void ppa_end_print(ppa_stat* prn)
 {
   unsigned char pageA[4] = { 0x05, 0x01, 0x03, 0x84 };
@@ -219,12 +226,14 @@ void ppa_end_print(ppa_stat* prn)
     scp3_put (prn->fptr, 0x0181, sizeof(pageA), 7, 2, 0, pageA);
 }
 
+
+
 void ppa_init_page(ppa_stat* prn)
 {
   unsigned char pageA[16] = {0x28, 0x2d, 0x00, 0x41, 0x29, 0x2e, 0x00, 0x42,
-			     0x29, 0x2e, 0x00, 0x42, 0x29, 0x2e, 0x00, 0x42 };
+                             0x29, 0x2e, 0x00, 0x42, 0x29, 0x2e, 0x00, 0x42 };
   unsigned char pageB[16] = {0x28, 0x2d, 0x00, 0x41, 0x2d, 0x32, 0x00, 0x46,
-			     0x2d, 0x32, 0x00, 0x46, 0x2d, 0x32, 0x00, 0x46 };
+                             0x2d, 0x32, 0x00, 0x46, 0x2d, 0x32, 0x00, 0x46 };
 
   switch(prn->version)
   {
@@ -242,6 +251,8 @@ void ppa_init_page(ppa_stat* prn)
   }
 }
 
+
+
 void ppa_load_page(ppa_stat* prn)
 {
   unsigned char loadA[4] = {0x01, 0x01, 0x09, 0x60 };
@@ -264,6 +275,8 @@ void ppa_load_page(ppa_stat* prn)
   }
 }
 
+
+
 void ppa_eject_page(ppa_stat* prn)
 {
   unsigned char loadA[4] = {0x02, 0x01, 0x09, 0x60 };
@@ -288,8 +301,8 @@ void ppa_eject_page(ppa_stat* prn)
 
 
 
-static int 
-compress(unsigned char *in, int num_lines_d2, int final_len, 
+static int
+compress(unsigned char *in, int num_lines_d2, int final_len,
              unsigned char *iout)
 {
   unsigned char* out = iout;
@@ -301,89 +314,91 @@ compress(unsigned char *in, int num_lines_d2, int final_len,
       /* Find the size of duplicate values */
       int dup_len = 0;
       while ((i + dup_len < len)
-	     && (in[i + dup_len] == in[i])) {
-	dup_len++;
+             && (in[i + dup_len] == in[i])) {
+        dup_len++;
       }
       /* See if we have enough zeros to be worth compressing. */
       /* I figure one is enough. */
       if ((dup_len >= 1) && (in[i] == 0)) {
-	/* Output run of zeros. */
-	while (dup_len >= 128) {
-	  /* Max is 128 */
-	  *out++ = 0x00;
-	  i += 128;
-	  dup_len -= 128;
-	}
-	if (dup_len >= 1)
-	{
-	  *out++ = dup_len;
-	  i += dup_len;
-	}
-	/* See if we have enough non-zeros to be worth compressing. */
-	/* Here two should be enough. */
+        /* Output run of zeros. */
+        while (dup_len >= 128) {
+          /* Max is 128 */
+          *out++ = 0x00;
+          i += 128;
+          dup_len -= 128;
+        }
+        if (dup_len >= 1)
+        {
+          *out++ = dup_len;
+          i += dup_len;
+        }
+        /* See if we have enough non-zeros to be worth compressing. */
+        /* Here two should be enough. */
       }
       else if (dup_len >= 2)
       {
-	/* Output run of duplicates. */
-	while (dup_len >= 64) {
-	  /* Max is 64 */
-	  *out++ = 0x80;
-	  *out++ = in[i];
-	  i += 64;
-	  dup_len -= 64;
-	}
-	if (dup_len >= 2)
-	{
-	  *out++ = dup_len + 0x80;
-	  *out++ = in[i];
-	  i += dup_len;
-	}
+        /* Output run of duplicates. */
+        while (dup_len >= 64) {
+          /* Max is 64 */
+          *out++ = 0x80;
+          *out++ = in[i];
+          i += 64;
+          dup_len -= 64;
+        }
+        if (dup_len >= 2)
+        {
+          *out++ = dup_len + 0x80;
+          *out++ = in[i];
+          i += dup_len;
+        }
       }
       else
       {
-	/* Look for two zeros, or three duplicates to end literal run. */
-	/* Note this is one more than the number to start a run. */
-	int lit_len = -1;
-	int add_more = 1;
-	while (add_more) {
-	  lit_len++;
-	  if (i + lit_len == len) add_more = 0;
-	  /* Always add more if we are near the very end. */
-	  if (i + lit_len < len - 3) {
-	    char a = in[i + lit_len + 0];
-	    char b = in[i + lit_len + 1];
-	    char c = in[i + lit_len + 2];
-	    /* See if there are enough zeros */
-	    if ((a == b) && (b == 0)) add_more = 0;
-	    /* See if there are enough duplicates */
-	    if ((a == b) && (b == c)) add_more = 0;
-	  }
-	}
-	/* Output run of literals. */
-	while (lit_len >= 64) {
-	  /* Max is 64 */
-	  int j;
-	  *out++ = 0xc0;
-	  for (j = i; j < i + 64; j++) {
-	    *out++ = in[j];
-	  }
-	  i += 64;
-	  lit_len -= 64;
-	} 
-	if (lit_len) {
-	  int j;
-	  *out++ = lit_len + 0xc0;
-	  for (j = i; j < i + lit_len; j++) {
-	    *out++ = in[j];
-	  }
-	  i += lit_len;
-	}
+        /* Look for two zeros, or three duplicates to end literal run. */
+        /* Note this is one more than the number to start a run. */
+        int lit_len = -1;
+        int add_more = 1;
+        while (add_more) {
+          lit_len++;
+          if (i + lit_len == len) add_more = 0;
+          /* Always add more if we are near the very end. */
+          if (i + lit_len < len - 3) {
+            char a = in[i + lit_len + 0];
+            char b = in[i + lit_len + 1];
+            char c = in[i + lit_len + 2];
+            /* See if there are enough zeros */
+            if ((a == b) && (b == 0)) add_more = 0;
+            /* See if there are enough duplicates */
+            if ((a == b) && (b == c)) add_more = 0;
+          }
+        }
+        /* Output run of literals. */
+        while (lit_len >= 64) {
+          /* Max is 64 */
+          int j;
+          *out++ = 0xc0;
+          for (j = i; j < i + 64; j++) {
+            *out++ = in[j];
+          }
+          i += 64;
+          lit_len -= 64;
+        }
+        if (lit_len) {
+          int j;
+          *out++ = lit_len + 0xc0;
+          for (j = i; j < i + lit_len; j++) {
+            *out++ = in[j];
+          }
+          i += lit_len;
+        }
       }
     }
   }
   return out-iout;
 }
 
+
+
 static void __inline__ place_2bytes(int x,unsigned char* y)
 { y[0]=x>>8; y[1]=x; }
 static void __inline__ place_4bytes(int x,unsigned char* y)
@@ -519,9 +534,13 @@ void ppa_print_sweep(ppa_stat* prn,ppa_sweep_data* data)
 }
 
 
+
 void ppa_print_sweeps(ppa_stat* prn,ppa_sweep_data* data)
 {
   ppa_sweep_data* current_sweep;
   for(current_sweep=data; current_sweep; current_sweep=current_sweep->next)
     ppa_print_sweep(prn,current_sweep);
 }
+
+
+
diff --git a/converter/pbm/pbmtoppa/ppa.h b/converter/pbm/pbmtoppa/ppa.h
index 1c7e6f18..cfa18c11 100644
--- a/converter/pbm/pbmtoppa/ppa.h
+++ b/converter/pbm/pbmtoppa/ppa.h
@@ -32,7 +32,7 @@ typedef struct
 } ppa_stat;
 
 typedef struct
-{ 
+{
   int DPI;
   int right;
   int left;
diff --git a/converter/pbm/pbmtoppa/ppapbm.h b/converter/pbm/pbmtoppa/ppapbm.h
index 1ffc093b..10ef4233 100644
--- a/converter/pbm/pbmtoppa/ppapbm.h
+++ b/converter/pbm/pbmtoppa/ppapbm.h
@@ -22,7 +22,7 @@ typedef struct
 } pbm_stat;
 
 int make_pbm_stat(pbm_stat*,FILE*);
-int pbm_readline(pbm_stat*,unsigned char*); 
+int pbm_readline(pbm_stat*,unsigned char*);
   /* reads a single line into char* */
 void pbm_unreadline(pbm_stat*,void*); /* pushes a single line back */
 
diff --git a/converter/pbm/pbmtopsg3.c b/converter/pbm/pbmtopsg3.c
index 8163b70a..c3bb636d 100644
--- a/converter/pbm/pbmtopsg3.c
+++ b/converter/pbm/pbmtopsg3.c
@@ -1,20 +1,20 @@
 /* pbmtopsg3
 
    Reads a series of PBM images and writes a Postscript program
-   containing these images as individual pages with Fax-G3 
+   containing these images as individual pages with Fax-G3
    (CCITT-Fiter) compression. (Useful for combining scanned pages into
    a comfortably printable document.)
 
-   Copyright (C) 2001 Kristof Koehler 
+   Copyright (C) 2001 Kristof Koehler
        <kristof@fachschaft.physik.uni-karlsruhe.de>
 
    Netpbm adaptation by Bryan Henderson June 2001.
- 
+
    This program is free software; you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation; either version 2 of the License, or
    (at your option) any later version.
- 
+
    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
@@ -55,7 +55,7 @@ parseCommandLine(int argc, char ** argv,
 
     OPTENT3(0, "dpi",      OPT_FLOAT,  &dpiOpt,   &dpiSpec,   0);
     OPTENT3(0, "title",    OPT_STRING, &titleOpt, &titleSpec, 0);
-    
+
     opt.opt_table = option_def;
     opt.short_allowed = FALSE;
     opt.allowNegNum = FALSE;
@@ -75,67 +75,71 @@ parseCommandLine(int argc, char ** argv,
     cmdlineP->title = titleSpec ? titleOpt : NULL;
 }
 
-    
 
-static void 
+
+static void
 write85 ( unsigned int bits, int *col )
 {
-	char buf[5] ;
-	if ( bits == 0 ) {
-		fputc ( 'z', stdout ) ;
-		*col += 1 ;
-	} else {
-		buf[4] = bits % 85 + '!' ;
-		bits /= 85 ;
-		buf[3] = bits % 85 + '!' ;
-		bits /= 85 ;
-		buf[2] = bits % 85 + '!' ;
-		bits /= 85 ;
-		buf[1] = bits % 85 + '!' ;
-		bits /= 85 ;
-		buf[0] = bits % 85 + '!' ;
-		fwrite ( buf, 1, 5, stdout ) ;
-		*col += 5 ;
-	}
-	if ( *col > 70 ) {
-		printf ( "\n" ) ;
-		*col = 0 ;
-	}
+        char buf[5] ;
+        if ( bits == 0 ) {
+                fputc ( 'z', stdout ) ;
+                *col += 1 ;
+        } else {
+                buf[4] = bits % 85 + '!' ;
+                bits /= 85 ;
+                buf[3] = bits % 85 + '!' ;
+                bits /= 85 ;
+                buf[2] = bits % 85 + '!' ;
+                bits /= 85 ;
+                buf[1] = bits % 85 + '!' ;
+                bits /= 85 ;
+                buf[0] = bits % 85 + '!' ;
+                fwrite ( buf, 1, 5, stdout ) ;
+                *col += 5 ;
+        }
+        if ( *col > 70 ) {
+                printf ( "\n" ) ;
+                *col = 0 ;
+        }
 }
 
 
-static void 
+
+static void
 writebits ( unsigned int *outbits, int *outbitsidx, int *col,
             unsigned int bits, int n )
 {
-	int k, m ;
-	unsigned int usedbits ;
-	while ( n > 0 ) {
-		if ( *outbitsidx == 0 )
-			*outbits = 0 ;
-		k = 32 - *outbitsidx ;
-		m = n > k ? k : n ;
-		usedbits = (bits >> (n-m)) & ((1<<m)-1) ;
-		*outbits |= usedbits << (k-m) ;
-		*outbitsidx += m ;
-		n -= m ;
-		if ( *outbitsidx == 32 ) {
-			write85 ( *outbits, col ) ;
-			*outbitsidx = 0 ;
-		}
-	}
+        int k, m ;
+        unsigned int usedbits ;
+        while ( n > 0 ) {
+                if ( *outbitsidx == 0 )
+                        *outbits = 0 ;
+                k = 32 - *outbitsidx ;
+                m = n > k ? k : n ;
+                usedbits = (bits >> (n-m)) & ((1<<m)-1) ;
+                *outbits |= usedbits << (k-m) ;
+                *outbitsidx += m ;
+                n -= m ;
+                if ( *outbitsidx == 32 ) {
+                        write85 ( *outbits, col ) ;
+                        *outbitsidx = 0 ;
+                }
+        }
 }
 
 
-static void 
+
+static void
 flushbits ( unsigned int *outbits, int *outbitsidx, int *col )
 {
-	if ( *outbitsidx > 0 ) {
-		write85 ( *outbits, col ) ;
-		*outbitsidx = 0 ;
-	}
+        if ( *outbitsidx > 0 ) {
+                write85 ( *outbits, col ) ;
+                *outbitsidx = 0 ;
+        }
 }
 
+
+
 struct { unsigned int b, l ; } makeup[40][2] = {
     { { 0x001b, 5 } /*         11011 */ , { 0x000f,10 } /*    0000001111 */  },
     { { 0x0012, 5 } /*         10010 */ , { 0x00c8,12 } /*  000011001000 */  },
@@ -243,7 +247,7 @@ struct { unsigned int b, l ; } term[64][2] = {
     { { 0x004b, 8 } /*      01001011 */ , { 0x002c,12 } /*  000000101100 */  },
     { { 0x0032, 8 } /*      00110010 */ , { 0x005a,12 } /*  000001011010 */  },
     { { 0x0033, 8 } /*      00110011 */ , { 0x0066,12 } /*  000001100110 */  },
-    { { 0x0034, 8 } /*      00110100 */ , { 0x0067,12 } /*  000001100111 */  } 
+    { { 0x0034, 8 } /*      00110100 */ , { 0x0067,12 } /*  000001100111 */  }
 } ;
 
 
@@ -251,16 +255,16 @@ static void
 writelength ( unsigned int *outbits, int *outbitsidx, int *col,
               int bit, int length )
 {
-	while ( length >= 64 ) {
-		int m = length / 64 ;
-		if ( m > 40 )
-			m = 40 ;
-		writebits ( outbits, outbitsidx, col,
-			    makeup[m-1][bit].b, makeup[m-1][bit].l ) ;
-		length -= 64*m ;
-	}
-	writebits ( outbits, outbitsidx, col,
-		    term[length][bit].b, term[length][bit].l ) ;
+        while ( length >= 64 ) {
+                int m = length / 64 ;
+                if ( m > 40 )
+                        m = 40 ;
+                writebits ( outbits, outbitsidx, col,
+                            makeup[m-1][bit].b, makeup[m-1][bit].l ) ;
+                length -= 64*m ;
+        }
+        writebits ( outbits, outbitsidx, col,
+                    term[length][bit].b, term[length][bit].l ) ;
 }
 
 
@@ -277,9 +281,9 @@ doPage(FILE *       const ifP,
     int outbitsidx, col ;
 
     pbm_readpbminit(ifP, &cols, &rows, &format);
-        
+
     bitrow = pbm_allocrow(cols);
-        
+
     pm_message("[%u]\n", pageNum);
 
     printf ("%%%%Page: %u %u\n", pageNum, pageNum);
@@ -288,16 +292,16 @@ doPage(FILE *       const ifP,
             "  << /Columns %u /Rows %u /EndOfBlock false >> "
                 "/CCITTFaxDecode filter\n"
             "  image } exec\n",
-            cols, rows, dpi/72.0, -dpi/72.0, rows, 
+            cols, rows, dpi/72.0, -dpi/72.0, rows,
             cols, rows) ;
-        
+
     outbitsidx = col = 0 ;
     for (row = 0 ; row < rows; ++row) {
         int lastbit, cnt ;
         unsigned int j;
 
         pbm_readpbmrow(ifP, bitrow, cols, format);
-            
+
         lastbit = cnt = 0 ;
         for (j = 0; j < cols; ++j) {
             if (bitrow[j] != lastbit) {
@@ -309,7 +313,7 @@ doPage(FILE *       const ifP,
         }
         writelength(&outbits, &outbitsidx, &col, lastbit, cnt);
     }
-        
+
     flushbits(&outbits, &outbitsidx, &col) ;
     printf("~>\nshowpage\n") ;
 
@@ -318,7 +322,7 @@ doPage(FILE *       const ifP,
 
 
 
-static void 
+static void
 doPages(FILE *         const ifP,
         unsigned int * const pagesP,
         double         const dpi) {
@@ -345,7 +349,7 @@ main(int    argc,
 
     FILE *ifP;
     unsigned int pages;
-    
+
     struct cmdline_info cmdline;
 
     pbm_init(&argc, argv);
@@ -360,7 +364,7 @@ main(int    argc,
     printf ("%%%%Creator: pbmtopsg3, Copyright (C) 2001 Kristof Koehler\n"
             "%%%%Pages: (atend)\n"
             "%%%%EndComments\n") ;
-    
+
     doPages(ifP, &pages, cmdline.dpi);
 
     printf ("%%%%Trailer\n"
@@ -370,6 +374,9 @@ main(int    argc,
 
     pm_close(ifP);
     pm_close(stdout);
-    
+
     return 0;
 }
+
+
+
diff --git a/converter/pbm/pbmtoptx.c b/converter/pbm/pbmtoptx.c
index 69f1707a..b9d4b756 100644
--- a/converter/pbm/pbmtoptx.c
+++ b/converter/pbm/pbmtoptx.c
@@ -87,3 +87,4 @@ main(int argc, const char ** argv)  {
 }
 
 
+
diff --git a/converter/pbm/pbmtosunicon.c b/converter/pbm/pbmtosunicon.c
index 95deab7c..af5cff91 100644
--- a/converter/pbm/pbmtosunicon.c
+++ b/converter/pbm/pbmtosunicon.c
@@ -42,7 +42,7 @@ putitem(uint16_t const item) {
     if (ip.itemCnt == 8 ) {
         /* Buffer is full.  Write out one line. */
         int rc;
-    
+
         rc = fprintf(ip.putFp,
                      "\t0x%04x,0x%04x,0x%04x,0x%04x,"
                      "0x%04x,0x%04x,0x%04x,0x%04x,\n",
@@ -50,9 +50,9 @@ putitem(uint16_t const item) {
                      ip.itemBuff[2], ip.itemBuff[3],
                      ip.itemBuff[4], ip.itemBuff[5],
                      ip.itemBuff[6], ip.itemBuff[7]);
-        if (rc < 0)        
+        if (rc < 0)
            pm_error("fprintf() failed to write Icon bitmap");
-           
+
         ip.itemCnt = 0;
     }
     ip.itemBuff[ip.itemCnt++] = item & 0xffff;
@@ -71,10 +71,10 @@ putterm(void) {
         rc = fprintf(ip.putFp, "%s0x%04x%c", i == 0  ? "\t" : "",
                      ip.itemBuff[i],
                      i == ip.itemCnt - 1 ? '\n' : ',');
-        if (rc < 0)        
+        if (rc < 0)
             pm_error("fprintf() failed to write Icon bitmap");
     }
-}     
+}
 
 
 
@@ -89,7 +89,7 @@ writeIconHeader(FILE *       const ofP,
                  "/* Format_version=1, Width=%u, Height=%u", width, height);
     if (rc < 0)
         pm_error("fprintf() failed to write Icon header");
-        
+
     rc = fprintf(ofP, ", Depth=1, Valid_bits_per_item=16\n */\n");
     if (rc < 0)
         pm_error("fprintf() failed to write Icon header");
@@ -123,7 +123,7 @@ writeIcon(FILE *       const ifP,
 
         for (itemSeq = 0; itemSeq < items; ++itemSeq) {
             /* Read bits from bitrow, send to format & print function. */
-            
+
             putitem((bitrow[itemSeq*2]<<8) + bitrow[itemSeq*2+1]);
         }
     }
@@ -151,7 +151,7 @@ main(int argc,
         inputFileName = argv[1];
     else
         inputFileName = "-";
-    
+
     ifP = pm_openr(inputFileName);
 
     pbm_readpbminit(ifP, &cols, &rows, &format);
@@ -163,3 +163,5 @@ main(int argc,
     return 0;
 }
 
+
+
diff --git a/converter/pbm/pbmtowbmp.c b/converter/pbm/pbmtowbmp.c
index 2907fd68..e1b2b146 100644
--- a/converter/pbm/pbmtowbmp.c
+++ b/converter/pbm/pbmtowbmp.c
@@ -1,9 +1,9 @@
 /* pbmtowbmp.c - convert a portable bitmap to a Wireless Bitmap file
 
-   This is derived for Netpbm from the pbmwbmp package from 
+   This is derived for Netpbm from the pbmwbmp package from
    <http://www.looplab.com/wap/tools> on 2000.06.06.
-   
-   The specifications for the wbmp format are part of the Wireless 
+
+   The specifications for the wbmp format are part of the Wireless
    Application Environment specification at
    <http://www.wapforum.org/what/technical.htm>.
 
@@ -19,7 +19,7 @@
 
 #include "pbm.h"
 
-static void 
+static void
 outputint(int i) {
   int c = 1;
   while(i & 0x7f << 7*c) c++;
@@ -29,7 +29,7 @@ outputint(int i) {
 
 
 
-int 
+int
 main(int argc, char *argv[]) {
   FILE *f;
   bit **image;
@@ -58,13 +58,15 @@ main(int argc, char *argv[]) {
     for(col = 0; col < cols; col++) {
       if(image[row][col] == PBM_WHITE) c = c | (1 << (7-p));
       if(++p == 8) {
-	putchar(c);
-	p = c = 0;
+        putchar(c);
+        p = c = 0;
       }
     }
     if(p) putchar(c);
   }
-  
+
   return 0;
 }
 
+
+
diff --git a/converter/pbm/pbmtox10bm b/converter/pbm/pbmtox10bm
index deb3aeab..ca82fcd2 100644
--- a/converter/pbm/pbmtox10bm
+++ b/converter/pbm/pbmtox10bm
@@ -37,6 +37,16 @@ exec perl -w -x -S -- "$0" "$@"
 use strict;
 use File::Basename;
 use Cwd 'abs_path';
+use IO::Handle;
+
+
+
+sub pm_message($) {
+    STDERR->print("pbmtox10bm: $_[0]\n");
+}
+
+
+
 
 sub doVersionHack($) {
     my ($argvR) = @_;
@@ -56,13 +66,12 @@ my $infile;
 foreach (@ARGV) {
     if (/^-/) {
         # It's an option.  But Pbmtox10bm didn't have any options.
-        print(STDERR "Invalid option '$_'\n");
+        pm_message("Invalid option '$_'");
         exit(10);
     } else {
         # It's a parameter
         if (defined($infile)) {
-            print(STDERR
-                  "You may specify at most one non-option parameter.\n");
+            pm_message("You may specify at most one non-option parameter.");
             exit(10);
         } else {
             $infile = $_;
diff --git a/converter/pbm/pbmtoxbm.c b/converter/pbm/pbmtoxbm.c
index ecb72b30..a452d6fa 100644
--- a/converter/pbm/pbmtoxbm.c
+++ b/converter/pbm/pbmtoxbm.c
@@ -10,10 +10,10 @@
 ** implied warranty.
 */
 
-/* 2006.10 (afu)   
+/* 2006.10 (afu)
    Changed bitrow from plain to raw, read function from pbm_readpbmrow() to
    pbm_readpbmrow_packed().  Retired bitwise transformation functions.
- 
+
    Output function putitem rewritten to handle both X10 and X11.
 
    Added -name option.  There is no check for the string thus given.
@@ -35,7 +35,7 @@
 #include "nstring.h"
 
 
-enum xbmVersion { X10, X11 };
+enum XbmVersion { X10, X11 };
 
 struct CmdlineInfo {
     /* All the information the user supplied in the command line,
@@ -43,16 +43,16 @@ struct CmdlineInfo {
     */
     const char *    inputFileName;
     const char *    name;
-    enum xbmVersion xbmVersion;
+    enum XbmVersion xbmVersion;
 };
 
 static void
-parseCommandLine(int                 argc, 
+parseCommandLine(int                 argc,
                  const char **       argv,
                  struct CmdlineInfo *cmdlineP ) {
 /*----------------------------------------------------------------------------
    Parse program command line described in Unix standard form by argc
-   and argv.  Return the information in the options as *cmdlineP.  
+   and argv.  Return the information in the options as *cmdlineP.
 
    If command line is internally inconsistent (invalid options, etc.),
    issue error message to stderr and abort program.
@@ -61,8 +61,6 @@ parseCommandLine(int                 argc,
    was passed to us as the argv array.  We also trash *argv.
 -----------------------------------------------------------------------------*/
     optEntry * option_def;
-    /* Instructions to pm_optParseOptions3 on how to parse our options. */
-
     optStruct3 opt;
     unsigned int option_def_index;
     unsigned int x10, x11, nameSpec;
@@ -78,7 +76,7 @@ parseCommandLine(int                 argc,
     opt.short_allowed = FALSE;  /* We have no short (old-fashioned) options */
     opt.allowNegNum = FALSE;  /* We have no parms that are negative numbers */
 
-    pm_optParseOptions3(&argc, (char **)argv, opt, sizeof(opt), 0);
+    pm_optParseOptions4(&argc, argv, opt, sizeof(opt), 0);
         /* Uses and sets argc, argv, and some of *cmdlineP and others. */
 
     if (!nameSpec)
@@ -96,19 +94,19 @@ parseCommandLine(int                 argc,
                 pm_error("Image name '%s' contains invalid character (%c).",
                          cmdlineP->name, cmdlineP->name[i]);
     }
-    
+
     if (x10 && x11)
         pm_error("You can't specify both -x10 and -x11");
     else if (x10)
         cmdlineP->xbmVersion = X10;
-    else 
+    else
         cmdlineP->xbmVersion = X11;
-        
-    if (argc-1 < 1) 
+
+    if (argc-1 < 1)
         cmdlineP->inputFileName = "-";
     else {
         cmdlineP->inputFileName = argv[1];
-        
+
         if (argc-1 > 1)
             pm_error("Program takes zero or one argument (filename).  You "
                      "specified %u", argc-1);
@@ -141,22 +139,22 @@ generateName(char          const filenameArg[],
         /* indices into the input and output buffers */
 
         /* Start just after the rightmost slash, or at beginning if no slash */
-        if (strrchr(filenameArg, '/') == 0) 
+        if (strrchr(filenameArg, '/') == 0)
             argIndex = 0;
         else argIndex = strrchr(filenameArg, '/') - filenameArg + 1;
 
-        if (filenameArg[argIndex] == '\0') 
+        if (filenameArg[argIndex] == '\0')
             *nameP = strdup("noname");
         else {
             char * name;
             nameIndex = 0;  /* Start at beginning of name buffer */
 
             name = malloc(strlen(filenameArg));
-    
-            while (filenameArg[argIndex] != '\0' 
+
+            while (filenameArg[argIndex] != '\0'
                    && filenameArg[argIndex] != '.') {
                 const char filenameChar = filenameArg[argIndex++];
-                name[nameIndex++] = 
+                name[nameIndex++] =
                     ISALNUM(filenameChar) ? filenameChar : '_';
             }
             name[nameIndex] = '\0';
@@ -167,37 +165,46 @@ generateName(char          const filenameArg[],
 
 
 
-static unsigned short int itemBuff[22];
-static int itemCnt;    /* takes values 0 to 15 (x11) or 21 (x10) */
-static enum xbmVersion itemVersion;
+typedef struct {
+    unsigned short int buff[22];
+    int cnt;    /* takes values 0 to 15 (x11) or 21 (x10) */
+    enum XbmVersion version;
+} ItemWriter;
+
+static ItemWriter itemWriter;
 
 
 
 static void
 putitemX10(unsigned char const item) {
 
-    if (itemCnt == 22) {
+    if (itemWriter.cnt == 22) {
         /* Buffer is full.  Write out one line. */
         int rc;
         rc = printf(" 0x%02x%02x,0x%02x%02x,0x%02x%02x,0x%02x%02x,"
                     "0x%02x%02x,0x%02x%02x,0x%02x%02x,0x%02x%02x,"
                     "0x%02x%02x,0x%02x%02x,0x%02x%02x,\n",
-                    itemBuff[ 1], itemBuff[ 0], itemBuff[ 3], itemBuff[ 2],
-                    itemBuff[ 5], itemBuff[ 4], itemBuff[ 7], itemBuff[ 6],
-                    itemBuff[ 9], itemBuff[ 8], itemBuff[11], itemBuff[10],
-                    itemBuff[13], itemBuff[12], itemBuff[15], itemBuff[14],
-                    itemBuff[17], itemBuff[16], itemBuff[19], itemBuff[18],
-                    itemBuff[21], itemBuff[20]
+                    itemWriter.buff[ 1], itemWriter.buff[ 0],
+                    itemWriter.buff[ 3], itemWriter.buff[ 2],
+                    itemWriter.buff[ 5], itemWriter.buff[ 4],
+                    itemWriter.buff[ 7], itemWriter.buff[ 6],
+                    itemWriter.buff[ 9], itemWriter.buff[ 8],
+                    itemWriter.buff[11], itemWriter.buff[10],
+                    itemWriter.buff[13], itemWriter.buff[12],
+                    itemWriter.buff[15], itemWriter.buff[14],
+                    itemWriter.buff[17], itemWriter.buff[16],
+                    itemWriter.buff[19], itemWriter.buff[18],
+                    itemWriter.buff[21], itemWriter.buff[20]
             );
 
-        if (rc < 0)        
+        if (rc < 0)
             pm_error("Error writing X10 bitmap raster item.  "
                      "printf() failed with errno %d (%s)",
                      errno, strerror(errno));
-        
-        itemCnt = 0;
+
+        itemWriter.cnt = 0;
     }
-    itemBuff[itemCnt++] = bitreverse[item];
+    itemWriter.buff[itemWriter.cnt++] = bitreverse[item];
 }
 
 
@@ -205,26 +212,30 @@ putitemX10(unsigned char const item) {
 static void
 putitemX11(unsigned char const item) {
 
-    if (itemCnt == 15 ) {
+    if (itemWriter.cnt == 15 ) {
         /* Buffer is full.  Write out one line. */
         int rc;
         rc = printf(" 0x%02x,0x%02x,0x%02x,0x%02x,"
                     "0x%02x,0x%02x,0x%02x,0x%02x,"
                     "0x%02x,0x%02x,0x%02x,0x%02x,"
                     "0x%02x,0x%02x,0x%02x,\n",
-                    itemBuff[0], itemBuff[1], itemBuff[2], itemBuff[3],
-                    itemBuff[4], itemBuff[5], itemBuff[6], itemBuff[7],
-                    itemBuff[8], itemBuff[9], itemBuff[10],itemBuff[11],
-                    itemBuff[12],itemBuff[13],itemBuff[14]
+                    itemWriter.buff[ 0], itemWriter.buff[ 1],
+                    itemWriter.buff[ 2], itemWriter.buff[ 3],
+                    itemWriter.buff[ 4], itemWriter.buff[ 5],
+                    itemWriter.buff[ 6], itemWriter.buff[ 7],
+                    itemWriter.buff[ 8], itemWriter.buff[ 9],
+                    itemWriter.buff[10], itemWriter.buff[11],
+                    itemWriter.buff[12], itemWriter.buff[13],
+                    itemWriter.buff[14]
             );
-        if (rc < 0)        
+        if (rc < 0)
             pm_error("Error writing X11 bitmap raster item.  "
                      "printf() failed with errno %d (%s)",
                      errno, strerror(errno));
-        
-        itemCnt = 0;
+
+        itemWriter.cnt = 0;
     }
-    itemBuff[itemCnt++] = bitreverse[item];
+    itemWriter.buff[itemWriter.cnt++] = bitreverse[item];
 }
 
 
@@ -232,7 +243,7 @@ putitemX11(unsigned char const item) {
 static void
 putitem(unsigned char const item) {
 
-    switch (itemVersion) {
+    switch (itemWriter.version) {
     case X10: putitemX10(item); break;
     case X11: putitemX11(item); break;
     }
@@ -245,19 +256,19 @@ puttermX10(void) {
 
     unsigned int i;
 
-    assert(itemCnt % 2 == 0);
+    assert(itemWriter.cnt % 2 == 0);
 
-    for (i = 0; i < itemCnt; i += 2) {
+    for (i = 0; i < itemWriter.cnt; i += 2) {
         int rc;
 
-        assert(i + 1 < itemCnt);
+        assert(i + 1 < itemWriter.cnt);
 
         rc = printf("%s0x%02x%02x%s",
                     (i == 0) ? " " : "",
-                    itemBuff[i+1],
-                    itemBuff[i], 
-                    (i + 2 >= itemCnt) ? "" : ",");
-        if (rc < 0)        
+                    itemWriter.buff[i+1],
+                    itemWriter.buff[i],
+                    (i + 2 >= itemWriter.cnt) ? "" : ",");
+        if (rc < 0)
             pm_error("Error writing Item %u at end of X10 bitmap raster.  "
                      "printf() failed with errno %d (%s)",
                      i, errno, strerror(errno));
@@ -271,15 +282,15 @@ puttermX11(void) {
 
     unsigned int i;
 
-    for (i = 0; i < itemCnt; ++i) {
+    for (i = 0; i < itemWriter.cnt; ++i) {
         int rc;
 
         rc = printf("%s0x%02x%s",
                     (i == 0)  ? " " : "",
-                    itemBuff[i],
-                    (i + 1 >= itemCnt) ? "" : ",");
+                    itemWriter.buff[i],
+                    (i + 1 >= itemWriter.cnt) ? "" : ",");
 
-        if (rc < 0)        
+        if (rc < 0)
             pm_error("Error writing Item %u at end of X11 bitmap raster.  "
                      "printf() failed with errno %d (%s)",
                      i, errno, strerror(errno));
@@ -289,10 +300,10 @@ puttermX11(void) {
 
 
 static void
-putinit(enum xbmVersion const xbmVersion) {
+putinit(enum XbmVersion const xbmVersion) {
 
-    itemCnt = 0;
-    itemVersion = xbmVersion;
+    itemWriter.cnt = 0;
+    itemWriter.version = xbmVersion;
 }
 
 
@@ -300,7 +311,7 @@ putinit(enum xbmVersion const xbmVersion) {
 static void
 putterm(void) {
 
-    switch (itemVersion) {
+    switch (itemWriter.version) {
     case X10: puttermX10(); break;
     case X11: puttermX11(); break;
     }
@@ -310,7 +321,7 @@ putterm(void) {
 
         rc = printf("};\n");
 
-        if (rc < 0)        
+        if (rc < 0)
             pm_error("Error writing end of X11 bitmap raster.  "
                      "printf() failed with errno %d (%s)",
                      errno, strerror(errno));
@@ -320,7 +331,7 @@ putterm(void) {
 
 
 static void
-writeXbmHeader(enum xbmVersion const xbmVersion,
+writeXbmHeader(enum XbmVersion const xbmVersion,
                const char *    const name,
                unsigned int    const width,
                unsigned int    const height,
@@ -341,11 +352,11 @@ convertRaster(FILE *          const ifP,
               unsigned int    const rows,
               int             const format,
               FILE *          const ofP,
-              enum xbmVersion const xbmVersion) {
-              
-    unsigned int const bitsPerUnit = xbmVersion == X10 ? 16 : 8;   
+              enum XbmVersion const xbmVersion) {
+
+    unsigned int const bitsPerUnit = xbmVersion == X10 ? 16 : 8;
     unsigned int const padright = ROUNDUP(cols, bitsPerUnit) - cols;
-        /* Amount of padding to round cols up to the nearest multiple of 
+        /* Amount of padding to round cols up to the nearest multiple of
            8 (if x11) or 16 (if x10).
         */
     unsigned int const bitrowBytes = (cols + padright) / 8;
@@ -353,10 +364,14 @@ convertRaster(FILE *          const ifP,
     unsigned char * bitrow;
     unsigned int row;
 
+    if (cols > UINT_MAX - bitsPerUnit)
+        pm_error("Image is too wide (%u columns) for computations",
+                 cols);
+
     putinit(xbmVersion);
 
     bitrow = pbm_allocrow_packed(cols + padright);
-    
+
     for (row = 0; row < rows; ++row) {
         unsigned int i;
 
@@ -382,7 +397,7 @@ int
 main(int           argc,
      const char ** argv) {
 
-    struct CmdlineInfo cmdline; 
+    struct CmdlineInfo cmdline;
     FILE * ifP;
     int rows, cols, format;
     const char * name;
@@ -390,15 +405,15 @@ main(int           argc,
     pm_proginit(&argc, argv);
 
     parseCommandLine(argc, argv, &cmdline);
-    if (cmdline.name == NULL) 
+    if (cmdline.name == NULL)
         generateName(cmdline.inputFileName, &name);
     else
         name = strdup(cmdline.name);
 
     ifP = pm_openr(cmdline.inputFileName);
-    
+
     pbm_readpbminit(ifP, &cols, &rows, &format);
-    
+
     writeXbmHeader(cmdline.xbmVersion, name, cols, rows, stdout);
 
     convertRaster(ifP, cols, rows, format, stdout, cmdline.xbmVersion);
diff --git a/converter/pbm/pbmtoybm.c b/converter/pbm/pbmtoybm.c
index 27ce6cb1..7281866c 100644
--- a/converter/pbm/pbmtoybm.c
+++ b/converter/pbm/pbmtoybm.c
@@ -66,7 +66,7 @@ main(int argc, const char *argv[]) {
         pm_error("Input image is too large.");
 
     bitrow = pbm_allocrow_packed(cols + 8);
-    
+
     putinit(cols, rows);
 
     bitrow[pbm_packed_bytes(cols + 8) - 1] = 0x00;
@@ -95,3 +95,4 @@ main(int argc, const char *argv[]) {
 }
 
 
+
diff --git a/converter/pbm/pbmtozinc.c b/converter/pbm/pbmtozinc.c
index a89b8c9f..3bf3acd0 100644
--- a/converter/pbm/pbmtozinc.c
+++ b/converter/pbm/pbmtozinc.c
@@ -182,3 +182,6 @@ main(int argc, const char * argv[]) {
 
     return 0;
 }
+
+
+
diff --git a/converter/pbm/pi3topbm.c b/converter/pbm/pi3topbm.c
index 17b07d6f..36ff4127 100644
--- a/converter/pbm/pi3topbm.c
+++ b/converter/pbm/pi3topbm.c
@@ -40,13 +40,13 @@ struct CmdlineInfo {
 
 
 
-static void 
-parseCommandLine(int argc, 
-                 const char ** argv, 
+static void
+parseCommandLine(int argc,
+                 const char ** argv,
                  struct CmdlineInfo * const cmdlineP) {
 /* --------------------------------------------------------------------------
    Parse program command line described in Unix standard form by argc
-   and argv.  Return the information in the options as *cmdlineP.  
+   and argv.  Return the information in the options as *cmdlineP.
 
    If command line is internally inconsistent (invalid options, etc.),
    issue error message to stderr and abort program.
@@ -56,22 +56,21 @@ parseCommandLine(int argc,
 --------------------------------------------------------------------------*/
     optEntry * option_def;
     optStruct3 opt;
-        /* Instructions to pm_optParseOptions3 on how to parse our options. */
     unsigned int option_def_index;
-  
+
     MALLOCARRAY_NOFAIL(option_def, 100);
 
     option_def_index = 0;   /* incremented by OPTENT3 */
     OPTENT3(0, "debug",    OPT_FLAG,    NULL,       &cmdlineP->debug,       0);
-  
+
     opt.opt_table = option_def;
     opt.short_allowed = FALSE;  /* We have no short (old-fashioned) options */
     opt.allowNegNum = FALSE;   /* We have no parms that are negative numbers */
 
-    pm_optParseOptions3(&argc, (char **)argv, opt, sizeof(opt), 0);
+    pm_optParseOptions4(&argc, argv, opt, sizeof(opt), 0);
         /* Uses and sets argc, argv, and some of *cmdlineP and others. */
 
-    if (argc-1 < 1) 
+    if (argc-1 < 1)
         cmdlineP->inputFileName = "-";
     else {
         cmdlineP->inputFileName = argv[1];
@@ -166,3 +165,6 @@ main(int argc, const char ** argv) {
 
     return 0;
 }
+
+
+
diff --git a/converter/pbm/pktopbm.c b/converter/pbm/pktopbm.c
index 712f339f..201b046a 100644
--- a/converter/pbm/pktopbm.c
+++ b/converter/pbm/pktopbm.c
@@ -7,159 +7,277 @@
      * fix bitmap y placement of dynamically packed char
      * skip char early if no output file allocated
      - added debug output
-  
+
   compile with: cc -lpbm -o pktopbm pktopbm.c
   */
 
+#include <stdbool.h>
 #include <stdio.h>
 #include <string.h>
 
 #include "pm_c_util.h"
 #include "nstring.h"
+#include "mallocvar.h"
+#include "shhopt.h"
 #include "pbm.h"
 
 #define NAMELENGTH 80
 #define MAXROWWIDTH 3200
 #define MAXPKCHAR 256
 
-typedef int integer ;
-typedef unsigned char quarterword ;
-typedef char boolean ;
-typedef quarterword eightbits ;
-
-static FILE *pkfile ;
-static char pkname[NAMELENGTH+1] ;
-static integer pktopbm_pkloc = 0;
-static char *filename[MAXPKCHAR] ;
-static bit **bitmap = NULL ;
-static integer dynf ;
-static eightbits inputbyte ;
-static eightbits bitweight ;
-static integer repeatcount ;
-static integer flagbyte ;
-static integer debug=0;
+struct CmdlineInfo {
+    /* All the information the user supplied in the command line,
+       in a form easy for the program to use.
+    */
+    const char * inputFileNm;
+    unsigned int outputFileCt;
+        /* The number of output files */
+    const char * outputFileNm[MAXPKCHAR];
+        /* The output file name, in order */
+    unsigned int character;
+    unsigned int xSpec;
+    unsigned int x;
+    unsigned int ySpec;
+    unsigned int y;
+    unsigned int debug;
+};
+
 
-#define dprintf(s,d) if (debug) printf(s,d)
-#define dprintf0(s) if (debug) printf(s)
 
-/* add a suffix to a filename in an allocated space */
 static void
-pktopbm_add_suffix(char *       const name, 
-                   const char * const suffix) {
-
-    char * const slash = strrchr(name, '/');
-    char * const dot   = strrchr(name, '.');
-    
-    if ((dot && slash ? dot < slash : !dot) && !streq(name, "-"))
-        strcat(name, suffix);
+parseCommandLine(int argc, const char ** argv,
+                 struct CmdlineInfo * const cmdlineP) {
+/*----------------------------------------------------------------------------
+   Note that the file spec strings we return are stored in the storage that
+   was passed to us as the argv array.
+-----------------------------------------------------------------------------*/
+    optEntry * option_def;
+    optStruct3 opt;
+
+    unsigned int option_def_index;
+    unsigned int characterSpec;
+    unsigned int firstOutputArgNm;
+
+    MALLOCARRAY_NOFAIL(option_def, 100);
+
+    option_def_index = 0;   /* incremented by OPTENTRY */
+    OPTENT3(0, "character",   OPT_UINT, &cmdlineP->character,
+            &characterSpec, 0);
+    OPTENT3(0, "x",   OPT_UINT, &cmdlineP->x,
+            &cmdlineP->xSpec, 0);
+    OPTENT3(0, "X",   OPT_UINT, &cmdlineP->x,
+            &cmdlineP->xSpec, 0);
+    OPTENT3(0, "y",   OPT_UINT, &cmdlineP->y,
+            &cmdlineP->ySpec, 0);
+    OPTENT3(0, "Y",   OPT_UINT, &cmdlineP->y,
+            &cmdlineP->ySpec, 0);
+    OPTENT3(0, "debug",   OPT_UINT, NULL,
+            &cmdlineP->debug, 0);
+
+    opt.opt_table = option_def;
+    opt.short_allowed = FALSE;  /* We have no short (old-fashioned) options */
+    opt.allowNegNum = FALSE;  /* We may have parms that are negative numbers */
+
+    pm_optParseOptions4(&argc, argv, opt, sizeof(opt), 0);
+        /* Uses and sets argc, argv, and some of *cmdlineP and others. */
+
+    if (characterSpec) {
+        if (cmdlineP->character >= MAXPKCHAR)
+            pm_error("Character number (-character) must be in range 0 to %u",
+                     MAXPKCHAR-1);
+    } else
+        cmdlineP->character = 0;
+
+    if (argc-1 < 1) {
+        cmdlineP->inputFileNm = "-";
+        firstOutputArgNm = 1;
+    } else {
+        cmdlineP->inputFileNm = argv[1];
+        firstOutputArgNm = 2;
+    }
+
+    cmdlineP->outputFileCt = 0;  /* initial value */
+    {
+        unsigned int argn;
+        bool stdoutUsed;
+        for (argn = firstOutputArgNm, stdoutUsed = false;
+             argn < argc;
+             ++argn) {
+            if (cmdlineP->outputFileCt >= MAXPKCHAR)
+                pm_error("You may not specify more than %u output files.",
+                         MAXPKCHAR);
+            cmdlineP->outputFileNm[cmdlineP->outputFileCt++] = argv[argn];
+            if (streq(argv[argn], "-")) {
+                if (stdoutUsed)
+                    pm_error("You cannot specify Standard Output ('-') "
+                             "for more than one output file");
+                stdoutUsed = true;
+            }
+        }
+    }
+    if (cmdlineP->outputFileCt < 1)
+        cmdlineP->outputFileNm[cmdlineP->outputFileCt++] = "-";
+
+    if (cmdlineP->character + cmdlineP->outputFileCt >= MAXPKCHAR)
+        pm_error("Number of output files (%u) "
+                 "plus -character value (%u) exceeds "
+                 "the maximum number of characters is a PK font file (%u)",
+                 cmdlineP->character, cmdlineP->outputFileCt, MAXPKCHAR);
 }
 
 
 
-/* get a byte from the PK file */
-static eightbits 
-pktopbm_pkbyte(void) {
-   pktopbm_pkloc++ ;
-   return(getc(pkfile)) ;
+typedef unsigned char eightbits ;
+
+static FILE * ifP;
+static unsigned int pkLoc;
+static const char * fileName[MAXPKCHAR];
+static int dynf ;
+static eightbits inputByte ;
+static eightbits bitWeight ;
+static int repeatCount ;
+static int flagByte ;
+static int debug = 0;
+
+#define dprintf(s,d) if (debug) printf(s,d)
+#define dprintf0(s) if (debug) printf(s)
+
+static eightbits
+pkByte() {
+/*----------------------------------------------------------------------------
+  Get a byte from the PK file
+-----------------------------------------------------------------------------*/
+    ++pkLoc;
+
+    return getc(ifP);
 }
 
 
 
-/* get a 16-bit half word from the PK file */
-static integer 
-get16(void) {
-   integer const a = pktopbm_pkbyte() ;
-   return((a<<8) + pktopbm_pkbyte()) ;
+static int
+get16() {
+/*----------------------------------------------------------------------------
+  Get a 16-bit half word from the PK file
+-----------------------------------------------------------------------------*/
+    int const a = pkByte() ;
+
+    return (a<<8) + pkByte();
 }
 
 
 
-/* get a 32-bit word from the PK file */
-static integer get32(void) {
-    integer a;
-    a = get16() ;
-    if (a > 32767) a -= 65536 ;
-    return((a<<16) + get16()) ;
+static int
+get32() {
+/*----------------------------------------------------------------------------
+  Get a 32-bit word from the PK file
+-----------------------------------------------------------------------------*/
+    int a;
+
+    a = get16();  /* initial value */
+
+    if (a > 32767)
+        a -= 65536;
+
+    return (a << 16) + get16();
 }
 
 
 
-/* get a nibble from current input byte, or new byte if no current byte */
-static integer 
-getnyb(void) {
+static int
+getNybble() {
+/*----------------------------------------------------------------------------
+  Get a nibble from current input byte, or new byte if no current byte
+-----------------------------------------------------------------------------*/
     eightbits temp;
-    if (bitweight == 0) {
-        inputbyte = pktopbm_pkbyte() ;
-        bitweight = 16 ;
+
+    if (bitWeight == 0) {
+        inputByte = pkByte() ;
+        bitWeight = 16 ;
     }
-    temp = inputbyte / bitweight ;
-    inputbyte -= temp * bitweight ;
-    bitweight >>= 4 ;
-    return(temp) ;
+    temp = inputByte / bitWeight ;
+    inputByte -= temp * bitWeight ;
+    bitWeight >>= 4 ;
+
+    return temp;
 }
 
 
 
-/* get a bit from the current input byte, or a new byte if no current byte */
 static bool
-getbit(void) {
+getBit() {
+/*----------------------------------------------------------------------------
+  Get a bit from the current input byte, or a new byte if no current byte
+-----------------------------------------------------------------------------*/
     bool temp ;
-    bitweight >>= 1 ;
-    if (bitweight == 0) {
-        inputbyte = pktopbm_pkbyte() ;
-        bitweight = 128 ;
+
+    bitWeight >>= 1 ;
+    if (bitWeight == 0) {
+        inputByte = pkByte();
+        bitWeight = 128 ;
     }
-    temp = (inputbyte >= bitweight) ;
-    if (temp) inputbyte -= bitweight ;
-    return(temp) ;
+    temp = (inputByte >= bitWeight);
+    if (temp)
+        inputByte -= bitWeight;
+
+    return temp;
 }
 
 
 
-/* unpack a dynamically packed number. dynf is dynamic packing threshold  */
-static integer 
-pkpackednum(void) {
-    integer i, j ;
-    i = getnyb() ;
+static int
+pkPackedNum() {
+/*----------------------------------------------------------------------------
+  Unpack a dynamically packed number. dynf is dynamic packing threshold
+-----------------------------------------------------------------------------*/
+    int i, j ;
+
+    i = getNybble() ;
+
     if (i == 0) {           /* large run count, >= 3 nibbles */
         do {
-            j = getnyb() ;          /* count extra nibbles */
+            j = getNybble() ;          /* count extra nibbles */
             i++ ;
         } while (j == 0) ;
         while (i > 0) {
-            j = (j<<4) + getnyb() ; /* add extra nibbles */
+            j = (j<<4) + getNybble() ; /* add extra nibbles */
             i-- ;
         }
         return (j - 15 +((13 - dynf)<<4) + dynf) ;
     } else if (i <= dynf) return (i) ;  /* number > 0 and <= dynf */
-    else if (i < 14) return (((i - dynf - 1)<<4) + getnyb() + dynf + 1) ;
+    else if (i < 14) return (((i - dynf - 1)<<4) + getNybble() + dynf + 1) ;
     else {
-        if (i == 14) repeatcount = pkpackednum() ;  /* get repeat count */
-        else repeatcount = 1 ;      /* value 15 indicates repeat count 1 */
-        return(pkpackednum()) ;
+        if (i == 14)
+            repeatCount = pkPackedNum() ;  /* get repeat count */
+        else
+            repeatCount = 1 ;      /* value 15 indicates repeat count 1 */
+
+        return pkPackedNum();
     }
 }
 
 
 
-/* skip specials in PK files, inserted by Metafont or some other program */
 static void
-skipspecials(void) {
-    integer i, j;
+skipSpecials() {
+/*----------------------------------------------------------------------------
+  Skip specials in PK files, inserted by Metafont or some other program
+-----------------------------------------------------------------------------*/
     do {
-        flagbyte = pktopbm_pkbyte() ;
-        if (flagbyte >= 240)
-            switch(flagbyte) {
+        flagByte = pkByte() ;
+        if (flagByte >= 240)
+            switch(flagByte) {
             case 240:           /* specials of size 1-4 bytes */
             case 241:
             case 242:
-            case 243:
+            case 243: {
+                int i, j;
+
                 i = 0 ;
-                for (j = 240 ; j <= flagbyte ; ++j) 
-                    i = (i<<8) + pktopbm_pkbyte() ;
-                for (j = 1 ; j <= i ; ++j) 
-                    pktopbm_pkbyte() ;  /* ignore special */
-                break ;
+                for (j = 240 ; j <= flagByte ; ++j)
+                    i = (i<<8) + pkByte() ;
+                for (j = 1 ; j <= i ; ++j)
+                    pkByte() ;  /* ignore special */
+            } break ;
             case 244:           /* no-op, parameters to specials */
                 get32() ;
             case 245:           /* start of postamble */
@@ -174,272 +292,378 @@ skipspecials(void) {
             case 253:
             case 254:
             case 255:
-                pm_error("unexpected flag byte %d", flagbyte) ;
+                pm_error("unexpected flag byte %d", flagByte) ;
             }
-    } while (!(flagbyte < 240 || flagbyte == 245)) ;
+    } while (!(flagByte < 240 || flagByte == 245)) ;
 }
 
 
 
-/* ignore character packet */
 static void
-ignorechar(integer const car, 
-           integer const endofpacket) {
+ignoreChar(int          const car,
+           unsigned int const endOfPacket) {
+/*----------------------------------------------------------------------------
+   ignore character packet
+-----------------------------------------------------------------------------*/
+   while (pkLoc != endOfPacket)
+       pkByte();
 
-   while (pktopbm_pkloc != endofpacket) pktopbm_pkbyte() ;
    if (car < 0 || car >= MAXPKCHAR)
       pm_message("Character %d out of range", car) ;
-   skipspecials() ;
+
+   skipSpecials() ;
 }
 
 
 
-int
-main(int argc, char *argv[]) {
-    integer x;
-    integer endofpacket ;
-    boolean turnon ;
-    integer i, j;
-    integer car ;
-    integer bmx=0, bmy=0;
-    integer set_bmx=0, set_bmy=0;
-    bit row[MAXROWWIDTH+1] ;
-    const char * const usage = 
-        "pkfile[.pk] [-d] [[-x width] [-y height] [-c num] pbmfile]...";
-   
-    pbm_init(&argc, argv);
-    for (i = 0 ; i < MAXPKCHAR ; i ++) filename[i] = NULL ;
-
-    pm_message("This is PKtoPBM, version 2.5") ;
-
-    if (--argc < 1) pm_usage(usage) ;
-
-    ++argv;
-    if(strlen(*argv) + 4 > NAMELENGTH)
-        pm_error("pkname is too long");
-    strcpy(pkname, *argv) ;
-    pktopbm_add_suffix(pkname, ".pk") ;
-
-    car = 0 ;
-    /* urg: use getopt */
-    while (++argv, --argc) {
-        if (argv[0][0] == '-' && argv[0][1])
-            switch (argv[0][1]) {
-            case 'X':
-            case 'x':
-                if (argv[0][2]) bmx = atoi(*argv+2) ;
-                else if (++argv, --argc) set_bmx = atoi(*argv) ;
-                else pm_usage(usage) ;
-                continue ;
-            case 'Y':
-            case 'y':
-                if (argv[0][2]) bmy = atoi(*argv+2) ;
-                else if (++argv, --argc) set_bmy = atoi(*argv) ;
-                else pm_usage(usage) ;
-                continue ;
-            case 'C':
-            case 'c':
-                if (argv[0][2]) car = atoi(*argv+2) ;
-                else if (++argv, --argc) car = atoi(*argv) ;
-                else pm_usage(usage) ;
-                break ;
-            case 'd':
-                debug=1;
-                break ;
-            default:
-                pm_usage(usage) ;
-            } else if (car < 0 || car >= MAXPKCHAR) {
-                pm_error("character must be in range 0 to %d (-c)", 
-                         MAXPKCHAR-1) ;
-            } else filename[car++] = *argv ;
-    }
+static void
+readHeader() {
+/*----------------------------------------------------------------------------
+   Read the header of the input file.
+
+   Surprisingly, nothing in the header is useful to this program, so we're
+   just reading past it and doing some validation.
 
-    pkfile = pm_openr(pkname);
-    if (pktopbm_pkbyte() != 247)
+   We read through the first flag byte and update the global variable
+   'flagByte'.
+-----------------------------------------------------------------------------*/
+    unsigned int commentSz;
+    unsigned int i;
+
+    if (pkByte() != 247)
         pm_error("bad PK file (pre command missing)") ;
-    if (pktopbm_pkbyte() != 89)
+
+    if (pkByte() != 89)
         pm_error("wrong version of packed file") ;
-    j = pktopbm_pkbyte() ;              /* get header comment size */
-    for (i = 1 ; i <= j ; i ++) pktopbm_pkbyte() ;  /* ignore header comment */
+
+    commentSz = pkByte() ;              /* get header comment size */
+
+    for (i = 1 ; i <= commentSz ; ++i)
+        pkByte() ;  /* ignore header comment */
+
     get32() ;                   /* ignore designsize */
     get32() ;                   /* ignore checksum */
     if (get32() != get32())         /* h & v pixels per point */
         pm_message("Warning: aspect ratio not 1:1") ;
-    skipspecials() ;
-    while (flagbyte != 245) {           /* not at postamble */
-        integer cheight, cwidth ;
-        integer xoffs=0, yoffs=0;
-        FILE *ofp;
-
-        bmx=set_bmx;
-        bmy=set_bmy;
-        dynf = (flagbyte>>4) ;          /* get dynamic packing value */
-        flagbyte &= 15 ;
-        turnon = (flagbyte >= 8) ;      /* black or white initially? */
-        if (turnon) flagbyte &= 7 ;     /* long or short form */
-        if (flagbyte == 7) {            /* long form preamble */
-            integer packetlength = get32() ;    /* character packet length */
-            car = get32() ;         /* character number */
-            endofpacket = packetlength + pktopbm_pkloc;
-                /* calculate end of packet */
-            if ((car >= MAXPKCHAR) || !filename[car]) {
-                ignorechar(car, endofpacket);
-                continue;
-            }
-            dprintf0 ("flagbyte7\n");
-            dprintf ("car: %d\n", car);
-            get32() ;               /* ignore tfmwidth */
-            x=get32() ;             /* ignore horiz escapement */
-            x=get32() ;             /* ignore vert escapement */
-            dprintf ("horiz esc %d\n", x);
-            dprintf ("vert esc %d\n", x);
-            cwidth = get32() ;          /* bounding box width */
-            cheight = get32() ;         /* bounding box height */
-            dprintf ("cwidth %d\n", cwidth);
-            dprintf ("cheight %d\n", cheight);
-            if (cwidth < 0 || cheight < 0 || 
-                cwidth > 65535 || cheight > 65535) {
-                ignorechar(car, endofpacket);
-                continue;
-            }
-            xoffs= get32() ;              /* horiz offset */
-            yoffs= get32() ;              /* vert offset */
-            dprintf ("xoffs %d\n", xoffs);
-            dprintf ("yoffs %d\n", yoffs);
-        } else if (flagbyte > 3) {      /* extended short form */
-            integer packetlength = ((flagbyte - 4)<<16) + get16() ;
-            /* packet length */
-            car = pktopbm_pkbyte() ;            /* char number */
-            endofpacket = packetlength + pktopbm_pkloc ; 
-                /* calculate end of packet */
-            if ((car >= MAXPKCHAR) || !filename[car]) {
-                ignorechar(car, endofpacket);
-                continue;
-            }
-            dprintf0 ("flagbyte>3\n");
-            dprintf ("car: %d\n", car);
-            pktopbm_pkbyte() ;              /* ignore tfmwidth (3 bytes) */
-            get16() ;               /* ignore tfmwidth (3 bytes) */
-            get16() ;               /* ignore horiz escapement */
-            cwidth = get16() ;          /* bounding box width */
-            cheight = get16() ;         /* bounding box height */
-            dprintf ("cwidth %d\n", cwidth);
-            dprintf ("cheight %d\n", cheight);
-            xoffs=get16();                         /* horiz offset */
-            if (xoffs >= 32768)
-                xoffs-= 65536;
-            yoffs=get16();                         /* vert offset */
-            if (yoffs >= 32768)
-                yoffs-= 65536;
-            dprintf ("xoffs %d\n", xoffs);
-            dprintf ("yoffs %d\n", yoffs);
-        } else {                    /* short form preamble */
-            integer packetlength = (flagbyte<<8) + pktopbm_pkbyte() ;
-            /* packet length */
-            car = pktopbm_pkbyte() ;            /* char number */
-            endofpacket = packetlength + pktopbm_pkloc ;    
-                /* calculate end of packet */
-            if ((car >= MAXPKCHAR) || !filename[car]) {
-                ignorechar(car, endofpacket);
-                continue;
-            }
-            dprintf0 ("flagbyte<=3\n");
-            dprintf ("car: %d\n", car);
-            pktopbm_pkbyte() ;          /* ignore tfmwidth (3 bytes) */
-            get16() ;               /* ignore tfmwidth (3 bytes) */
-            x = pktopbm_pkbyte() ;  /* ignore horiz escapement */
-            dprintf ("horiz esc %d\n", x);
-            cwidth = pktopbm_pkbyte() ;            /* bounding box width */
-            cheight = pktopbm_pkbyte() ;           /* bounding box height */
-            dprintf ("cwidth %d\n", cwidth);
-            dprintf ("cheight %d\n", cheight);
-            xoffs=pktopbm_pkbyte ();               /* horiz offset */
-            if (xoffs >= 128)
-                xoffs-=256;
-            yoffs=pktopbm_pkbyte ();               /* vert offset */
-            if (yoffs >= 128)
-                yoffs-=256;
+
+    skipSpecials();
+}
+
+
+
+static void
+readCharacterHeader(int *          const carP,
+                    unsigned int * const endOfPacketP,
+                    bool *         const mustIgnoreP,
+                    int *          const cheightP,
+                    int *          const cwidthP,
+                    int *          const xoffsP,
+                    int *          const yoffsP,
+                    bool *         const turnonP) {
+
+    int packetLength;
+        /* character packet length field value */
+    int cheight, cwidth;
+        /* bounding box height, width field values */
+    int xoffs=0, yoffs=0;
+    bool turnon ;
+    int x;
+
+    dynf = (flagByte >> 4);          /* get dynamic packing value */
+    flagByte &= 15;
+    turnon = (flagByte >= 8) ;      /* black or white initially? */
+    if (turnon)
+        flagByte &= 7;     /* long or short form */
+
+    if (flagByte == 7) {            /* long form preamble */
+        packetLength  = get32();
+        *carP         = get32();         /* character number */
+
+        dprintf0("flagByte7\n");
+        dprintf("car: %d\n", *carP);
+        get32();               /* ignore tfmwidth */
+        x=get32();             /* ignore horiz escapement */
+        dprintf("horiz esc %d\n", x);
+        x=get32();             /* ignore vert escapement */
+        dprintf("vert esc %d\n", x);
+        cwidth = get32();          /* bounding box width */
+        cheight = get32();         /* bounding box height */
+        dprintf("cwidth %d\n", cwidth);
+        dprintf("cheight %d\n", cheight);
+        if (cwidth < 0 || cheight < 0 ||
+            cwidth > 65535 || cheight > 65535) {
+            *mustIgnoreP = true;
+        } else {
+            *mustIgnoreP = false;
+            xoffs = get32() ;              /* horiz offset */
+            yoffs = get32() ;              /* vert offset */
             dprintf ("xoffs %d\n", xoffs);
             dprintf ("yoffs %d\n", yoffs);
         }
-        if (filename[car]) {
-            if (!bmx) bmx= cwidth;
-            if (!bmy) bmy= cheight;
-            bitmap = pbm_allocarray(bmx, bmy) ;
-            if (bitmap == NULL)
-                pm_error("out of memory allocating bitmap") ;
-        } else {
-            ignorechar(car, endofpacket);
-            continue;
+    } else if (flagByte > 3) {      /* extended short form */
+        packetLength = ((flagByte - 4)<<16) + get16() ;
+
+        *carP = pkByte() ;            /* char number */
+
+        *mustIgnoreP = false;
+
+        dprintf0("flagByte>3\n");
+        dprintf("car: %d\n", *carP);
+        pkByte();              /* ignore tfmwidth (3 bytes) */
+        get16();               /* ignore tfmwidth (3 bytes) */
+        get16();               /* ignore horiz escapement */
+        cwidth = get16();          /* bounding box width */
+        cheight = get16();         /* bounding box height */
+        dprintf("cwidth %d\n", cwidth);
+        dprintf("cheight %d\n", cheight);
+        xoffs = get16();                         /* horiz offset */
+        if (xoffs >= 32768)
+            xoffs -= 65536;
+        yoffs = get16();                         /* vert offset */
+        if (yoffs >= 32768)
+            yoffs -= 65536;
+        dprintf("xoffs %d\n", xoffs);
+        dprintf("yoffs %d\n", yoffs);
+    } else {                    /* short form preamble */
+        packetLength  = (flagByte << 8) + pkByte();
+        *carP         = pkByte();            /* char number */
+
+        *mustIgnoreP = false;
+
+        dprintf0("flagByte<=3\n");
+        dprintf("car: %d\n", *carP);
+        pkByte();          /* ignore tfmwidth (3 bytes) */
+        get16();               /* ignore tfmwidth (3 bytes) */
+        x = pkByte() ;  /* ignore horiz escapement */
+        dprintf("horiz esc %d\n", x);
+        cwidth = pkByte();            /* bounding box width */
+        cheight = pkByte() ;           /* bounding box height */
+        dprintf("cwidth %d\n", cwidth);
+        dprintf("cheight %d\n", cheight);
+        xoffs = pkByte();               /* horiz offset */
+        if (xoffs >= 128)
+            xoffs -=256;
+        yoffs = pkByte();               /* vert offset */
+        if (yoffs >= 128)
+            yoffs -= 256;
+        dprintf("xoffs %d\n", xoffs);
+        dprintf("yoffs %d\n", yoffs);
+    }
+    if (packetLength < 0)
+        pm_error("Invalid character header - negative packet length");
+    if (packetLength > UINT_MAX - pkLoc)
+        pm_error("Invalid character header - excessive packet length");
+
+    *endOfPacketP = packetLength + pkLoc;
+
+    *cheightP = cheight;
+    *cwidthP  = cwidth;
+    *xoffsP   = xoffs;
+    *yoffsP   = yoffs;
+    *turnonP  = turnon;
+}
+
+
+
+static void
+readOneCharacter(bool           const bmxOverrideSpec,
+                 int            const bmxOverride,
+                 bool           const bmyOverrideSpec,
+                 int            const bmyOverride,
+                 unsigned int * const carP,
+                 bool *         const mustIgnoreP,
+                 bit ***        const bitmapP,
+                 unsigned int * const bmxP,
+                 unsigned int * const bmyP) {
+
+    int car;
+    unsigned int endOfPacket;
+    bool mustIgnore;
+    int cheight, cwidth;
+    int xoffs, yoffs;
+    bool turnon;
+    bit row[MAXROWWIDTH+1];
+
+    readCharacterHeader(&car, &endOfPacket, &mustIgnore,
+                        &cheight, &cwidth, &xoffs, &yoffs, &turnon);
+
+    *carP = car;
+
+    if (mustIgnore || !fileName[car]) {
+        /* Ignore this character in the font */
+        ignoreChar(car, endOfPacket);
+        *mustIgnoreP = true;
+    } else {
+        bit ** bitmap;
+        unsigned int i;
+
+        int const bmx = bmxOverrideSpec ? bmxOverride : cwidth;
+        int const bmy = bmyOverrideSpec ? bmyOverride : cheight;
+
+        *mustIgnoreP = false;
+
+        bitmap = pbm_allocarray(bmx, bmy);
+
+        bitWeight = 0 ;
+        for (i = 0 ; i < bmy ; ++i) {
+            /* make it blank */
+            unsigned int j;
+
+            for (j = 0 ; j < bmx ; ++j)
+                bitmap[i][j] = PBM_WHITE;
         }
-        bitweight = 0 ;
-        for (i = 0 ; i < bmy ; i ++)           /* make it blank */
-            for (j = 0 ; j < bmx ; j ++)
-                bitmap[i][j]= PBM_WHITE;
         if (dynf == 14) {               /* bitmapped character */
-            dprintf ("bmy: %d\n ", bmy);
-            dprintf ("y: %d\n ", bmy-yoffs-1);
-            for (i = 0 ; i < cheight ; i ++) {
-                int yi= i+(bmy-yoffs-1);
-                for (j = 0 ; j < cwidth ; j ++) {
-                    int xj= j-xoffs;
-                    if (getbit() && 0<=xj && xj<bmx && 0<=yi && yi<bmy)
+            dprintf("bmy: %d\n ", bmy);
+            dprintf("y: %d\n ", bmy - yoffs - 1);
+            for (i = 0 ; i < cheight ; ++i) {
+                unsigned int const yi = i + (bmy - yoffs - 1);
+                unsigned int j;
+                for (j = 0 ; j < cwidth ; ++j) {
+                    unsigned int const xj = j - xoffs;
+                    if (getBit() && 0 <= xj && xj < bmx && 0 <= yi && yi < bmy)
                         bitmap[yi][xj] = PBM_BLACK ;
                 }
             }
         } else {                    /* dynamically packed char */
-            integer rowsleft = cheight ;
-            integer hbit = cwidth ;
-            integer rp = 0;
-            repeatcount = 0 ;
-            dprintf ("bmy: %d\n ", bmy);
-            dprintf ("y: %d\n", cheight-rowsleft+(bmy-2*yoffs-1));
+            int rowsleft = cheight ;
+            int hbit = cwidth ;
+            int rp = 0;
+            repeatCount = 0 ;
+            dprintf("bmy: %d\n ", bmy);
+            dprintf("y: %d\n", cheight-rowsleft+(bmy-2*yoffs-1));
             while (rowsleft > 0) {
-                integer count = pkpackednum() ; /* get current color count */
+                int count = pkPackedNum() ; /* get current color count */
                 while (count > 0) {
                     if (count < hbit) {     /* doesn't extend past row */
                         hbit -= count ;
                         while (count--)
                             row[rp++] = turnon ? PBM_BLACK : PBM_WHITE;
                     } else {                /* reaches end of row */
-                        count -= hbit ;
+                        count -= hbit;
                         while (hbit--)
                             row[rp++] = turnon ? PBM_BLACK : PBM_WHITE;
-                        for (i = 0; i <= repeatcount; i++) {  /* fill row */
-                            int yi= i+cheight-rowsleft-1;
-                            if (0<=yi && yi < bmy)
+                        for (i = 0; i <= repeatCount; i++) {  /* fill row */
+                            unsigned int const yi = i + cheight - rowsleft - 1;
+                            if (0 <= yi && yi < bmy) {
+                                unsigned int j;
                                 for (j = 0; j < cwidth; j++) {
-                                    int xj= j-xoffs;
-                                    if (0<=xj && xj<bmx)
+                                    unsigned int const xj= j - xoffs;
+                                    if (0 <= xj && xj < bmx)
                                         bitmap[yi][xj] = row[j] ;
                                 }
+                            }
                         }
-                        rowsleft -= repeatcount + 1;
-                        repeatcount = rp = 0 ;
-                        hbit = cwidth ;
+                        rowsleft -= repeatCount + 1;
+                        repeatCount = rp = 0;
+                        hbit = cwidth;
                     }
                 }
-                turnon = !turnon ;
+                turnon = !turnon;
             }
             if (rowsleft != 0 || hbit != cwidth)
                 pm_error("bad pk file (more bits than required)") ;
         }
-        if (endofpacket != pktopbm_pkloc)
+        if (endOfPacket != pkLoc)
             pm_error("bad pk file (bad packet length)") ;
-
-        ofp = pm_openw(filename[car]);
-        filename[car] = NULL;
-        pbm_writepbm(ofp, bitmap, bmx, bmy, 0) ;
-        pbm_freearray(bitmap, bmy) ;
-        pm_close(ofp) ;
-        skipspecials() ;
+        *bitmapP = bitmap;
+        *bmxP    = bmx;
+        *bmyP    = bmy;
     }
-    while (! feof(pkfile)) pktopbm_pkbyte() ;       /* skip trailing junk */
-    pm_close(pkfile);
-    for (car = 0; car < MAXPKCHAR; car++)
-        if (filename[car])
+}
+
+
+
+static void
+generatePbmFile(const char * const fileNm,
+                bit **       const bitmap,
+                unsigned int const cols,
+                unsigned int const rows) {
+
+    FILE * ofP;
+
+    ofP = pm_openw(fileNm);
+
+    pbm_writepbm(ofP, bitmap, cols, rows, 0);
+
+    pm_close(ofP);
+}
+
+
+
+static void
+warnMissingCodePoint() {
+
+    unsigned int car;
+
+    for (car = 0; car < MAXPKCHAR; ++car) {
+        if (fileName[car])
             pm_message("Warning: No character in position %d (file %s).",
-                       car, filename[car]) ;
-    pm_message("%d bytes read from packed file.", pktopbm_pkloc-1) ;
+                       car, fileName[car]) ;
+    }
+}
+
+
+
+int
+main(int argc, const char ** argv) {
+
+    struct CmdlineInfo cmdline;
+    unsigned int i;
+
+    pm_proginit(&argc, argv);
+
+    parseCommandLine(argc, argv, &cmdline);
+
+    debug = cmdline.debug;
+
+    for (i = 0; i < cmdline.character; ++i)
+        fileName[i] = NULL;
+    for (i = 0; i < cmdline.outputFileCt; ++i)
+        fileName[cmdline.character + i] = cmdline.outputFileNm[i];
+    for (i = cmdline.character + cmdline.outputFileCt;
+         i < MAXPKCHAR;
+         ++i)
+        fileName[i] = NULL;
+
+    ifP = pm_openr(cmdline.inputFileNm);
+
+    pkLoc = 0;
+
+    readHeader();
+
+    while (flagByte != 245) {  /* not at postamble */
+
+        unsigned int car;
+        bool mustIgnore;
+        bit ** bitmap;
+        unsigned int cols, rows;
+
+        readOneCharacter(!!cmdline.xSpec, cmdline.x,
+                         !!cmdline.ySpec, cmdline.y,
+                         &car, &mustIgnore, &bitmap, &cols, &rows);
+
+        if (!mustIgnore) {
+            generatePbmFile(fileName[car], bitmap, cols, rows);
+
+            pbm_freearray(bitmap, rows) ;
+        }
+
+        fileName[car] = NULL;
+
+        skipSpecials();
+    }
+
+    while (!feof(ifP))
+        pkByte() ;       /* skip trailing junk */
+
+    pm_close(ifP);
+
+    warnMissingCodePoint();
+
+    pm_message("%u bytes read from packed file.", pkLoc);
+
     return 0;
 }
+
+
+
diff --git a/converter/pbm/thinkjettopbm.l b/converter/pbm/thinkjettopbm.l
index 5de4f2bb..c55a0085 100644
--- a/converter/pbm/thinkjettopbm.l
+++ b/converter/pbm/thinkjettopbm.l
@@ -38,6 +38,7 @@
 #include <errno.h>
 #include <unistd.h>
 #include "pm_c_util.h"
+#include "mallocvar.h"
 #include "pbm.h"
 #include "shhopt.h"
 
@@ -114,8 +115,10 @@ DIG             [0-9]
 <RASTERMODE>\033\*b{DIG}+W  {
                             int l;
                             if (rowCount >= rowCapacity) {
+                                if (rowCapacity > INT_MAX-100)
+                                    pm_error("Too many rows to count");
                                 rowCapacity += 100;
-                                rows = realloc (rows, rowCapacity * sizeof *rows);
+                                REALLOCARRAY(rows, rowCapacity);
                                 if (rows == NULL)
                                     pm_error ("Out of memory.");
                             }
@@ -223,6 +226,9 @@ yywrap (void)
 
     debug ("Got %d rows, %d columns\n", rowCount, maxRowLength);
 
+    if (maxRowLength > INT_MAX/8)
+        pm_error("A row has an uncomputably large number of columns: %d",
+                 maxRowLength);
     /*
      * Quite simple since ThinkJet bit arrangement matches PBM
      */
diff --git a/converter/pbm/wbmptopbm.c b/converter/pbm/wbmptopbm.c
index a3ce7ec3..3b941fcb 100644
--- a/converter/pbm/wbmptopbm.c
+++ b/converter/pbm/wbmptopbm.c
@@ -1,9 +1,9 @@
 /* wbmptopbm.c - convert a wbmp file to a portable bitmap
 
-   This is derived for Netpbm from the pbmwbmp package from 
+   This is derived for Netpbm from the pbmwbmp package from
    <http://www.looplab.com/wap/tools> on 2000.06.06.
-   
-   The specifications for the wbmp format are part of the Wireless 
+
+   The specifications for the wbmp format are part of the Wireless
    Application Environment specification at
    <http://www.wapforum.org/what/technical.htm>.
 
@@ -19,7 +19,7 @@
 
 #include "pbm.h"
 
-static int 
+static int
 readc(FILE *f) {
   int c = fgetc(f);
   if(c == EOF) pm_error("EOF / read error");
@@ -28,7 +28,7 @@ readc(FILE *f) {
 
 
 
-static int 
+static int
 readint(FILE *f) {
   int c=0, pos=0, sum=0;
   do {
@@ -40,7 +40,7 @@ readint(FILE *f) {
 
 
 
-static void 
+static void
 readheader(int h, FILE *f) {
   int c,i;
   switch(h & 0x60) {
@@ -81,7 +81,7 @@ readwbmp(FILE *f, int *cols, int *rows) {
     for(j=0; j<row; j++) {
       c=readc(f);
       for(k=0; k<8 && j*8+k<*cols; k++) {
-	image[i][j*8+k] = c & (0x80 >> k) ? PBM_WHITE : PBM_BLACK;
+        image[i][j*8+k] = c & (0x80 >> k) ? PBM_WHITE : PBM_BLACK;
       }
     }
   }
@@ -90,7 +90,7 @@ readwbmp(FILE *f, int *cols, int *rows) {
 
 
 
-int 
+int
 main(int argc, char *argv[]) {
   FILE *f;
   bit **image;
@@ -110,3 +110,5 @@ main(int argc, char *argv[]) {
   return 0;
 }
 
+
+
diff --git a/converter/pbm/xbmtopbm.c b/converter/pbm/xbmtopbm.c
index 1f5384ed..d3595ca1 100644
--- a/converter/pbm/xbmtopbm.c
+++ b/converter/pbm/xbmtopbm.c
@@ -384,6 +384,8 @@ main(int    argc,
     return 0;
 }
 
+
+
 /*  CHANGE HISTORY:
 
   99.09.08 bryanh    Recognize "static unsigned char" declaration.
diff --git a/converter/pbm/ybmtopbm.c b/converter/pbm/ybmtopbm.c
index 2a429086..13210e43 100644
--- a/converter/pbm/ybmtopbm.c
+++ b/converter/pbm/ybmtopbm.c
@@ -10,6 +10,8 @@
 ** implied warranty.
 */
 
+#include <limits.h>
+
 #include "pm.h"
 #include "pbm.h"
 #include "bitreverse.h"
@@ -19,45 +21,48 @@ static short const ybmMagic = ( ( '!' << 8 ) | '!' );
 
 
 static void
-getinit(FILE *  const ifP,
-        short * const colsP,
-        short * const rowsP,
-        short * const depthP) {
+getinit(FILE *         const ifP,
+        unsigned int * const colsP,
+        unsigned int * const rowsP,
+        int *          const depthP) {
 
-    short magic;
+    short int magic;
+    short int cols, rows;
     int rc;
 
     rc = pm_readbigshort(ifP, &magic);
     if (rc == -1)
         pm_error("EOF / read error");
-
-    if (magic != ybmMagic)
+    else if (magic != ybmMagic)
         pm_error("bad magic number in YBM file");
 
-    rc = pm_readbigshort(ifP, colsP);
+    rc = pm_readbigshort(ifP, &cols);
     if (rc == -1 )
         pm_error("EOF / read error");
+    else if (cols <= 0)
+        pm_error("invalid width value in YBM file");
 
-    rc = pm_readbigshort(ifP, rowsP);
+    rc = pm_readbigshort(ifP, &rows);
     if (rc == -1)
         pm_error("EOF / read error");
+    else if (rows <= 0)
+        pm_error("invalid height value in YBM file");
 
+    *colsP = (unsigned int) cols;
+    *rowsP = (unsigned int) rows;
     *depthP = 1;
 }
 
 
 
-
-
-
 int
 main(int argc, const char * argv[]) {
 
     FILE * ifP;
     bit * bitrow;
-    short rows, cols;
+    unsigned int rows, cols;
     unsigned int row;
-    short depth;
+    int depth;
     const char * inputFile;
 
     pm_proginit(&argc, argv);
@@ -76,8 +81,11 @@ main(int argc, const char * argv[]) {
 
     getinit(ifP, &cols, &rows, &depth);
     if (depth != 1)
-        pm_error("YBM file has depth of %u, must be 1", (unsigned)depth);
-    
+        pm_error("YBM file has depth of %u, must be 1", (unsigned int) depth);
+    if (cols > INT_MAX - 15)
+        pm_error("YBM file has uncomputably large width %d", cols);
+
+
     pbm_writepbminit(stdout, cols, rows, 0);
 
     bitrow = pbm_allocrow_packed(cols + 8);
@@ -92,7 +100,7 @@ main(int argc, const char * argv[]) {
         for (i = 0; i < itemCt; ++i) {
             short int item;
             pm_readbigshort(ifP, &item);
-            itemrow[i] = (uint16_t) item; 
+            itemrow[i] = (uint16_t) item;
         }
 
         for (i = 0; i < pbm_packed_bytes(cols); ++i)
@@ -108,3 +116,6 @@ main(int argc, const char * argv[]) {
 
     return 0;
 }
+
+
+
diff --git a/converter/pgm/asciitopgm.c b/converter/pgm/asciitopgm.c
index f4179de8..d8bc263b 100644
--- a/converter/pgm/asciitopgm.c
+++ b/converter/pgm/asciitopgm.c
@@ -124,7 +124,7 @@ convertAsciiToPgm(FILE *         const ifP,
         else {
             if (beginningOfLine) {
                 if (c == '+') {
-                    /* + at start of line means rest of line 
+                    /* + at start of line means rest of line
                        overstrikes previous
                     */
                     c = getc(ifP);
@@ -192,7 +192,7 @@ main(int argc, const char ** argv) {
     rows = 0;  /* initial value */
     cols = 0;  /* initial value */
     divisor = 1; /* initial value */
-    
+
     argn = 1;
 
     if ( argc < 3 || argc > 6 )
@@ -246,3 +246,6 @@ main(int argc, const char ** argv) {
 
     return 0;
 }
+
+
+
diff --git a/converter/pgm/bioradtopgm.c b/converter/pgm/bioradtopgm.c
index e0bc3584..471709c1 100644
--- a/converter/pgm/bioradtopgm.c
+++ b/converter/pgm/bioradtopgm.c
@@ -44,32 +44,32 @@ main( argc, argv )
 
     while ( argn < argc && argv[argn][0] == '-' && argv[argn][1] != '\0' )
     {
-	if ( ISDIGIT( argv[argn][1] ))
-	{
-	    image_num = atoi( (argv[argn]+1) );
-	}
-	else
-	    pm_usage( usage );
-	++argn;
+        if ( ISDIGIT( argv[argn][1] ))
+        {
+            image_num = atoi( (argv[argn]+1) );
+        }
+        else
+            pm_usage( usage );
+        ++argn;
     }
 
     if ( argn < argc )
-	{
-	ifp = pm_openr( argv[argn] );
-	++argn;
-	}
+        {
+        ifp = pm_openr( argv[argn] );
+        ++argn;
+        }
     else
-	ifp = stdin;
+        ifp = stdin;
 
     if ( argn != argc )
-	pm_usage( usage );
+        pm_usage( usage );
 
     for ( i = 0; i < BIORAD_HEADER_LENGTH; ++i )
     {
-	val = getc( ifp );
-	if ( val == EOF )
-	    pm_error( "EOF / read error" );
-	buf[ i ] = val;
+        val = getc( ifp );
+        if ( val == EOF )
+            pm_error( "EOF / read error" );
+        buf[ i ] = val;
     }
 
     cols = BYTE_TO_WORD(buf[0], buf[1]);
@@ -79,74 +79,77 @@ main( argc, argv )
     check_word = BYTE_TO_WORD(buf[54], buf[55]);
 
     if ( check_word != 12345 )
-	pm_error( "Not a Biorad file" );
+        pm_error( "Not a Biorad file" );
 
     if ( cols <= 0 )
-	pm_error( "Strange image size, cols = %d", cols);
+        pm_error( "Strange image size, cols = %d", cols);
 
     if ( rows <= 0 )
-	pm_error( "Strange image size, rows = %d", rows);
+        pm_error( "Strange image size, rows = %d", rows);
 
     if ( image_count <= 0 )
-	pm_error( "Number of images in file is %d", image_count);
+        pm_error( "Number of images in file is %d", image_count);
 
     if ( byte_word )
-	maxval = 255;
+        maxval = 255;
     else
     {
-	maxval = 65535;   /* Perhaps this should be something else */
+        maxval = 65535;   /* Perhaps this should be something else */
 
     }
 
     pm_message( "Image size: %d cols, %d rows", cols, rows);
     pm_message( "%s",
-	       (byte_word) ? "Byte image (8 bits)" : "Word image (16 bits)");
+               (byte_word) ? "Byte image (8 bits)" : "Word image (16 bits)");
 
     if ( image_num < 0 )
-	pm_message( "Input contains %d image%c",
-		   image_count, (image_count > 1) ? 's' : '\0');
+        pm_message( "Input contains %d image%c",
+                   image_count, (image_count > 1) ? 's' : '\0');
     else
     {
-	if ( image_num >= image_count )
-	    pm_error( "Cannot extract image %d, input contains only %d image%s",
-		     image_num, image_count, (image_count > 1) ? "s" : "" );
-	for ( i = (byte_word) ? image_num : image_num*2 ; i > 0 ; --i ) {
-	    for ( row = 0; row < rows; ++row)
-		for ( col = 0; col < cols; ++col )
-		{
-		    val = getc( ifp );
-		    if ( val == EOF ) {
-			pm_error( "EOF / read error" );
-		    }
-		}
-	}
-
-	pgm_writepgminit( stdout, cols, rows, (gray) maxval, 0 );
-	grayrow = pgm_allocrow( cols );
-
-	for ( row = 0; row < rows; ++row)
-	{
-	    for ( col = 0, gP = grayrow; col < cols; ++col )
-	    {
-		val = getc( ifp );
-		if ( val == EOF )
-		    pm_error( "EOF / read error" );
-		if (byte_word)
-		    *gP++ = val;
-		else
-		{
-		    val2 = getc( ifp );
-		    if ( val2 == EOF )
-			pm_error( "EOF / read error" );
-		    *gP++ = BYTE_TO_WORD(val, val2);
-		}
-	    }
-	    pgm_writepgmrow( stdout, grayrow, cols, (gray) maxval, 0 );
-	}
-
-	pm_close( ifp );
-	pm_close( stdout );
+        if ( image_num >= image_count )
+            pm_error( "Cannot extract image %d, input contains only %d image%s",
+                     image_num, image_count, (image_count > 1) ? "s" : "" );
+        for ( i = (byte_word) ? image_num : image_num*2 ; i > 0 ; --i ) {
+            for ( row = 0; row < rows; ++row)
+                for ( col = 0; col < cols; ++col )
+                {
+                    val = getc( ifp );
+                    if ( val == EOF ) {
+                        pm_error( "EOF / read error" );
+                    }
+                }
+        }
+
+        pgm_writepgminit( stdout, cols, rows, (gray) maxval, 0 );
+        grayrow = pgm_allocrow( cols );
+
+        for ( row = 0; row < rows; ++row)
+        {
+            for ( col = 0, gP = grayrow; col < cols; ++col )
+            {
+                val = getc( ifp );
+                if ( val == EOF )
+                    pm_error( "EOF / read error" );
+                if (byte_word)
+                    *gP++ = val;
+                else
+                {
+                    val2 = getc( ifp );
+                    if ( val2 == EOF )
+                        pm_error( "EOF / read error" );
+                    *gP++ = BYTE_TO_WORD(val, val2);
+                }
+            }
+            pgm_writepgmrow( stdout, grayrow, cols, (gray) maxval, 0 );
+        }
+
+        pm_close( ifp );
+        pm_close( stdout );
 
     }
     exit( 0 );
 }
+
+
+
diff --git a/converter/pgm/fstopgm.c b/converter/pgm/fstopgm.c
index 1f574604..63ccb3c5 100644
--- a/converter/pgm/fstopgm.c
+++ b/converter/pgm/fstopgm.c
@@ -47,7 +47,7 @@ warnNonsquarePixels(unsigned int const cols,
                     unsigned int const xcols,
                     unsigned int const rows,
                     unsigned int const xrows) {
-    
+
     const char * const baseMsg = "warning, non-square pixels";
 
     if (pm_have_float_format()) {
@@ -57,7 +57,7 @@ warnNonsquarePixels(unsigned int const cols,
         pm_message("%s; to fix do a 'pamscale -%cscale %g'",
                    baseMsg,
                    rowratio > colratio ? 'y' : 'x',
-                   rowratio > colratio ? 
+                   rowratio > colratio ?
                    rowratio / colratio : colratio / rowratio);
     } else
         pm_message("%s", baseMsg);
@@ -153,3 +153,5 @@ main(int argc, const char ** argv) {
     return 0;
 }
 
+
+
diff --git a/converter/pgm/hipstopgm.c b/converter/pgm/hipstopgm.c
index 2f5956e1..17048ce7 100644
--- a/converter/pgm/hipstopgm.c
+++ b/converter/pgm/hipstopgm.c
@@ -16,21 +16,21 @@
 #include "pgm.h"
 
 struct HIPS_Header {
-    char* orig_name;	/* An indication of the originator of this sequence. */
-    char* seq_name;	/* The sequence name. */
-    int num_frame;	/* The number of frames in this sequence. */
-    char* orig_date;	/* The date the sequence was originated. */
-    int rows;		/* The number of rows in each image, the height. */
-    int cols;		/* The number of columns in each image, the width. */
-    int bits_per_pixel;	/* The number of significant bits per pixel. */
-    int bit_packing;	/* Nonzero if the bits were packed such as to
+    char* orig_name;    /* An indication of the originator of this sequence. */
+    char* seq_name;     /* The sequence name. */
+    int num_frame;      /* The number of frames in this sequence. */
+    char* orig_date;    /* The date the sequence was originated. */
+    int rows;           /* The number of rows in each image, the height. */
+    int cols;           /* The number of columns in each image, the width. */
+    int bits_per_pixel; /* The number of significant bits per pixel. */
+    int bit_packing;    /* Nonzero if the bits were packed such as to
                            eliminate any unused bits resulting from a
                            bits_per_pixel value which was not an even
                            multiple of eight. */
-    int pixel_format;	/* An indication of the format of each pixel. */
-    char* seq_history;	/* A description of the sequence of transformations
+    int pixel_format;   /* An indication of the format of each pixel. */
+    char* seq_history;  /* A description of the sequence of transformations
                            leading up to the current image. */
-    char* seq_desc;	/* A free form description of the contents of the
+    char* seq_desc;     /* A free form description of the contents of the
                        sequence. */
 };
 #define HIPS_PFBYTE 0
@@ -52,7 +52,6 @@ read_line(FILE * const fd,
 
 
 
-
 static void
 read_hips_header( fd, hP )
     FILE* fd;
@@ -95,9 +94,9 @@ read_hips_header( fd, hP )
 
     /* Now read and toss lines until we get one with just a period. */
     do
-	{
+        {
         read_line( fd, buf, 5000 );
-	}
+        }
     while ( !streq( buf, ".\n" ) );
 }
 
@@ -121,10 +120,10 @@ main(int argc, char * argv[]) {
     argn = 1;
 
     if ( argn < argc )
-	{
+        {
         ifp = pm_openr( argv[argn] );
         argn++;
-	}
+        }
     else
         ifp = stdin;
 
@@ -137,8 +136,8 @@ main(int argc, char * argv[]) {
     rows = h.rows * h.num_frame;
 
     switch ( h.pixel_format )
-	{
-	case HIPS_PFBYTE:
+        {
+        case HIPS_PFBYTE:
         if ( h.bits_per_pixel != 8 )
             pm_error(
                 "can't handle unusual bits_per_pixel %d", h.bits_per_pixel );
@@ -147,16 +146,16 @@ main(int argc, char * argv[]) {
         maxval = 255;
         break;
 
-	default:
+        default:
         pm_error( "unknown pixel format %d", h.pixel_format );
-	}
+        }
 
     pgm_writepgminit( stdout, cols, rows, (gray) maxval, 0 );
     grayrow = pgm_allocrow( cols );
     for ( row = 0; row < rows; row++)
-	{
+        {
         for ( col = 0, gP = grayrow; col < cols; col++, gP++ )
-	    {
+            {
             int ich;
 
             switch ( h.pixel_format )
@@ -171,11 +170,14 @@ main(int argc, char * argv[]) {
             default:
                 pm_error( "can't happen" );
             }
-	    }
+            }
         pgm_writepgmrow( stdout, grayrow, cols, (gray) maxval, 0 );
-	}
+        }
     pm_close( ifp );
     pm_close( stdout );
 
     return 0;
 }
+
+
+
diff --git a/converter/pgm/lispmtopgm.c b/converter/pgm/lispmtopgm.c
index 40dd3fb4..29f280f3 100644
--- a/converter/pgm/lispmtopgm.c
+++ b/converter/pgm/lispmtopgm.c
@@ -16,6 +16,8 @@
 **   this doesn't matter if you're using only single plane images.
 */
 
+#include <assert.h>
+#include <limits.h>
 #include <stdio.h>
 #include <string.h>
 
@@ -24,149 +26,161 @@
 
 #define LISPM_MAGIC  "This is a BitMap file"
 
-static void getinit ARGS(( FILE* file, short* colsP, short* rowsP, short* depthP, short* padrightP ));
-static int depth_to_word_size ARGS(( int depth ));
-static unsigned int getval ARGS(( FILE* file ));
-
-int
-main( argc, argv )
-    int argc;
-    char* argv[];
-    {
-    FILE* ifp;
-    gray* grayrow;
-    register gray* gP;
-    short rows, cols, padright, row, col;
-    short depth;
-    int maxval;
 
 
-    pgm_init( &argc, argv );
-
-    if ( argc > 2 )
-	pm_usage( "[lispmfile]" );
+static long item, bitmask;
+static unsigned int bitsperitem, maxbitsperitem, bitshift;
 
-    if ( argc == 2 )
-        ifp = pm_openr( argv[1] );
-    else
-	ifp = stdin;
-
-    getinit( ifp, &cols, &rows, &depth, &padright );
-    maxval = 1 << depth;
-
-    if ( maxval > PGM_OVERALLMAXVAL )
-        pm_error( "depth (%d bits) is too large", depth);
-
-    pgm_writepgminit( stdout, cols, rows, (gray) maxval, 0 );
-    grayrow = pgm_allocrow( ( cols + 7 ) / 8 * 8 );
-
-    for ( row = 0; row < rows; ++row )
-	{
-        for ( col = 0, gP = grayrow; col < cols; ++col, ++gP )
-	    *gP = getval( ifp );
-	pgm_writepgmrow( stdout, grayrow, cols, (gray) maxval, 0 );
-	}
-    pm_close( ifp );
-    pm_close( stdout );
-    exit( 0 );
+static unsigned int
+wordSizeFmDepth(unsigned int const depth) {
+/*----------------------------------------------------------------------------
+  Lispm architecture specific - if a bitmap is written out with a depth of 5,
+  it really has a depth of 8, and is stored that way in the file.
+-----------------------------------------------------------------------------*/
+    if (depth==0 || depth==1) return  1;
+    else if (depth ==  2)     return  2;
+    else if (depth <=  4)     return  4;
+    else if (depth <=  8)     return  8;
+    else if (depth <= 16)     return 16;
+    else if (depth <= 32)     return 32;
+    else {
+        pm_error("depth was %u, which is not in the range 1-32.", depth);
+        assert(false);
     }
+}
+
 
-static long item, bitmask;
-static unsigned int bitsperitem, maxbitsperitem, bitshift;
 
 static void
-getinit( file, colsP, rowsP, depthP, padrightP )
-    FILE* file;
-    short* colsP;
-    short* rowsP;
-    short* padrightP;
-    short* depthP;
-    {
-    short cols_32;
+getinit(FILE *         const ifP,
+        unsigned int * const colsP,
+        unsigned int * const rowsP,
+        unsigned int * const depthP,
+        unsigned int * const padrightP) {
+
+    short cols, rows, cols32;
     char magic[sizeof(LISPM_MAGIC)];
-    int i;
+    unsigned int i;
+
+    for (i = 0; i < sizeof(magic)-1; ++i)
+        magic[i] = getc(ifP);
 
-    for ( i = 0; i < sizeof(magic)-1; ++i )
-        magic[i] = getc( file );
     magic[i]='\0';
+
     if (!streq(LISPM_MAGIC, magic))
-        pm_error( "bad id string in Lispm file" );
-    
-    if ( pm_readlittleshort( file, colsP ) == -1 )
-        pm_error( "EOF / read error" );
-    if ( pm_readlittleshort( file, rowsP ) == -1 )
-        pm_error( "EOF / read error" );
-    if ( pm_readlittleshort( file, &cols_32 ) == -1 )
-        pm_error( "EOF / read error" );
-    *depthP = getc( file );
-    
-    if ( *depthP == 0 )
-	*depthP = 1;	/* very old file */
-    
-    *padrightP = ( ( *colsP + 31 ) / 32 ) * 32 - *colsP;
-    
-    if ( *colsP != (cols_32 - *padrightP) ) {
-/*    pm_message( "inconsistent input: Width and Width(mod32) fields don't agree" );  */
-/*    *padrightP = cols_32 - *colsP;   */ /*    hmmmm....   */
-      /* This is a dilemma.  Usually the output is rounded up to mod32, but not always.
-       * For the Lispm code to not round up, the array size must be the same size as the
-       * portion being written - that is, the array itself must be an odd size, not just
-       * the selected portion.  Since arrays that are odd sizes can't be handed to bitblt,
-       * such arrays are probably not image data - so punt on it for now.
-       *
-       * Also, the lispm code for saving bitmaps has a bug, in that if you are writing a
-       * bitmap which is not mod32 across, the file may be up to 7 bits too short!  They
-       * round down instead of up.
-       *
-       * The code in 'pgmtolispm.c' always rounds up to mod32, which is totally reasonable.
-       */
-      }
-    bitsperitem = 0;
-    maxbitsperitem = depth_to_word_size( *depthP );
-    bitmask = ( 1 << maxbitsperitem ) - 1;		/* for depth=3, mask=00000111 */
+        pm_error("bad id string in Lispm file");
+
+    pm_readlittleshort(ifP, &cols);
+    pm_readlittleshort(ifP, &rows);
+    pm_readlittleshort(ifP, &cols32);
+
+    *colsP = cols;
+    *rowsP = rows;
+
+    *depthP = getc(ifP);
+
+    if (*depthP == 0)
+        *depthP = 1;    /* very old file */
 
-    for ( i = 0; i < 9; ++i )
-	getc( file );	/* discard bytes reserved for future use */
+    assert(*colsP < UINT_MAX - 31);
+
+    *padrightP = ROUNDUP(*colsP, 32) - *colsP;
+
+# if 0
+    if (*colsP != (cols32 - *padrightP)) {
+        pm_message("inconsistent input: "
+                   "Width and Width(mod32) fields don't agree" );
+        *padrightP = cols32 - *colsP;   /*    hmmmm....   */
+
+        /* This is a dilemma.  Usually the output is rounded up to mod32, but
+           not always.  For the Lispm code to not round up, the array size
+           must be the same size as the portion being written - that is, the
+           array itself must be an odd size, not just the selected portion.
+           Since arrays that are odd sizes can't be handed to bitblt, such
+           arrays are probably not image data - so punt on it for now.
+
+           Also, the lispm code for saving bitmaps has a bug, in that if you
+           are writing a bitmap which is not mod32 across, the file may be up
+           to 7 bits too short!  They round down instead of up.
+
+            The code in 'pgmtolispm.c' always rounds up to mod32, which is
+            totally reasonable.
+       */
     }
+#endif
+    bitsperitem = 0;
+    maxbitsperitem = wordSizeFmDepth(*depthP);
+    bitmask = (1 << maxbitsperitem) - 1;     /* for depth=3, mask=00000111 */
 
-static int
-depth_to_word_size (depth)	
-     int depth;			
-     /* Lispm architecture specific - if a bitmap is written    */
-     /* out with a depth of 5, it really has a depth of 8, and  */
-     /* is stored that way in the file.			   */
-{				
-    if (depth==0 || depth==1)	return ( 1);
-    else if (depth ==  2)	return ( 2);
-    else if (depth <=  4)	return ( 4);
-    else if (depth <=  8)	return ( 8);
-    else if (depth <= 16)	return (16);
-    else if (depth <= 32)	return (32);
-    else {
-      pm_error( "depth was %d, which is not in the range 1-32.", depth );
-      /* Should never reach here */
-      return(-1);
-  }
+    for (i = 0; i < 9; ++i)
+        getc(ifP);   /* discard bytes reserved for future use */
 }
 
 
 
 static unsigned int
-getval( file )
-    FILE* file;
-    {
+getval(FILE * const ifP) {
+
     unsigned int b;
 
-    if ( bitsperitem == 0 )
-	{
-	if ( pm_readlittlelong( file, &item ) == -1 )
-	    pm_error( "EOF / read error" );
-	bitsperitem = 32;
-	bitshift = 0;
-	item = ~item;
-	}
-    b = ( ( item >> bitshift ) & bitmask );
+    if (bitsperitem == 0) {
+        pm_readlittlelong(ifP, &item);
+        bitsperitem = 32;
+        bitshift = 0;
+        item = ~item;
+    }
+    b           = ((item >> bitshift ) & bitmask);
     bitsperitem = bitsperitem - maxbitsperitem;
-    bitshift = bitshift + maxbitsperitem;
+    bitshift    = bitshift + maxbitsperitem;
     return b;
+}
+
+
+
+int
+main(int argc, const char ** argv) {
+
+    FILE * ifP;
+    gray * grayrow;
+    unsigned int rows, cols, depth, padright;
+    unsigned int row;
+    gray maxval;
+
+
+    pm_proginit(&argc, argv);
+
+    if (argc-1 > 1)
+        pm_error("Too many arguments.  The only possible argument is the "
+                 "input file name");
+
+    if (argc-1 == 1)
+        ifP = pm_openr(argv[1]);
+    else
+        ifP = stdin;
+
+    getinit(ifP, &cols, &rows, &depth, &padright);
+
+    if (depth > 16)
+        pm_error("Invalid depth (%u bits).  Maximum is 15", depth);
+
+    maxval = (1 << depth);
+
+    pgm_writepgminit(stdout, cols, rows, maxval, 0);
+
+    grayrow = pgm_allocrow(ROUNDUP(cols, 8));
+
+    for (row = 0; row < rows; ++row) {
+        unsigned int col;
+
+        for (col = 0; col < cols; ++col)
+            grayrow[col] = getval(ifP);
+
+        pgm_writepgmrow(stdout, grayrow, cols, maxval, 0);
     }
+    pm_close(ifP);
+    pm_close(stdout);
+    exit(0);
+}
+
+
+
diff --git a/converter/pgm/pgmtofs.c b/converter/pgm/pgmtofs.c
index 53a2e7b3..8780b35a 100644
--- a/converter/pgm/pgmtofs.c
+++ b/converter/pgm/pgmtofs.c
@@ -35,14 +35,14 @@ main( argc, argv )
     argn = 1;
 
     if ( argn < argc )
-	{
+        {
         ifp = pm_openr( argv[argn] );
         ++argn;
-	}
+        }
     else
-	{
+        {
         ifp = stdin;
-	}
+        }
 
     if ( argn != argc )
         pm_usage( usage );
@@ -60,19 +60,19 @@ main( argc, argv )
         pm_error(
             "maxval of %d is too large for FaceSaver(tm)", maxval );
     nmaxval = pm_bitstomaxval( bps );
-    
+
     /* Compute padding to round cols * bps up to the nearest multiple of 8. */
     padright = ( ( cols * bps + 7 ) / 8 ) * 8 - cols * bps;
 
     putinit( cols, rows, bps );
     for ( row = rows - 1; row >= 0; --row )
-	{
+        {
         for ( col = 0, gP = grays[row]; col < cols; ++col, ++gP )
-	    {
+            {
             if ( maxval != nmaxval )
                 *gP = (int) *gP * nmaxval / maxval;
             putgray( *gP );
-	    }
+            }
         for ( col = 0; col < padright; ++col )
             putgray( 0 );
     }
@@ -83,6 +83,7 @@ main( argc, argv )
 }
 
 
+
 static int bitspersample, item, bitsperitem, bitshift, itemsperline, items;
 
 static void
@@ -109,16 +110,18 @@ putinit( cols, rows, bps )
     bitshift = 8 - bitspersample;
 }
 
+
+
 static void
 putitem( )
 {
     const char* const hexits = "0123456789abcdef";
 
     if ( itemsperline == 30 )
-	{
+        {
         putchar( '\n' );
         itemsperline = 0;
-	}
+        }
     putchar( hexits[item >> 4] );
     putchar( hexits[item & 15] );
     ++itemsperline;
@@ -128,6 +131,8 @@ putitem( )
     bitshift = 8 - bitspersample;
 }
 
+
+
 static void
 putgray( gray g )
 {
@@ -138,6 +143,8 @@ putgray( gray g )
     bitshift -= bitspersample;
 }
 
+
+
 static void
 putrest( )
 {
@@ -145,3 +152,6 @@ putrest( )
         putitem( );
     printf( "\n" );
 }
+
+
+
diff --git a/converter/pgm/pgmtolispm.c b/converter/pgm/pgmtolispm.c
index 7d931fb3..4309228e 100644
--- a/converter/pgm/pgmtolispm.c
+++ b/converter/pgm/pgmtolispm.c
@@ -1,4 +1,4 @@
-/* pgmtolispm.c - read a pgm and write a file acceptable to the 
+/* pgmtolispm.c - read a pgm and write a file acceptable to the
 ** tv:read-bit-array-file function of TI Explorer and Symbolics Lisp Machines.
 **
 ** Written by Jamie Zawinski based on code (C) 1988 by Jef Poskanzer.
@@ -12,7 +12,7 @@
 **
 **   When one writes a multi-plane bitmap with tv:write-bit-array-file, it is
 **   usually a color image; but a color map is not written in the file, so we
-**   treat this as a graymap instead.  To convert a color image to Lispm 
+**   treat this as a graymap instead.  To convert a color image to Lispm
 **   format, you must convert it to a pgm, and hand-edit a color map...  Ick.
 **
 ** Feb 2010 afu
@@ -37,7 +37,7 @@ depth_to_word_size(unsigned int const depth) {
     /* out with a depth of 5, it really has a depth of 8, and  */
     /* is stored that way in the file.                         */
 
-    unsigned int const wordSize = 
+    unsigned int const wordSize =
         depth ==  1 ?  1 :
         depth ==  2 ?  2 :
         depth <=  4 ?  4 :
@@ -178,3 +178,6 @@ main(int argc, const char * argv[]) {
 
     return 0;
 }
+
+
+
diff --git a/converter/pgm/pgmtopgm.c b/converter/pgm/pgmtopgm.c
index 250bb4dc..71b12754 100644
--- a/converter/pgm/pgmtopgm.c
+++ b/converter/pgm/pgmtopgm.c
@@ -20,9 +20,9 @@ main(int argc, char *argv[]) {
     gray maxval;
     int row;
     gray * grayrow;
-    
+
     pgm_init(&argc, argv);
-    
+
     if (argc-1 != 0)
         pm_error("Program takes no arguments.  Input is from Standard Input");
 
@@ -42,3 +42,6 @@ main(int argc, char *argv[]) {
 
     return 0;
 }
+
+
+
diff --git a/converter/pgm/pgmtosbig.c b/converter/pgm/pgmtosbig.c
index 0a302dd8..cdc867cb 100644
--- a/converter/pgm/pgmtosbig.c
+++ b/converter/pgm/pgmtosbig.c
@@ -128,3 +128,6 @@ main(int argc, const char * argv[]) {
 
     return 0;
 }
+
+
+
diff --git a/converter/pgm/pgmtost4.c b/converter/pgm/pgmtost4.c
index fa101ac9..aa691464 100644
--- a/converter/pgm/pgmtost4.c
+++ b/converter/pgm/pgmtost4.c
@@ -76,7 +76,7 @@ main(int argc, const char * argv[]) {
     if (inpam.width != st4Width)
         pm_error("Image is wrong width for ST-4 SBIG: %u pixels.  "
                  "Must be %u", inpam.width, st4Width);
-    
+
     /* Really, we should just scale to maxval 255.  There are library routines
        for that, but we're too lazy even for that, since nobody is really
        going to use this program.
@@ -102,3 +102,6 @@ main(int argc, const char * argv[]) {
 
     return 0;
 }
+
+
+
diff --git a/converter/pgm/psidtopgm.c b/converter/pgm/psidtopgm.c
index 07417d1b..58e84855 100644
--- a/converter/pgm/psidtopgm.c
+++ b/converter/pgm/psidtopgm.c
@@ -10,6 +10,7 @@
 ** implied warranty.
 */
 
+#include "pm_c_util.h"
 #include "pgm.h"
 
 
@@ -36,19 +37,20 @@ gethexit(FILE * const ifp) {
 
 
 int
-main(int     argc,
-     char ** argv) {
+main(int           argc,
+     const char ** argv) {
 
     FILE * ifP;
     gray * grayrow;
-    int argn, row;
+    unsigned int argn;
+    unsigned int row;
     gray maxval;
     int rows, cols, bitspersample;
 
-    pgm_init(&argc, argv);
+    pm_proginit(&argc, argv);
+
+    argn = 1;  /* initial value */
 
-    argn = 1;
-    
     if (argn + 3 > argc)
         pm_error("Too few arguments");
 
@@ -78,7 +80,9 @@ main(int     argc,
         pm_error("bits/sample (%d) is too large.", bitspersample);
 
     pgm_writepgminit(stdout, cols, rows, maxval, 0);
-    grayrow = pgm_allocrow((cols + 7) / 8 * 8);
+
+    grayrow = pgm_allocrow(ROUNDUP(cols, 8));
+
     for (row = 0; row < rows; ++row) {
         unsigned int col;
         for (col = 0; col < cols; ) {
@@ -115,10 +119,10 @@ main(int     argc,
 
             default:
                 pm_error("This program does not know how to interpret a"
-                         "%d bitspersample image", bitspersample );
+                         "%d bitspersample image", bitspersample);
             }
         }
-        pgm_writepgmrow(stdout, grayrow, cols, (gray) maxval, 0);
+        pgm_writepgmrow(stdout, grayrow, cols, maxval, 0);
     }
     pgm_freerow(grayrow);
     pm_close(ifP);
@@ -126,3 +130,6 @@ main(int     argc,
 
     return 0;
 }
+
+
+
diff --git a/converter/pgm/rawtopgm.c b/converter/pgm/rawtopgm.c
index 7eb68694..a90bbf46 100644
--- a/converter/pgm/rawtopgm.c
+++ b/converter/pgm/rawtopgm.c
@@ -45,8 +45,6 @@ parseCommandLine(int argc, const char ** argv,
    was passed to us as the argv array.
 -----------------------------------------------------------------------------*/
     optEntry * option_def;
-        /* Instructions to OptParseOptions3 on how to parse our options.
-         */
     optStruct3 opt;
 
     unsigned int option_def_index;
@@ -85,7 +83,7 @@ parseCommandLine(int argc, const char ** argv,
     opt.short_allowed = false;  /* We have no short (old-fashioned) options */
     opt.allowNegNum = false;  /* We may have parms that are negative numbers */
 
-    pm_optParseOptions3(&argc, (char **)argv, opt, sizeof(opt), 0);
+    pm_optParseOptions4(&argc, argv, opt, sizeof(opt), 0);
         /* Uses and sets argc, argv, and some of *cmdlineP and others. */
 
     if (argc-1 == 0) {
diff --git a/converter/pgm/sbigtopgm.c b/converter/pgm/sbigtopgm.c
index 7833cb62..c56d5eae 100644
--- a/converter/pgm/sbigtopgm.c
+++ b/converter/pgm/sbigtopgm.c
@@ -46,21 +46,19 @@ parseCommandLine(int argc, const char ** argv,
    was passed to as as the argv array.
 -----------------------------------------------------------------------------*/
     optEntry * option_def;
-        /* Instructions to pm_optParseOptions3 on how to parse our options.
-         */
     optStruct3 opt;
 
     unsigned int option_def_index;
 
     MALLOCARRAY_NOFAIL(option_def, 100);
-    
+
     OPTENTINIT;
 
     opt.opt_table     = option_def;
     opt.short_allowed = FALSE; /* We have no short (old-fashioned) options */
     opt.allowNegNum   = FALSE; /* We have no parms that are negative numbers */
-    
-    pm_optParseOptions3(&argc, (char **)argv, opt, sizeof(opt), 0);
+
+    pm_optParseOptions4(&argc, argv, opt, sizeof(opt), 0);
         /* Uses and sets argc, argv, and some of *cmdlineP and others */
 
     if (argc-1 < 1)
@@ -208,7 +206,7 @@ readSbigHeader(FILE *              const ifP,
                 *ep = ' ';
             }
         }
-        
+
         looseCanon(cursor);
             /* Convert from standard SBIG to an internal format */
 
@@ -270,7 +268,7 @@ writeRaster(FILE *            const ifP,
             unsigned short rowlen;        /* Compressed row length */
 
             pm_readlittleshortu(ifP, &rowlen);
-            
+
             /*  If compression results in a row length >= the uncompressed
                 row length, that row is output uncompressed.  We detect this
                 by observing that the compressed row length is equal to
diff --git a/converter/pgm/spottopgm.c b/converter/pgm/spottopgm.c
index 59240ba8..26801cb2 100644
--- a/converter/pgm/spottopgm.c
+++ b/converter/pgm/spottopgm.c
@@ -37,7 +37,7 @@ static int Colbool = 0;        /* 1 if color */
  * requested by the user (i.e 1, 2 or 3). I could create a ppm file
  * but I couldn't be bothered with the rearranging of the data.
  */
-static int 
+static int
 get_image(long length)
 {
     int cnt;
@@ -72,7 +72,7 @@ get_image(long length)
             pm_error ("seek error");
         if (pm_readbiglong (spotfile, &numpixels) == -1)
             pm_error ("EOF / read error reading line ender");
-    
+
         /* Determine the picture size */
         Bufptr = &linebuf[Firstcol];
         if (Lastcol == 0 || Lastcol > numpixels)
@@ -95,7 +95,7 @@ get_image(long length)
     fprintf(stderr,
             "Line %4d, %3d, %3d, time %4d, l/r "
             "pixmar %4d %4d len %d pixnum %d\n",
-            linehdr.linenum, linehdr.recseq, 
+            linehdr.linenum, linehdr.recseq,
             linehdr.spectseq, linehdr.linetime,
             linehdr.leftpixmar, linehdr.rightpixmar, length, numpixels);
 #endif
@@ -116,7 +116,7 @@ get_image(long length)
  *  element 9 == S --> sequential (i.e only one color here)
  *  element 9 == I --> interleaved (1 or more colors)
  */
-static int 
+static int
 get_imghdr(int length)
 {
     struct Imghdr
@@ -145,7 +145,7 @@ get_imghdr(int length)
 
 #ifdef DEBUG
     fprintf(stderr, "Dummy str is >%s<\n", header.dummy1);
-    fprintf(stderr, "Imghdr str is >%s<, col %d\n", 
+    fprintf(stderr, "Imghdr str is >%s<, col %d\n",
             header.description, Colbool);
 #endif
     /* Return the amount to fseek */
@@ -153,6 +153,7 @@ get_imghdr(int length)
 }
 
 
+
 static void
 usage()
 {
@@ -162,6 +163,8 @@ usage()
     exit(1);
 }
 
+
+
 int
 main(int argc, char *argv[])
 {
@@ -176,7 +179,7 @@ main(int argc, char *argv[])
     } arecord;
 
     pgm_init( &argc, argv );
-   
+
     switch (argc)
     {
     case 7:
@@ -219,7 +222,7 @@ main(int argc, char *argv[])
             arecord.length = get_imghdr(arecord.length);
 #ifdef DEBUG
         else
-            fprintf(stderr, 
+            fprintf(stderr,
                     "Rcrd %3d, type %03o, stype %03o %03o %03o, length %d\n",
                     arecord.record, arecord.type, arecord.sub1, arecord.sub2,
                     (int) arecord.sub3 & 0xff, arecord.length);
@@ -229,3 +232,6 @@ main(int argc, char *argv[])
     }
     exit (0);
 }
+
+
+
diff --git a/converter/pgm/st4topgm.c b/converter/pgm/st4topgm.c
index 90be6b72..89ec930d 100644
--- a/converter/pgm/st4topgm.c
+++ b/converter/pgm/st4topgm.c
@@ -56,6 +56,7 @@ validateFileSize(FILE * const ifP) {
 }
 
 
+
 static void
 writeRaster(FILE *       const ifP,
             struct pam * const pamP) {
@@ -69,11 +70,11 @@ writeRaster(FILE *       const ifP,
         unsigned int col;
 
         for (col = 0; col < st4Width; ++col) {
-            char c;
+            unsigned char c;
 
-            pm_readchar(ifP, &c);
+            pm_readcharu(ifP, &c);
 
-            tuplerow[col][0] = (unsigned char)c;
+            tuplerow[col][0] = c;
         }
         pnm_writepamrow(pamP, tuplerow);
     }
@@ -188,15 +189,15 @@ readFooter(FILE *             const ifP,
 static void
 reportFooter(struct St4Footer const footer) {
 
-	pm_message("Comment:                 %s", footer.comment);
+        pm_message("Comment:                 %s", footer.comment);
 
-	pm_message("Exposure time (1/100 s): %s", footer.exposureTime);
+        pm_message("Exposure time (1/100 s): %s", footer.exposureTime);
 
-	pm_message("Focal length (in):       %s", footer.focalLength);
+        pm_message("Focal length (in):       %s", footer.focalLength);
 
-	pm_message("Aperture area (sq in):   %s", footer.apertureArea);
+        pm_message("Aperture area (sq in):   %s", footer.apertureArea);
 
-	pm_message("Calibration factor:      %s", footer.calibrationFactor);
+        pm_message("Calibration factor:      %s", footer.calibrationFactor);
 }
 
 
@@ -219,7 +220,7 @@ main(int argc, const char **argv) {
             pm_error("Too many arguments: %u.  "
                      "The only possible argument is the "
                      "optional input file name", argc-1);
-    }        
+    }
 
     /* We check the file size to catch the common problem of the input not
        being valid ST-4 SBIG input.  Unlike most formats, this one does not
@@ -258,3 +259,4 @@ main(int argc, const char **argv) {
 }
 
 
+
diff --git a/converter/ppm/411toppm.c b/converter/ppm/411toppm.c
index eb2372a5..9d338fa7 100644
--- a/converter/ppm/411toppm.c
+++ b/converter/ppm/411toppm.c
@@ -86,8 +86,6 @@ parseCommandLine(int argc, const char ** argv,
 -----------------------------------------------------------------------------*/
 
     optEntry * option_def;
-        /* Instructions to OptParseOptions2 on how to parse our options.
-         */
     optStruct3 opt;
 
     unsigned int option_def_index;
@@ -105,8 +103,8 @@ parseCommandLine(int argc, const char ** argv,
     opt.opt_table = option_def;
     opt.short_allowed = FALSE;  /* We have no short (old-fashioned) options */
     opt.allowNegNum = FALSE;  /* We have no parms that are negative numbers */
-    
-    pm_optParseOptions3(&argc, (char **)argv, opt, sizeof(opt), 0);
+
+    pm_optParseOptions4(&argc, argv, opt, sizeof(opt), 0);
         /* Uses and sets argc, argv, and some of *cmdlineP and others. */
 
     if (cmdlineP->width <= 0)
@@ -182,7 +180,7 @@ YUVtoPPM(FILE  * const ifP,
         r = CHOP((int)(tempR >> 16));
         g = CHOP((int)(tempG >> 16));
         b = CHOP((int)(tempB >> 16));
-        
+
         PPM_ASSIGN(pixrow[col], r, g, b);
     }
 }
@@ -225,6 +223,8 @@ main(int argc, const char **argv) {
     return 0;
 }
 
+
+
 /*
    By default a .411 file is width=64, height=48, 4608 bytes.
    There is no header.
diff --git a/converter/ppm/autocad.h b/converter/ppm/autocad.h
index 3005782b..ef82cf6f 100644
--- a/converter/ppm/autocad.h
+++ b/converter/ppm/autocad.h
@@ -56,7 +56,7 @@ static unsigned char acadcol[256][3] = {
     {76, 38, 66}, {38, 0, 28}, {38, 19, 33}, {255, 0, 127}, {255, 127, 191},
     {165, 0, 82}, {165, 82, 124}, {127, 0, 63}, {127, 63, 95}, {76, 0, 38},
     {76, 38, 57}, {38, 0, 19}, {38, 19, 28}, {255, 0, 63}, {255, 127, 159},
-    {165, 0, 41}, {165, 82, 103}, {127, 0, 31}, {127, 63, 79},	{76, 0, 19},
+    {165, 0, 41}, {165, 82, 103}, {127, 0, 31}, {127, 63, 79},  {76, 0, 19},
     {76, 38, 47}, {38, 0, 9}, {38, 19, 23}, {84, 84, 84}, {118, 118, 118},
     {152, 152, 152}, {186, 186, 186}, {220, 220, 220}, {255, 255, 255}
 };
diff --git a/converter/ppm/eyuvtoppm.c b/converter/ppm/eyuvtoppm.c
index 910a125b..3ec29268 100644
--- a/converter/ppm/eyuvtoppm.c
+++ b/converter/ppm/eyuvtoppm.c
@@ -1,6 +1,6 @@
 /* Bryan got this from mm.ftp-cs.berkeley.edu from the package
-   mpeg-encode-1.5b-src under the name eyuvtoppm.c on March 30, 2000.  
-   The file was dated April 14, 1995.  
+   mpeg-encode-1.5b-src under the name eyuvtoppm.c on March 30, 2000.
+   The file was dated April 14, 1995.
 
    Bryan rewrote the program entirely to match Netpbm coding style,
    use the Netpbm libraries and also to output to stdout and ignore
@@ -70,7 +70,7 @@ parseCommandLine(int argc, char ** argv,
     option_def_index = 0;   /* incremented by OPTENT3 */
     OPTENT3('w', "width",     OPT_UINT,  &cmdlineP->width,   NULL,         0);
     OPTENT3('h', "height",    OPT_UINT,  &cmdlineP->height,  NULL,         0);
-    
+
     /* DEFAULTS */
     cmdlineP->width = 352;
     cmdlineP->height = 240;
@@ -93,7 +93,7 @@ parseCommandLine(int argc, char ** argv,
                  "You specified %u.", cmdlineP->height);
 
 
-    if (argc-1 == 0) 
+    if (argc-1 == 0)
         cmdlineP->inputFileName = "-";
     else if (argc-1 != 1)
         pm_error("Program takes zero or one argument (filename).  You "
@@ -106,7 +106,7 @@ parseCommandLine(int argc, char ** argv,
 
 
 
-static uint8 ** 
+static uint8 **
 allocUint8Array(unsigned int const cols,
                 unsigned int const rows) {
 
@@ -129,7 +129,7 @@ allocUint8Array(unsigned int const cols,
 
 
 
-static void 
+static void
 freeUint8Array(uint8 **     const array,
                unsigned int const rows) {
 
@@ -162,28 +162,28 @@ freeStorage(unsigned int const rows,
             uint8 **     const orig_y,
             uint8 **     const orig_cb,
             uint8 **     const orig_cr) {
-    
-    freeUint8Array(orig_y,  rows); 
-    freeUint8Array(orig_cb, rows); 
+
+    freeUint8Array(orig_y,  rows);
+    freeUint8Array(orig_cb, rows);
     freeUint8Array(orig_cr, rows);
 
 }
 
 
 
-static void 
+static void
 YUVtoPPM(FILE *       const ofP,
          unsigned int const cols,
          unsigned int const rows,
          uint8 **     const orig_y,
          uint8 **     const orig_cb,
-         uint8 **     const orig_cr) { 
+         uint8 **     const orig_cr) {
 /*----------------------------------------------------------------------------
    Convert the YUV image in arrays orig_y[][], orig_cb[][], and orig_cr[][]
    to a PPM image and write it to file *ofP.
 -----------------------------------------------------------------------------*/
     pixel * const pixrow = ppm_allocrow(cols);
-    
+
     unsigned int row;
 
     ppm_writeppminit(ofP, cols, rows, 255, FALSE);
@@ -202,11 +202,11 @@ YUVtoPPM(FILE *       const ofP,
             tempR = 104635*v + 76310*y;
             tempG = -25690*u + -53294*v + 76310*y;
             tempB = 132278*u + 76310*y;
-            
+
             r = CHOP((int)(tempR >> 16));
             g = CHOP((int)(tempG >> 16));
             b = CHOP((int)(tempB >> 16));
-            
+
             PPM_ASSIGN(pixrow[col], r, g, b);
         }
         ppm_writeppmrow(stdout, pixrow, cols, 255, FALSE);
@@ -216,12 +216,12 @@ YUVtoPPM(FILE *       const ofP,
 
 
 
-static void 
+static void
 ReadYUV(FILE *       const ifP,
         unsigned int const cols,
         unsigned int const rows,
-        uint8 **     const orig_y, 
-        uint8 **     const orig_cb, 
+        uint8 **     const orig_y,
+        uint8 **     const orig_cb,
         uint8 **     const orig_cr,
         bool *       const eofP) {
 
@@ -240,7 +240,7 @@ ReadYUV(FILE *       const ifP,
         if (bytesRead != cols)
             eof = true;
     }
-        
+
     for (row = 0; row < rows / 2 && !eof; ++row) {  /* U */
         size_t bytesRead;
 
@@ -249,7 +249,7 @@ ReadYUV(FILE *       const ifP,
         if (bytesRead != cols / 2)
             eof = true;
     }
-        
+
     for (row = 0; row < rows / 2 && !eof; ++row) { /* V */
         size_t bytesRead;
 
@@ -297,7 +297,7 @@ main(int argc, const char **argv) {
 
     for (frameSeq = 0, eof = false; !eof; ++frameSeq) {
 
-        ReadYUV(ifP, cmdline.width, cmdline.height, 
+        ReadYUV(ifP, cmdline.width, cmdline.height,
                 orig_y, orig_cb, orig_cr, &eof);
 
         if (!eof) {
@@ -317,3 +317,4 @@ main(int argc, const char **argv) {
 }
 
 
+
diff --git a/converter/ppm/gouldtoppm.c b/converter/ppm/gouldtoppm.c
index 5db7c51a..6cc7726c 100644
--- a/converter/ppm/gouldtoppm.c
+++ b/converter/ppm/gouldtoppm.c
@@ -22,101 +22,106 @@ main( argc, argv )
 int argc;
 char *argv[];
 {
-	FILE *ifp;
-	pixel *pixrow;
+        FILE *ifp;
+        pixel *pixrow;
 
-	unsigned long cols, nlines, bytesperline, bitsperpixel, NB, x, y;
-	unsigned char pbuffer[4];
+        unsigned long cols, nlines, bytesperline, bitsperpixel, NB, x, y;
+        unsigned char pbuffer[4];
 
-	int color_type;
+        int color_type;
 
 
-	ppm_init( &argc, argv );
+        ppm_init( &argc, argv );
 
-	if ( argc > 2 )
-		pm_usage( "[gouldfile]" );
+        if ( argc > 2 )
+                pm_usage( "[gouldfile]" );
 
-	if ( argc == 2 )
-		ifp = pm_openr( argv[1] );
-	else
-		ifp = stdin;
+        if ( argc == 2 )
+                ifp = pm_openr( argv[1] );
+        else
+                ifp = stdin;
 
-	getgouldheader( ifp, &cols, &nlines, &bytesperline, &bitsperpixel, &NB);
+        getgouldheader( ifp, &cols, &nlines, &bytesperline, &bitsperpixel, &NB);
 
-	ppm_writeppminit(stdout, cols, nlines, MAXVAL, 0);
+        ppm_writeppminit(stdout, cols, nlines, MAXVAL, 0);
 
-	color_type = bitsperpixel/8;
-	if (color_type == 0) color_type = NB;
+        color_type = bitsperpixel/8;
+        if (color_type == 0) color_type = NB;
 
-	pixrow = ppm_allocrow(cols);
+        pixrow = ppm_allocrow(cols);
 
-	for (y = 0; y < nlines; ++y)
-	{
-		for (x = 0; x < cols; ++x)
-		{
-			switch (color_type)
-			{
-			case 0:
-				pm_error("incorrect color type" );
+        for (y = 0; y < nlines; ++y)
+        {
+                for (x = 0; x < cols; ++x)
+                {
+                        switch (color_type)
+                        {
+                        case 0:
+                                pm_error("incorrect color type" );
 
-			case 1:
-				fread(pbuffer, 1, 1, ifp);
-				PPM_ASSIGN( pixrow[x], pbuffer[0], pbuffer[0], pbuffer[0]);
-				break;
+                        case 1:
+                                fread(pbuffer, 1, 1, ifp);
+                                PPM_ASSIGN( pixrow[x], pbuffer[0], pbuffer[0], pbuffer[0]);
+                                break;
 
-			case 2:
-				fread(pbuffer, 2, 1, ifp);
-				PPM_ASSIGN( pixrow[x], pbuffer[0], pbuffer[1], pbuffer[1]);
-				break;
+                        case 2:
+                                fread(pbuffer, 2, 1, ifp);
+                                PPM_ASSIGN( pixrow[x], pbuffer[0], pbuffer[1], pbuffer[1]);
+                                break;
 
-			case 3:
-				fread(pbuffer, 3, 1, ifp);
-				PPM_ASSIGN( pixrow[x], pbuffer[0], pbuffer[1], pbuffer[2]);
-				break;
+                        case 3:
+                                fread(pbuffer, 3, 1, ifp);
+                                PPM_ASSIGN( pixrow[x], pbuffer[0], pbuffer[1], pbuffer[2]);
+                                break;
 
-			default :
-				fread(pbuffer, 3, 1, ifp);
-				PPM_ASSIGN( pixrow[x], pbuffer[0], pbuffer[1], pbuffer[2]);
-				break;
+                        default :
+                                fread(pbuffer, 3, 1, ifp);
+                                PPM_ASSIGN( pixrow[x], pbuffer[0], pbuffer[1], pbuffer[2]);
+                                break;
 
-			} /* switch */
-		}
-		ppm_writeppmrow(stdout, pixrow, cols, MAXVAL, 0);
-	}
+                        } /* switch */
+                }
+                ppm_writeppmrow(stdout, pixrow, cols, MAXVAL, 0);
+        }
 
-	pm_close(ifp);
-	pm_close(stdout);
+        pm_close(ifp);
+        pm_close(stdout);
 
-	exit(0);
+        exit(0);
 }
 
+
+
 static void
 getgouldheader( infile, cols, nlines, bytesperline, bitsperpixel, NB)
 FILE *infile;
 unsigned long *cols, *nlines, *bytesperline, *bitsperpixel, *NB;
 {
-	unsigned long nlines_new, bytesperline_new, numheaderrec;
-	unsigned char headerblk[512];
-	int i;
-
-	if (fread(headerblk, 512, 1, infile) == 0)
-		pm_error("cannot read gould header" );
-
-	*nlines       = (headerblk[3]<<8) | headerblk[2];
-	*bytesperline = (headerblk[5]<<8) | headerblk[4];
-	*bitsperpixel = (headerblk[7]<<8) | headerblk[6];
-	numheaderrec  = (headerblk[9]<<8) | headerblk[8];
-	nlines_new    = (headerblk[15]<<24)| (headerblk[14]<<16) | (headerblk[13]<<8) | (headerblk[12]);
-	bytesperline_new = (headerblk[19]<<24)| (headerblk[18]<<16) | (headerblk[17]<<8) | (headerblk[16]);
-	*NB           = (headerblk[23]<<24)| (headerblk[22]<<16) | (headerblk[21]<<8) | (headerblk[20]);
-
-	if (numheaderrec > 1)
-		for (i = 1 ; i <numheaderrec; ++i)
-			if (fread(headerblk, 512, 1, infile) == 0)
-				pm_error("cannot read gould header(2nd)" );
-
-	if (*nlines==0) *nlines=nlines_new;
-	if (*bytesperline==0) *bytesperline=bytesperline_new;
-
-	*cols = (*bytesperline)*8 / (*bitsperpixel);
+        unsigned long nlines_new, bytesperline_new, numheaderrec;
+        unsigned char headerblk[512];
+        int i;
+
+        if (fread(headerblk, 512, 1, infile) == 0)
+                pm_error("cannot read gould header" );
+
+        *nlines       = (headerblk[3]<<8) | headerblk[2];
+        *bytesperline = (headerblk[5]<<8) | headerblk[4];
+        *bitsperpixel = (headerblk[7]<<8) | headerblk[6];
+        numheaderrec  = (headerblk[9]<<8) | headerblk[8];
+        nlines_new    = (headerblk[15]<<24)| (headerblk[14]<<16) | (headerblk[13]<<8) | (headerblk[12]);
+        bytesperline_new = (headerblk[19]<<24)| (headerblk[18]<<16) | (headerblk[17]<<8) | (headerblk[16]);
+        *NB           = (headerblk[23]<<24)| (headerblk[22]<<16) | (headerblk[21]<<8) | (headerblk[20]);
+
+        if (numheaderrec > 1)
+                for (i = 1 ; i <numheaderrec; ++i)
+                        if (fread(headerblk, 512, 1, infile) == 0)
+                                pm_error("cannot read gould header(2nd)" );
+
+        if (*nlines==0) *nlines=nlines_new;
+        if (*bytesperline==0) *bytesperline=bytesperline_new;
+
+        *cols = (*bytesperline)*8 / (*bitsperpixel);
 }
+
+
+
diff --git a/converter/ppm/hpcdtoppm/Makefile b/converter/ppm/hpcdtoppm/Makefile
index 59ba3630..9633017e 100644
--- a/converter/ppm/hpcdtoppm/Makefile
+++ b/converter/ppm/hpcdtoppm/Makefile
@@ -7,11 +7,29 @@ VPATH=.:$(SRCDIR)/$(SUBDIR)
 
 include $(BUILDDIR)/config.mk
 
-all: hpcdtoppm
+SCRIPTS =  pcdovtoppm
+
+ifeq ($(file <hpcdtoppm-import/Makefile)x,x)
+  # The file does not exist, which means user did not augment the
+  # Netpbm source tree by adding hpcdtoppm source code.
+  #
+  # Therefore, we package the dummy 'hpcdtoppm' program that just tells the
+  # user how to get the real one.
+  #
+  # See README in this directory.
+  #
+  # (Note that empty file and nonexistent file look the same with
+  # $(file)).
+  SCRIPTS += hpcdtoppm
+else
+  SUBDIRS += hpcdtoppm-import
+endif
 
-SCRIPTS = hpcdtoppm pcdovtoppm
 MERGE_OBJECTS =
 
+.PHONY: all
+all: $(BINARIES) $(SUBDIRS:%=%/all)
+
 include $(SRCDIR)/common.mk
 
 install.bin install.merge: install.bin.local
@@ -19,7 +37,7 @@ install.bin install.merge: install.bin.local
 install.bin.local: $(PKGDIR)/bin
 # In June 2002, pcdovtoppm replaced pcdindex
 	cd $(PKGDIR)/bin ; \
-	$(SYMLINK) pcdovtoppm$(EXE) pcdindex$(EXE) 
+	$(SYMLINK) pcdovtoppm pcdindex
 
 
 FORCE:
diff --git a/converter/ppm/hpcdtoppm/README b/converter/ppm/hpcdtoppm/README
index a1c7c8c2..ec23ec1b 100644
--- a/converter/ppm/hpcdtoppm/README
+++ b/converter/ppm/hpcdtoppm/README
@@ -1,20 +1,25 @@
-This 'hpcdtoppm' directory is really just a placeholder for the real
-Hpcdtoppm source code.  
+The 'hpcdtoppm' code in this directory is just a dummy version of the program
+that tells you where to get the real code.
 
-The real Hpcdtoppm source code cannot be distributed on Sourceforge
-because a copyright holder does not license it in a way open enough to
-meet Sourceforge's requirements.
+The real "hpcdtoppm' source code cannot be distributed on Sourceforge because
+a copyright holder does not license it in a way open enough to meet
+Sourceforge's requirements.
 
-Therefore, the Netpbm maintainer distributes Hpcdtoppm via another channel
-and distributes this dummy directory in the main Netpbm source tree on 
-Sourceforge.  When you run the program named 'hpcdtoppm' in this directory,
-it tells you how to get the real Hpcdtoppm.
+Therefore, the Netpbm maintainer distributes 'hpcdtoppm' via another channel
+and distributes this dummy directory in the main Netpbm source tree on
+Sourceforge.
 
-When you get the real Hpcdtoppm tarball, just unpack it and replace
-this entire 'hpcdtoppm' directory with its contents.  Then build
-Netpbm normally.
+The code is at 
+
+  http://ibiblio.org/pub/Linux/apps/graphics/convert/hpcdtoppm-netpbm.tgz
+
+When you get the real 'hpcdtoppm' tarball, just unpack its contents into the
+'hpcdtoppm-import' subdirectory.  Then build Netpbm normally.  The build
+detects the presence of the code and builds and packages the real 'hpcdtoppm'
+program instead of the dummy one.
+
+Bear in mind when you get the real 'hpcdtoppm' that it is not as openly
+licensed as what's in the rest of the Netpbm source tree.  As you'll see in
+the license that comes with 'hpcdtoppm', you may _not_ sell it to someone
+else.)
 
-Bear in mind when you get the real Hpcdtoppm, that it is not as openly
-licensed as what's in the rest of the Netpbm source tree.  As you'll
-see in the license that comes with Hpcdtoppm, you may _not_ sell it to
-someone else.)
diff --git a/converter/ppm/hpcdtoppm/hpcdtoppm b/converter/ppm/hpcdtoppm/hpcdtoppm
index ec3f1763..2a61aa9d 100755
--- a/converter/ppm/hpcdtoppm/hpcdtoppm
+++ b/converter/ppm/hpcdtoppm/hpcdtoppm
@@ -8,17 +8,15 @@ The real 'hpcdtoppm' is a program that converts an image from Photo CD format
 to PPM format.  The program you are running now just issues the message you
 are reading.
 
-You can get a copy of Hpcdtoppm from 
-
-  http://metalab.unc.edu/pub/Linux/apps/graphics/convert/hpcdtoppm.linux.tar.gz
-
-and replace this stand-in program with the real one.
+Instructions for getting the 'hpcdtoppm' source code and building it into
+Netpbm are in the file converter/ppm/hpcdtoppm/README in the distributed
+Netpbm source tree.
 
 The point of this is that this stand-in 'hpcdtoppm' is distributed with Netpbm
-on Sourceforge.  Hpcdtoppm does not meet the requirements to be distributed on
-Sourceforge because a copyright holder does not permit people to sell copies.
-At one time, the real Hpcdtoppm was distributed with Netpbm on Sourceforge by
-mistake.
+on Sourceforge.  'hpcdtoppm' does not meet the requirements to be distributed
+on Sourceforge because a copyright holder does not permit people to sell
+copies.  At one time, the real 'hpcdtoppm' was distributed with Netpbm on
+Sourceforge by mistake.
 
 EOF
 
diff --git a/converter/ppm/hpcdtoppm/pcdovtoppm b/converter/ppm/hpcdtoppm/pcdovtoppm
index b86048cc..2a875690 100755
--- a/converter/ppm/hpcdtoppm/pcdovtoppm
+++ b/converter/ppm/hpcdtoppm/pcdovtoppm
@@ -144,7 +144,7 @@ tempdir=$(mktemp -d "${TMPDIR:-/tmp}/pcdovtoppm.XXXXXXXX") ||
     { echo "Could not create temporary file. Exiting." 1>&2; exit 1; }
 trap 'rm -rf $tempdir' 0
 
-tmpfile=`tempfile -p pi -m 600`
+tmpfile=$(mktemp --tmpdir piXXXXXX)
 
 # Convert the PCD overview file to many PPM images
 if [ -f $1 ] ; then
@@ -183,11 +183,12 @@ do
     ttext="$i:t"
 
     if [ "$back" = "-white" ] ; then
-        pbmtext $font "$ttext" | pnmcrop -quiet | pnmmargin -white 2| \
-        pnmcat $back -tb $tmpfile - > $imagefile
+        pbmtext $font "$ttext" | pnmcrop -quiet | pnmmargin -white 2 | \
+        pamcat $back -topbottom $tmpfile - > $imagefile
     else
         pbmtext $font "$ttext" | pnmcrop -quiet | pnmmargin -white 2 | \
-        pnminvert | pnmcat $back -tb $tmpfile - > $imagefile
+          pnminvert | \
+          pamcat $back -topbottom $tmpfile - > $imagefile
     fi
 
     rm -f $tmpfile
@@ -199,9 +200,9 @@ do
         rowfile=${tempdir}/pi.${row}
         rm -f $rowfile
     if [ "$colors" = "n" ] ; then
-        pnmcat $back -lr -jbottom $imagefiles > $rowfile
+        pamcat $back -leftright -jbottom $imagefiles > $rowfile
     else
-        pnmcat $back -lr -jbottom $imagefiles | \
+        pamcat $back -leftright -jbottom $imagefiles | \
         ppmquant -quiet $colors > $rowfile
     fi
     rm -f $imagefiles
@@ -219,10 +220,10 @@ if [ -n $imagefiles ] ; then
     rowfile=${tempdir}/pi.${row}
     rm -f $rowfile
     if [ "$colors" = "n" ] ; then
-        pnmcat $back -lr -jbottom $imagefiles > $rowfile
+        pamcat $back -leftright -jbottom $imagefiles > $rowfile
     else
-        pnmcat $back -lr -jbottom $imagefiles | \
-        ppmquant -quiet $colors > $rowfile
+        pamcat $back -leftright -jbottom $imagefiles | \
+          ppmquant -quiet $colors > $rowfile
     fi
     rm -f $imagefiles
     rowfiles="$rowfiles $rowfile"
@@ -232,9 +233,11 @@ if [ $(echo $rowfiles|wc -w) -eq 1 ] ; then
     ppmtoppm $plainopt < $rowfiles
 else
     if [ "$colors" = "n" ] ; then
-        pnmcat $back -tb $plainopt $rowfiles
+        pamcat $back -topbottom $rowfiles | \
+          ppmtoppm $plainopt
     else
-        pnmcat $back -tb $rowfiles | ppmquant $plainopt -quiet $colors
+        pamcat $back -tb $rowfiles | \
+          ppmquant $plainopt -quiet $colors
     fi
 fi
 
diff --git a/converter/ppm/ilbm.h b/converter/ppm/ilbm.h
index c0fac7d2..2f08a12f 100644
--- a/converter/ppm/ilbm.h
+++ b/converter/ppm/ilbm.h
@@ -1,9 +1,17 @@
+/*=============================================================================
+                                 ilbm.h
+===============================================================================
+  Facilities for processign IFF ILBM files
+=============================================================================*/
 #ifndef ILBM_H_INCLUDED
 #define ILBM_H_INCLUDED
 
-/* ilbm.h - definitions for IFF ILBM files */
+static __inline__ unsigned int
+ilbm_rowByteCt(unsigned int const cols) {
+
+    return (cols / 16 + (cols % 16 == 0 ? 0 : 1)) * 2;
+}
 
-#define RowBytes(cols)          ((((cols) + 15) / 16) * 2)
 
 
 /* definitions for BMHD */
diff --git a/converter/ppm/ilbmtoppm.c b/converter/ppm/ilbmtoppm.c
index b9b89862..8a8cf9f3 100644
--- a/converter/ppm/ilbmtoppm.c
+++ b/converter/ppm/ilbmtoppm.c
@@ -112,6 +112,7 @@ ID2string(IFF_ID const id) {
 }
 
 
+
 /****************************************************************************
  Memory allocation
  ****************************************************************************/
@@ -154,6 +155,7 @@ alloc_rawrow(unsigned int const cols) {
 }
 
 
+
 /****************************************************************************
  Basic I/O functions
  ****************************************************************************/
@@ -207,6 +209,8 @@ get_byte(FILE *          const ifP,
     return (unsigned char) i;
 }
 
+
+
 static long
 get_big_long(FILE *          const ifP,
              IFF_ID          const iffid,
@@ -540,6 +544,7 @@ read_bmhd(FILE *        const ifP,
 }
 
 
+
 /****************************************************************************
  ILBM functions
  ****************************************************************************/
@@ -594,70 +599,78 @@ read_ilbm_plane(FILE *          const ifP,
 }
 
 
+
 static const unsigned char bit_mask[] = {1, 2, 4, 8, 16, 32, 64, 128};
 
 static void
-decode_row(FILE *          const ifP,
-           unsigned long * const remainingChunksizeP,
-           rawtype *       const chunkyrow,
-           int             const nPlanes,
-           BitMapHeader *  const bmhdP) {
-
-    int plane, col, cols, cbit, bytes;
-    unsigned char *ilp;
-    rawtype *chp;
-
-    cols = bmhdP->w;
-    bytes = RowBytes(cols);
-    for( plane = 0; plane < nPlanes; plane++ ) {
+decodeRow(FILE *          const ifP,
+          unsigned long * const remainingChunksizeP,
+          rawtype *       const chunkyrow,
+          int             const nPlanes,
+          BitMapHeader *  const bmhdP) {
+
+    int plane;
+    int col;
+    int cols;
+    int bytes;
+    unsigned char * ilP;
+    rawtype * chP;
+
+    cols  = bmhdP->w;
+    bytes = ilbm_rowByteCt(cols);
+
+    for (plane = 0; plane < nPlanes; ++plane) {
         int mask;
+        int cbit;
 
         mask = 1 << plane;
         read_ilbm_plane(ifP, remainingChunksizeP, bytes, bmhdP->compression);
 
-        ilp = ilbmrow;
-        chp = chunkyrow;
+        ilP = ilbmrow;
+        chP = chunkyrow;
 
-        cbit = 7;
-        for( col = 0; col < cols; col++, cbit--, chp++ ) {
-            if( cbit < 0 ) {
+        for (col = 0, cbit = 7; col < cols; col++, cbit--, chP++ ) {
+            if (cbit < 0) {
                 cbit = 7;
-                ilp++;
+                ++ilP;
             }
-            if( *ilp & bit_mask[cbit] )
-                *chp |= mask;
+            if (*ilP & bit_mask[cbit])
+                *chP |= mask;
             else
-                *chp &= ~mask;
+                *chP &= ~mask;
         }
     }
 }
 
 
+
 static void
-decode_mask(FILE *          const ifP,
-            unsigned long * const remainingChunksizeP,
-            rawtype *       const chunkyrow,
-            BitMapHeader *  const bmhdP) {
+decodeMask(FILE *          const ifP,
+           unsigned long * const remainingChunksizeP,
+           rawtype *       const chunkyrow,
+           BitMapHeader *  const bmhdP) {
 
-    int col, cols, cbit;
-    unsigned char *ilp;
+    int cols;
+    unsigned char * ilP;
 
     cols = bmhdP->w;
     switch (bmhdP->masking) {
     case mskNone:
         break;
     case mskHasMask:        /* mask plane */
-        read_ilbm_plane(ifP, remainingChunksizeP, RowBytes(cols),
+        read_ilbm_plane(ifP, remainingChunksizeP, ilbm_rowByteCt(cols),
                         bmhdP->compression);
         if (maskfile) {
-            ilp = ilbmrow;
-            cbit = 7;
-            for (col = 0; col < cols; ++col, --cbit) {
+            int col;
+            int cbit;
+
+            ilP = ilbmrow;
+            for (col = 0, cbit = 7; col < cols; ++col, --cbit) {
                 if (cbit < 0) {
                     cbit = 7;
-                    ++ilp;
+                    ++ilP;
                 }
-                if (*ilp & bit_mask[cbit])
+                if (*ilP & bit_mask[cbit])
                     maskrow[col] = PBM_BLACK;
                 else
                     maskrow[col] = PBM_WHITE;
@@ -668,9 +681,11 @@ decode_mask(FILE *          const ifP,
         break;
     case mskHasTransparentColor:
         if (!chunkyrow)
-            pm_error("decode_mask(): chunkyrow == NULL - can't happen");
+            pm_error("decodeMask(): chunkyrow == NULL - can't happen");
 
         if (maskfile) {
+            unsigned int col;
+
             for (col = 0; col < cols; ++col) {
                 if (chunkyrow[col] == bmhdP->transparentColor)
                     maskrow[col] = PBM_WHITE;
@@ -685,12 +700,13 @@ decode_mask(FILE *          const ifP,
         pm_error("This program does not know how to process Lasso masking");
         break;
     default:
-        pm_error("decode_mask(): unknown masking type %d - can't happen",
+        pm_error("decodeMask(): unknown masking type %d - can't happen",
                  bmhdP->masking);
     }
 }
 
 
+
 /****************************************************************************
  Multipalette handling
  ****************************************************************************/
@@ -1129,8 +1145,8 @@ ham_to_ppm(FILE *         const ifP,
             if( HAS_MULTIPALETTE(cmap) )
                 multi_update(cmap, row);
 
-            decode_row(ifP, &remainingChunksize, rawrow, bmhdP->nPlanes, bmhdP);
-            decode_mask(ifP, &remainingChunksize, rawrow, bmhdP);
+            decodeRow(ifP, &remainingChunksize, rawrow, bmhdP->nPlanes, bmhdP);
+            decodeMask(ifP, &remainingChunksize, rawrow, bmhdP);
 
             r = g = b = 0;
             for( col = 0; col < cols; col++ ) {
@@ -1225,8 +1241,8 @@ std_to_ppm(FILE *         const ifP,
             if( HAS_MULTIPALETTE(cmap) )
                 multi_update(cmap, row);
 
-            decode_row(ifP, &remainingChunksize, rawrow, bmhdP->nPlanes, bmhdP);
-            decode_mask(ifP, &remainingChunksize, rawrow, bmhdP);
+            decodeRow(ifP, &remainingChunksize, rawrow, bmhdP->nPlanes, bmhdP);
+            decodeMask(ifP, &remainingChunksize, rawrow, bmhdP);
 
             for( col = 0; col < cols; col++ ) {
                 pixval r, g, b;
@@ -1255,25 +1271,27 @@ deep_to_ppm(FILE *         const ifP,
     unsigned int const rows = bmhdP->h;
     unsigned int const planespercolor = bmhdP->nPlanes / 3;
 
-    unsigned int col, row;
-    rawtype *Rrow, *Grow, *Brow;
+    unsigned int row;
+    rawtype * Rrow;
+    rawtype * Grow;
+    rawtype * Brow;
     pixval maxval;
     unsigned long remainingChunksize;
     pixel * transpColorP;
 
     pm_message("input is a deep (%d-bit) ILBM", bmhdP->nPlanes);
-    if( planespercolor > MAXPLANES )
+    if (planespercolor > MAXPLANES)
         pm_error("too many planes (max %d)", MAXPLANES * 3);
 
-    if( bmhdP->masking == mskHasTransparentColor ||
-        bmhdP->masking == mskLasso ) {
+    if (bmhdP->masking == mskHasTransparentColor ||
+        bmhdP->masking == mskLasso) {
         pm_message("masking type '%s' in a deep ILBM?? - ignoring it",
                    mskNAME[bmhdP->masking]);
         bmhdP->masking = mskNone;
     }
 
     maxval = lut_maxval(cmap, pm_bitstomaxval(planespercolor));
-    if( maxval > PPM_OVERALLMAXVAL )
+    if (maxval > PPM_OVERALLMAXVAL)
         pm_error("nPlanes is too large");
 
     transpColorP = transpColor(bmhdP, cmap, transpName, maxval);
@@ -1286,19 +1304,21 @@ deep_to_ppm(FILE *         const ifP,
 
     remainingChunksize = chunksize;  /* initial value */
 
-    for( row = 0; row < rows; row++ ) {
-        decode_row(ifP, &remainingChunksize, Rrow, planespercolor, bmhdP);
-        decode_row(ifP, &remainingChunksize, Grow, planespercolor, bmhdP);
-        decode_row(ifP, &remainingChunksize, Brow, planespercolor, bmhdP);
-        decode_mask(ifP, &remainingChunksize, NULL, bmhdP);
+    for (row = 0; row < rows; ++row) {
+        unsigned int col;
 
-        for( col = 0; col < cols; col++ ) {
-            if( transpColorP && maskrow && maskrow[col] == PBM_WHITE )
+        decodeRow(ifP, &remainingChunksize, Rrow, planespercolor, bmhdP);
+        decodeRow(ifP, &remainingChunksize, Grow, planespercolor, bmhdP);
+        decodeRow(ifP, &remainingChunksize, Brow, planespercolor, bmhdP);
+        decodeMask(ifP, &remainingChunksize, NULL, bmhdP);
+
+        for (col = 0; col < cols; ++col) {
+            if (transpColorP && maskrow && maskrow[col] == PBM_WHITE)
                 pixelrow[col] = *transpColorP;
             else
-                PPM_ASSIGN(pixelrow[col],   lookup_red(cmap, Rrow[col]),
-                                            lookup_green(cmap, Grow[col]),
-                                            lookup_blue(cmap, Brow[col]) );
+                PPM_ASSIGN(pixelrow[col], lookup_red(cmap, Rrow[col]),
+                                          lookup_green(cmap, Grow[col]),
+                                          lookup_blue(cmap, Brow[col]));
         }
         ppm_writeppmrow(stdout, pixelrow, cols, maxval, 0);
     }
@@ -1320,33 +1340,35 @@ dcol_to_ppm(FILE *         const ifP,
     unsigned int const greenplanes = dcol->g;
     unsigned int const blueplanes  = dcol->b;
 
-    int col, row;
-    rawtype *Rrow, *Grow, *Brow;
+    int row;
+    rawtype * Rrow;
+    rawtype * Grow;
+    rawtype * Brow;
     pixval maxval, redmaxval, greenmaxval, bluemaxval;
     pixval *redtable, *greentable, *bluetable;
     unsigned long remainingChunksize;
     pixel * transpColorP;
 
     pm_message("input is a %d:%d:%d direct color ILBM",
-                redplanes, greenplanes, blueplanes);
+               redplanes, greenplanes, blueplanes);
 
-    if( redplanes > MAXPLANES ||
+    if (redplanes > MAXPLANES ||
         blueplanes > MAXPLANES ||
-        greenplanes > MAXPLANES )
+        greenplanes > MAXPLANES)
         pm_error("too many planes (max %d per color component)", MAXPLANES);
 
-    if( bmhdP->nPlanes != (redplanes + greenplanes + blueplanes) )
+    if (bmhdP->nPlanes != (redplanes + greenplanes + blueplanes))
         pm_error("%s/%s plane number mismatch",
                  ID2string(ID_BMHD), ID2string(ID_DCOL));
 
-    if( bmhdP->masking == mskHasTransparentColor ||
-        bmhdP->masking == mskLasso ) {
+    if (bmhdP->masking == mskHasTransparentColor ||
+        bmhdP->masking == mskLasso) {
         pm_message("masking type '%s' in a direct color ILBM?? - ignoring it",
                    mskNAME[bmhdP->masking]);
         bmhdP->masking = mskNone;
     }
 
-    if( HAS_COLORLUT(cmap) ) {
+    if (HAS_COLORLUT(cmap)) {
         pm_error("This program does not know how to process a %s chunk "
                  "in direct color", ID2string(ID_CLUT));
         cmap->redlut = cmap->greenlut = cmap->bluelut = NULL;
@@ -1357,15 +1379,15 @@ dcol_to_ppm(FILE *         const ifP,
     bluemaxval  = pm_bitstomaxval(blueplanes);
     maxval = MAX(redmaxval, MAX(greenmaxval, bluemaxval));
 
-    if( maxval > PPM_OVERALLMAXVAL )
+    if (maxval > PPM_OVERALLMAXVAL)
         pm_error("too many planes");
 
-    if( redmaxval != maxval || greenmaxval != maxval || bluemaxval != maxval )
-        pm_message("scaling colors to %d bits", pm_maxvaltobits(maxval));
+    if (redmaxval != maxval || greenmaxval != maxval || bluemaxval != maxval)
+        pm_message("scaling colors to %u bits", pm_maxvaltobits(maxval));
 
-    MALLOCARRAY_NOFAIL(redtable,   redmaxval   +1);
-    MALLOCARRAY_NOFAIL(greentable, greenmaxval +1);
-    MALLOCARRAY_NOFAIL(bluetable,  bluemaxval  +1);
+    MALLOCARRAY_NOFAIL(redtable,   redmaxval   + 1);
+    MALLOCARRAY_NOFAIL(greentable, greenmaxval + 1);
+    MALLOCARRAY_NOFAIL(bluetable,  bluemaxval  + 1);
 
     {
         unsigned int i;
@@ -1386,19 +1408,21 @@ dcol_to_ppm(FILE *         const ifP,
 
     remainingChunksize = chunksize;  /* initial value */
 
-    for( row = 0; row < rows; row++ ) {
-        decode_row(ifP, &remainingChunksize, Rrow, redplanes, bmhdP);
-        decode_row(ifP, &remainingChunksize, Grow, greenplanes, bmhdP);
-        decode_row(ifP, &remainingChunksize, Brow, blueplanes, bmhdP);
-        decode_mask(ifP, &remainingChunksize, NULL, bmhdP);
+    for (row = 0; row < rows; ++row) {
+        unsigned int col;
 
-        for( col = 0; col < cols; col++ ) {
-            if( transpColorP && maskrow && maskrow[col] == PBM_WHITE )
+        decodeRow(ifP, &remainingChunksize, Rrow, redplanes, bmhdP);
+        decodeRow(ifP, &remainingChunksize, Grow, greenplanes, bmhdP);
+        decodeRow(ifP, &remainingChunksize, Brow, blueplanes, bmhdP);
+        decodeMask(ifP, &remainingChunksize, NULL, bmhdP);
+
+        for (col = 0; col < cols; ++col) {
+            if (transpColorP && maskrow && maskrow[col] == PBM_WHITE)
                 pixelrow[col] = *transpColorP;
             else
-                PPM_ASSIGN( pixelrow[col],  redtable[Rrow[col]],
-                                            greentable[Grow[col]],
-                                            bluetable[Brow[col]]   );
+                PPM_ASSIGN(pixelrow[col], redtable[Rrow[col]],
+                                          greentable[Grow[col]],
+                                          bluetable[Brow[col]]);
         }
         ppm_writeppmrow(stdout, pixelrow, cols, maxval, 0);
     }
@@ -1593,6 +1617,8 @@ rgbn_to_ppm(FILE *         const ifP,
     chunk_end(ifP, ID_BODY, remainingChunksize);
 }
 
+
+
 /****************************************************************************
  Multipalette chunk reader
 
@@ -1766,30 +1792,30 @@ PCHG_Decompress(PCHGHeader *     const PCHG,
 }
 
 
+
 static void
 PCHG_ConvertSmall(PCHGHeader *    const pchgP,
                   ColorMap *      const cmapP,
                   unsigned char * const mask,
                   unsigned long   const dataSize) {
 
-    unsigned char *data;
+    unsigned char * dataCursor;
     unsigned long remDataSize;
     unsigned char thismask;
-    int bits, row, i, changes, masklen, reg;
-    unsigned char ChangeCount16, ChangeCount32;
-    unsigned short SmallChange;
-    unsigned long totalchanges;
-    int changedlines;
+    int bits, row, masklen, reg;
+    unsigned int totalChangeCt;
+    unsigned int changedLineCt;
     unsigned char * maskCursor;
 
-    totalchanges = 0;  /* initial value */
-    changedlines = pchgP->ChangedLines;  /* initial value */
+    totalChangeCt = 0;  /* initial value */
+    changedLineCt = pchgP->ChangedLines;  /* initial value */
     masklen = 4 * MaskLongWords(pchgP->LineCount);
     maskCursor = mask;
-    data = maskCursor + masklen; remDataSize = dataSize - masklen;
-
+    dataCursor  = maskCursor + masklen;
+    remDataSize = dataSize - masklen;
     bits = 0;
-    for (row = pchgP->StartLine; changedlines && row < 0; ++row) {
+
+    for (row = pchgP->StartLine; changedLineCt > 0 && row < 0; ++row) {
         if (bits == 0) {
             if (masklen == 0) goto fail2;
             thismask = *maskCursor++;
@@ -1798,72 +1824,95 @@ PCHG_ConvertSmall(PCHGHeader *    const pchgP,
         }
         if (thismask & (1<<7)) {
             if (remDataSize < 2) goto fail;
-            ChangeCount16 = *data++;
-            ChangeCount32 = *data++;
-            remDataSize -= 2;
-
-            changes = ChangeCount16 + ChangeCount32;
-            for (i = 0; i < changes; ++i) {
-                if (totalchanges >= pchgP->TotalChanges) goto fail;
-                if (remDataSize < 2) goto fail;
-                SmallChange = BIG_WORD(data); data += 2; remDataSize -= 2;
-                reg = ((SmallChange & 0xf000) >> 12) +
-                    (i >= ChangeCount16 ? 16 : 0);
-                cmapP->mp_init[reg - pchgP->MinReg].reg = reg;
-                cmapP->mp_init[reg - pchgP->MinReg].r =
-                    ((SmallChange & 0x0f00) >> 8) * FACTOR_4BIT;
-                cmapP->mp_init[reg - pchgP->MinReg].g =
-                    ((SmallChange & 0x00f0) >> 4) * FACTOR_4BIT;
-                cmapP->mp_init[reg - pchgP->MinReg].b =
-                    ((SmallChange & 0x000f) >> 0) * FACTOR_4BIT;
-                ++totalchanges;
+            else {
+                unsigned int const changeCt16 = *dataCursor++;
+                unsigned int const changeCt32 = *dataCursor++;
+                unsigned int const changeCt = changeCt16 + changeCt32;
+
+                unsigned int i;
+
+                remDataSize -= 2;
+
+                for (i = 0; i < changeCt; ++i) {
+                    if (totalChangeCt >= pchgP->TotalChanges) goto fail;
+                    if (remDataSize < 2) goto fail;
+                    else {
+                        unsigned short const smallChange =
+                            BIG_WORD(dataCursor);
+
+                        dataCursor += 2; remDataSize -= 2;
+
+                        reg = ((smallChange & 0xf000) >> 12) +
+                            (i >= changeCt ? 16 : 0);
+                        cmapP->mp_init[reg - pchgP->MinReg].reg = reg;
+                        cmapP->mp_init[reg - pchgP->MinReg].r =
+                            ((smallChange & 0x0f00) >> 8) * FACTOR_4BIT;
+                        cmapP->mp_init[reg - pchgP->MinReg].g =
+                            ((smallChange & 0x00f0) >> 4) * FACTOR_4BIT;
+                        cmapP->mp_init[reg - pchgP->MinReg].b =
+                            ((smallChange & 0x000f) >> 0) * FACTOR_4BIT;
+                        ++totalChangeCt;
+                    }
+                }
+                --changedLineCt;
             }
-            --changedlines;
         }
         thismask <<= 1;
         --bits;
     }
 
-    for (row = pchgP->StartLine; changedlines && row < cmapP->mp_rows; row++) {
+    for (row = pchgP->StartLine;
+         changedLineCt > 0 && row < cmapP->mp_rows;
+         ++row) {
         if (bits == 0) {
             if (masklen == 0) goto fail2;
             thismask = *maskCursor++;
             --masklen;
             bits = 8;
         }
-        if(thismask & (1<<7)) {
+        if (thismask & (1<<7)) {
             if (remDataSize < 2) goto fail;
-            ChangeCount16 = *data++;
-            ChangeCount32 = *data++;
-            remDataSize -= 2;
-
-            changes = ChangeCount16 + ChangeCount32;
-            MALLOCARRAY_NOFAIL(cmapP->mp_change[row], changes + 1);
-            for (i = 0; i < changes; ++i) {
-                if (totalchanges >= pchgP->TotalChanges) goto fail;
-                if (remDataSize < 2) goto fail;
-                SmallChange = BIG_WORD(data); data += 2; remDataSize -= 2;
-                reg = ((SmallChange & 0xf000) >> 12) +
-                    (i >= ChangeCount16 ? 16 : 0);
-                cmapP->mp_change[row][i].reg = reg;
-                cmapP->mp_change[row][i].r =
-                    ((SmallChange & 0x0f00) >> 8) * FACTOR_4BIT;
-                cmapP->mp_change[row][i].g =
-                    ((SmallChange & 0x00f0) >> 4) * FACTOR_4BIT;
-                cmapP->mp_change[row][i].b =
-                    ((SmallChange & 0x000f) >> 0) * FACTOR_4BIT;
-                ++totalchanges;
+            else {
+                unsigned int const changeCt16 = *dataCursor++;
+                unsigned int const changeCt32 = *dataCursor++;
+                unsigned int const changeCt = changeCt16 + changeCt32;
+
+                unsigned int i;
+
+                remDataSize -= 2;
+
+                MALLOCARRAY_NOFAIL(cmapP->mp_change[row], changeCt + 1);
+                for (i = 0; i < changeCt; ++i) {
+                    if (totalChangeCt >= pchgP->TotalChanges) goto fail;
+                    if (remDataSize < 2) goto fail;
+                    else {
+                        unsigned short const smallChange =
+                            BIG_WORD(dataCursor);
+
+                        dataCursor += 2; remDataSize -= 2;
+                        reg = ((smallChange & 0xf000) >> 12) +
+                            (i >= changeCt16 ? 16 : 0);
+                        cmapP->mp_change[row][i].reg = reg;
+                        cmapP->mp_change[row][i].r =
+                            ((smallChange & 0x0f00) >> 8) * FACTOR_4BIT;
+                        cmapP->mp_change[row][i].g =
+                            ((smallChange & 0x00f0) >> 4) * FACTOR_4BIT;
+                        cmapP->mp_change[row][i].b =
+                            ((smallChange & 0x000f) >> 0) * FACTOR_4BIT;
+                        ++totalChangeCt;
+                    }
+                }
+                cmapP->mp_change[row][changeCt].reg = MP_REG_END;
+            --changedLineCt;
             }
-            cmapP->mp_change[row][changes].reg = MP_REG_END;
-            --changedlines;
         }
         thismask <<= 1;
         --bits;
     }
-    if (totalchanges != pchgP->TotalChanges)
-        pm_message("warning - got %ld change structures, "
+    if (totalChangeCt != pchgP->TotalChanges)
+        pm_message("warning - got %u change structures, "
                    "chunk header reports %ld",
-                   totalchanges, pchgP->TotalChanges);
+                   totalChangeCt, pchgP->TotalChanges);
     return;
 fail:
     pm_error("insufficient data in SmallLineChanges structures");
@@ -1989,20 +2038,20 @@ static void
 read_pchg(FILE *     const ifP,
           IFF_ID     const iffid,
           long       const chunksize,
-          ColorMap * const cmap) {
+          ColorMap * const cmapP) {
 
-    if( cmap->mp_type >= MP_TYPE_PCHG ) {
+    if (cmapP->mp_type >= MP_TYPE_PCHG ) {
         skip_chunk(ifP, iffid, chunksize);
     } else {
         PCHGHeader      PCHG;
-        unsigned char   *data;
+        unsigned char * data;
         unsigned long   datasize;
         unsigned long   remainingChunksize;
         int i;
 
-        if( cmap->mp_type )
-            multi_free(cmap);
-        cmap->mp_type = MP_TYPE_PCHG;
+        if (cmapP->mp_type)
+            multi_free(cmapP);
+        cmapP->mp_type = MP_TYPE_PCHG;
 
         remainingChunksize = chunksize;  /* initial value */
 
@@ -2014,7 +2063,7 @@ read_pchg(FILE *     const ifP,
         PCHG.MinReg      = get_big_short(ifP, iffid, &remainingChunksize);
         PCHG.MaxReg      = get_big_short(ifP, iffid, &remainingChunksize);
         PCHG.MaxChanges  = get_big_short(ifP, iffid, &remainingChunksize);
-        PCHG.TotalChanges= get_big_long(ifP, iffid, &remainingChunksize);
+        PCHG.TotalChanges= get_big_long (ifP, iffid, &remainingChunksize);
 
 #ifdef DEBUG
         pm_message("PCHG StartLine   : %d", PCHG.StartLine);
@@ -2023,9 +2072,10 @@ read_pchg(FILE *     const ifP,
         pm_message("PCHG TotalChanges: %d", PCHG.TotalChanges);
 #endif
 
-        if( PCHG.Compression != PCHG_COMP_NONE ) {
+        if (PCHG.Compression != PCHG_COMP_NONE) {
             PCHGCompHeader  CompHdr;
-            unsigned char *compdata, *comptree;
+            unsigned char * compdata;
+            unsigned char * comptree;
             long treesize, compsize;
 
             CompHdr.CompInfoSize     =
@@ -2057,37 +2107,47 @@ read_pchg(FILE *     const ifP,
             read_bytes(ifP, datasize, data, iffid, &remainingChunksize);
         }
 
-        if( PCHG.Flags & PCHGF_USE_ALPHA )
+        if (PCHG.Flags & PCHGF_USE_ALPHA)
             pm_message("warning - ignoring PCHG alpha channel because "
                        "this program doesn't know what to do with it");
 
-        cmap->mp_rows = PCHG.StartLine + PCHG.LineCount;
-        MALLOCARRAY_NOFAIL(cmap->mp_change, cmap->mp_rows);
-        for( i = 0; i < cmap->mp_rows; i++ )
-            cmap->mp_change[i] = NULL;
-        if( PCHG.StartLine < 0 ) {
-            int nch;
-            nch = PCHG.MaxReg - PCHG.MinReg +1;
-            MALLOCARRAY_NOFAIL(cmap->mp_init, nch + 1);
-            for( i = 0; i < nch; i++ )
-                cmap->mp_init[i].reg = MP_REG_IGNORE;
-            cmap->mp_init[nch].reg = MP_REG_END;
+        cmapP->mp_rows = PCHG.StartLine + PCHG.LineCount;
+        MALLOCARRAY_NOFAIL(cmapP->mp_change, cmapP->mp_rows);
+        for (i = 0; i < cmapP->mp_rows; ++i)
+            cmapP->mp_change[i] = NULL;
+
+        if (PCHG.StartLine < 0) {
+            if (PCHG.MaxReg < PCHG.MinReg)
+                pm_error("PCHG chunk says maxreg (%u) "
+                         "is less than minreg (%u)",
+                         PCHG.MaxReg, PCHG.MinReg);
+            else {
+                unsigned int const nch = PCHG.MaxReg - PCHG.MinReg + 1;
+
+                unsigned int i;
+
+                MALLOCARRAY_NOFAIL(cmapP->mp_init, nch + 1);
+
+                for (i = 0; i < nch; ++i)
+                    cmapP->mp_init[i].reg = MP_REG_IGNORE;
+
+                cmapP->mp_init[nch].reg = MP_REG_END;
+            }
         }
 
-        if( PCHG.Flags & PCHGF_12BIT ) {
+        if (PCHG.Flags & PCHGF_12BIT) {
 #ifdef DEBUG
             pm_message("SmallLineChanges");
 #endif
-            PCHG_ConvertSmall(&PCHG, cmap, data, datasize);
+            PCHG_ConvertSmall(&PCHG, cmapP, data, datasize);
         }
         else {
-            if( PCHG.Flags & PCHGF_32BIT ) {
+            if (PCHG.Flags & PCHGF_32BIT) {
 #ifdef DEBUG
                 pm_message("BigLineChanges");
 #endif
-                PCHG_ConvertBig(&PCHG, cmap, data, datasize);
-            }
-            else
+                PCHG_ConvertBig(&PCHG, cmapP, data, datasize);
+            } else
                 pm_error("unknown palette changes structure "
                          "format in %s chunk",
                          ID2string(iffid));
@@ -2143,7 +2203,7 @@ process_body( FILE *          const ifP,
     if (typeid == ID_ILBM) {
         int isdeep;
 
-        MALLOCARRAY_NOFAIL(ilbmrow, RowBytes(bmhdP->w));
+        MALLOCARRAY_NOFAIL(ilbmrow, ilbm_rowByteCt(bmhdP->w));
         *viewportmodesP |= fakeviewport;      /* -isham/-isehb */
 
         if( isdeepopt > 0 && (bmhdP->nPlanes % 3 != 0) ) {
diff --git a/converter/ppm/imgtoppm.c b/converter/ppm/imgtoppm.c
index 7078b882..60280383 100644
--- a/converter/ppm/imgtoppm.c
+++ b/converter/ppm/imgtoppm.c
@@ -12,131 +12,133 @@
 ** implied warranty.
 */
 
+#include <stdbool.h>
+#include <limits.h>
 #include <string.h>
+
+#include "nstring.h"
 #include "ppm.h"
 
 
 
 int
-main(int argc, char ** argv) {
+main(int argc, const char ** argv) {
 
-    FILE* ifp;
-    pixel* pixelrow;
+    FILE * ifP;
+    pixel * pixelrow;
     pixel colormap[256];
-    register pixel* pP;
     unsigned int cols;
     unsigned int rows;
-    int argn, row, i;
-    int col;
     pixval maxval;
     unsigned int cmaplen;
-    int len, gotAT, gotCM, gotPD;
+    bool gotAt, gotCm, gotPd;
     unsigned char buf[4096];
-    unsigned char* bP;
-
 
-    ppm_init( &argc, argv );
+    pm_proginit(&argc, argv);
 
-    argn = 1;
-
-    if ( argn < argc )
-    {
-        ifp = pm_openr( argv[argn] );
-        argn++;
-    }
+    if (argc-1 >= 1)
+        ifP = pm_openr(argv[1]);
     else
-        ifp = stdin;
+        ifP = stdin;
 
-    if ( argn != argc )
-        pm_usage( "[imgfile]" );
+    if (argc-1 > 1)
+        pm_error("Too many arguments (%u).  "
+                 "The only possible argument is the input file name", argc-1);
 
     /* Get signature. */
-    fread( buf, 8, 1, ifp );
+    fread(buf, 8, 1, ifP);
     buf[8] = '\0';
 
     /* Get entries. */
-    gotAT = 0;
-    gotCM = 0;
-    gotPD = 0;
-    while ( fread( buf, 2, 1, ifp ) == 1 )
-    {
-        if ( strncmp( (char*) buf, "AT", 2 ) == 0 )
-        {
-            if ( fread( buf, 8, 1, ifp ) != 1 )
-                pm_error( "bad attributes header" );
+    gotAt = false; /* initial value */
+    gotCm = false; /* initial value */
+    gotPd = false; /* initial value */
+    while (fread( buf, 2, 1, ifP) == 1) {
+        if (strneq((char*) buf, "AT", 2)) {
+            unsigned int len;
+
+            if (fread(buf, 8, 1, ifP) != 1)
+                pm_error("bad attributes header");
             buf[8] = '\0';
-            len = atoi( (char*) buf );
-            if ( fread( buf, len, 1, ifp ) != 1 )
-                pm_error( "bad attributes buf" );
+            len = atoi((char*) buf);
+            if (fread(buf, len, 1, ifP) != 1)
+                pm_error("bad attributes buf");
             buf[len] = '\0';
-            sscanf( (char*) buf, "%4u%4u%4u", &cols, &rows, &cmaplen );
+            sscanf((char*) buf, "%4u%4u%4u", &cols, &rows, &cmaplen);
+            if (cols > UINT_MAX/rows)
+                pm_message("height (%u) and width (%u) in header are "
+                           "uncomputably large", rows, cols);
+            if (cmaplen > UINT_MAX/3)
+                pm_message("colormap length (%u) in header is "
+                           "uncomputably large", cmaplen);
             maxval = 255;
-            gotAT = 1;
-        }
-
-        else if ( strncmp( (char*) buf, "CM", 2 ) == 0 )
-        {
-            if ( ! gotAT )
-                pm_error( "missing attributes header" );
-            if ( fread( buf, 8, 1, ifp ) != 1 )
-                pm_error( "bad colormap header" );
+            gotAt = true;
+        } else if (strneq((char*) buf, "CM", 2)) {
+            unsigned int i;
+            unsigned int len;
+
+            if (!gotAt)
+                pm_error("missing attributes header");
+            if (fread(buf, 8, 1, ifP) != 1)
+                pm_error("bad colormap header");
             buf[8] = '\0';
-            len = atoi((char*) buf );
-            if ( fread( buf, len, 1, ifp ) != 1 )
-                pm_error( "bad colormap buf" );
-            if ( cmaplen * 3 != len )
-            {
+            len = atoi((char*) buf);
+            if (fread(buf, len, 1, ifP) != 1)
+                pm_error("bad colormap buf");
+            if (len != cmaplen * 3) {
                 pm_message(
-                    "cmaplen (%d) and colormap buf length (%d) do not match",
-                    cmaplen, len );
-                if ( cmaplen * 3 < len )
+                    "cmaplen (%u) and colormap buf length (%u) do not match",
+                    cmaplen, len);
+                if (len > cmaplen * 3)
                     len = cmaplen * 3;
-                else if ( cmaplen * 3 > len )
+                else
                     cmaplen = len / 3;
             }
-            for ( i = 0; i < len; i += 3 )
-                PPM_ASSIGN( colormap[i / 3], buf[i], buf[i + 1], buf[i + 2] );
-            gotCM = 1;
-        }
-
-        else if ( strncmp( (char*) buf, "PD", 2 ) == 0 )
-        {
-            if ( fread( buf, 8, 1, ifp ) != 1 )
-                pm_error( "bad pixel data header" );
+            for (i = 0; i < len; i += 3)
+                PPM_ASSIGN(colormap[i / 3], buf[i], buf[i + 1], buf[i + 2]);
+            gotCm = true;
+        } else if (strneq((char*) buf, "PD", 2)) {
+            unsigned int len;
+            unsigned int row;
+
+            if (fread(buf, 8, 1, ifP) != 1)
+                pm_error("bad pixel data header");
             buf[8] = '\0';
-            len = atoi((char*) buf );
-            if ( len != cols * rows )
+            len = atoi((char*) buf);
+            if (len != cols * rows)
                 pm_message(
-                    "pixel data length (%d) does not match image size (%d)",
-                    len, cols * rows );
-
-            ppm_writeppminit( stdout, cols, rows, maxval, 0 );
-            pixelrow = ppm_allocrow( cols );
-
-            for ( row = 0; row < rows; row++ )
-            {
-                if ( fread( buf, 1, cols, ifp ) != cols )
-                    pm_error( "EOF / read error" );
-                for ( col = 0, pP = pixelrow, bP = buf;
-                      col < cols; col++, pP++, bP++ )
-                {
-                    if ( gotCM )
-                        *pP = colormap[*bP];
+                    "pixel data length (%u) does not match image size (%u)",
+                    len, cols * rows);
+
+            ppm_writeppminit(stdout, cols, rows, maxval, 0);
+            pixelrow = ppm_allocrow(cols);
+
+            for (row = 0; row < rows; ++row) {
+                unsigned int col;
+
+                if (fread(buf, 1, cols, ifP) != cols)
+                    pm_error("EOF / read error");
+                for (col = 0; col < cols; ++col) {
+                    if (gotCm)
+                        pixelrow[col] = colormap[buf[col]];
                     else
-                        PPM_ASSIGN( *pP, *bP, *bP, *bP );
+                        PPM_ASSIGN(pixelrow[col],
+                                   buf[col], buf[col], buf[col]);
                 }
-                ppm_writeppmrow( stdout, pixelrow, cols, maxval, 0 );
+                ppm_writeppmrow(stdout, pixelrow, cols, maxval, 0);
             }
-            gotPD = 1;
-
+            gotPd = true;
         }
     }
-    if ( ! gotPD )
-        pm_error( "missing pixel data header" );
+    if (!gotPd)
+        pm_error("missing pixel data header");
 
-    pm_close( ifp );
+    pm_close(ifP);
     /* If the program failed, it previously aborted with nonzero completion
        code, via various function calls.
     */
     return 0;
 }
+
+
+
diff --git a/converter/ppm/leaftoppm.c b/converter/ppm/leaftoppm.c
index 61c19c1e..0dcc1255 100644
--- a/converter/ppm/leaftoppm.c
+++ b/converter/ppm/leaftoppm.c
@@ -10,7 +10,7 @@
  * implied warranty.
  *
  * known problems: doesn't do compressed ileaf images.
- * 
+ *
  */
 
 #include <stdio.h>
@@ -20,11 +20,11 @@
 #define LEAF_MAXVAL 255
 
 static void
-leaf_init(FILE *  const fp, 
+leaf_init(FILE *  const fp,
           int *   const colsP,
-          int *   const rowsP, 
-          int *   const depthP, 
-          int *   const ncolorsP, 
+          int *   const rowsP,
+          int *   const depthP,
+          int *   const ncolorsP,
           pixel * const colors) {
 
     unsigned char buf[256];
@@ -34,41 +34,41 @@ leaf_init(FILE *  const fp,
     short rows;
     short depth;
     long magic;
-    
+
     pm_readbiglong(fp, &magic);
     if ((uint32_t)magic != 0x894f5053)
         pm_error("Bad magic number.  First 4 bytes should be "
                  "0x894f5053 but are instead 0x%08x", (unsigned)magic);
-    
+
     /* version =   2 bytes
-       hres =      2 
+       hres =      2
        vres =      2
        unique id = 4
        offset x =  2
        offset y =  2
-       TOTAL    =  14 bytes 
+       TOTAL    =  14 bytes
     */
-    
+
     pm_readbigshort(fp, &version);
 
     if (fread(buf, 1, 12, fp) != 12)
         pm_error("bad header, short file?");
-    
+
     pm_readbigshort(fp, &cols);
     *colsP = cols;
     pm_readbigshort(fp, &rows);
     *rowsP = rows;
     pm_readbigshort(fp, &depth);
     *depthP = depth;
-    
+
     if ((compressed = fgetc(fp)) != 0)
         pm_error("Can't do compressed images.");
 
     if ((*depthP == 1) && (version < 4)) {
-        fgetc(fp); 
+        fgetc(fp);
         *ncolorsP = 0;
     } else if ((*depthP == 8) && (version < 4)) {
-        fgetc(fp); 
+        fgetc(fp);
         *ncolorsP = 0;
     } else {
         long format;
@@ -121,19 +121,19 @@ main(int argc, char * argv[]) {
     pixel colormap[MAXCOLORS];
     int rows, cols, row, col, depth, ncolors;
 
-    
+
     ppm_init(&argc, argv);
-    
+
     if (argc-1 > 1)
         pm_error("Too many arguments.  Only argument is ileaf file name");
-    
+
     if (argc-1 == 1)
         ifd = pm_openr(argv[1]);
     else
         ifd = stdin;
-    
+
     leaf_init(ifd, &cols, &rows, &depth, &ncolors, colormap);
-    
+
     if ((depth == 8) && (ncolors == 0)) {
         /* gray image */
         gray * grayrow;
@@ -177,7 +177,7 @@ main(int argc, char * argv[]) {
 
         ppm_writeppminit(stdout, cols, rows, (pixval) maxval, 0);
         pixrow = ppm_allocrow( cols );
-    
+
         for (row = 0; row < rows; ++row) {
             for (col = 0; col < cols; ++col)
                 pixrow[col] = colormap[fgetc(ifd)];
@@ -190,18 +190,18 @@ main(int argc, char * argv[]) {
         /* mono image */
         bit *bitrow;
         unsigned int row;
-        
+
         pbm_writepbminit(stdout, cols, rows, 0);
         bitrow = pbm_allocrow(cols);
-    
+
         for (row = 0; row < rows; ++row) {
             unsigned char bits;
             bits = 0x00;  /* initial value */
             for (col = 0; col < cols; ++col) {
                 int const shift = col % 8;
-                if (shift == 0) 
+                if (shift == 0)
                     bits = (unsigned char) fgetc(ifd);
-                bitrow[col] = (bits & (unsigned char)(0x01 << (7 - shift))) ? 
+                bitrow[col] = (bits & (unsigned char)(0x01 << (7 - shift))) ?
                     PBM_WHITE : PBM_BLACK;
             }
             if ((cols % 16) && (cols % 16) <= 8)
@@ -211,6 +211,9 @@ main(int argc, char * argv[]) {
         pbm_freerow(bitrow);
     }
     pm_close(ifd);
-    
+
     return 0;
 }
+
+
+
diff --git a/converter/ppm/mitsu.h b/converter/ppm/mitsu.h
index bca4fbdf..b0ae9aa5 100644
--- a/converter/ppm/mitsu.h
+++ b/converter/ppm/mitsu.h
@@ -10,19 +10,30 @@
 #define A_MAXROWS   1350
 #define AS_MAXROWS  1650
 
+/* To use the macros in this file that generate Mitsu output, define a
+   function named 'cmd' that outputs a character.  Like this:
+
+    static void
+    cmd(char const arg) {
+
+        fputc(arg, stdout);
+    }
+*/
+
 #define ONLINE         cmd('\021')
 #define CLRMEM         cmd('\033'), cmd('Z')
 
-struct mediasize {
-        char size;
-        int  maxcols, maxrows;
+struct Mediasize {
+    char         size;
+    unsigned int maxcols;
+    unsigned int maxrows;
 };
 
-const struct mediasize MSize_User={' ',1184,1350};
-const struct mediasize MSize_A4  ={'0',1184,1452};
-const struct mediasize MSize_A   ={'1',1216,1350};
-const struct mediasize MSize_A4S ={'2',1184,1754};
-const struct mediasize MSize_AS  ={'3',1216,1650};
+static struct Mediasize const MSize_User={' ',1184,1350};
+static struct Mediasize const MSize_A4  ={'0',1184,1452};
+static struct Mediasize const MSize_A   ={'1',1216,1350};
+static struct Mediasize const MSize_A4S ={'2',1184,1754};
+static struct Mediasize const MSize_AS  ={'3',1216,1650};
 #define MEDIASIZE(chr) cmd('\033'), cmd('#'), cmd('P'), cmd((chr).size)
 
 #define HENLARGE(enl)  cmd('\033'), cmd('&'), cmd('P'), cmd(enl), cmd('\001')
diff --git a/converter/ppm/mtvtoppm.c b/converter/ppm/mtvtoppm.c
index e8558632..42f99428 100644
--- a/converter/ppm/mtvtoppm.c
+++ b/converter/ppm/mtvtoppm.c
@@ -30,39 +30,42 @@ main( argc, argv )
     ppm_init( &argc, argv );
 
     if ( argc > 2 )
-	pm_usage( "[mtvfile]" );
+        pm_usage( "[mtvfile]" );
 
     if ( argc == 2 )
-	ifp = pm_openr( argv[1] );
+        ifp = pm_openr( argv[1] );
     else
-	ifp = stdin;
+        ifp = stdin;
 
     /* Read in the MTV file.  First the header. */
     if ( fgets( line, MAXLINE, ifp ) == NULL )
-	pm_error( "unable to read MTV file header" );
+        pm_error( "unable to read MTV file header" );
     if ( sscanf( line, "%d%d", &cols, &rows ) != 2 )
-	pm_error( "unable to parse MTV file header" );
+        pm_error( "unable to parse MTV file header" );
 
     if ( cols <= 0 || rows <= 0 )
-	pm_error( "invalid size: %d %d", cols, rows );
+        pm_error( "invalid size: %d %d", cols, rows );
     maxval = 255;
 
     ppm_writeppminit( stdout, cols, rows, maxval, 0 );
     pixelrow = ppm_allocrow( cols );
 
     for ( row = 0; row < rows; row++ )
-	{
-	for ( col = 0, pP = pixelrow; col < cols; col++, pP++ )
-	    {
-	    if ( fread( buf, sizeof(buf), 1, ifp ) != 1 )
-		pm_error( "EOF / read error" );
-	    PPM_ASSIGN( *pP, buf[0], buf[1], buf[2] );
-	    }
-	ppm_writeppmrow( stdout, pixelrow, cols, maxval, 0 );
-	}
+        {
+        for ( col = 0, pP = pixelrow; col < cols; col++, pP++ )
+            {
+            if ( fread( buf, sizeof(buf), 1, ifp ) != 1 )
+                pm_error( "EOF / read error" );
+            PPM_ASSIGN( *pP, buf[0], buf[1], buf[2] );
+            }
+        ppm_writeppmrow( stdout, pixelrow, cols, maxval, 0 );
+        }
 
     pm_close( ifp );
     pm_close( stdout );
 
     exit( 0 );
     }
+
+
+
diff --git a/converter/ppm/neotoppm.c b/converter/ppm/neotoppm.c
index d8cf2918..6ce5ef43 100644
--- a/converter/ppm/neotoppm.c
+++ b/converter/ppm/neotoppm.c
@@ -57,7 +57,7 @@ main( int argc, char * argv[] ) {
         /* Read the palette. */
         for ( i = 0; i < 16; ++i ) {
             short j;
-            
+
             pm_readbigshort (ifp, &j);
             PPM_ASSIGN( pal[i],
                         ( j & 0x700 ) >> 8,
@@ -102,3 +102,6 @@ main( int argc, char * argv[] ) {
 
     exit( 0 );
 }
+
+
+
diff --git a/converter/ppm/pc1toppm.c b/converter/ppm/pc1toppm.c
index ec6678a4..45d09faa 100644
--- a/converter/ppm/pc1toppm.c
+++ b/converter/ppm/pc1toppm.c
@@ -13,7 +13,7 @@
  documentation.  This software is provided "as is" without express or
  implied warranty.
 
- Algorithm for PC1 compression from "gimp-degas" GIMP plugin 
+ Algorithm for PC1 compression from "gimp-degas" GIMP plugin
  by Markus F.X.J. Oberhumer
 
 */
@@ -39,7 +39,7 @@ unsigned int const colsPerBlock = 16;
 
 
 static void
-readPalette(FILE *   const ifP, 
+readPalette(FILE *   const ifP,
             pixel (* const palP)[]) {
 
     /* Read the palette. */
@@ -78,7 +78,7 @@ processStretch(unsigned int     const countbyte,
         }
     } else {
         /* next byte repeated 257-countbyte times */
-                
+
         unsigned char const duplicated_color = getc(ifP);
         unsigned int  const count = 257 - countbyte;
         unsigned int i;
@@ -121,8 +121,8 @@ readPc1(FILE * const ifP,
             unsigned int const countbyte = getc(ifP);
 
             processStretch(countbyte, ifP, &col, &bufferCursor);
-	    }
-	}
+            }
+        }
 }
 
 
@@ -130,7 +130,7 @@ readPc1(FILE * const ifP,
 static void
 reInterleave(unsigned char     const buffer[],
              unsigned short (* const screenP)[]) {
-    
+
     /* The buffer is in one plane for each line, to optimize packing */
     /* Re-interleave to match the Atari screen layout                */
 
@@ -142,10 +142,10 @@ reInterleave(unsigned char     const buffer[],
         for (block = 0; block < BLOCKS; ++block) {
             unsigned int plane;
             for (plane = 0; plane < planes; ++plane) {
-                unsigned int const blockIndex = 
+                unsigned int const blockIndex =
                     row*ROWBYTES + plane*PLANEBYTES + block*BLOCKBYTES;
 
-                screen[row*ROWSHORTS + block*BLOCKSHORTS + plane] = 
+                screen[row*ROWSHORTS + block*BLOCKSHORTS + plane] =
                     (buffer[blockIndex+0] << 8) + (buffer[blockIndex+1]);
             }
         }
@@ -202,9 +202,9 @@ main(int argc, char ** argv) {
     const char * inputFilename;
     FILE* ifP;
     pixel palette[16];  /* Degas palette */
-    static unsigned short screen[32000/2];   
+    static unsigned short screen[32000/2];
         /* simulates the Atari's video RAM */
-    static unsigned char buffer[32000];   
+    static unsigned char buffer[32000];
         /* simulates the Atari's video RAM */
 
     ppm_init(&argc, argv);
@@ -231,3 +231,6 @@ main(int argc, char ** argv) {
 
     return 0;
 }
+
+
+
diff --git a/converter/ppm/pcxtoppm.c b/converter/ppm/pcxtoppm.c
index e252ba22..f06dd4e8 100644
--- a/converter/ppm/pcxtoppm.c
+++ b/converter/ppm/pcxtoppm.c
@@ -31,6 +31,9 @@
  *  - moved check of 16-color-palette into pcx_16col_to_ppm(),
  *    now checks if it contains only a single color
  */
+#include <stdbool.h>
+#include <limits.h>
+
 #include "pm_c_util.h"
 #include "mallocvar.h"
 #include "shhopt.h"
@@ -52,30 +55,31 @@ static pixel stdPalette[16];
 static void
 generateStdPalette(void) {
 
-    int i;
-    for (i = 0; i < 16; i++)
+    unsigned int i;
+
+    for (i = 0; i < 16; ++i)
         PPM_ASSIGN(stdPalette[i], StdRed[i], StdGreen[i], StdBlue[i]);
 }
 
 
 
-struct cmdlineInfo {
+struct CmdlineInfo {
     /* All the information the user supplied in the command line,
        in a form easy for the program to use.
     */
-    const char *inputFilespec;  /* '-' if stdin */
-    unsigned int verbose;  
+    const char * inputFileNm;  /* '-' if stdin */
+    unsigned int verbose;
     unsigned int stdpalette;
 };
 
 
 
 static void
-parseCommandLine ( int argc, char ** argv,
-                   struct cmdlineInfo *cmdlineP ) {
+parseCommandLine(int argc, const char ** argv,
+                 struct CmdlineInfo * const cmdlineP) {
 /*----------------------------------------------------------------------------
-   parse program command line described in Unix standard form by argc
-   and argv.  Return the information in the options as *cmdlineP.  
+   Parse program command line described in Unix standard form by argc
+   and argv.  Return the information in the options as *cmdlineP.
 
    If command line is internally inconsistent (invalid options, etc.),
    issue error message to stderr and abort program.
@@ -83,30 +87,30 @@ parseCommandLine ( int argc, char ** argv,
    Note that the strings we return are stored in the storage that
    was passed to us as the argv array.  We also trash *argv.
 -----------------------------------------------------------------------------*/
-    optEntry *option_def = malloc( 100*sizeof( optEntry ) );
-        /* Instructions to pm_optParseOptions3 on how to parse our options.
-         */
+    optEntry * option_def;
     optStruct3 opt;
 
     unsigned int option_def_index;
 
+    MALLOCARRAY_NOFAIL(option_def, 100);
+
     option_def_index = 0;   /* incremented by OPTENT3 */
-    OPTENT3(0, "stdpalette",     OPT_FLAG,   NULL,                  
+    OPTENT3(0, "stdpalette",     OPT_FLAG,   NULL,
             &cmdlineP->stdpalette,    0 );
-    OPTENT3(0, "verbose",        OPT_FLAG,   NULL,                  
+    OPTENT3(0, "verbose",        OPT_FLAG,   NULL,
             &cmdlineP->verbose,       0 );
 
     opt.opt_table = option_def;
-    opt.short_allowed = FALSE;  /* We have no short (old-fashioned) options */
-    opt.allowNegNum = FALSE;  /* We have no parms that are negative numbers */
+    opt.short_allowed = false;  /* We have no short (old-fashioned) options */
+    opt.allowNegNum = false;  /* We have no parms that are negative numbers */
 
-    pm_optParseOptions3( &argc, argv, opt, sizeof(opt), 0 );
+    pm_optParseOptions4(&argc, argv, opt, sizeof(opt), 0);
         /* Uses and sets argc, argv, and some of *cmdline_p and others. */
 
     if (argc-1 < 1)
-        cmdlineP->inputFilespec = "-";
+        cmdlineP->inputFileNm = "-";
     else if (argc-1 == 1)
-        cmdlineP->inputFilespec = argv[1];
+        cmdlineP->inputFileNm = argv[1];
     else
         pm_error("Program takes at most one argument "
                  "(input file specification).  You specified %d",
@@ -115,13 +119,13 @@ parseCommandLine ( int argc, char ** argv,
 
 
 
-struct pcxHeader {
+struct PcxHeader {
     int Version;
     /* Xmin, Ymin, Xmax, and Ymax are positions in some field (in units of
        pixels) of the edges of the image.  They may be negative.  You can
        derive the image width and height from these.
     */
-    short Xmin;            
+    short Xmin;
     short Ymin;
     short Xmax;
     short Ymax;
@@ -141,23 +145,8 @@ struct pcxHeader {
 
 
 
-static void
-readInt(FILE * const ifP, short * const retvalP) {
-/*----------------------------------------------------------------------------
-   Read a 2-byte little-endian word from the file.
------------------------------------------------------------------------------*/
-    int rc;
-
-    rc = pm_readlittleshort(ifP, retvalP);
-
-    if (rc != 0)
-        pm_error("EOF/error reading integer from input file.");
-}
-
-
-
 static int
-GetByte(FILE * const fp) {
+getByte(FILE * const fp) {
 
     int    c;
 
@@ -170,55 +159,55 @@ GetByte(FILE * const fp) {
 
 
 static void
-readPcxHeader(FILE *             const ifP, 
-              struct pcxHeader * const pcxHeaderP) {
+readPcxHeader(FILE *             const ifP,
+              struct PcxHeader * const pcxHeaderP) {
 /*----------------------------------------------------------------------------
    Read the PCX header
 -----------------------------------------------------------------------------*/
-    if (GetByte(ifP) != PCX_MAGIC)
+    if (getByte(ifP) != PCX_MAGIC)
         pm_error("bad magic number - not a PCX file");
 
-    pcxHeaderP->Version = GetByte(ifP);  /* get version # */
+    pcxHeaderP->Version = getByte(ifP);  /* get version # */
 
-    pcxHeaderP->Encoding = GetByte(ifP);
+    pcxHeaderP->Encoding = getByte(ifP);
     if (pcxHeaderP->Encoding != 1)    /* check for PCX run length encoding   */
         pm_error("unknown encoding scheme: %d", pcxHeaderP->Encoding);
 
-    pcxHeaderP->BitsPerPixel= GetByte(ifP);
-    readInt(ifP, &pcxHeaderP->Xmin);
-    readInt(ifP, &pcxHeaderP->Ymin);
-    readInt(ifP, &pcxHeaderP->Xmax);
-    readInt(ifP, &pcxHeaderP->Ymax);
+    pcxHeaderP->BitsPerPixel= getByte(ifP);
+    pm_readlittleshort(ifP, &pcxHeaderP->Xmin);
+    pm_readlittleshort(ifP, &pcxHeaderP->Ymin);
+    pm_readlittleshort(ifP, &pcxHeaderP->Xmax);
+    pm_readlittleshort(ifP, &pcxHeaderP->Ymax);
 
     if (pcxHeaderP->Xmax < pcxHeaderP->Xmin)
         pm_error("Invalid PCX input:  minimum X value (%d) is greater than "
-                 "maximum X value (%d).", 
+                 "maximum X value (%d).",
                  pcxHeaderP->Xmin, pcxHeaderP->Xmax);
     if (pcxHeaderP->Ymax < pcxHeaderP->Ymin)
         pm_error("Invalid PCX input:  minimum Y value (%d) is greater than "
-                 "maximum Y value (%d).", 
+                 "maximum Y value (%d).",
                  pcxHeaderP->Ymin, pcxHeaderP->Ymax);
 
-    readInt(ifP, &pcxHeaderP->HorizontalResolution);  
-    readInt(ifP, &pcxHeaderP->VerticalResolution);  
+    pm_readlittleshort(ifP, &pcxHeaderP->HorizontalResolution);
+    pm_readlittleshort(ifP, &pcxHeaderP->VerticalResolution);
 
     {
-        int i;
+        unsigned int i;
         /*
          * get the 16-color color map
          */
-        for (i = 0; i < 16; i++) {
-            unsigned int const r = GetByte(ifP);
-            unsigned int const g = GetByte(ifP);
-            unsigned int const b = GetByte(ifP);
+        for (i = 0; i < 16; ++i) {
+            unsigned int const r = getByte(ifP);
+            unsigned int const g = getByte(ifP);
+            unsigned int const b = getByte(ifP);
             PPM_ASSIGN(pcxHeaderP->cmap16[i], r, g, b);
         }
     }
 
-    GetByte(ifP);                /* skip reserved byte       */
-    pcxHeaderP->Planes      = GetByte(ifP);     /* # of color planes        */
-    readInt(ifP, &pcxHeaderP->BytesPerLine);
-    readInt(ifP, &pcxHeaderP->PaletteInfo);
+    getByte(ifP);                /* skip reserved byte       */
+    pcxHeaderP->Planes = getByte(ifP);     /* # of color planes        */
+    pm_readlittleshort(ifP, &pcxHeaderP->BytesPerLine);
+    pm_readlittleshort(ifP, &pcxHeaderP->PaletteInfo);
 
     /* Read past a bunch of reserved space in the header.  We have read
        70 bytes of the header so far.  We would just seek here, except that
@@ -228,28 +217,29 @@ readPcxHeader(FILE *             const ifP,
         unsigned int pos;
 
         for (pos = 70; pos < PCX_HDR_SIZE; ++pos)
-            GetByte(ifP);
+            getByte(ifP);
     }
 }
 
 
 
-static void 
-reportPcxHeader(struct pcxHeader const pcxHeader) {
+static void
+reportPcxHeader(struct PcxHeader const pcxHeader) {
 
     pm_message("Version: %d", pcxHeader.Version);
     pm_message("BitsPerPixel: %d", pcxHeader.BitsPerPixel);
-    pm_message("Xmin: %d   Ymin: %d   Xmax: %d   Ymax: %d", 
+    pm_message("Xmin: %d   Ymin: %d   Xmax: %d   Ymax: %d",
                pcxHeader.Xmin, pcxHeader.Ymin, pcxHeader.Xmax, pcxHeader.Ymax);
-    pm_message("Planes: %d    BytesPerLine: %d    PaletteInfo: %d", 
-               pcxHeader.Planes, pcxHeader.BytesPerLine, 
+    pm_message("Planes: %d    BytesPerLine: %d    PaletteInfo: %d",
+               pcxHeader.Planes, pcxHeader.BytesPerLine,
                pcxHeader.PaletteInfo);
     pm_message("Color map in image:  (index: r/g/b)");
+
     if (pcxHeader.BitsPerPixel < 8) {
         unsigned int colorIndex;
         for (colorIndex = 0; colorIndex < 16; ++colorIndex) {
             pixel const p = pcxHeader.cmap16[colorIndex];
-            pm_message("  %u: %u/%u/%u", colorIndex, 
+            pm_message("  %u: %u/%u/%u", colorIndex,
                        PPM_GETR(p), PPM_GETG(p), PPM_GETB(p));
         }
     }
@@ -278,42 +268,39 @@ allBlackPalette(pixel cmap16[]) {
 
 
 
-/*
- *  read a single row encoded row, handles encoding across rows
- */
 static void
-GetPCXRow(FILE * const ifP, unsigned char * const pcxrow, 
-          int const bytesperline) {
+getPCXRow(FILE *          const ifP,
+          unsigned char * const pcxrow,
+          unsigned int    const bytesperline) {
 /*----------------------------------------------------------------------------
    Read one row from the PCX raster.
-   
-   The PCX raster is run length encoded as follows:  If the upper two
-   bits of a byte are 11, the lower 6 bits are a repetition count for the
-   raster byte that follows.  If the upper two bits are not 11, the byte 
-   _is_ a raster byte, with repetition count 1.
-
-   A run can't span rows, but it can span planes within a row.  That's
-   why 'repetitionsLeft' and 'c' are static variables in this
-   subroutine.
+
+   The PCX raster is run length encoded as follows: If the upper two bits of a
+   byte are 11, the lower 6 bits are a repetition count for the raster byte
+   that follows.  If the upper two bits are not 11, the byte _is_ a raster
+   byte, with repetition count 1.
+
+   A run can't span rows, but it can span planes within a row.  That's why
+   'repetitionsLeft' and 'c' are static variables in this subroutine.
 -----------------------------------------------------------------------------*/
     static int repetitionsLeft = 0;
     static int c;
-    int bytesGenerated;
+    unsigned int bytesGenerated;
 
     bytesGenerated = 0;
-    while( bytesGenerated < bytesperline ) {
-        if(repetitionsLeft > 0) {
+    while(bytesGenerated < bytesperline) {
+        if (repetitionsLeft > 0) {
             pcxrow[bytesGenerated++] = c;
             --repetitionsLeft;
         } else {
-            c = GetByte(ifP);
+            c = getByte(ifP);
             if ((c & 0xc0) != 0xc0)
                 /* This is a 1-shot byte, not a repetition count */
                 pcxrow[bytesGenerated++] = c;
             else {
                 /* This is a repetition count for the following byte */
                 repetitionsLeft = c & 0x3f;
-                c = GetByte(ifP);
+                c = getByte(ifP);
             }
         }
     }
@@ -321,187 +308,185 @@ GetPCXRow(FILE * const ifP, unsigned char * const pcxrow,
 
 
 
-/*
- * convert packed pixel format into 1 pixel per byte
- */
 static void
-pcx_unpack_pixels(pixels, bitplanes, bytesperline, planes, bitsperpixel)
-    unsigned char   *pixels;
-    unsigned char   *bitplanes;
-    int             bytesperline;
-    int             planes;
-    int             bitsperpixel;
-{
-    register int        bits;
+pcxUnpackPixels(unsigned char * const pixels,
+                unsigned char * const bitplanes,
+                unsigned int    const bytesperline,
+                unsigned int    const planes,
+                unsigned int    const bitsperpixel) {
+/*----------------------------------------------------------------------------
+   Convert packed pixel format in bitplanes[] into 1 pixel per byte
+   in pixels[].
+-----------------------------------------------------------------------------*/
+    unsigned int i;
 
     if (planes != 1)
         pm_error("can't handle packed pixels with more than 1 plane" );
-#if 0
-    if (bitsperpixel == 8)
-    {
-        while (--bytesperline >= 0)
-            *pixels++ = *bitplanes++;
-    }
-    else
-#endif
-        if (bitsperpixel == 4)
-        {
-            while (--bytesperline >= 0)
-            {
-                bits        = *bitplanes++;
-                *pixels++   = (bits >> 4) & 0x0f;
-                *pixels++   = (bits     ) & 0x0f;
-            }
-        }
-        else if (bitsperpixel == 2)
-        {
-            while (--bytesperline >= 0)
-            {
-                bits        = *bitplanes++;
-                *pixels++   = (bits >> 6) & 0x03;
-                *pixels++   = (bits >> 4) & 0x03;
-                *pixels++   = (bits >> 2) & 0x03;
-                *pixels++   = (bits     ) & 0x03;
-            }
-        }
-        else if (bitsperpixel == 1)
-        {
-            while (--bytesperline >= 0)
-            {
-                bits        = *bitplanes++;
-                *pixels++   = ((bits & 0x80) != 0);
-                *pixels++   = ((bits & 0x40) != 0);
-                *pixels++   = ((bits & 0x20) != 0);
-                *pixels++   = ((bits & 0x10) != 0);
-                *pixels++   = ((bits & 0x08) != 0);
-                *pixels++   = ((bits & 0x04) != 0);
-                *pixels++   = ((bits & 0x02) != 0);
-                *pixels++   = ((bits & 0x01) != 0);
-            }
+
+    for (i = 0; i < bytesperline; ++i) {
+        unsigned int const bits = bitplanes[i];
+
+        switch (bitsperpixel) {
+        case 4:
+            pixels[2*i + 0] = (bits >> 4) & 0x0f;
+            pixels[2*i + 1] = (bits     ) & 0x0f;
+            break;
+        case 2:
+            pixels[i*4 + 0] = (bits >> 6) & 0x03;
+            pixels[i*4 + 1] = (bits >> 4) & 0x03;
+            pixels[i*4 + 2] = (bits >> 2) & 0x03;
+            pixels[i*4 + 3] = (bits     ) & 0x03;
+            break;
+        case 1:
+            pixels[i*8 + 0]  = ((bits & 0x80) != 0);
+            pixels[i*8 + 1]  = ((bits & 0x40) != 0);
+            pixels[i*8 + 2]  = ((bits & 0x20) != 0);
+            pixels[i*8 + 3]  = ((bits & 0x10) != 0);
+            pixels[i*8 + 4]  = ((bits & 0x08) != 0);
+            pixels[i*8 + 5]  = ((bits & 0x04) != 0);
+            pixels[i*8 + 6]  = ((bits & 0x02) != 0);
+            pixels[i*8 + 7]  = ((bits & 0x01) != 0);
+            break;
+        default:
+        pm_error("pcxUnpackPixels - can't handle %u bits per pixel",
+                 bitsperpixel);
         }
-        else
-            pm_error("pcx_unpack_pixels - can't handle %d bits per pixel", 
-                     bitsperpixel);
+    }
 }
 
 
 
-/*
- * convert multi-plane format into 1 pixel per byte
- */
 static void
-pcx_planes_to_pixels(pixels, bitplanes, bytesperline, planes, bitsperpixel)
-    unsigned char   *pixels;
-    unsigned char   *bitplanes;
-    int             bytesperline;
-    int             planes;
-    int             bitsperpixel;
-{
-    int  i, j;
-    int  npixels;
-    unsigned char    *p;
+pcxPlanesToPixels(unsigned char * const pixels,
+                  unsigned char * const bitPlanes,
+                  unsigned int    const bytesPerLine,
+                  unsigned int    const planes,
+                  unsigned int    const bitsPerPixel) {
+/*----------------------------------------------------------------------------
+   Convert multi-plane format into 1 pixel per byte.
+-----------------------------------------------------------------------------*/
+    unsigned int const npixels = (bytesPerLine * 8) / bitsPerPixel;
+
+    unsigned int  i;
 
     if (planes > 4)
-        pm_error("can't handle more than 4 planes" );
-    if (bitsperpixel != 1)
-        pm_error("can't handle more than 1 bit per pixel" );
+        pm_error("can't handle more than 4 planes");
+    if (bitsPerPixel != 1)
+        pm_error("can't handle more than 1 bit per pixel");
 
-    /*
-     * clear the pixel buffer
-     */
-    npixels = (bytesperline * 8) / bitsperpixel;
-    p    = pixels;
-    while (--npixels >= 0)
-        *p++ = 0;
+    /* Clear the pixel buffer - initial value */
+    for (i = 0; i < npixels; ++i)
+        pixels[i] = 0;
 
-    /*
-     * do the format conversion
-     */
-    for (i = 0; i < planes; i++)
-    {
-        int pixbit, bits, mask;
-
-        p    = pixels;
-        pixbit    = (1 << i);
-        for (j = 0; j < bytesperline; j++)
-        {
-            bits = *bitplanes++;
-            for (mask = 0x80; mask != 0; mask >>= 1, p++)
+    for (i = 0; i < planes; ++i) {
+        unsigned int const pixbit = (1 << i);
+
+        unsigned int j;
+
+        for (j = 0; j < bytesPerLine; ++j) {
+            unsigned int const bits = bitPlanes[j];
+
+            unsigned int mask;
+            unsigned int k;
+
+            for (mask = 0x80, k = 0; mask != 0; mask >>= 1, ++k)
                 if (bits & mask)
-                    *p |= pixbit;
+                    pixels[k] |= pixbit;
         }
     }
 }
 
 
 
-static void
-pcx_16col_to_ppm(FILE *       const ifP,
-                 unsigned int const headerCols,
-                 unsigned int const rows,
-                 unsigned int const BytesPerLine,
-                 unsigned int const BitsPerPixel,
-                 unsigned int const Planes,
-                 pixel *      const cmap) {
+static bool
+paletteIsOk(const pixel * const cmap,
+            unsigned int  const colorCt) {
 
-    unsigned int cols;
-    int row, col, rawcols, colors;
-    unsigned char * pcxrow;
-    unsigned char * rawrow;
-    pixel * ppmrow;
     bool paletteOk;
+    unsigned int col;
 
-    paletteOk = FALSE;
+    paletteOk = false;  /* initial assumption */
 
     /* check if palette is ok  */
-    colors = (1 << BitsPerPixel) * (1 << Planes);
-    for (col = 0; col < colors - 1; ++col) {
+    for (col = 0; col < colorCt - 1; ++col) {
         if (!PPM_EQUAL(cmap[col], cmap[col+1])) {
-            paletteOk = TRUE;
-            break;
+            paletteOk = true;
         }
     }
+    return paletteOk;
+}
+
+
+
+static void
+pcx16ColToPpm(FILE *       const ifP,
+              unsigned int const headerCols,
+              unsigned int const rows,
+              unsigned int const bytesPerLine,
+              unsigned int const bitsPerPixel,
+              unsigned int const planes,
+              pixel *      const cmap) {
+
+    unsigned int const colors = (1 << bitsPerPixel) * (1 << planes);
+    bool const paletteOk = paletteIsOk(cmap, colors);
+
+    unsigned int cols;
+    unsigned int row;
+    unsigned int rawcols;
+    unsigned char * pcxrow;
+    unsigned char * rawrow;
+    pixel * ppmrow;
+
     if (!paletteOk) {
         unsigned int col;
+
         pm_message("warning - useless header palette, "
                    "using builtin standard palette");
+
         for (col = 0; col < colors; ++col)
             PPM_ASSIGN(cmap[col], StdRed[col], StdGreen[col], StdBlue[col]);
     }
 
-    /*  BytesPerLine should be >= BitsPerPixel * cols / 8  */
-    rawcols = BytesPerLine * 8 / BitsPerPixel;
+    if (bytesPerLine > UINT_MAX/8)
+        pm_error("Image too wide to compute (%u bytes per line)",
+                 bytesPerLine);
+
+    /*  bytesPerLine should be >= bBitsPerPixel * cols / 8  */
+    rawcols = bytesPerLine * 8 / bitsPerPixel;
+
     if (headerCols > rawcols) {
-        pm_message("warning - BytesPerLine = %d, "
-                   "truncating image to %d pixels",
-                   BytesPerLine, rawcols);
+        pm_message("warning - BytesPerLine = %u, "
+                   "truncating image to %u pixels",
+                   bytesPerLine, rawcols);
         cols = rawcols;
     } else
         cols = headerCols;
 
-    MALLOCARRAY(pcxrow, Planes * BytesPerLine);
+    MALLOCARRAY(pcxrow, planes * bytesPerLine);
     if (pcxrow == NULL)
-        pm_error("Out of memory");
+        pm_error("Can't get memory for %u planes, %u bytes per line",
+                 planes, bytesPerLine);
     MALLOCARRAY(rawrow, rawcols);
     if (rawrow == NULL)
-        pm_error("Out of memory");
+        pm_error("Can't get memory for %u columns", rawcols);
 
     ppmrow = ppm_allocrow(cols);
 
     for (row = 0; row < rows; ++row) {
         unsigned int col;
 
-        GetPCXRow(ifP, pcxrow, Planes * BytesPerLine);
+        getPCXRow(ifP, pcxrow, planes * bytesPerLine);
 
-        if (Planes == 1)
-            pcx_unpack_pixels(rawrow, pcxrow, BytesPerLine, 
-                              Planes, BitsPerPixel);
+        if (planes == 1)
+            pcxUnpackPixels(rawrow, pcxrow, bytesPerLine,
+                            planes, bitsPerPixel);
         else
-            pcx_planes_to_pixels(rawrow, pcxrow, BytesPerLine, 
-                                 Planes, BitsPerPixel);
+            pcxPlanesToPixels(rawrow, pcxrow, bytesPerLine,
+                              planes, bitsPerPixel);
 
         for (col = 0; col < cols; ++col)
             ppmrow[col] = cmap[rawrow[col]];
+
         ppm_writeppmrow(stdout, ppmrow, cols, PCX_MAXVAL, 0);
     }
     ppm_freerow(ppmrow);
@@ -512,10 +497,10 @@ pcx_16col_to_ppm(FILE *       const ifP,
 
 
 static void
-pcx_256col_to_ppm(FILE *       const ifP,
-                  unsigned int const headerCols,
-                  unsigned int const rows,
-                  unsigned int const BytesPerLine) {
+pcx256ColToPpm(FILE *       const ifP,
+               unsigned int const headerCols,
+               unsigned int const rows,
+               unsigned int const bytesPerLine) {
 
     unsigned int cols;
     pixel colormap[256];
@@ -524,37 +509,37 @@ pcx_256col_to_ppm(FILE *       const ifP,
     unsigned char colormapSignature;
     unsigned int row;
 
-    if (headerCols > BytesPerLine) {
+    if (headerCols > bytesPerLine) {
         pm_message("warning - BytesPerLine = %u, "
                    "truncating image to %u pixels",
-                   BytesPerLine,  BytesPerLine);
-        cols = BytesPerLine;
+                   bytesPerLine,  bytesPerLine);
+        cols = bytesPerLine;
     } else
         cols = headerCols;
 
-    MALLOCARRAY2(image, rows, BytesPerLine);
+    MALLOCARRAY2(image, rows, bytesPerLine);
 
     for (row = 0; row < rows; ++row)
-        GetPCXRow(ifP, image[row], BytesPerLine);
+        getPCXRow(ifP, image[row], bytesPerLine);
 
     /*
      * 256 color images have their color map at the end of the file
      * preceded by a magic byte
      */
-    colormapSignature = GetByte(ifP);
+    colormapSignature = getByte(ifP);
     if (colormapSignature != PCX_256_COLORS)
         pm_error("bad color map signature.  In a 1-plane PCX image "
                  "such as this, we expect a magic number of %u in the byte "
                  "following the raster, to introduce the color map.  "
-                 "Instead, this image has %u.", 
+                 "Instead, this image has %u.",
                  PCX_256_COLORS, colormapSignature);
     else {
         unsigned int colorIndex;
-        
+
         for (colorIndex = 0; colorIndex < 256; ++colorIndex) {
-            pixval const r = GetByte(ifP);
-            pixval const g = GetByte(ifP);
-            pixval const b = GetByte(ifP);
+            pixval const r = getByte(ifP);
+            pixval const g = getByte(ifP);
+            pixval const b = getByte(ifP);
             PPM_ASSIGN(colormap[colorIndex], r, g, b);
         }
     }
@@ -574,51 +559,56 @@ pcx_256col_to_ppm(FILE *       const ifP,
 
 
 static void
-pcx_truecol_to_ppm(FILE *       const ifP,
-                   unsigned int const headerCols,
-                   unsigned int const rows,
-                   unsigned int const BytesPerLine,
-                   unsigned int const Planes) {
-
-    unsigned int cols;
-    unsigned char *redrow, *greenrow, *bluerow, *intensityrow;
-    pixel * ppmrow;
-    unsigned int row;
-    
-    if (headerCols > BytesPerLine) {
+pcxTruecolToPpm(FILE *       const ifP,
+                unsigned int const headerCols,
+                unsigned int const rows,
+                unsigned int const bytesPerLine,
+                unsigned int const planes) {
+
+    unsigned int    cols;
+    unsigned char * redrow;
+    unsigned char * grnrow;
+    unsigned char * blurow;
+    unsigned char * intensityrow;
+    pixel *         ppmrow;
+    unsigned int    row;
+
+    if (headerCols > bytesPerLine) {
         pm_message("warning - BytesPerLine = %u, "
                    "truncating image to %u pixels",
-                   BytesPerLine,  BytesPerLine);
-        cols = BytesPerLine;
+                   bytesPerLine, bytesPerLine);
+        cols = bytesPerLine;
     } else
         cols = headerCols;
 
-    MALLOCARRAY(redrow, BytesPerLine);
-    MALLOCARRAY(greenrow, BytesPerLine);
-    MALLOCARRAY(bluerow, BytesPerLine);
+    MALLOCARRAY(redrow, bytesPerLine);
+    MALLOCARRAY(grnrow, bytesPerLine);
+    MALLOCARRAY(blurow, bytesPerLine);
 
-    if (redrow == NULL || greenrow == NULL || bluerow == NULL)
-        pm_error("out of memory");
+    if (redrow == NULL || grnrow == NULL || blurow == NULL)
+        pm_error("Can't get memory for %u-byte row buffer", bytesPerLine);
 
-    if (Planes == 4) {
-        MALLOCARRAY(intensityrow, BytesPerLine);
+    if (planes == 4) {
+        MALLOCARRAY(intensityrow, bytesPerLine);
         if (intensityrow == NULL)
-            pm_error("out of memory");
+            pm_error("Can't get memory for %u-byte row buffer", bytesPerLine);
     } else
         intensityrow = NULL;
 
     ppmrow = ppm_allocrow(cols);
     for (row = 0; row < rows; ++row) {
         unsigned int col;
-        GetPCXRow(ifP, redrow, BytesPerLine);
-        GetPCXRow(ifP, greenrow, BytesPerLine);
-        GetPCXRow(ifP, bluerow, BytesPerLine);
-        if( intensityrow )
-            GetPCXRow(ifP, intensityrow, BytesPerLine);
+
+        getPCXRow(ifP, redrow, bytesPerLine);
+        getPCXRow(ifP, grnrow, bytesPerLine);
+        getPCXRow(ifP, blurow, bytesPerLine);
+        if (intensityrow)
+            getPCXRow(ifP, intensityrow, bytesPerLine);
+
         for (col = 0; col < cols; ++col) {
             unsigned int const r = redrow[col];
-            unsigned int const g = greenrow[col];
-            unsigned int const b = bluerow[col];
+            unsigned int const g = grnrow[col];
+            unsigned int const b = blurow[col];
             unsigned int const i = intensityrow ? intensityrow[col] : 256;
 
             PPM_ASSIGN(ppmrow[col],
@@ -630,29 +620,29 @@ pcx_truecol_to_ppm(FILE *       const ifP,
     ppm_freerow(ppmrow);
     if (intensityrow)
         free(intensityrow);
-    free(bluerow);
-    free(greenrow);
+    free(blurow);
+    free(grnrow);
     free(redrow);
 }
 
 
 
 int
-main(int argc, char *argv[]) {
+main(int argc, const char *argv[]) {
 
     FILE * ifP;
-    struct cmdlineInfo cmdline;
-    struct pcxHeader pcxHeader;
+    struct CmdlineInfo cmdline;
+    struct PcxHeader pcxHeader;
     unsigned int Width, Height;
     pixel * cmap16;
 
-    ppm_init(&argc, argv);
+    pm_proginit(&argc, argv);
 
     generateStdPalette();
 
     parseCommandLine(argc, argv, &cmdline);
 
-    ifP = pm_openr(cmdline.inputFilespec);
+    ifP = pm_openr(cmdline.inputFileNm);
 
     readPcxHeader(ifP, &pcxHeader);
 
@@ -668,31 +658,32 @@ main(int argc, char *argv[]) {
         cmap16 = pcxHeader.cmap16;
 
     ppm_writeppminit(stdout, Width, Height, PCX_MAXVAL, 0);
+
     switch (pcxHeader.BitsPerPixel) {
     case 1:
         if(pcxHeader.Planes >= 1 && pcxHeader.Planes <= 4)
-            pcx_16col_to_ppm(ifP, Width, Height, pcxHeader.BytesPerLine, 
-                             pcxHeader.BitsPerPixel, pcxHeader.Planes, cmap16);
+            pcx16ColToPpm(ifP, Width, Height, pcxHeader.BytesPerLine,
+                          pcxHeader.BitsPerPixel, pcxHeader.Planes, cmap16);
         else
             goto fail;
         break;
     case 2:
     case 4:
         if (pcxHeader.Planes == 1)
-            pcx_16col_to_ppm(ifP, Width, Height, pcxHeader.BytesPerLine, 
-                             pcxHeader.BitsPerPixel, pcxHeader.Planes, cmap16);
+            pcx16ColToPpm(ifP, Width, Height, pcxHeader.BytesPerLine,
+                          pcxHeader.BitsPerPixel, pcxHeader.Planes, cmap16);
         else
             goto fail;
         break;
     case 8:
         switch(pcxHeader.Planes) {
         case 1:
-            pcx_256col_to_ppm(ifP, Width, Height, pcxHeader.BytesPerLine);
+            pcx256ColToPpm(ifP, Width, Height, pcxHeader.BytesPerLine);
             break;
         case 3:
         case 4:
-            pcx_truecol_to_ppm(ifP, Width, Height, 
-                               pcxHeader.BytesPerLine, pcxHeader.Planes);
+            pcxTruecolToPpm(ifP, Width, Height,
+                            pcxHeader.BytesPerLine, pcxHeader.Planes);
             break;
         default:
             goto fail;
@@ -704,8 +695,9 @@ main(int argc, char *argv[]) {
                  pcxHeader.BitsPerPixel, pcxHeader.Planes);
     }
     pm_close(ifP);
-    
+
     return 0;
 }
 
 
+
diff --git a/converter/ppm/pi1toppm.c b/converter/ppm/pi1toppm.c
index 69b99863..9a07f535 100644
--- a/converter/ppm/pi1toppm.c
+++ b/converter/ppm/pi1toppm.c
@@ -90,3 +90,6 @@ main( argc, argv )
 
     exit( 0 );
     }
+
+
+
diff --git a/converter/ppm/picttoppm.c b/converter/ppm/picttoppm.c
index 4bc53378..fc73a92c 100644
--- a/converter/ppm/picttoppm.c
+++ b/converter/ppm/picttoppm.c
@@ -35,6 +35,7 @@
 #include "pbmfont.h"
 #include "mallocvar.h"
 #include "nstring.h"
+#include "shhopt.h"
 
 
 /*
@@ -46,6 +47,81 @@ typedef unsigned short Word;
 typedef unsigned long Longword;
 
 
+struct CmdlineInfo {
+    /* All the information the user supplied in the command line,
+       in a form easy for the program to use.
+    */
+    const char * inputFileName;  /* File name of input file */
+
+    unsigned int fullres;
+    unsigned int noheader;
+    unsigned int quickdraw;
+    const char * fontdir;  /* Null if not specified */
+    unsigned int verbose;
+};
+
+
+
+static void
+parseCommandLine(int argc,
+                 const char ** argv,
+                 struct CmdlineInfo  * const cmdlineP) {
+/* --------------------------------------------------------------------------
+   Parse program command line described in Unix standard form by argc
+   and argv.  Return the information in the options as *cmdlineP.
+
+   If command line is internally inconsistent (invalid options, etc.),
+   issue error message to stderr and abort program.
+
+   Note that the strings we return are stored in the storage that
+   was passed to us as the argv array.  We also trash *argv.
+--------------------------------------------------------------------------*/
+    optEntry * option_def;
+    optStruct3 opt;
+
+    unsigned int option_def_index;
+
+    unsigned int fontdirSpec, verboseSpec;
+
+    MALLOCARRAY_NOFAIL(option_def, 100);
+
+    option_def_index = 0;   /* incremented by OPTENT3 */
+    OPTENT3(0, "fontdir",     OPT_STRING,    &cmdlineP->fontdir,
+            &fontdirSpec,                     0);
+    OPTENT3(0, "fullres",     OPT_FLAG,      NULL,
+            &cmdlineP->fullres,               0);
+    OPTENT3(0, "noheader",    OPT_FLAG,      NULL,
+            &cmdlineP->noheader,              0);
+    OPTENT3(0, "quickdraw",   OPT_FLAG,      NULL,
+            &cmdlineP->quickdraw,             0);
+    OPTENT3(0, "verbose",     OPT_UINT,      &cmdlineP->verbose,
+            &verboseSpec,               0);
+
+    opt.opt_table = option_def;
+    opt.short_allowed = false;  /* We have no short (old-fashioned) options */
+    opt.allowNegNum = false;   /* We have no parms that are negative numbers */
+
+    pm_optParseOptions4(&argc, argv, opt, sizeof(opt), 0);
+        /* Uses and sets argc, argv, and some of *cmdlineP and others. */
+
+    if (!fontdirSpec)
+        cmdlineP->fontdir = NULL;
+
+    if (!verboseSpec)
+        cmdlineP->verbose = 0;
+
+    if (argc-1 < 1)
+        cmdlineP->inputFileName = "-";
+    else {
+        cmdlineP->inputFileName = argv[1];
+        if (argc-1 > 1)
+            pm_error("Too many arguments: %u.  The only possible non-option "
+                     "argument is the input file name", argc-1);
+    }
+}
+
+
+
 /*
  * Data structures for QuickDraw (and hence PICT) stuff.
  */
@@ -65,20 +141,20 @@ struct Rect {
     /* "End" means last plus one */
 };
 
-struct pixMap {
+struct PixMap {
     struct Rect Bounds;
-    Word version;
-    Word packType;
-    Longword packSize;
-    Longword hRes;
-    Longword vRes;
-    Word pixelType;
-    Word pixelSize;
-    Word cmpCount;
-    Word cmpSize;
-    Longword planeBytes;
-    Longword pmTable;
-    Longword pmReserved;
+    Word        version;
+    Word        packType;
+    Longword    packSize;
+    Longword    hRes;
+    Longword    vRes;
+    Word        pixelType;
+    Word        pixelSize;
+    Word        cmpCount;
+    Word        cmpSize;
+    Longword    planeBytes;
+    Longword    pmTable;
+    Longword    pmReserved;
 };
 
 struct RGBColor {
@@ -109,7 +185,7 @@ struct RgbPlanes {
     Word * blu;
 };
 
-struct canvas {
+struct Canvas {
     struct RgbPlanes planes;
 };
 
@@ -120,7 +196,6 @@ static struct Rect picFrame;
 static Word rowlen;
 static Word collen;
 static int verbose;
-static int fullres;
 static int recognize_comment;
 
 static struct RGBColor black = { 0, 0, 0 };
@@ -157,7 +232,7 @@ static int ps_cent_x;
 static int ps_cent_y;
 static int ps_cent_set;
 
-struct raster {
+struct Raster {
 /*----------------------------------------------------------------------------
    An image raster.  May be either truecolor or paletted.
 
@@ -188,7 +263,7 @@ struct raster {
 
 
 static void
-allocateRaster(struct raster * const rasterP,
+allocateRaster(struct Raster * const rasterP,
                unsigned int    const width,
                unsigned int    const height,
                unsigned int    const bitsPerPixel) {
@@ -217,19 +292,24 @@ allocateRaster(struct raster * const rasterP,
         /* TODO: I'm still trying to figure out this format.
 
            My theory today:
-           The row data is in plane order (a row consists of red
-           plane, then, green, then blue, then some 4th plane).
 
-           The old hack code said 3 bytes per pixel here, and could get
-           away with it because it never got to decoding the 4th plane.
+           The row data is in plane order (a row consists of red plane, then,
+           green, then blue, then some 4th plane).
+
+           If the image is compressed, each row is compressed separately, with
+           the planes opaque to the compressor.
 
-           But the new clean code needs to tell it like it is and allocate
-           4 bytes per pixel.  If we say 3 bytes per pixel here, we get an
-           "invalid PICT" error because the image actually contains 4
-           bytes per pixel and as we decompress it, we run out of place
-           to put the data.
+           The old hack code said 3 bytes per pixel here, and could get away
+           with it because it never got to decoding the 4th plane.
 
-           We have yet to see if we can properly interpret the data.
+           But the new clean code needs to tell it like it is and allocate 4
+           bytes per pixel.  If we say 3 bytes per pixel here, we get an
+           "invalid PICT" error on one image because the image actually
+           contains 4 bytes per pixel and as we decompress it, we run out of
+           place to put the data.
+
+           On another image we've seen, the decompressor generates 3 bytes per
+           pixel.
         */
 
         rasterP->rowSize = allocWidth * 4;
@@ -258,38 +338,40 @@ allocateRaster(struct raster * const rasterP,
 }
 
 
+
 static void
-freeRaster(struct raster const raster) {
+freeRaster(struct Raster const raster) {
 
     free(raster.bytes);
 }
 
 
-struct blit_info {
-    struct Rect        srcRect;
-    struct Rect        srcBounds;
-    struct raster      srcplane;
-    int                pixSize;
-    struct Rect        dstRect;
-    struct RGBColor *  colorMap;
-    int                mode;
-    struct blit_info * next;
+
+struct BlitInfo {
+    struct Rect       srcRect;
+    struct Rect       srcBounds;
+    struct Raster     srcplane;
+    int               pixSize;
+    struct Rect       dstRect;
+    struct RGBColor * colorMap;
+    int               mode;
+    struct BlitInfo * next;
 };
 
 typedef struct {
-    struct blit_info * firstP;
-    struct blit_info ** connectorP;
+    struct BlitInfo * firstP;
+    struct BlitInfo ** connectorP;
     bool unblittableText;
         /* The image contains text opcodes, and we don't know how to put that
            in a blit list (I really don't even know what a blit _is_), so
            the image information here is incomplete.
         */
-} blitList;
+} BlitList;
 
 
-typedef void (drawFn)(struct canvas *, blitList *, int);
+typedef void (drawFn)(FILE *, struct Canvas *, BlitList *, int);
 
-struct opdef {
+struct Opdef {
     const char* name;
     int len;
         /* If non-negative, this is the length of the argument of the
@@ -322,16 +404,15 @@ struct opdef {
 #define RGB_LEN (6)
 
 
-static FILE* ifp;
 static int align = 0;
 
 
 
 static Byte
-readByte(void) {
+readByte(FILE * const ifP) {
     int c;
 
-    if ((c = fgetc(ifp)) == EOF)
+    if ((c = fgetc(ifP)) == EOF)
         pm_error("EOF / read error while %s", stage);
 
     ++align;
@@ -341,27 +422,29 @@ readByte(void) {
 
 
 static Word
-readWord(void) {
+readWord(FILE * const ifP) {
 
-    Byte const hi = readByte();
-    Byte const lo = readByte();
+    Byte const hi = readByte(ifP);
+    Byte const lo = readByte(ifP);
 
     return (hi << 8) | (lo << 0);
 }
 
 
 
-static void readPoint(struct Point * const p) {
-    p->y = readWord();
-    p->x = readWord();
+static void readPoint(FILE *         const ifP,
+                      struct Point * const p) {
+    p->y = readWord(ifP);
+    p->x = readWord(ifP);
 }
 
 
 
 static Longword
-readLong(void) {
-    Word const hi = readWord();
-    Word const lo = readWord();
+readLong(FILE * const ifP) {
+
+    Word const hi = readWord(ifP);
+    Word const lo = readWord(ifP);
 
     return (hi << 16) | (lo << 0);
 }
@@ -369,40 +452,45 @@ readLong(void) {
 
 
 static SignedByte
-readSignedByte(void) {
-    return (SignedByte)readByte();
+readSignedByte(FILE * const ifP) {
+    return (SignedByte)readByte(ifP);
 }
 
 
 
 static void
-readShortPoint(struct Point * const p) {
-    p->x = readSignedByte();
-    p->y = readSignedByte();
+readShortPoint(FILE *         const ifP,
+               struct Point * const p) {
+
+    p->x = readSignedByte(ifP);
+    p->y = readSignedByte(ifP);
 }
 
 
 
 static void
-skip(int const byteCount) {
-    static Byte buf[1024];
+skip(FILE *       const ifP,
+     unsigned int const byteCount) {
+
+    Byte buf[1024];
     int n;
 
     align += byteCount;
 
-    for (n = byteCount; n > 0; n -= 1024)
-        if (fread(buf, n > 1024 ? 1024 : n, 1, ifp) != 1)
+    for (n = byteCount; n > 0; n -= 1024) {
+        if (fread(buf, n > 1024 ? 1024 : n, 1, ifP) != 1)
             pm_error("EOF / read error while %s", stage);
+    }
 }
 
 
 
-struct const_name {
+struct ConstName {
     int value;
     const char * name;
 };
 
-struct const_name const transfer_name[] = {
+struct ConstName const transfer_name[] = {
     { 0,    "srcCopy" },
     { 1,    "srcOr" },
     { 2,    "srcXor" },
@@ -422,7 +510,7 @@ struct const_name const transfer_name[] = {
     { -1,   0 }
 };
 
-struct const_name font_name[] = {
+struct ConstName font_name[] = {
     { 0,    "systemFont" },
     { 1,    "applFont" },
     { 2,    "newYork" },
@@ -443,7 +531,7 @@ struct const_name font_name[] = {
     { -1,   0 }
 };
 
-struct const_name ps_just_name[] = {
+struct ConstName ps_just_name[] = {
     { 0,    "no" },
     { 1,    "left" },
     { 2,    "center" },
@@ -452,7 +540,7 @@ struct const_name ps_just_name[] = {
     { -1,   0 }
 };
 
-struct const_name ps_flip_name[] = {
+struct ConstName ps_flip_name[] = {
     { 0,    "no" },
     { 1,    "horizontal" },
     { 2,    "vertical" },
@@ -462,8 +550,8 @@ struct const_name ps_flip_name[] = {
 
 
 static const char*
-const_name(const struct const_name * const table,
-           unsigned int              const ct) {
+constName(const struct ConstName * const table,
+          unsigned int             const ct) {
 
     static char numbuf[32];
 
@@ -480,8 +568,9 @@ const_name(const struct const_name * const table,
 
 
 static void
-picComment(Word const type,
-           int const length) {
+picComment(FILE * const ifP,
+           Word   const type,
+           int    const length) {
 
     unsigned int remainingLength;
 
@@ -489,10 +578,10 @@ picComment(Word const type,
     case 150:
         if (verbose) pm_message("TextBegin");
         if (length >= 6) {
-            ps_just = readByte();
-            ps_flip = readByte();
-            ps_rotation = readWord();
-            ps_linespace = readByte();
+            ps_just = readByte(ifP);
+            ps_flip = readByte(ifP);
+            ps_rotation = readWord(ifP);
+            ps_linespace = readByte(ifP);
             remainingLength = length - 5;
             if (recognize_comment)
                 ps_text = 1;
@@ -500,8 +589,8 @@ picComment(Word const type,
             if (verbose) {
                 pm_message("%s justification, %s flip, %d degree rotation, "
                            "%d/2 linespacing",
-                           const_name(ps_just_name, ps_just),
-                           const_name(ps_flip_name, ps_flip),
+                           constName(ps_just_name, ps_just),
+                           constName(ps_flip_name, ps_flip),
                            ps_rotation, ps_linespace);
             }
         } else
@@ -525,14 +614,14 @@ picComment(Word const type,
         if (length < 8)
             remainingLength = length;
         else {
-            ps_cent_y = readWord();
+            ps_cent_y = readWord(ifP);
             if (ps_cent_y > 32767)
                 ps_cent_y -= 65536;
-            skip(2); /* ignore fractional part */
-            ps_cent_x = readWord();
+            skip(ifP, 2); /* ignore fractional part */
+            ps_cent_x = readWord(ifP);
             if (ps_cent_x > 32767)
                 ps_cent_x -= 65536;
-            skip(2); /* ignore fractional part */
+            skip(ifP, 2); /* ignore fractional part */
             remainingLength = length - 8;
             if (verbose)
                 pm_message("offset %d %d", ps_cent_x, ps_cent_y);
@@ -628,7 +717,7 @@ picComment(Word const type,
         break;
     }
     if (remainingLength > 0)
-        skip(remainingLength);
+        skip(ifP, remainingLength);
 }
 
 
@@ -636,11 +725,12 @@ picComment(Word const type,
 static drawFn ShortComment;
 
 static void
-ShortComment(struct canvas * const canvasP,
-             blitList *      const blitListP,
+ShortComment(FILE *          const ifP,
+             struct Canvas * const canvasP,
+             BlitList *      const blitListP,
              int             const version) {
 
-    picComment(readWord(), 0);
+    picComment(ifP, readWord(ifP), 0);
 }
 
 
@@ -648,30 +738,33 @@ ShortComment(struct canvas * const canvasP,
 static drawFn LongComment;
 
 static void
-LongComment(struct canvas * const canvasP,
-            blitList *      const blitListP,
+LongComment(FILE *          const ifP,
+            struct Canvas * const canvasP,
+            BlitList *      const blitListP,
             int             const version) {
 
     Word type;
 
-    type = readWord();
-    picComment(type, readWord());
+    type = readWord(ifP);
+    picComment(ifP, type, readWord(ifP));
 }
 
 
 
-static drawFn skip_poly_or_region;
+static drawFn skipPolyOrRegion;
 
 static void
-skip_poly_or_region(struct canvas * const canvasP,
-                    blitList *      const blitListP,
-                    int             const version) {
+skipPolyOrRegion(FILE *          const ifP,
+                 struct Canvas * const canvasP,
+                 BlitList *      const blitListP,
+                 int             const version) {
 
     stage = "skipping polygon or region";
-    skip(readWord() - 2);
+    skip(ifP, readWord(ifP) - 2);
 }
 
 
+
 #define NA (0)
 
 #define FNT_BOLD    (1)
@@ -684,17 +777,17 @@ skip_poly_or_region(struct canvas * const canvasP,
 
 /* Some font searching routines */
 
-struct fontinfo {
+struct FontInfo {
     int font;
     int size;
     int style;
     char* filename;
     struct font* loaded;
-    struct fontinfo* next;
+    struct FontInfo* next;
 };
 
-static struct fontinfo* fontlist = 0;
-static struct fontinfo** fontlist_ins = &fontlist;
+static struct FontInfo* fontlist = 0;
+static struct FontInfo** fontlist_ins = &fontlist;
 
 
 
@@ -729,9 +822,9 @@ tokenize(char *         const s,
 
 static void
 parseFontLine(const char **      const token,
-              struct fontinfo ** const fontinfoPP) {
+              struct FontInfo ** const fontinfoPP) {
 
-    struct fontinfo * fontinfoP;
+    struct FontInfo * fontinfoP;
 
     MALLOCVAR(fontinfoP);
     if (fontinfoP == NULL)
@@ -752,7 +845,7 @@ parseFontLine(const char **      const token,
 
 
 static int
-load_fontdir(const char * const dirfile) {
+loadFontdir(const char * const dirfile) {
 /*----------------------------------------------------------------------------
    Load the font directory from file named 'dirfile'.  Add its contents
    to the global list of fonts 'fontlist'.
@@ -777,7 +870,7 @@ load_fontdir(const char * const dirfile) {
         } else if (nToken != 4) {
             /* Unrecognized format - ignore */
         } else {
-            struct fontinfo * fontinfoP;
+            struct FontInfo * fontinfoP;
 
             parseFontLine(token, &fontinfoP);
 
@@ -795,6 +888,23 @@ load_fontdir(const char * const dirfile) {
 
 
 static void
+loadDefaultFontDir(void) {
+/*----------------------------------------------------------------------------
+   Load the fonts from the font directory file "fontdir" (in the current
+   directory), if it exists.
+-----------------------------------------------------------------------------*/
+    struct stat statbuf;
+    int rc;
+
+    rc = stat("fontdir", &statbuf);
+
+    if (rc == 0)
+        loadFontdir("fontdir");
+}
+
+
+
+static void
 dumpRect(const char * const label,
          struct Rect  const rectangle) {
 
@@ -807,7 +917,8 @@ dumpRect(const char * const label,
 
 
 static void
-readRect(struct Rect * const r) {
+readRect(FILE *        const ifP,
+         struct Rect * const r) {
 
     /* We don't have a formal specification for the Pict format, but we have
        seen samples that have the rectangle corners either in top left, bottom
@@ -819,10 +930,10 @@ readRect(struct Rect * const r) {
        So now we accept all 4 possibilities.
     */
 
-    Word const y1 = readWord();
-    Word const x1 = readWord();
-    Word const y2 = readWord();
-    Word const x2 = readWord();
+    Word const y1 = readWord(ifP);
+    Word const x1 = readWord(ifP);
+    Word const y2 = readWord(ifP);
+    Word const x2 = readWord(ifP);
 
     r->top    = MIN(y1, y2);
     r->left   = MIN(x1, x2);
@@ -860,6 +971,7 @@ rectequal(const struct Rect * const comparand,
 }
 
 
+
 static int
 rectheight(const struct Rect * const r) {
 
@@ -909,7 +1021,7 @@ rectscale(struct Rect * const r,
 
 
 static void
-initBlitList(blitList * const blitListP) {
+initBlitList(BlitList * const blitListP) {
 
     blitListP->firstP          = NULL;
     blitListP->connectorP      = &blitListP->firstP;
@@ -919,16 +1031,16 @@ initBlitList(blitList * const blitListP) {
 
 
 static void
-addBlitList(blitList *        const blitListP,
+addBlitList(BlitList *        const blitListP,
             struct Rect       const srcRect,
             struct Rect       const srcBounds,
-            struct raster     const srcplane,
+            struct Raster     const srcplane,
             int               const pixSize,
             struct Rect       const dstRect,
             struct RGBColor * const colorMap,
             int               const mode) {
 
-    struct blit_info * biP;
+    struct BlitInfo * biP;
 
     MALLOCVAR(biP);
     if (biP == NULL)
@@ -945,7 +1057,7 @@ addBlitList(blitList *        const blitListP,
         biP->next = NULL;
 
         *blitListP->connectorP = biP;
-        blitListP->connectorP = &biP->next;
+        blitListP->connectorP  = &biP->next;
     }
 }
 
@@ -970,12 +1082,15 @@ rgbAllSame(const struct RGBColor * const colorP,
 }
 
 
+
 static bool
 rgbIsWhite(const struct RGBColor * const colorP) {
 
     return rgbAllSame(colorP, 0xffff);
 }
 
+
+
 static bool
 rgbIsBlack(const struct RGBColor * const colorP) {
 
@@ -983,122 +1098,133 @@ rgbIsBlack(const struct RGBColor * const colorP) {
 }
 
 
+
 static void
-srcCopy(struct RGBColor * const src,
-        struct RGBColor * const dst) {
+srcCopy(struct RGBColor * const srcP,
+        struct RGBColor * const dstP) {
 
-    if (rgbIsBlack(src))
-        *dst = foreground;
+    if (rgbIsBlack(srcP))
+        *dstP = foreground;
     else
-        *dst = background;
+        *dstP = background;
 }
 
 
 
 static void
-srcOr(struct RGBColor * const src,
-      struct RGBColor * const dst) {
-    if (rgbIsBlack(src))
-        *dst = foreground;
+srcOr(struct RGBColor * const srcP,
+      struct RGBColor * const dstP) {
+
+    if (rgbIsBlack(srcP))
+        *dstP = foreground;
 }
 
 
 
 static void
-srcXor(struct RGBColor * const src,
-       struct RGBColor * const dst) {
-    dst->red ^= ~src->red;
-    dst->grn ^= ~src->grn;
-    dst->blu ^= ~src->blu;
+srcXor(struct RGBColor * const srcP,
+       struct RGBColor * const dstP) {
+
+    dstP->red ^= ~srcP->red;
+    dstP->grn ^= ~srcP->grn;
+    dstP->blu ^= ~srcP->blu;
 }
 
 
 
 static void
-srcBic(struct RGBColor * const src,
-       struct RGBColor * const dst) {
-    if (rgbIsBlack(src))
-        *dst = background;
+srcBic(struct RGBColor * const srcP,
+       struct RGBColor * const dstP) {
+
+    if (rgbIsBlack(srcP))
+        *dstP = background;
 }
 
 
 
 static void
-notSrcCopy(struct RGBColor * const src,
-           struct RGBColor * const dst) {
-    if (rgbIsWhite(src))
-        *dst = foreground;
-    else if (rgbIsBlack(src))
-        *dst = background;
+notSrcCopy(struct RGBColor * const srcP,
+           struct RGBColor * const dstP) {
+
+    if (rgbIsWhite(srcP))
+        *dstP = foreground;
+    else if (rgbIsBlack(srcP))
+        *dstP = background;
 }
 
 
 
 static void
-notSrcOr(struct RGBColor * const src,
-         struct RGBColor * const dst) {
-    if (rgbIsWhite(src))
-        *dst = foreground;
+notSrcOr(struct RGBColor * const srcP,
+         struct RGBColor * const dstP) {
+
+    if (rgbIsWhite(srcP))
+        *dstP = foreground;
 }
 
 
 
 static void
-notSrcBic(struct RGBColor * const src,
-          struct RGBColor * const dst) {
-    if (rgbIsWhite(src))
-        *dst = background;
+notSrcBic(struct RGBColor * const srcP,
+          struct RGBColor * const dstP) {
+
+    if (rgbIsWhite(srcP))
+        *dstP = background;
 }
 
 
 
 static void
-notSrcXor(struct RGBColor * const src,
-          struct RGBColor * const dst) {
-    dst->red ^= src->red;
-    dst->grn ^= src->grn;
-    dst->blu ^= src->blu;
+notSrcXor(struct RGBColor * const srcP,
+          struct RGBColor * const dstP) {
+
+    dstP->red ^= srcP->red;
+    dstP->grn ^= srcP->grn;
+    dstP->blu ^= srcP->blu;
 }
 
 
 
 static void
-addOver(struct RGBColor * const src,
-        struct RGBColor * const dst) {
-    dst->red += src->red;
-    dst->grn += src->grn;
-    dst->blu += src->blu;
+addOver(struct RGBColor * const srcP,
+        struct RGBColor * const dstP) {
+
+    dstP->red += srcP->red;
+    dstP->grn += srcP->grn;
+    dstP->blu += srcP->blu;
 }
 
 
 
 static void
-addPin(struct RGBColor * const src,
-       struct RGBColor * const dst) {
-    if ((long)dst->red + (long)src->red > (long)op_color.red)
-        dst->red = op_color.red;
+addPin(struct RGBColor * const srcP,
+       struct RGBColor * const dstP) {
+
+    if ((long)dstP->red + (long)srcP->red > (long)op_color.red)
+        dstP->red = op_color.red;
     else
-        dst->red = dst->red + src->red;
+        dstP->red = dstP->red + srcP->red;
 
-    if ((long)dst->grn + (long)src->grn > (long)op_color.grn)
-        dst->grn = op_color.grn;
+    if ((long)dstP->grn + (long)srcP->grn > (long)op_color.grn)
+        dstP->grn = op_color.grn;
     else
-        dst->grn = dst->grn + src->grn;
+        dstP->grn = dstP->grn + srcP->grn;
 
-    if ((long)dst->blu + (long)src->blu > (long)op_color.blu)
-        dst->blu = op_color.blu;
+    if ((long)dstP->blu + (long)srcP->blu > (long)op_color.blu)
+        dstP->blu = op_color.blu;
     else
-        dst->blu = dst->blu + src->blu;
+        dstP->blu = dstP->blu + srcP->blu;
 }
 
 
 
 static void
-subOver(struct RGBColor * const src,
-        struct RGBColor * const dst) {
-    dst->red -= src->red;
-    dst->grn -= src->grn;
-    dst->blu -= src->blu;
+subOver(struct RGBColor * const srcP,
+        struct RGBColor * const dstP) {
+
+    dstP->red -= srcP->red;
+    dstP->grn -= srcP->grn;
+    dstP->blu -= srcP->blu;
 }
 
 
@@ -1107,74 +1233,81 @@ subOver(struct RGBColor * const src,
 
 
 static void
-subPin(struct RGBColor * const src,
-       struct RGBColor * const dst) {
-    if ((long)dst->red - (long)src->red < (long)op_color.red)
-        dst->red = op_color.red;
+subPin(struct RGBColor * const srcP,
+       struct RGBColor * const dstP) {
+
+    if ((long)dstP->red - (long)srcP->red < (long)op_color.red)
+        dstP->red = op_color.red;
     else
-        dst->red = dst->red - src->red;
+        dstP->red = dstP->red - srcP->red;
 
-    if ((long)dst->grn - (long)src->grn < (long)op_color.grn)
-        dst->grn = op_color.grn;
+    if ((long)dstP->grn - (long)srcP->grn < (long)op_color.grn)
+        dstP->grn = op_color.grn;
     else
-        dst->grn = dst->grn - src->grn;
+        dstP->grn = dstP->grn - srcP->grn;
 
-    if ((long)dst->blu - (long)src->blu < (long)op_color.blu)
-        dst->blu = op_color.blu;
+    if ((long)dstP->blu - (long)srcP->blu < (long)op_color.blu)
+        dstP->blu = op_color.blu;
     else
-        dst->blu = dst->blu - src->blu;
+        dstP->blu = dstP->blu - srcP->blu;
 }
 
 
 
 static void
-adMax(struct RGBColor * const src,
-      struct RGBColor * const dst) {
-    if (src->red > dst->red) dst->red = src->red;
-    if (src->grn > dst->grn) dst->grn = src->grn;
-    if (src->blu > dst->blu) dst->blu = src->blu;
+adMax(struct RGBColor * const srcP,
+      struct RGBColor * const dstP) {
+
+    if (srcP->red > dstP->red) dstP->red = srcP->red;
+    if (srcP->grn > dstP->grn) dstP->grn = srcP->grn;
+    if (srcP->blu > dstP->blu) dstP->blu = srcP->blu;
 }
 
 
 
 static void
-adMin(struct RGBColor * const src,
-      struct RGBColor * const dst) {
-    if (src->red < dst->red) dst->red = src->red;
-    if (src->grn < dst->grn) dst->grn = src->grn;
-    if (src->blu < dst->blu) dst->blu = src->blu;
+adMin(struct RGBColor * const srcP,
+      struct RGBColor * const dstP) {
+
+    if (srcP->red < dstP->red) dstP->red = srcP->red;
+    if (srcP->grn < dstP->grn) dstP->grn = srcP->grn;
+    if (srcP->blu < dstP->blu) dstP->blu = srcP->blu;
 }
 
 
 
 static void
-blend(struct RGBColor * const src,
-      struct RGBColor * const dst) {
+blend(struct RGBColor * const srcP,
+      struct RGBColor * const dstP) {
+
 #define blend_component(cmp)    \
-    ((long)src->cmp * (long)op_color.cmp) / 65536 +    \
-    ((long)dst->cmp * (long)(65536 - op_color.cmp) / 65536)
+    ((long)srcP->cmp * (long)op_color.cmp) / 65536 +    \
+    ((long)dstP->cmp * (long)(65536 - op_color.cmp) / 65536)
 
-    dst->red = blend_component(red);
-    dst->grn = blend_component(grn);
-    dst->blu = blend_component(blu);
+    dstP->red = blend_component(red);
+    dstP->grn = blend_component(grn);
+    dstP->blu = blend_component(blu);
 }
 
 
 
 static void
-transparent(struct RGBColor * const src,
-            struct RGBColor * const dst) {
-    if (src->red != background.red ||
-        src->grn != background.grn ||
-        src->blu != background.blu) {
-        *dst = *src;
+transparent(struct RGBColor * const srcP,
+            struct RGBColor * const dstP) {
+
+    if (srcP->red != background.red ||
+        srcP->grn != background.grn ||
+        srcP->blu != background.blu) {
+
+        *dstP = *srcP;
     }
 }
 
 
 
 static transfer_func
-transfer(int const mode) {
+transferFunctionForMode(unsigned int const mode) {
+
     switch (mode) {
     case  0: return srcCopy;
     case  1: return srcOr;
@@ -1193,9 +1326,8 @@ transfer(int const mode) {
     case 38: return subOver;
     case 39: return adMin;
     default:
-        if (mode != 0)
-            pm_message("no transfer function for code %s, using srcCopy",
-                const_name(transfer_name, mode));
+        pm_message("no transfer function for code %s, using srcCopy",
+                   constName(transfer_name, mode));
         return srcCopy;
     }
 }
@@ -1393,7 +1525,7 @@ doDiffSize(struct Rect       const srcRect,
         }
     } break;
     case 32: {
-        unsigned int const planeSize = srcwid / 4;
+        unsigned int const planeSize = rectwidth(&srcRect);
         unsigned int row;
 
         for (row = 0; row < rectheight(&srcRect); ++row) {
@@ -1447,186 +1579,171 @@ putRgb(struct RGBColor  const rgb,
 
 
 static void
-doSameSize(transfer_func           trf,
-           int               const pixSize,
-           struct Rect       const srcRect,
-           unsigned char *   const src,
-           unsigned int      const srcwid,
-           struct RGBColor * const color_map,
-           struct RgbPlanes  const dst,
-           unsigned int      const dstwid) {
-/*----------------------------------------------------------------------------
-   Transfer pixels from 'src' to 'dst', applying the transfer function
-   'trf'.
+doSameSize8bpp(transfer_func           trf,
+               unsigned int      const xsize,
+               unsigned int      const ysize,
+               unsigned char *   const src,
+               unsigned int      const srcwid,
+               struct RGBColor * const colorMap,
+               struct RgbPlanes  const dst,
+               unsigned int      const dstwid) {
+
+    unsigned int rowNumber;
+
+    for (rowNumber = 0; rowNumber < ysize; ++rowNumber) {
+        unsigned char * const srcrow = &src[rowNumber * srcwid];
+        unsigned int const dstRowCurs = rowNumber * dstwid;
+
+        unsigned int colNumber;
+        for (colNumber = 0; colNumber < xsize; ++colNumber) {
+            unsigned int const dstCursor = dstRowCurs + colNumber;
+            unsigned int const colorIndex = srcrow[colNumber];
+
+            if (trf) {
+                struct RGBColor dstColor;
 
-   'src' has the same format as the 'bytes' member of struct raster.
-   'srcwid' is the size in bytes of each row, like raster.rowSize.
+                getRgb(dst, dstCursor, &dstColor);
+                (*trf)(&colorMap[colorIndex], &dstColor);
+                putRgb(dstColor, dstCursor, dst);
+            } else
+                putRgb(colorMap[colorIndex], dstCursor, dst);
+        }
+    }
+}
 
-   We use only the first 'ysize' rows and only the first 'xsize'
-   pixels of each row.
 
-   We really should clean this up so that we can take pixels out of
-   the middle of a row and rows out of the middle of the raster.  As
-   it stands, Caller achieves the same result by passing as 'src'
-   a pointer into the middle of a raster -- the upper left corner of
-   the rectangle he wants.  But that is messy and nonobvious.
 
-   Each plane of 'dst' is one word per pixel and contains actual
-   colors, never a palette index.  It is an array in row-major order
-   with 'dstwid' words per row.
------------------------------------------------------------------------------*/
-    unsigned int const xsize = rectwidth(&srcRect);
-    unsigned int const ysize = rectheight(&srcRect);
+static void
+doSameSize16bpp(transfer_func           trf,
+                unsigned int      const xsize,
+                unsigned int      const ysize,
+                unsigned char *   const src,
+                unsigned int      const srcwid,
+                struct RgbPlanes  const dst,
+                unsigned int      const dstwid) {
 
-    switch (pixSize) {
-    case 8: {
-        unsigned int rowNumber;
+    unsigned int rowNumber;
 
-        for (rowNumber = 0; rowNumber < ysize; ++rowNumber) {
-            unsigned char * const srcrow = &src[rowNumber * srcwid];
-            unsigned int const dstRowCurs = rowNumber * dstwid;
+    for (rowNumber = 0; rowNumber < ysize; ++rowNumber) {
+        unsigned char * const row = &src[rowNumber * srcwid];
+        unsigned int const dstRowCurs = rowNumber * dstwid;
 
-            unsigned int colNumber;
-            for (colNumber = 0; colNumber < xsize; ++colNumber) {
-                unsigned int const dstCursor = dstRowCurs + colNumber;
-                unsigned int const colorIndex = srcrow[colNumber];
-                struct RGBColor dstColor;
-                getRgb(dst, dstCursor, &dstColor);
-                (*trf)(&color_map[colorIndex], &dstColor);
-                putRgb(dstColor, dstCursor, dst);
-            }
-        }
-    } break;
-    case 16: {
-        unsigned int rowNumber;
+        unsigned int colNumber;
+        for (colNumber = 0; colNumber < xsize; ++colNumber) {
+            unsigned int const dstCursor = dstRowCurs + colNumber;
+            struct RGBColor const srcColor = decode16(&row[colNumber*2]);
+
+            struct RGBColor scaledSrcColor;
 
-        for (rowNumber = 0; rowNumber < ysize; ++rowNumber) {
-            unsigned char * const row = &src[rowNumber * srcwid];
-            unsigned int const dstRowCurs = rowNumber * dstwid;
+            scaledSrcColor.red = srcColor.red << 11;
+            scaledSrcColor.grn = srcColor.grn << 11;
+            scaledSrcColor.blu = srcColor.blu << 11;
 
-            unsigned int colNumber;
-            for (colNumber = 0; colNumber < xsize; ++colNumber) {
-                unsigned int const dstCursor = dstRowCurs + colNumber;
-                struct RGBColor const srcColor = decode16(&row[colNumber*2]);
+            if (trf) {
                 struct RGBColor dstColor;
-                struct RGBColor scaledSrcColor;
-                scaledSrcColor.red = srcColor.red << 11;
-                scaledSrcColor.grn = srcColor.grn << 11;
-                scaledSrcColor.blu = srcColor.blu << 11;
+
                 getRgb(dst, dstCursor, &dstColor);
                 (*trf)(&scaledSrcColor, &dstColor);
                 putRgb(dstColor, dstCursor, dst);
-            }
+            } else
+                putRgb(scaledSrcColor, dstCursor, dst);
         }
-    } break;
-    case 32: {
-        unsigned int const planeSize = srcwid / 4;
-        unsigned int rowNumber;
+    }
+}
 
-        for (rowNumber = 0; rowNumber < ysize; ++rowNumber) {
-            unsigned char * const row = &src[rowNumber * srcwid];
-            unsigned char * const redPlane = &row[planeSize * 0];
-            unsigned char * const grnPlane = &row[planeSize * 1];
-            unsigned char * const bluPlane = &row[planeSize * 2];
-            unsigned int const dstRowCurs = rowNumber * dstwid;
 
-            unsigned int colNumber;
 
-            for (colNumber = 0; colNumber < xsize; ++colNumber) {
-                unsigned int const dstCursor = dstRowCurs + colNumber;
-                struct RGBColor srcColor, dstColor;
+static void
+doSameSize32bpp(transfer_func           trf,
+                unsigned int      const xsize,
+                unsigned int      const ysize,
+                unsigned char *   const src,
+                unsigned int      const srcwid,
+                struct RgbPlanes  const dst,
+                unsigned int      const dstwid) {
+
+    unsigned int const planeSize = xsize;
+
+    unsigned int rowNumber;
+
+    for (rowNumber = 0; rowNumber < ysize; ++rowNumber) {
+        unsigned char * const row = &src[rowNumber * srcwid];
+        unsigned char * const redPlane = &row[planeSize * 0];
+        unsigned char * const grnPlane = &row[planeSize * 1];
+        unsigned char * const bluPlane = &row[planeSize * 2];
+        unsigned int const dstRowCurs = rowNumber * dstwid;
+
+        unsigned int colNumber;
+
+        for (colNumber = 0; colNumber < xsize; ++colNumber) {
+            unsigned int const dstCursor = dstRowCurs + colNumber;
+
+            struct RGBColor srcColor;
+
+            srcColor.red = redPlane[colNumber] << 8;
+            srcColor.grn = grnPlane[colNumber] << 8;
+            srcColor.blu = bluPlane[colNumber] << 8;
+
+            if (trf) {
+                struct RGBColor dstColor;
+
                 getRgb(dst, dstCursor, &dstColor);
-                srcColor.red = redPlane[colNumber] << 8;
-                srcColor.grn = grnPlane[colNumber] << 8;
-                srcColor.blu = bluPlane[colNumber] << 8;
                 (*trf)(&srcColor, &dstColor);
                 putRgb(dstColor, dstCursor, dst);
-            }
+            } else
+                putRgb(srcColor, dstCursor, dst);
         }
-    } break;
-    default:
-        pm_error("Impossible value of pixSize: %u", pixSize);
     }
 }
 
 
 
 static void
-blitIdempotent(unsigned int          const pixSize,
-               struct Rect           const srcRect,
-               unsigned char *       const src,
-               unsigned int          const srcwid,
-               struct RGBColor *     const colorMap,
-               struct RgbPlanes      const dst,
-               unsigned int          const dstwid) {
+doSameSize(transfer_func           trf,
+           int               const pixSize,
+           struct Rect       const srcRect,
+           unsigned char *   const src,
+           unsigned int      const srcwid,
+           struct RGBColor * const colorMap,
+           struct RgbPlanes  const dst,
+           unsigned int      const dstwid) {
 /*----------------------------------------------------------------------------
-  This is the same as doSameSize(), except optimized for the case that
-  the transfer function is idempotent (i.e. it's just a straight copy).
-  The original author's comments suggest that this optimization isn't
-  all that important -- that he just wrote this first and instead of
-  expanding it to handle arbitrary transfer functions, added functions
-  for that.
+   Transfer pixels from 'src' to 'dst', applying the transfer function
+   'trf'.
+
+   'src' has the same format as the 'bytes' member of struct Raster.
+   'srcwid' is the size in bytes of each row, like raster.rowSize.
+   Note that there may be padding in there; there isn't necessarily
+   'srcwid' bytes of information in a row.
+
+   We use only the first 'ysize' rows and only the first 'xsize'
+   pixels of each row.
+
+   We really should clean this up so that we can take pixels out of
+   the middle of a row and rows out of the middle of the raster.  As
+   it stands, Caller achieves the same result by passing as 'src'
+   a pointer into the middle of a raster -- the upper left corner of
+   the rectangle he wants.  But that is messy and nonobvious.
+
+   Each plane of 'dst' is one word per pixel and contains actual
+   colors, never a palette index.  It is an array in row-major order
+   with 'dstwid' words per row.
 -----------------------------------------------------------------------------*/
     unsigned int const xsize = rectwidth(&srcRect);
     unsigned int const ysize = rectheight(&srcRect);
 
     switch (pixSize) {
-    case 8: {
-        unsigned int rowNumber;
-
-        for (rowNumber = 0; rowNumber < ysize; ++rowNumber) {
-            unsigned char * const srcrow = &src[rowNumber * srcwid];
-            unsigned int const dstRowCurs = rowNumber * dstwid;
-            unsigned int colNumber;
-            for (colNumber = 0; colNumber < xsize; ++colNumber) {
-                unsigned int const dstCursor = dstRowCurs + colNumber;
-                struct RGBColor * const ct = colorMap + srcrow[colNumber];
-                dst.red[dstCursor] = ct->red;
-                dst.grn[dstCursor] = ct->grn;
-                dst.blu[dstCursor] = ct->blu;
-            }
-        }
-    } break;
-    case 16: {
-        unsigned int rowNumber;
-
-        for (rowNumber = 0; rowNumber < ysize; ++rowNumber) {
-            unsigned char * const srcrow = &src[rowNumber * srcwid];
-            unsigned int const dstRowCurs = rowNumber * dstwid;
-            unsigned int colNumber;
-            for (colNumber = 0; colNumber < xsize; ++colNumber) {
-                unsigned int const dstCursor = dstRowCurs + colNumber;
-                struct RGBColor const srcColor =
-                    decode16(&srcrow[colNumber * 2]);
-                dst.red[dstCursor] = srcColor.red << 11;
-                dst.grn[dstCursor] = srcColor.grn << 11;
-                dst.blu[dstCursor] = srcColor.blu << 11;
-            }
-        }
-    } break;
-    case 32: {
-        unsigned int const planeSize = srcwid / 4;
-        unsigned int rowNumber;
-
-        for (rowNumber = 0; rowNumber < ysize; ++rowNumber) {
-            unsigned char * const srcrow = &src[rowNumber * srcwid];
-            unsigned char * const redPlane = &srcrow[planeSize * 0];
-            unsigned char * const grnPlane = &srcrow[planeSize * 1];
-            unsigned char * const bluPlane = &srcrow[planeSize * 2];
-            unsigned int const dstRowCurs = rowNumber * dstwid;
-
-            unsigned int colNumber;
-            for (colNumber = 0; colNumber < xsize; ++colNumber) {
-                unsigned int const dstCursor = dstRowCurs + colNumber;
-                dst.red[dstCursor] = redPlane[colNumber] << 8;
-                dst.grn[dstCursor] = grnPlane[colNumber] << 8;
-                dst.blu[dstCursor] = bluPlane[colNumber] << 8;
-            }
-        }
-    } break;
+    case 8:
+        doSameSize8bpp(trf, xsize, ysize, src, srcwid, colorMap, dst, dstwid);
+        break;
+    case 16:
+        doSameSize16bpp(trf, xsize, ysize, src, srcwid, dst, dstwid);
+        break;
+    case 32:
+        doSameSize32bpp(trf, xsize, ysize, src, srcwid, dst, dstwid);
+        break;
     default:
-        pm_error("INTERNAL ERROR: invalid bits per pixel (%u) in "
-                 "blitIdempotent()", pixSize);
+        pm_error("Impossible value of pixSize: %u", pixSize);
     }
 }
 
@@ -1636,16 +1753,15 @@ static void
 doBlit(struct Rect       const srcRect,
        struct Rect       const dstRect,
        struct Rect       const srcBounds,
-       struct raster     const srcplane,
+       struct Raster     const srcplane,
        struct Rect       const dstBounds,
        struct RgbPlanes  const canvasPlanes,
        int               const pixSize,
        int               const dstwid,
-       struct RGBColor * const color_map,
-       int               const mode) {
+       struct RGBColor * const colorMap,
+       unsigned int      const mode) {
 /*----------------------------------------------------------------------------
-   Transfer some pixels from 'srcplane' to 'canvasPlanes', applying the
-   transfer function 'trf'.
+   Transfer some pixels from 'srcplane' to 'canvasPlanes'.
 
    'srcplane' contains the rectangle 'srcBounds' of the image.
    'canvasPlanes' contains the rectangle 'dstRect' of the image.
@@ -1661,6 +1777,9 @@ doBlit(struct Rect       const srcRect,
     struct RgbPlanes dst;
     int dstoff;
     transfer_func trf;
+        /* A transfer function to use as we transfer the pixels.
+           NULL for none.
+        */
 
     if (verbose) {
         dumpRect("copying from:", srcRect);
@@ -1697,35 +1816,31 @@ doBlit(struct Rect       const srcRect,
     if ((mode & ~64) == 0)
         trf = NULL;    /* optimized srcCopy */
     else
-        trf = transfer(mode & ~64);
+        trf = transferFunctionForMode(mode & ~64);
 
     if (!rectsamesize(srcRect, dstRect))
         doDiffSize(srcRect, dstRect, pixSize,
-                   trf, color_map, src, srcplane.rowSize, dst);
+                   trf, colorMap, src, srcplane.rowSize, dst);
     else {
-        if (trf == NULL)
-            blitIdempotent(pixSize, srcRect, src, srcplane.rowSize,
-                           color_map, dst, dstwid);
-        else
-            doSameSize(trf, pixSize, srcRect, src, srcplane.rowSize,
-                       color_map, dst, dstwid);
+        doSameSize(trf, pixSize, srcRect, src, srcplane.rowSize,
+                   colorMap, dst, dstwid);
     }
 }
 
 
 
-static int
+static void
 blit(struct Rect       const srcRect,
      struct Rect       const srcBounds,
-     struct raster     const srcplane,
-     struct canvas *   const canvasP,
-     blitList *        const blitListP,
+     struct Raster     const srcplane,
+     struct Canvas *   const canvasP,
+     BlitList *        const blitListP,
      int               const pixSize,
      struct Rect       const dstRect,
      struct Rect       const dstBounds,
      int               const dstwid,
      struct RGBColor * const color_map,
-     int               const mode) {
+     unsigned int      const mode) {
 /*----------------------------------------------------------------------------
    'srcplane' contains the rectangle 'srcBounds' of the image.
 
@@ -1734,19 +1849,8 @@ blit(struct Rect       const srcRect,
    if 'blitListP' is non-null, we don't draw anything on 'canvasP'; instead,
    we add to the list *blitlistP a description of what needs to be drawn.
 -----------------------------------------------------------------------------*/
-
-    /* I can't tell what the result value of this function is supposed to mean,
-       but I found several return statements that did not set it to anything,
-       and several calls that examine it.  I'm guessing that "1" is the
-       appropriate thing to return in those cases, so I made it so.
-       -Bryan 00.03.02
-    */
-
-    int retval;
-
-    if (ps_text)
-        retval = 1;
-    else {
+    if (ps_text) {
+    } else {
         /* Almost got it.  Clip source rect with source bounds.
            clip dest rect with dest bounds.
         */
@@ -1760,17 +1864,12 @@ blit(struct Rect       const srcRect,
             addBlitList(blitListP,
                         clipsrc, srcBounds, srcplane, pixSize,
                         clipdst, color_map, mode);
-
-            retval = 0;
         } else {
             doBlit(clipsrc, clipdst,
                    srcBounds, srcplane, dstBounds, canvasP->planes,
                    pixSize, dstwid, color_map, mode);
-
-            retval = 1;
         }
     }
-    return retval;
 }
 
 
@@ -1828,11 +1927,11 @@ compact(Word const input) {
 
 
 static void
-reportBlitList(blitList * const blitListP) {
+reportBlitList(BlitList * const blitListP) {
 
     if (verbose) {
         unsigned int count;
-        struct blit_info * biP;
+        struct BlitInfo * biP;
 
         for (count = 0, biP = blitListP->firstP; biP; biP = biP->next)
             ++count;
@@ -1844,15 +1943,15 @@ reportBlitList(blitList * const blitListP) {
 
 
 static void
-doBlitList(struct canvas * const canvasP,
-           blitList *      const blitListP) {
+doBlitList(struct Canvas * const canvasP,
+           BlitList *      const blitListP) {
 /*----------------------------------------------------------------------------
    Do the list of blits *blitListP, drawing on canvas *canvasP.
 
    We allocate new plane data structures in *canvasP.  We assume it doesn't
    have them already.
 -----------------------------------------------------------------------------*/
-    struct blit_info * bi;
+    struct BlitInfo * bi;
     int srcwidth, dstwidth, srcheight, dstheight;
     double  scale, scalelow, scalehigh;
     double  xscale = 1.0;
@@ -1862,8 +1961,6 @@ doBlitList(struct canvas * const canvasP,
 
     reportBlitList(blitListP);
 
-    fullres = 0;
-
     for (bi = blitListP->firstP; bi; bi = bi->next) {
         srcwidth = rectwidth(&bi->srcRect);
         dstwidth = rectwidth(&bi->dstRect);
@@ -1940,7 +2037,7 @@ doBlitList(struct canvas * const canvasP,
     }
 
     if (xscale != 1.0 || yscale != 1.0) {
-        struct blit_info * biP;
+        struct BlitInfo * biP;
 
         for (biP = blitListP->firstP; biP; biP = biP->next)
             rectscale(&biP->dstRect, xscale, yscale);
@@ -2007,19 +2104,20 @@ outputPpm(FILE *           const ofP,
  * is padded with a null.
  */
 static Word
-nextOp(int const version) {
+nextOp(FILE *       const ifP,
+       unsigned int const version) {
 
     if ((align & 0x1) && version == 2) {
         stage = "aligning for opcode";
-        readByte();
+        readByte(ifP);
     }
 
     stage = "reading opcode";
 
     if (version == 1)
-        return readByte();
+        return readByte(ifP);
     else
-        return readWord();
+        return readWord(ifP);
 }
 
 
@@ -2027,11 +2125,12 @@ nextOp(int const version) {
 static drawFn ClipRgn;
 
 static void
-ClipRgn(struct canvas * const canvasP,
-        blitList *      const blitListP,
+ClipRgn(FILE *          const ifP,
+        struct Canvas * const canvasP,
+        BlitList *      const blitListP,
         int             const version) {
 
-    Word const len = readWord();
+    Word const len = readWord(ifP);
         /* Length in bytes of the parameter (including this word) */
 
     if (len == 10) {    /* null rgn */
@@ -2046,7 +2145,7 @@ ClipRgn(struct canvas * const canvasP,
         */
         struct Rect clipRgnParm;
 
-        readRect(&clipRgnParm);
+        readRect(ifP, &clipRgnParm);
 
         rectintersect(&clipRgnParm, &picFrame, &clip_rect);
 
@@ -2060,7 +2159,7 @@ ClipRgn(struct canvas * const canvasP,
         if (verbose)
             dumpRect("clipping to", clip_rect);
     } else
-        skip(len - 2);
+        skip(ifP, len - 2);
 }
 
 
@@ -2068,35 +2167,37 @@ ClipRgn(struct canvas * const canvasP,
 static drawFn OpColor;
 
 static void
-OpColor(struct canvas * const canvasP,
-        blitList *      const blitListP,
+OpColor(FILE *          const ifP,
+        struct Canvas * const canvasP,
+        BlitList *      const blitListP,
         int             const version) {
 
-    op_color.red = readWord();
-    op_color.grn = readWord();
-    op_color.blu = readWord();
+    op_color.red = readWord(ifP);
+    op_color.grn = readWord(ifP);
+    op_color.blu = readWord(ifP);
 }
 
 
 
 static void
-readPixmap(struct pixMap * const p) {
+readPixmap(FILE *          const ifP,
+           struct PixMap * const p) {
 
     stage = "getting pixMap header";
 
-    readRect(&p->Bounds);
-    p->version    = readWord();
-    p->packType   = readWord();
-    p->packSize   = readLong();
-    p->hRes       = readLong();
-    p->vRes       = readLong();
-    p->pixelType  = readWord();
-    p->pixelSize  = readWord();
-    p->cmpCount   = readWord();
-    p->cmpSize    = readWord();
-    p->planeBytes = readLong();
-    p->pmTable    = readLong();
-    p->pmReserved = readLong();
+    readRect(ifP, &p->Bounds);
+    p->version    = readWord(ifP);
+    p->packType   = readWord(ifP);
+    p->packSize   = readLong(ifP);
+    p->hRes       = readLong(ifP);
+    p->vRes       = readLong(ifP);
+    p->pixelType  = readWord(ifP);
+    p->pixelSize  = readWord(ifP);
+    p->cmpCount   = readWord(ifP);
+    p->cmpSize    = readWord(ifP);
+    p->planeBytes = readLong(ifP);
+    p->pmTable    = readLong(ifP);
+    p->pmReserved = readLong(ifP);
 
     if (verbose) {
         pm_message("pixelType: %d", p->pixelType);
@@ -2119,19 +2220,20 @@ readPixmap(struct pixMap * const p) {
 
 
 static struct RGBColor*
-readColorTable(void) {
+readColorTable(FILE * const ifP) {
+
     Longword ctSeed;
     Word ctFlags;
     Word ctSize;
     Word val;
     int i;
-    struct RGBColor* color_table;
+    struct RGBColor* colorTable;
 
     stage = "getting color table info";
 
-    ctSeed = readLong();
-    ctFlags = readWord();
-    ctSize = readWord();
+    ctSeed  = readLong(ifP);
+    ctFlags = readWord(ifP);
+    ctSize  = readWord(ifP);
 
     if (verbose) {
         pm_message("ctSeed:  %ld", ctSeed);
@@ -2141,12 +2243,12 @@ readColorTable(void) {
 
     stage = "reading color table";
 
-    MALLOCARRAY(color_table, ctSize + 1);
-    if (color_table == NULL)
+    MALLOCARRAY(colorTable, ctSize + 1);
+    if (!colorTable)
         pm_error("no memory for color table");
 
-    for (i = 0; i <= ctSize; i++) {
-        val = readWord();
+    for (i = 0; i <= ctSize; ++i) {
+        val = readWord(ifP);
         /* The indices in a device color table are bogus and usually == 0.
          * so I assume we allocate up the list of colors in order.
          */
@@ -2154,18 +2256,19 @@ readColorTable(void) {
             val = i;
         if (val > ctSize)
             pm_error("pixel value greater than color table size");
-        color_table[val].red = readWord();
-        color_table[val].grn = readWord();
-        color_table[val].blu = readWord();
+
+        colorTable[val].red = readWord(ifP);
+        colorTable[val].grn = readWord(ifP);
+        colorTable[val].blu = readWord(ifP);
 
         if (verbose > 1)
             pm_message("Color %3u: [%u,%u,%u]", val,
-                color_table[val].red,
-                color_table[val].grn,
-                color_table[val].blu);
+                colorTable[val].red,
+                colorTable[val].grn,
+                colorTable[val].blu);
     }
 
-    return color_table;
+    return colorTable;
 }
 
 
@@ -2261,7 +2364,7 @@ expand1Bit(unsigned char * const packed,
 static void
 unpackBuf(unsigned char *  const packed,
           unsigned int     const packedLen,
-          int              const bitsPerPixel,
+          unsigned int     const bitsPerPixel,
           unsigned char ** const expandedP,
           unsigned int *   const expandedLenP) {
 /*----------------------------------------------------------------------------
@@ -2317,7 +2420,7 @@ unpackBuf(unsigned char *  const packed,
 
 static void
 unpackUncompressedBits(FILE *          const ifP,
-                       struct raster   const raster,
+                       struct Raster   const raster,
                        unsigned int    const rowBytes,
                        unsigned int    const bitsPerPixel) {
 /*----------------------------------------------------------------------------
@@ -2332,6 +2435,9 @@ unpackUncompressedBits(FILE *          const ifP,
     unsigned int rowOfRect;
     unsigned char * linebuf;
 
+    if (verbose)
+        pm_message("Bits are not packed");
+
     MALLOCARRAY(linebuf, rowBytes + 100);
     if (linebuf == NULL)
         pm_error("can't allocate memory for line buffer");
@@ -2364,13 +2470,15 @@ reportValidateCompressedLineLen(unsigned int const row,
                                 unsigned int const linelen,
                                 unsigned int const rowSize) {
 /*----------------------------------------------------------------------------
-   'row' is a row number in the raster.
+  Report the line length and fail the program if it is obviously wrong.
+
+ 'row' is a row number in the raster.
 
-   'linelen' is the number of bytes of PICT that the PICT says hold the
-   compressed version of that row.
+ 'linelen' is the number of bytes of PICT that the PICT says hold the
+ compressed version of that row.
 
-   'rowSize' is the number of bytes we expect the uncompressed line to
-   be (includes pad pixels on the right).
+ 'rowSize' is the number of bytes we expect the uncompressed line to
+ be (includes pad pixels on the right).
 -----------------------------------------------------------------------------*/
     if (verbose > 1)
         pm_message("Row %u: %u-byte compressed line", row, linelen);
@@ -2428,7 +2536,7 @@ expandRun(unsigned char * const block,
 
         assert(block[0] & 0x80);  /* It's a run */
 
-        if (verbose > 1)
+        if (verbose > 2)
             pm_message("Block: run of %u packed %u-byte units",
                        runLength, pkpixsize);
 
@@ -2507,7 +2615,7 @@ copyPixelGroup(unsigned char * const block,
         assert(blockLimit >= 1);  /* block[0] exists */
         assert((block[0] & 0x80) == 0);  /* It's not a run */
 
-        if (verbose > 1)
+        if (verbose > 2)
             pm_message("Block: %u explicit packed %u-byte units",
                        groupLen, pkpixsize);
 
@@ -2576,13 +2684,13 @@ interpretCompressedLine(unsigned char * const linebuf,
                         unsigned int    const rowSize,
                         unsigned int    const bitsPerPixel) {
 /*----------------------------------------------------------------------------
-   linebuf[] contains 'linelen' bytes from the PICT image that represents
-   one row of the image, in compressed format.  Return the
-   uncompressed pixels of that row as rowRaster[].
+   linebuf[] contains 'linelen' bytes from the PICT image that represents one
+   row of the image, in compressed format.  Return the uncompressed pixels of
+   that row as rowRaster[].
 
-   rowRaster[] has 'rowSize' bytes of space.  Caller ensures that
-   linebuf[] does not contain more pixels than that, unless the PICT
-   image from which it comes is corrupt.
+   rowRaster[] has 'rowSize' bytes of space.  Caller ensures that linebuf[]
+   does not contain more pixels than that, unless the PICT image from which it
+   comes is corrupt.
 -----------------------------------------------------------------------------*/
     unsigned int lineCursor;
         /* Cursor into linebuf[] -- the compressed data */
@@ -2609,10 +2717,12 @@ interpretCompressedLine(unsigned char * const linebuf,
         assert(rasterCursor <= rowSize);
     }
     if (verbose > 1)
-        pm_message("Got %u pixels for row", rasterCursor);
+        pm_message("Decompressed %u bytes into %u bytes for row",
+                   lineCursor, rasterCursor);
 }
 
 
+
 /* There is some confusion about when, in PICT, a line length is one byte and
   when it is two.  An Apple document says it is two bytes when the number of
   pixels in the row, padded, is > 250.  Ppmtopict generated PICTs that way
@@ -2642,11 +2752,11 @@ interpretCompressedLine(unsigned char * const linebuf,
 
 static void
 unpackCompressedBits(FILE *          const ifP,
-                     struct raster   const raster,
+                     struct Raster   const raster,
                      unsigned int    const rowBytes,
                      unsigned int    const bitsPerPixel) {
 /*----------------------------------------------------------------------------
-   Read the raster on file *ifP and place it in 'raster'.
+   Set the raster bytes of 'raster' with bytes read from *ifP.
 
    The data in the file is compressed with run length encoding and
    possibly packed multiple pixels per byte as well.
@@ -2665,6 +2775,9 @@ unpackCompressedBits(FILE *          const ifP,
     unsigned char * linebuf;
     unsigned int linebufSize;
 
+    if (verbose)
+        pm_message("Bits are packed");
+
     linebufSize = rowBytes;
     MALLOCARRAY(linebuf, linebufSize);
     if (linebuf == NULL)
@@ -2676,9 +2789,9 @@ unpackCompressedBits(FILE *          const ifP,
         unsigned int linelen;
 
         if (llsize == 2)
-            linelen = readWord();
+            linelen = readWord(ifP);
         else
-            linelen = readByte();
+            linelen = readByte(ifP);
 
         reportValidateCompressedLineLen(row, linelen, raster.rowSize);
 
@@ -2702,19 +2815,19 @@ static void
 unpackbits(FILE *           const ifP,
            struct Rect *    const boundsP,
            Word             const rowBytesArg,
-           int              const bitsPerPixel,
-           struct raster *  const rasterP) {
+           unsigned int     const bitsPerPixel,
+           struct Raster *  const rasterP) {
 
     unsigned int const rectHeight = boundsP->bottom - boundsP->top;
     unsigned int const rectWidth  = boundsP->right  - boundsP->left;
 
-    struct raster raster;
+    struct Raster raster;
     unsigned int rowBytes;
 
     stage = "unpacking packbits";
 
     if (verbose)
-        pm_message("rowBytes = %u, bitsPerPixel = %d",
+        pm_message("rowBytes = %u, bitsPerPixel = %u",
                    rowBytesArg, bitsPerPixel);
 
     allocateRaster(&raster, rectWidth, rectHeight, bitsPerPixel);
@@ -2754,33 +2867,33 @@ interpretRowBytesWord(Word           const rowBytesWord,
  * a pattern in the fabled complete version.
  */
 static void
-readPattern(void) {
+readPattern(FILE * const ifP) {
 
     Word PatType;
 
     stage = "Reading a pattern";
 
-    PatType = readWord();
+    PatType = readWord(ifP);
 
     switch (PatType) {
     case 2:
-        skip(8); /* old pattern data */
-        skip(5); /* RGB for pattern */
+        skip(ifP, 8); /* old pattern data */
+        skip(ifP, 5); /* RGB for pattern */
         break;
     case 1: {
         Word rowBytesWord;
         bool pixMap;
         unsigned int rowBytes;
-        struct pixMap p;
-        struct raster raster;
+        struct PixMap p;
+        struct Raster raster;
         struct RGBColor * ct;
 
-        skip(8); /* old pattern data */
-        rowBytesWord = readWord();
+        skip(ifP, 8); /* old pattern data */
+        rowBytesWord = readWord(ifP);
         interpretRowBytesWord(rowBytesWord, &pixMap, &rowBytes);
-        readPixmap(&p);
-        ct = readColorTable();
-        unpackbits(ifp, &p.Bounds, rowBytes, p.pixelSize, &raster);
+        readPixmap(ifP, &p);
+        ct = readColorTable(ifP);
+        unpackbits(ifP, &p.Bounds, rowBytes, p.pixelSize, &raster);
         freeRaster(raster);
         free(ct);
     } break;
@@ -2791,16 +2904,17 @@ readPattern(void) {
 
 
 
-/* these 3 do nothing but skip over their data! */
+/* These three do nothing but skip over their data! */
 
 static drawFn BkPixPat;
 
 static void
-BkPixPat(struct canvas * const canvasP,
-         blitList *      const blitListP,
+BkPixPat(FILE *          const ifP,
+         struct Canvas * const canvasP,
+         BlitList *      const blitListP,
          int             const version) {
 
-    readPattern();
+    readPattern(ifP);
 }
 
 
@@ -2808,11 +2922,12 @@ BkPixPat(struct canvas * const canvasP,
 static drawFn PnPixPat;
 
 static void
-PnPixPat(struct canvas * const canvasP,
-         blitList *      const blitListP,
+PnPixPat(FILE *          const ifP,
+         struct Canvas * const canvasP,
+         BlitList *      const blitListP,
          int             const version) {
 
-    readPattern();
+    readPattern(ifP);
 }
 
 
@@ -2820,17 +2935,20 @@ PnPixPat(struct canvas * const canvasP,
 static drawFn FillPixPat;
 
 static void
-FillPixPat(struct canvas * const canvasP,
-           blitList *      const blitListP,
+FillPixPat(FILE *          const ifP,
+           struct Canvas * const canvasP,
+           BlitList *      const blitListP,
            int             const version) {
 
-    readPattern();
+    readPattern(ifP);
 }
 
 
 
 static void
-read8x8Pattern(struct Pattern * const pat) {
+read8x8Pattern(FILE *           const ifP,
+               struct Pattern * const pat) {
+
     unsigned char buf[8];
     unsigned char * exp;
     unsigned int len;
@@ -2838,7 +2956,7 @@ read8x8Pattern(struct Pattern * const pat) {
     unsigned int i;
 
     len = 8;  /* initial value */
-    readBytes(ifp, len, buf);
+    readBytes(ifP, len, buf);
     if (verbose) {
         pm_message("pattern: %02x%02x%02x%02x",
                    buf[0], buf[1], buf[2], buf[3]);
@@ -2855,11 +2973,12 @@ read8x8Pattern(struct Pattern * const pat) {
 static drawFn BkPat;
 
 static void
-BkPat(struct canvas * const canvasP,
-      blitList *      const blitListP,
+BkPat(FILE *          const ifP,
+      struct Canvas * const canvasP,
+      BlitList *      const blitListP,
       int             const version) {
 
-    read8x8Pattern(&bkpat);
+    read8x8Pattern(ifP, &bkpat);
 }
 
 
@@ -2867,11 +2986,12 @@ BkPat(struct canvas * const canvasP,
 static drawFn PnPat;
 
 static void
-PnPat(struct canvas * const canvasP,
-      blitList *      const blitListP,
+PnPat(FILE *          const ifP,
+      struct Canvas * const canvasP,
+      BlitList *      const blitListP,
       int             const version) {
 
-    read8x8Pattern(&pen_pat);
+    read8x8Pattern(ifP, &pen_pat);
 }
 
 
@@ -2879,11 +2999,12 @@ PnPat(struct canvas * const canvasP,
 static drawFn FillPat;
 
 static void
-FillPat(struct canvas * const canvasP,
-        blitList *      const blitListP,
+FillPat(FILE *          const ifP,
+        struct Canvas * const canvasP,
+        BlitList *      const blitListP,
         int             const version) {
 
-    read8x8Pattern(&fillpat);
+    read8x8Pattern(ifP, &fillpat);
 }
 
 
@@ -2891,12 +3012,14 @@ FillPat(struct canvas * const canvasP,
 static drawFn PnSize;
 
 static void
-PnSize(struct canvas * const canvasP,
-       blitList *      const blitListP,
+PnSize(FILE *          const ifP,
+       struct Canvas * const canvasP,
+       BlitList *      const blitListP,
        int             const version) {
 
-    pen_height = readWord();
-    pen_width = readWord();
+    pen_height = readWord(ifP);
+    pen_width  = readWord(ifP);
+
     if (verbose)
         pm_message("pen size %d x %d", pen_width, pen_height);
 }
@@ -2906,28 +3029,31 @@ PnSize(struct canvas * const canvasP,
 static drawFn PnSize;
 
 static void
-PnMode(struct canvas * const canvasP,
-       blitList *      const blitListP,
+PnMode(FILE *          const ifP,
+       struct Canvas * const canvasP,
+       BlitList *      const blitListP,
        int             const version) {
 
-    pen_mode = readWord();
+    pen_mode = readWord(ifP);
 
     if (pen_mode >= 8 && pen_mode < 15)
         pen_mode -= 8;
     if (verbose)
         pm_message("pen transfer mode = %s",
-            const_name(transfer_name, pen_mode));
+            constName(transfer_name, pen_mode));
 
-    pen_trf = transfer(pen_mode);
+    pen_trf = transferFunctionForMode(pen_mode);
 }
 
 
 
 static void
-readRgb(struct RGBColor * const rgb) {
-    rgb->red = readWord();
-    rgb->grn = readWord();
-    rgb->blu = readWord();
+readRgb(FILE *            const ifP,
+        struct RGBColor * const rgb) {
+
+    rgb->red = readWord(ifP);
+    rgb->grn = readWord(ifP);
+    rgb->blu = readWord(ifP);
 }
 
 
@@ -2935,11 +3061,13 @@ readRgb(struct RGBColor * const rgb) {
 static drawFn RGBFgCol;
 
 static void
-RGBFgCol(struct canvas * const canvasP,
-         blitList *      const blitListP,
+RGBFgCol(FILE *          const ifP,
+         struct Canvas * const canvasP,
+         BlitList *      const blitListP,
          int             const version) {
 
-    readRgb(&foreground);
+    readRgb(ifP, &foreground);
+
     if (verbose)
         pm_message("foreground now [%d,%d,%d]",
             foreground.red, foreground.grn, foreground.blu);
@@ -2950,11 +3078,13 @@ RGBFgCol(struct canvas * const canvasP,
 static drawFn RGBBkCol;
 
 static void
-RGBBkCol(struct canvas * const canvasP,
-         blitList *      const blitListP,
+RGBBkCol(FILE *          const ifP,
+         struct Canvas * const canvasP,
+         BlitList *      const blitListP,
          int             const version) {
 
-    readRgb(&background);
+    readRgb(ifP, &background);
+
     if (verbose)
         pm_message("background now [%d,%d,%d]",
             background.red, background.grn, background.blu);
@@ -2978,7 +3108,7 @@ pixelIndex(struct Rect  const picFrame,
 
 
 static void
-drawPixel(struct canvas *   const canvasP,
+drawPixel(struct Canvas *   const canvasP,
           int               const x,
           int               const y,
           struct RGBColor * const clr,
@@ -3006,7 +3136,7 @@ drawPixel(struct canvas *   const canvasP,
 
 
 static void
-drawPenRect(struct canvas * const canvasP,
+drawPenRect(struct Canvas * const canvasP,
             struct Rect *   const rP) {
 
     if (!rectisnull(rP)) {
@@ -3051,7 +3181,7 @@ drawPenRect(struct canvas * const canvasP,
 
 
 static void
-drawPen(struct canvas * const canvasP,
+drawPen(struct Canvas * const canvasP,
         int             const x,
         int             const y) {
 
@@ -3068,6 +3198,8 @@ drawPen(struct canvas * const canvasP,
     drawPenRect(canvasP, &clippedPenrect);
 }
 
+
+
 /*
  * Digital Line Drawing
  * by Paul Heckbert
@@ -3082,7 +3214,7 @@ drawPen(struct canvas * const canvasP,
  * Paul Heckbert    3 Sep 85
  */
 static void
-scanLine(struct canvas * const canvasP,
+scanLine(struct Canvas * const canvasP,
          short           const x1,
          short           const y1,
          short           const x2,
@@ -3133,16 +3265,19 @@ scanLine(struct canvas * const canvasP,
 static drawFn Line;
 
 static void
-Line(struct canvas * const canvasP,
-     blitList *      const blitListP,
+Line(FILE *          const ifP,
+     struct Canvas * const canvasP,
+     BlitList *      const blitListP,
      int             const version) {
 
   struct Point p1;
-  readPoint(&p1);
-  readPoint(&current);
+  readPoint(ifP, &p1);
+  readPoint(ifP, &current);
+
   if (verbose)
     pm_message("(%d,%d) to (%d, %d)",
            p1.x,p1.y,current.x,current.y);
+
   scanLine(canvasP, p1.x,p1.y,current.x,current.y);
 }
 
@@ -3151,12 +3286,15 @@ Line(struct canvas * const canvasP,
 static drawFn LineFrom;
 
 static void
-LineFrom(struct canvas * const canvasP,
-         blitList *      const blitListP,
+LineFrom(FILE *          const ifP,
+         struct Canvas * const canvasP,
+         BlitList *      const blitListP,
          int             const version) {
 
     struct Point p1;
-    readPoint(&p1);
+
+    readPoint(ifP, &p1);
+
     if (verbose)
         pm_message("(%d,%d) to (%d, %d)", current.x, current.y, p1.x, p1.y);
 
@@ -3172,15 +3310,19 @@ LineFrom(struct canvas * const canvasP,
 static drawFn ShortLine;
 
 static void
-ShortLine(struct canvas * const canvasP,
-          blitList *      const blitListP,
+ShortLine(FILE *          const ifP,
+          struct Canvas * const canvasP,
+          BlitList *      const blitListP,
           int             const version) {
 
     struct Point p1;
-    readPoint(&p1);
-    readShortPoint(&current);
+
+    readPoint(ifP,&p1);
+    readShortPoint(ifP, &current);
+
     if (verbose)
         pm_message("(%d,%d) delta (%d, %d)", p1.x, p1.y, current.x, current.y);
+
     current.x += p1.x;
     current.y += p1.y;
 
@@ -3193,19 +3335,25 @@ ShortLine(struct canvas * const canvasP,
 static drawFn ShortLineFrom;
 
 static void
-ShortLineFrom(struct canvas * const canvasP,
-              blitList *      const blitListP,
+ShortLineFrom(FILE *          const ifP,
+              struct Canvas * const canvasP,
+              BlitList *      const blitListP,
               int             const version) {
 
     struct Point p1;
-    readShortPoint(&p1);
+
+    readShortPoint(ifP, &p1);
+
     if (verbose)
         pm_message("(%d,%d) delta (%d, %d)",
                    current.x,current.y,p1.x,p1.y);
+
     p1.x += current.x;
     p1.y += current.y;
+
     if (!blitListP)
         scanLine(canvasP, current.x, current.y, p1.x, p1.y);
+
     current.x = p1.x;
     current.y = p1.y;
 }
@@ -3213,7 +3361,7 @@ ShortLineFrom(struct canvas * const canvasP,
 
 
 static void
-doPaintRect(struct canvas * const canvasP,
+doPaintRect(struct Canvas * const canvasP,
             struct Rect     const prect) {
 
     struct Rect rect;
@@ -3231,11 +3379,13 @@ doPaintRect(struct canvas * const canvasP,
 static drawFn paintRect;
 
 static void
-paintRect(struct canvas * const canvasP,
-          blitList *      const blitListP,
+paintRect(FILE *          const ifP,
+          struct Canvas * const canvasP,
+          BlitList *      const blitListP,
           int             const version) {
 
-    readRect(&cur_rect);
+    readRect(ifP, &cur_rect);
+
     if (!blitListP)
         doPaintRect(canvasP, cur_rect);
 }
@@ -3245,8 +3395,9 @@ paintRect(struct canvas * const canvasP,
 static drawFn paintSameRect;
 
 static void
-paintSameRect(struct canvas * const canvasP,
-              blitList *      const blitListP,
+paintSameRect(FILE *          const ifP,
+              struct Canvas * const canvasP,
+              BlitList *      const blitListP,
               int             const version) {
 
     if (!blitListP)
@@ -3256,7 +3407,7 @@ paintSameRect(struct canvas * const canvasP,
 
 
 static void
-doFrameRect(struct canvas * const canvasP,
+doFrameRect(struct Canvas * const canvasP,
             struct Rect     const rect) {
 
     if (verbose)
@@ -3282,11 +3433,12 @@ doFrameRect(struct canvas * const canvasP,
 static drawFn frameRect;
 
 static void
-frameRect(struct canvas * const canvasP,
-          blitList *      const blitListP,
+frameRect(FILE *          const ifP,
+          struct Canvas * const canvasP,
+          BlitList *      const blitListP,
           int             const version) {
 
-    readRect(&cur_rect);
+    readRect(ifP, &cur_rect);
 
     if (!blitListP)
         doFrameRect(canvasP, cur_rect);
@@ -3297,8 +3449,9 @@ frameRect(struct canvas * const canvasP,
 static drawFn frameSameRect;
 
 static void
-frameSameRect(struct canvas * const canvasP,
-              blitList *      const blitListP,
+frameSameRect(FILE *          const ifP,
+              struct Canvas * const canvasP,
+              BlitList *      const blitListP,
               int             const version) {
 
     if (!blitListP)
@@ -3343,7 +3496,7 @@ polySort(int const sort_index, struct Point points[]) {
 /* Watch out for the lack of error checking in the next two functions ... */
 
 static void
-scanPoly(struct canvas * const canvasP,
+scanPoly(struct Canvas * const canvasP,
          int             const np,
          struct Point          pts[]) {
 
@@ -3448,17 +3601,22 @@ scanPoly(struct canvas * const canvasP,
 static drawFn paintPoly;
 
 static void
-paintPoly(struct canvas * const canvasP,
-          blitList *      const blitListP,
+paintPoly(FILE *          const ifP,
+          struct Canvas * const canvasP,
+          BlitList *      const blitListP,
           int             const version) {
 
   struct Rect bb;
   struct Point pts[100];
-  int i, np = (readWord() - 10) >> 2;
+  int i;
+  int np;
 
-  readRect(&bb);
-  for (i=0; i<np; ++i)
-    readPoint(&pts[i]);
+  np = (readWord(ifP) - 10) >> 2;
+
+  readRect(ifP, &bb);
+
+  for (i = 0; i < np; ++i)
+      readPoint(ifP, &pts[i]);
 
   /* scan convert poly ... */
   if (!blitListP)
@@ -3470,11 +3628,14 @@ paintPoly(struct canvas * const canvasP,
 static drawFn PnLocHFrac;
 
 static void
-PnLocHFrac(struct canvas * const canvasP,
-           blitList *      const blitListP,
+PnLocHFrac(FILE *          const ifP,
+           struct Canvas * const canvasP,
+           BlitList *      const blitListP,
            int             const version) {
 
-    Word frac = readWord();
+    Word frac;
+
+    frac = readWord(ifP);
 
     if (verbose)
         pm_message("PnLocHFrac = %d", frac);
@@ -3485,20 +3646,21 @@ PnLocHFrac(struct canvas * const canvasP,
 static drawFn TxMode;
 
 static void
-TxMode(struct canvas * const canvasP,
-       blitList *      const blitListP,
+TxMode(FILE *          const ifP,
+       struct Canvas * const canvasP,
+       BlitList *      const blitListP,
        int             const version) {
 
-    text_mode = readWord();
+    text_mode = readWord(ifP);
 
     if (text_mode >= 8 && text_mode < 15)
         text_mode -= 8;
     if (verbose)
         pm_message("text transfer mode = %s",
-            const_name(transfer_name, text_mode));
+            constName(transfer_name, text_mode));
 
     /* ignore the text mask bit 'cause we don't handle it yet */
-    text_trf = transfer(text_mode & ~64);
+    text_trf = transferFunctionForMode(text_mode & ~64);
 }
 
 
@@ -3506,13 +3668,15 @@ TxMode(struct canvas * const canvasP,
 static drawFn TxFont;
 
 static void
-TxFont(struct canvas * const canvasP,
-       blitList *      const blitListP,
+TxFont(FILE *          const ifP,
+       struct Canvas * const canvasP,
+       BlitList *      const blitListP,
        int             const version) {
 
-    text_font = readWord();
+    text_font = readWord(ifP);
+
     if (verbose)
-        pm_message("text font %s", const_name(font_name, text_font));
+        pm_message("text font %s", constName(font_name, text_font));
 }
 
 
@@ -3520,11 +3684,13 @@ TxFont(struct canvas * const canvasP,
 static drawFn TxFace;
 
 static void
-TxFace(struct canvas * const canvasP,
-       blitList *      const blitListP,
+TxFace(FILE *          const ifP,
+       struct Canvas * const canvasP,
+       BlitList *      const blitListP,
        int             const version) {
 
-    text_face = readByte();
+    text_face = readByte(ifP);
+
     if (verbose)
         pm_message("text face %d", text_face);
 }
@@ -3534,11 +3700,13 @@ TxFace(struct canvas * const canvasP,
 static drawFn TxSize;
 
 static void
-TxSize(struct canvas * const canvasP,
-       blitList *      const blitListP,
+TxSize(FILE *          const ifP,
+       struct Canvas * const canvasP,
+       BlitList *      const blitListP,
        int             const version) {
 
-    text_size = readWord();
+    text_size = readWord(ifP);
+
     if (verbose)
         pm_message("text size %d", text_size);
 }
@@ -3546,9 +3714,10 @@ TxSize(struct canvas * const canvasP,
 
 
 static void
-skipText(blitList * const blitListP) {
+skipText(FILE *     const ifP,
+         BlitList * const blitListP) {
 
-    skip(readByte());
+    skip(ifP, readByte(ifP));
 
     blitListP->unblittableText = true;
 }
@@ -3571,7 +3740,7 @@ getFont(int const font,
         int const style) {
 
     int closeness, bestcloseness;
-    struct fontinfo* fi, *best;
+    struct FontInfo* fi, *best;
 
     best = 0;
     for (fi = fontlist; fi; fi = fi->next) {
@@ -3631,7 +3800,8 @@ rotate(int * const x,
 
 
 static void
-doPsText(struct canvas * const canvasP,
+doPsText(FILE *          const ifP,
+         struct Canvas * const canvasP,
          Word            const tx,
          Word            const ty) {
 
@@ -3648,12 +3818,12 @@ doPsText(struct canvas * const canvasP,
         ps_cent_set = 1;
     }
 
-    len = readByte();
+    len = readByte(ifP);
 
     /* XXX this width calculation is not completely correct */
     width = 0;
     for (i = 0; i < len; i++) {
-        ch = str[i] = readByte();
+        ch = str[i] = readByte(ifP);
         if (tfont->glyph[ch])
             width += tfont->glyph[ch]->xadd;
     }
@@ -3700,27 +3870,28 @@ doPsText(struct canvas * const canvasP,
 
 
 static void
-doText(struct canvas *  const canvasP,
-       blitList *       const blitListP,
+doText(FILE *           const ifP,
+       struct Canvas *  const canvasP,
+       BlitList *       const blitListP,
        Word             const startx,
        Word             const starty) {
 
     if (blitListP)
-        skipText(blitListP);
+        skipText(ifP, blitListP);
     else {
         if (!(tfont = getFont(text_font, text_size, text_face)))
             tfont = pbm_defaultfont("bdf");
 
         if (ps_text)
-            doPsText(canvasP, startx, starty);
+            doPsText(ifP, canvasP, startx, starty);
         else {
             int len;
             Word x, y;
 
             x = startx;
             y = starty;
-            for (len = readByte(); len > 0; --len) {
-                struct glyph* const glyph = tfont->glyph[readByte()];
+            for (len = readByte(ifP); len > 0; --len) {
+                struct glyph* const glyph = tfont->glyph[readByte(ifP)];
                 if (glyph) {
                     int dy;
                     int h;
@@ -3750,15 +3921,16 @@ doText(struct canvas *  const canvasP,
 static drawFn LongText;
 
 static void
-LongText(struct canvas * const canvasP,
-         blitList *      const blitListP,
+LongText(FILE *          const ifP,
+         struct Canvas * const canvasP,
+         BlitList *      const blitListP,
          int             const version) {
 
     struct Point p;
 
-    readPoint(&p);
+    readPoint(ifP, &p);
 
-    doText(canvasP, blitListP, p.x, p.y);
+    doText(ifP, canvasP, blitListP, p.x, p.y);
 }
 
 
@@ -3766,13 +3938,14 @@ LongText(struct canvas * const canvasP,
 static drawFn DHText;
 
 static void
-DHText(struct canvas * const canvasP,
-       blitList *      const blitListP,
+DHText(FILE *          const ifP,
+       struct Canvas * const canvasP,
+       BlitList *      const blitListP,
        int             const version) {
 
-    current.x += readByte();
+    current.x += readByte(ifP);
 
-    doText(canvasP, blitListP, current.x, current.y);
+    doText(ifP, canvasP, blitListP, current.x, current.y);
 }
 
 
@@ -3780,13 +3953,14 @@ DHText(struct canvas * const canvasP,
 static drawFn DVText;
 
 static void
-DVText(struct canvas * const canvasP,
-       blitList *      const blitListP,
+DVText(FILE *          const ifP,
+       struct Canvas * const canvasP,
+       BlitList *      const blitListP,
        int             const version) {
 
-    current.y += readByte();
+    current.y += readByte(ifP);
 
-    doText(canvasP, blitListP, current.x, current.y);
+    doText(ifP, canvasP, blitListP, current.x, current.y);
 }
 
 
@@ -3794,13 +3968,15 @@ DVText(struct canvas * const canvasP,
 static drawFn DHDVText;
 
 static void
-DHDVText(struct canvas * const canvasP,
-         blitList *      const blitListP,
+DHDVText(FILE *          const ifP,
+         struct Canvas * const canvasP,
+         BlitList *      const blitListP,
          int             const version) {
+
     Byte dh, dv;
 
-    dh = readByte();
-    dv = readByte();
+    dh = readByte(ifP);
+    dv = readByte(ifP);
 
     if (verbose)
         pm_message("dh, dv = %d, %d", dh, dv);
@@ -3808,7 +3984,7 @@ DHDVText(struct canvas * const canvasP,
     current.x += dh;
     current.y += dv;
 
-    doText(canvasP, blitListP, current.x, current.y);
+    doText(ifP, canvasP, blitListP, current.x, current.y);
 }
 
 
@@ -3818,50 +3994,51 @@ DHDVText(struct canvas * const canvasP,
  */
 
 static void
-directBits(struct canvas * const canvasP,
-           blitList *      const blitListP,
+directBits(FILE *          const ifP,
+           struct Canvas * const canvasP,
+           BlitList *      const blitListP,
            unsigned int    const pictVersion,
            bool            const skipRegion) {
 
-    struct pixMap   p;
+    struct PixMap   p;
     struct Rect     srcRect;
     struct Rect     dstRect;
-    struct raster   raster;
+    struct Raster   raster;
     Word            mode;
 
     /* skip fake len, and fake EOF */
-    skip(4);    /* Ptr baseAddr == 0x000000ff */
-    readWord();    /* version */
-    readRect(&p.Bounds);
-    p.packType = readWord();
-    p.packSize = readLong();
-    p.hRes = readLong();
-    p.vRes = readLong();
-    p.pixelType = readWord();
-    p.pixelSize = readWord();
-    p.pixelSize = readWord();    /* XXX twice??? */
-    p.cmpCount = readWord();
-    p.cmpSize = readWord();
-    p.planeBytes = readLong();
-    p.pmTable = readLong();
-    p.pmReserved = readLong();
-
-    readRect(&srcRect);
+    skip(ifP, 4);    /* Ptr baseAddr == 0x000000ff */
+    readWord(ifP);    /* version */
+    readRect(ifP, &p.Bounds);
+    p.packType   = readWord(ifP);
+    p.packSize   = readLong(ifP);
+    p.hRes       = readLong(ifP);
+    p.vRes       = readLong(ifP);
+    p.pixelType  = readWord(ifP);
+    p.pixelSize  = readWord(ifP);
+    p.pixelSize  = readWord(ifP);    /* XXX twice??? */
+    p.cmpCount   = readWord(ifP);
+    p.cmpSize    = readWord(ifP);
+    p.planeBytes = readLong(ifP);
+    p.pmTable    = readLong(ifP);
+    p.pmReserved = readLong(ifP);
+
+    readRect(ifP, &srcRect);
     if (verbose)
         dumpRect("source rectangle:", srcRect);
 
-    readRect(&dstRect);
+    readRect(ifP, &dstRect);
     if (verbose)
         dumpRect("destination rectangle:", dstRect);
 
-    mode = readWord();
+    mode = readWord(ifP);
     if (verbose)
-        pm_message("transfer mode = %s", const_name(transfer_name, mode));
+        pm_message("transfer mode = %s", constName(transfer_name, mode));
 
     if (skipRegion)
-        skip_poly_or_region(canvasP, blitListP, pictVersion);
+        skipPolyOrRegion(ifP, canvasP, blitListP, pictVersion);
 
-    unpackbits(ifp, &p.Bounds, 0, p.pixelSize, &raster);
+    unpackbits(ifP, &p.Bounds, 0, p.pixelSize, &raster);
 
     blit(srcRect, p.Bounds, raster, canvasP, blitListP, p.pixelSize,
          dstRect, picFrame, rowlen, NULL, mode);
@@ -3877,11 +4054,12 @@ directBits(struct canvas * const canvasP,
 static drawFn DirectBitsRect;
 
 static void
-DirectBitsRect(struct canvas * const canvasP,
-               blitList *      const blitListP,
+DirectBitsRect(FILE *          const ifP,
+               struct Canvas * const canvasP,
+               BlitList *      const blitListP,
                int             const version) {
 
-    directBits(canvasP, blitListP, version, SKIP_REGION_FALSE);
+    directBits(ifP, canvasP, blitListP, version, SKIP_REGION_FALSE);
 }
 
 
@@ -3889,18 +4067,20 @@ DirectBitsRect(struct canvas * const canvasP,
 static drawFn DirectBitsRgn;
 
 static void
-DirectBitsRgn(struct canvas * const canvasP,
-              blitList *      const blitListP,
+DirectBitsRgn(FILE *          const ifP,
+              struct Canvas * const canvasP,
+              BlitList *      const blitListP,
               int             const version) {
 
-    directBits(canvasP, blitListP, version, SKIP_REGION_TRUE);
+    directBits(ifP, canvasP, blitListP, version, SKIP_REGION_TRUE);
 }
 
 
 
 static void
-doPixmap(struct canvas * const canvasP,
-         blitList *      const blitListP,
+doPixmap(FILE *          const ifP,
+         struct Canvas * const canvasP,
+         BlitList *      const blitListP,
          int             const version,
          Word            const rowBytes,
          int             const is_region) {
@@ -3908,47 +4088,47 @@ doPixmap(struct canvas * const canvasP,
    Do a paletted image.
 -----------------------------------------------------------------------------*/
     Word mode;
-    struct pixMap p;
-    struct raster raster;
-    struct RGBColor * color_table;
+    struct PixMap p;
+    struct Raster raster;
+    struct RGBColor * colorTable;
     struct Rect srcRect;
     struct Rect dstRect;
 
-    readPixmap(&p);
+    readPixmap(ifP, &p);
 
     if (verbose)
         pm_message("%u x %u paletted image",
                    p.Bounds.right - p.Bounds.left,
                    p.Bounds.bottom - p.Bounds.top);
 
-    color_table = readColorTable();
+    colorTable = readColorTable(ifP);
 
-    readRect(&srcRect);
+    readRect(ifP, &srcRect);
 
     if (verbose)
         dumpRect("source rectangle:", srcRect);
 
-    readRect(&dstRect);
+    readRect(ifP, &dstRect);
 
     if (verbose)
         dumpRect("destination rectangle:", dstRect);
 
-    mode = readWord();
+    mode = readWord(ifP);
 
     if (verbose)
-        pm_message("transfer mode = %s", const_name(transfer_name, mode));
+        pm_message("transfer mode = %s", constName(transfer_name, mode));
 
     if (is_region)
-        skip_poly_or_region(canvasP, blitListP, version);
+        skipPolyOrRegion(ifP, canvasP, blitListP, version);
 
     stage = "unpacking rectangle";
 
-    unpackbits(ifp, &p.Bounds, rowBytes, p.pixelSize, &raster);
+    unpackbits(ifP, &p.Bounds, rowBytes, p.pixelSize, &raster);
 
     blit(srcRect, p.Bounds, raster, canvasP, blitListP, 8,
-         dstRect, picFrame, rowlen, color_table, mode);
+         dstRect, picFrame, rowlen, colorTable, mode);
 
-    free(color_table);
+    free(colorTable);
     freeRaster(raster);
 }
 
@@ -3956,8 +4136,8 @@ doPixmap(struct canvas * const canvasP,
 
 static void
 doBitmap(FILE *          const ifP,
-         struct canvas * const canvasP,
-         blitList *      const blitListP,
+         struct Canvas * const canvasP,
+         BlitList *      const blitListP,
          int             const version,
          int             const rowBytes,
          int             const is_region) {
@@ -3970,22 +4150,22 @@ doBitmap(FILE *          const ifP,
     struct Rect srcRect;
     struct Rect dstRect;
     Word mode;
-    struct raster raster;
+    struct Raster raster;
         /* This raster contains padding on the right to make a multiple
            of 16 pixels per row.
         */
     static struct RGBColor color_table[] = {
         {65535L, 65535L, 65535L}, {0, 0, 0} };
 
-    readRect(&Bounds);
-    readRect(&srcRect);
-    readRect(&dstRect);
-    mode = readWord();
+    readRect(ifP, &Bounds);
+    readRect(ifP, &srcRect);
+    readRect(ifP, &dstRect);
+    mode = readWord(ifP);
     if (verbose)
-        pm_message("transfer mode = %s", const_name(transfer_name, mode));
+        pm_message("transfer mode = %s", constName(transfer_name, mode));
 
     if (is_region)
-        skip_poly_or_region(canvasP, blitListP, version);
+        skipPolyOrRegion(ifP, canvasP, blitListP, version);
 
     stage = "unpacking rectangle";
 
@@ -4002,8 +4182,9 @@ doBitmap(FILE *          const ifP,
 static drawFn BitsRect;
 
 static void
-BitsRect(struct canvas * const canvasP,
-         blitList *      const blitListP,
+BitsRect(FILE *          const ifP,
+         struct Canvas * const canvasP,
+         BlitList *      const blitListP,
          int             const version) {
 
     Word rowBytesWord;
@@ -4011,14 +4192,14 @@ BitsRect(struct canvas * const canvasP,
     unsigned int rowBytes;
 
     stage = "Reading rowBytes word for bitsrect";
-    rowBytesWord = readWord();
+    rowBytesWord = readWord(ifP);
 
     interpretRowBytesWord(rowBytesWord, &pixMap, &rowBytes);
 
     if (pixMap)
-        doPixmap(canvasP, blitListP, version, rowBytes, 0);
+        doPixmap(ifP, canvasP, blitListP, version, rowBytes, 0);
     else
-        doBitmap(ifp, canvasP, blitListP, version, rowBytes, 0);
+        doBitmap(ifP, canvasP, blitListP, version, rowBytes, 0);
 }
 
 
@@ -4026,8 +4207,9 @@ BitsRect(struct canvas * const canvasP,
 static drawFn BitsRegion;
 
 static void
-BitsRegion(struct canvas * const canvasP,
-           blitList *      const blitListP,
+BitsRegion(FILE *          const ifP,
+           struct Canvas * const canvasP,
+           BlitList *      const blitListP,
            int             const version) {
 
     Word rowBytesWord;
@@ -4035,14 +4217,14 @@ BitsRegion(struct canvas * const canvasP,
     unsigned int rowBytes;
 
     stage = "Reading rowBytes for bitsregion";
-    rowBytesWord = readWord();
+    rowBytesWord = readWord(ifP);
 
     interpretRowBytesWord(rowBytesWord, &pixMap, &rowBytes);
 
     if (pixMap)
-        doPixmap(canvasP, blitListP, version, rowBytes, 1);
+        doPixmap(ifP, canvasP, blitListP, version, rowBytes, 1);
     else
-        doBitmap(ifp, canvasP, blitListP, version, rowBytes, 1);
+        doBitmap(ifP, canvasP, blitListP, version, rowBytes, 1);
 }
 
 
@@ -4051,7 +4233,7 @@ BitsRegion(struct canvas * const canvasP,
   * See http://developer.apple.com/techpubs/mac/QuickDraw/QuickDraw-461.html
   * for opcode description
   */
-static struct opdef const optable[] = {
+static struct Opdef const optable[] = {
 /* 0x00 */  { "NOP", 0, NULL, "nop" },
 /* 0x01 */  { "ClipRgn", NA, ClipRgn, "clip region" },
 /* 0x02 */  { "BkPat", 8, BkPat, "background pattern" },
@@ -4167,14 +4349,14 @@ static struct opdef const optable[] = {
 /* 0x6d */  RESERVED_OP(4),
 /* 0x6e */  RESERVED_OP(4),
 /* 0x6f */  RESERVED_OP(4),
-/* 0x70 */  { "framePoly", NA, skip_poly_or_region, "poly" },
+/* 0x70 */  { "framePoly", NA, skipPolyOrRegion, "poly" },
 /* 0x71 */  { "paintPoly", NA, paintPoly, "poly" },
-/* 0x72 */  { "erasePoly", NA, skip_poly_or_region, "poly" },
-/* 0x73 */  { "invertPoly", NA, skip_poly_or_region, "poly" },
-/* 0x74 */  { "fillPoly", NA, skip_poly_or_region, "poly" },
-/* 0x75 */  RESERVED_OP_F(skip_poly_or_region),
-/* 0x76 */  RESERVED_OP_F(skip_poly_or_region),
-/* 0x77 */  RESERVED_OP_F(skip_poly_or_region),
+/* 0x72 */  { "erasePoly", NA, skipPolyOrRegion, "poly" },
+/* 0x73 */  { "invertPoly", NA, skipPolyOrRegion, "poly" },
+/* 0x74 */  { "fillPoly", NA, skipPolyOrRegion, "poly" },
+/* 0x75 */  RESERVED_OP_F(skipPolyOrRegion),
+/* 0x76 */  RESERVED_OP_F(skipPolyOrRegion),
+/* 0x77 */  RESERVED_OP_F(skipPolyOrRegion),
 /* 0x78 */  { "frameSamePoly", 0, NULL, "poly (NYI)" },
 /* 0x79 */  { "paintSamePoly", 0, NULL, "poly (NYI)" },
 /* 0x7a */  { "eraseSamePoly", 0, NULL, "poly (NYI)" },
@@ -4183,14 +4365,14 @@ static struct opdef const optable[] = {
 /* 0x7d */  RESERVED_OP(0),
 /* 0x7e */  RESERVED_OP(0),
 /* 0x7f */  RESERVED_OP(0),
-/* 0x80 */  { "frameRgn", NA, skip_poly_or_region, "region" },
-/* 0x81 */  { "paintRgn", NA, skip_poly_or_region, "region" },
-/* 0x82 */  { "eraseRgn", NA, skip_poly_or_region, "region" },
-/* 0x83 */  { "invertRgn", NA, skip_poly_or_region, "region" },
-/* 0x84 */  { "fillRgn", NA, skip_poly_or_region, "region" },
-/* 0x85 */  RESERVED_OP_F(skip_poly_or_region),
-/* 0x86 */  RESERVED_OP_F(skip_poly_or_region),
-/* 0x87 */  RESERVED_OP_F(skip_poly_or_region),
+/* 0x80 */  { "frameRgn", NA, skipPolyOrRegion, "region" },
+/* 0x81 */  { "paintRgn", NA, skipPolyOrRegion, "region" },
+/* 0x82 */  { "eraseRgn", NA, skipPolyOrRegion, "region" },
+/* 0x83 */  { "invertRgn", NA, skipPolyOrRegion, "region" },
+/* 0x84 */  { "fillRgn", NA, skipPolyOrRegion, "region" },
+/* 0x85 */  RESERVED_OP_F(skipPolyOrRegion),
+/* 0x86 */  RESERVED_OP_F(skipPolyOrRegion),
+/* 0x87 */  RESERVED_OP_F(skipPolyOrRegion),
 /* 0x88 */  { "frameSameRgn", 0, NULL, "region (NYI)" },
 /* 0x89 */  { "paintSameRgn", 0, NULL, "region (NYI)" },
 /* 0x8a */  { "eraseSameRgn", 0, NULL, "region (NYI)" },
@@ -4225,9 +4407,10 @@ static struct opdef const optable[] = {
 
 
 static void
-processOpcode(Word            const opcode,
-              struct canvas * const canvasP,
-              blitList *      const blitListP,
+processOpcode(FILE *          const ifP,
+              Word            const opcode,
+              struct Canvas * const canvasP,
+              BlitList *      const blitListP,
               unsigned int    const version) {
 
     if (opcode < 0xa2) {
@@ -4240,15 +4423,15 @@ processOpcode(Word            const opcode,
         }
 
         if (optable[opcode].impl != NULL)
-            (*optable[opcode].impl)(canvasP, blitListP, version);
+            (*optable[opcode].impl)(ifP, canvasP, blitListP, version);
         else if (optable[opcode].len >= 0)
-            skip(optable[opcode].len);
+            skip(ifP, optable[opcode].len);
         else {
             /* It's a special length code */
             switch (optable[opcode].len) {
             case WORD_LEN: {
-                Word const len = readWord();
-                skip(len);
+                Word const len = readWord(ifP);
+                skip(ifP, len);
             } break;
             default:
                 pm_error("can't do length %d", optable[opcode].len);
@@ -4258,12 +4441,12 @@ processOpcode(Word            const opcode,
         if (verbose)
             pm_message("HeaderOp");
         stage = "HeaderOp";
-        skip(24);
+        skip(ifP, 24);
     } else if (opcode >= 0xa2 && opcode <= 0xaf) {
         stage = "skipping reserved";
         if (verbose)
             pm_message("%s 0x%x", stage, opcode);
-        skip(readWord());
+        skip(ifP, readWord(ifP));
     } else if (opcode >= 0xb0 && opcode <= 0xcf) {
         /* just a reserved opcode, no data */
         if (verbose)
@@ -4272,12 +4455,12 @@ processOpcode(Word            const opcode,
         stage = "skipping reserved";
         if (verbose)
             pm_message("%s 0x%x", stage, opcode);
-        skip(readLong());
+        skip(ifP, readLong(ifP));
     } else if (opcode >= 0x100 && opcode <= 0x7fff) {
         stage = "skipping reserved";
         if (verbose)
             pm_message("%s 0x%x", stage, opcode);
-        skip((opcode >> 7) & 255);
+        skip(ifP, (opcode >> 7) & 255);
     } else if (opcode >= 0x8000 && opcode <= 0x80ff) {
         /* just a reserved opcode, no data */
         if (verbose)
@@ -4286,7 +4469,7 @@ processOpcode(Word            const opcode,
         stage = "skipping reserved";
         if (verbose)
             pm_message("%s 0x%x", stage, opcode);
-        skip(readLong());
+        skip(ifP, readLong(ifP));
     } else
         pm_error("This program does not understand opcode 0x%04x", opcode);
 }
@@ -4294,15 +4477,23 @@ processOpcode(Word            const opcode,
 
 
 static void
-interpretPict(FILE * const ofP) {
+interpretPict(FILE *       const ifP,
+              FILE *       const ofP,
+              bool         const noheader,
+              bool         const fullres,
+              bool         const quickdraw,
+              unsigned int const verboseArg) {
 
     Byte ch;
     Word picSize;
     Word opcode;
     unsigned int version;
     unsigned int i;
-    struct canvas canvas;
-    blitList blitList;
+    struct Canvas canvas;
+    BlitList blitList;
+
+    verbose = verboseArg;
+    recognize_comment = !quickdraw;
 
     initBlitList(&blitList);
 
@@ -4310,18 +4501,24 @@ interpretPict(FILE * const ofP) {
         pen_pat.pix[i] = bkpat.pix[i] = fillpat.pix[i] = 1;
     pen_width = pen_height = 1;
     pen_mode = 0; /* srcCopy */
-    pen_trf = transfer(pen_mode);
+    pen_trf = transferFunctionForMode(pen_mode);
     text_mode = 0; /* srcCopy */
-    text_trf = transfer(text_mode);
+    text_trf = transferFunctionForMode(text_mode);
+
+    if (!noheader) {
+        stage = "Reading 512 byte header";
+        /* Note that the "header" in PICT is entirely comment! */
+        skip(ifP, 512);
+    }
 
     stage = "Reading picture size";
-    picSize = readWord();
+    picSize = readWord(ifP);
 
     if (verbose)
         pm_message("picture size = %u (0x%x)", picSize, picSize);
 
     stage = "reading picture frame";
-    readRect(&picFrame);
+    readRect(ifP, &picFrame);
 
     if (verbose) {
         dumpRect("Picture frame:", picFrame);
@@ -4339,18 +4536,18 @@ interpretPict(FILE * const ofP) {
         clip_rect = picFrame;
     }
 
-    while ((ch = readByte()) == 0)
+    while ((ch = readByte(ifP)) == 0)
         ;
     if (ch != 0x11)
         pm_error("No version number");
 
-    version = readByte();
+    version = readByte(ifP);
 
     switch (version) {
     case 1:
         break;
     case 2: {
-        unsigned char const subcode = readByte();
+        unsigned char const subcode = readByte(ifP);
         if (subcode != 0xff)
             pm_error("The only Version 2 PICT images this program "
                      "undertands are subcode 0xff.  This image has "
@@ -4363,8 +4560,9 @@ interpretPict(FILE * const ofP) {
     if (verbose)
         pm_message("PICT version %u", version);
 
-    while((opcode = nextOp(version)) != 0xff)
-        processOpcode(opcode, &canvas, fullres ? &blitList : NULL, version);
+    while((opcode = nextOp(ifP, version)) != 0xff)
+        processOpcode(ifP, opcode, &canvas, fullres ? &blitList : NULL,
+                      version);
 
     if (fullres) {
         if (blitList.unblittableText)
@@ -4379,77 +4577,25 @@ interpretPict(FILE * const ofP) {
 
 
 
-static void
-loadDefaultFontDir(void) {
-/*----------------------------------------------------------------------------
-   Load the fonts from the font directory file "fontdir" (in the current
-   directory), if it exists.
------------------------------------------------------------------------------*/
-    struct stat statbuf;
-    int rc;
-
-    rc = stat("fontdir", &statbuf);
+int
+main(int argc, const char *argv[]) {
 
-    if (rc == 0)
-        load_fontdir("fontdir");
-}
+    struct CmdlineInfo cmdline;
+    FILE * ifP;
 
+    pm_proginit(&argc, argv);
 
+    parseCommandLine(argc, argv, &cmdline);
 
-int
-main(int argc, char * argv[]) {
-    int argn;
-    int header;
-    const char* const usage =
-"[-verbose] [-fullres] [-noheader] [-quickdraw] [-fontdir file] [pictfile]";
-
-    ppm_init( &argc, argv );
-
-    argn = 1;
-    verbose = 0;
-    fullres = 0;
-    header = 1;
-    recognize_comment = 1;
-
-    while (argn < argc && argv[argn][0] == '-' && argv[argn][1] != '\0') {
-        if (pm_keymatch(argv[argn], "-verbose", 2))
-            verbose++;
-        else if (pm_keymatch(argv[argn], "-fullres", 3))
-            fullres = 1;
-        else if (pm_keymatch(argv[argn], "-noheader", 2))
-            header = 0;
-        else if (pm_keymatch(argv[argn], "-quickdraw", 2))
-            recognize_comment = 0;
-        else if (pm_keymatch(argv[argn], "-fontdir", 3)) {
-            argn++;
-            if (!argv[argn])
-                pm_usage(usage);
-            else
-                load_fontdir(argv[argn]);
-        }
-        else
-            pm_usage(usage);
-        ++argn;
-    }
-
-    if (argn < argc) {
-        ifp = pm_openr(argv[argn]);
-        ++argn;
-    } else
-        ifp = stdin;
+    ifP = pm_openr(cmdline.inputFileName);
 
-    if (argn != argc)
-        pm_usage(usage);
+    if (cmdline.fontdir)
+        loadFontdir(cmdline.fontdir);
 
     loadDefaultFontDir();
 
-    if (header) {
-        stage = "Reading 512 byte header";
-        /* Note that the "header" in PICT is entirely comment! */
-        skip(512);
-    }
-
-    interpretPict(stdout);
+    interpretPict(ifP, stdout, cmdline.noheader,
+                  cmdline.fullres, cmdline.quickdraw, cmdline.verbose);
 
     pm_close(stdout);
 
diff --git a/converter/ppm/pjtoppm.c b/converter/ppm/pjtoppm.c
index e556803f..45746495 100644
--- a/converter/ppm/pjtoppm.c
+++ b/converter/ppm/pjtoppm.c
@@ -1,4 +1,4 @@
-/* pjtoppm.c - convert an HP PainJetXL image to a portable pixmap file
+/* pjtoppm.c - convert an HP PainJetXL image to a PPM
 **
 ** Copyright (C) 1990 by Christos Zoulas (christos@ee.cornell.edu)
 **
@@ -11,13 +11,12 @@
 */
 
 #include <stdbool.h>
+#include <assert.h>
 
 #include "ppm.h"
 #include "pm_c_util.h"
 #include "mallocvar.h"
 
-static char usage[] =  "[paintjetfile]";
-
 
 
 static unsigned int
@@ -46,44 +45,142 @@ egetc(FILE * const ifP) {
 
 
 
+static void
+modifyImageMode1(unsigned int     const rows,
+                 unsigned int     const planes,
+                 const int *      const imlen,
+                 unsigned char ** const image,
+                 unsigned int *   const colsP) {
+
+    unsigned int const newcols = 10240;
+    /* It could not be larger than that! */
+
+    unsigned int cols;
+    unsigned int row;
+
+    for (row = 0, cols = 0; row < rows; ++row) {
+        unsigned int plane;
+        if (image[row * planes]) {
+            for (plane = 0; plane < planes; ++plane) {
+                unsigned int i;
+                unsigned int col;
+                unsigned char * buf;
+
+                MALLOCARRAY(buf, newcols);
+                if (buf == NULL)
+                    pm_error("out of memory");
+                for (i = 0, col = 0;
+                     col < imlen[row * planes + plane];
+                     col += 2) {
+                    int cmd, val;
+                    for (cmd = image[row * planes + plane][col],
+                             val = image[plane + row * planes][col+1];
+                         cmd >= 0 && i < newcols; --cmd, ++i)
+                        buf[i] = val;
+                }
+                cols = MAX(cols, i);
+                free(image[row * planes + plane]);
+
+                /*
+                 * This is less than what we have so it realloc should
+                 * not return null. Even if it does, tough! We will
+                 * lose a line, and probably die on the next line anyway
+                 */
+                image[row * planes + plane] = realloc(buf, i);
+            }
+        }
+    }
+    *colsP = cols * 8;  assert(cols < UINT_MAX/8);
+}
+
+
+
+static void
+writePpm(FILE *           const ofP,
+         unsigned int     const cols,
+         unsigned int     const rows,
+         unsigned int     const planes,
+         unsigned char ** const image,
+         int              const mode,
+         const int *      const imlen) {
+
+    pixel * pixrow;
+    unsigned int row;
+
+    ppm_writeppminit(stdout, cols, rows, 255, 0);
+    pixrow = ppm_allocrow(cols);
+
+    for (row = 0; row < rows; ++row) {
+        if (image[row * planes + 0] == NULL) {
+            unsigned int col;
+            for (col = 0; col < cols; ++col)
+                PPM_ASSIGN(pixrow[col], 0, 0, 0);
+        } else {
+            unsigned int col;
+            unsigned int cmd;
+            for (cmd = 0, col = 0; col < cols; col += 8, ++cmd) {
+                unsigned int i;
+                for (i = 0; i < 8 && col + i < cols; ++i) {
+                    unsigned int plane;
+                    unsigned char bf[3];
+
+                    assert(planes == 3);
+
+                    for (plane = 0; plane < planes; ++plane) {
+                        if (mode == 0 && cmd >= imlen[row * planes + plane])
+                            bf[plane] = 0;
+                        else
+                            bf[plane] = (image[row * planes + plane][cmd] &
+                                     (1 << (7 - i))) ? 255 : 0;
+                    }
+                    PPM_ASSIGN(pixrow[col + i], bf[0], bf[1], bf[2]);
+                }
+            }
+            ppm_writeppmrow(stdout, pixrow, cols, 255, 0);
+        }
+    }
+}
+
+
+
 int
 main(int argc, const char ** argv) {
 
     int cmd, val;
     char buffer[BUFSIZ];
-    int planes = 3;
+    unsigned int planes;
     unsigned int rows;
     unsigned int rowsX;
     unsigned int cols;
     bool colsIsSet;
-    unsigned char **image = NULL;
-    int *imlen;
+    unsigned char ** image;  /* malloc'ed */
+    int * imlen;  /* malloc'ed */
     FILE * ifP;
     int mode;
     bool modeIsSet;
-    int argn;
-    unsigned char bf[3];
-    pixel * pixrow;
     int c;
-    int row;
-    int plane;
+    unsigned int plane;
+    unsigned int row;
 
     pm_proginit(&argc, argv);
 
-    argn = 1;
-    if (argn != argc)
-        ifP = pm_openr(argv[argn++]);
+    if (argc-1 > 0)
+        ifP = pm_openr(argv[1]);
     else
         ifP = stdin;
 
-    if (argn != argc)
-        pm_usage(usage);
+    if (argc-1 > 2)
+        pm_error("Too many arguments (%u).  Only possible argument is "
+                 "input file name", argc-1);
 
     row = 0;  /* initial value */
     plane = 0;  /* initial value */
     modeIsSet = false;  /* initial value */
     colsIsSet = false;  /* initial value */
     rowsX = 0;  /* initial value */
+    image = NULL;  /* initial value */
+    imlen = NULL;  /* initial value */
+    planes = 3;  /* initial value */
 
     while ((c = fgetc(ifP)) != -1) {
         if (c != '\033')
@@ -170,13 +267,8 @@ main(int argc, const char ** argv) {
                     if (row >= rowsX || image == NULL) {
                         if (row >= rowsX)
                             rowsX += 100;
-                        if (image == NULL) {
-                            MALLOCARRAY(image, uintProduct(rowsX, planes));
-                            MALLOCARRAY(imlen, uintProduct(rowsX, planes));
-                        } else {
-                            REALLOCARRAY(image, uintProduct(rowsX, planes));
-                            REALLOCARRAY(imlen, uintProduct(rowsX, planes));
-                        }
+                        REALLOCARRAY(image, uintProduct(rowsX, planes));
+                        REALLOCARRAY(imlen, uintProduct(rowsX, planes));
                     }
                     if (image == NULL || imlen == NULL)
                         pm_error("out of memory");
@@ -196,6 +288,9 @@ main(int argc, const char ** argv) {
                         ++plane;
                     else {
                         plane = 0;
+                        if (row > UINT_MAX/planes-100)
+                            pm_error("Too many rows (more than %u) "
+                                     "for computation", row);
                         ++row;
                     }
                     break;
@@ -241,72 +336,14 @@ main(int argc, const char ** argv) {
         pm_error("Input does not contain a 'bM' transmission mode order");
 
     rows = row;
-    if (mode == 1) {
-        unsigned int const newcols = 10240;
-            /* It could not be larger than that! */
 
-        unsigned char * buf;
-        unsigned int row;
+    if (mode == 1) {
+        modifyImageMode1(rows, planes, imlen, image, &cols);
 
-        for (row = 0, cols = 0; row < rows; ++row) {
-            unsigned int plane;
-            if (image[row * planes] == NULL)
-                continue;
-            for (plane = 0; plane < planes; ++plane) {
-                unsigned int i;
-                unsigned int col;
-                MALLOCARRAY(buf, newcols);
-                if (buf == NULL)
-                    pm_error("out of memory");
-                for (i = 0, col = 0;
-                     col < imlen[plane + row * planes];
-                     col += 2)
-                    for (cmd = image[plane + row * planes][col],
-                             val = image[plane + row * planes][col+1];
-                         cmd >= 0 && i < newcols; cmd--, i++)
-                        buf[i] = val;
-                cols = MAX(cols, i);
-                free(image[plane + row * planes]);
-                /*
-                 * This is less than what we have so it realloc should
-                 * not return null. Even if it does, tough! We will
-                 * lose a line, and probably die on the next line anyway
-                 */
-                image[plane + row * planes] = realloc(buf, i);
-            }
-        }
-        cols *= 8;
     }
 
-    ppm_writeppminit(stdout, cols, rows, (pixval) 255, 0);
-    pixrow = ppm_allocrow(cols);
+    writePpm(stdout, cols, rows, planes, image, mode, imlen);
 
-    for (row = 0; row < rows; ++row) {
-        if (image[row * planes] == NULL) {
-            unsigned int col;
-            for (col = 0; col < cols; ++col)
-                PPM_ASSIGN(pixrow[col], 0, 0, 0);
-            continue;
-        }
-        {
-            unsigned int col;
-            unsigned int cmd;
-            for (cmd = 0, col = 0; col < cols; col += 8, ++cmd) {
-                unsigned int i;
-                for (i = 0; i < 8 && col + i < cols; ++i) {
-                    unsigned int plane;
-                    for (plane = 0; plane < planes; ++plane)
-                        if (mode == 0 && cmd >= imlen[row * planes + plane])
-                            bf[plane] = 0;
-                        else
-                            bf[plane] = (image[row * planes + plane][cmd] &
-                                     (1 << (7 - i))) ? 255 : 0;
-                    PPM_ASSIGN(pixrow[col + i], bf[0], bf[1], bf[2]);
-                }
-            }
-        }
-        ppm_writeppmrow(stdout, pixrow, cols, 255, 0);
-    }
     pm_close(stdout);
 
     return 0;
diff --git a/converter/ppm/ppmtoacad.c b/converter/ppm/ppmtoacad.c
index b5ee4d65..4f4dc5dd 100644
--- a/converter/ppm/ppmtoacad.c
+++ b/converter/ppm/ppmtoacad.c
@@ -108,33 +108,33 @@ static void outrun(color, ysize, y, xstart, xend)
                 stdout, (int) ((xend + 1) * aspect + 0.4999));
             (void) pm_writelittleshort(stdout, yb - yspan);
         } else {
-            (void) pm_writelittleshort(stdout, (short) 0xFD00); 
+            (void) pm_writelittleshort(stdout, (short) 0xFD00);
               /* Solid fill header */
-            (void) pm_writelittleshort(stdout, 4);      
+            (void) pm_writelittleshort(stdout, 4);
               /* Vertices to follow */
             (void) pm_writelittleshort(stdout, -2);     /* Fill type */
 
-            (void) pm_writelittleshort(stdout, (short)0xFD00); 
+            (void) pm_writelittleshort(stdout, (short)0xFD00);
               /* Solid fill vertex */
             (void) pm_writelittleshort(stdout, xstart);
             (void) pm_writelittleshort(stdout, yb);
 
-            (void) pm_writelittleshort(stdout, (short) 0xFD00); 
+            (void) pm_writelittleshort(stdout, (short) 0xFD00);
               /* Solid fill vertex */
             (void) pm_writelittleshort(stdout, xend + 1);
             (void) pm_writelittleshort(stdout, yb);
 
-            (void) pm_writelittleshort(stdout, (short) 0xFD00); 
+            (void) pm_writelittleshort(stdout, (short) 0xFD00);
               /* Solid fill vertex */
             (void) pm_writelittleshort(stdout, xend + 1);
             (void) pm_writelittleshort(stdout, yb - yspan);
 
-            (void) pm_writelittleshort(stdout, (short) 0xFD00); 
+            (void) pm_writelittleshort(stdout, (short) 0xFD00);
               /* Solid fill vertex */
             (void) pm_writelittleshort(stdout, xstart);
             (void) pm_writelittleshort(stdout, yb - yspan);
 
-            (void) pm_writelittleshort(stdout, (short) 0xFD00); 
+            (void) pm_writelittleshort(stdout, (short) 0xFD00);
               /* Solid fill trailer */
             (void) pm_writelittleshort(stdout, 4); /* Vertices that precede */
             (void) pm_writelittleshort(stdout, -2);     /* Fill type */
@@ -147,6 +147,8 @@ static void outrun(color, ysize, y, xstart, xend)
     }
 }
 
+
+
 /*  SLIDEOUT  --  Write an AutoCAD slide.  */
 
 static void slideout(xdots, ydots, ncolors, red, green, blue)
@@ -253,12 +255,14 @@ static void slideout(xdots, ydots, ncolors, red, green, blue)
     if (dxbmode) {
         putchar(0);                   /* DXB end sentinel */
     } else {
-        (void) pm_writelittleshort(stdout, (short) 0xFC00); 
+        (void) pm_writelittleshort(stdout, (short) 0xFC00);
           /* End of file marker */
     }
     pm_freerow((char *) acadmap);
 }
 
+
+
 /*  Main program.  */
 
 int main(argc, argv)
@@ -391,3 +395,6 @@ int main(argc, argv)
     pm_freerow((char *) Blue);
     exit(0);
 }
+
+
+
diff --git a/converter/ppm/ppmtoapplevol.c b/converter/ppm/ppmtoapplevol.c
index e1c7f2dc..50c85dc6 100644
--- a/converter/ppm/ppmtoapplevol.c
+++ b/converter/ppm/ppmtoapplevol.c
@@ -68,14 +68,18 @@ main (int argc, const char * argv[]) {
     if (rows != 12)
         pm_error("Input image must be 12 rows tall.  Yours is %u", rows);
 
+    if (cols > 255)
+        pm_error("Input image must not be more than 255 columns wide."
+                 "  Yours is %u", cols);
+
     writeHeader(cols, stdout);
 
     pixelrow = ppm_allocrow(cols);
 
     for (row = 0; row < rows; row++) {
         unsigned int col;
-        
-        ppm_readppmrow(stdin, pixelrow, cols, maxval, format);
+
+        ppm_readppmrow(ifP, pixelrow, cols, maxval, format);
 
         for (col = 0; col < cols; ++col) {
             unsigned int const maxval15Value =
@@ -93,3 +97,6 @@ main (int argc, const char * argv[]) {
 
     return 0;
 }
+
+
+
diff --git a/converter/ppm/ppmtoarbtxt.c b/converter/ppm/ppmtoarbtxt.c
index 6d4c6eac..a8d7a004 100644
--- a/converter/ppm/ppmtoarbtxt.c
+++ b/converter/ppm/ppmtoarbtxt.c
@@ -62,18 +62,16 @@ parseCommandLine(int argc, const char ** argv,
    in argv!
 -----------------------------------------------------------------------------*/
     optEntry * option_def;
-        /* Instructions to OptParseOptions3 on how to parse our options.
-         */
     optStruct3 opt;
 
     unsigned int hdSpec, tlSpec;
 
     unsigned int option_def_index;
-    
+
     MALLOCARRAY(option_def, 100);
 
     option_def_index = 0;   /* incremented by OPTENTRY */
-    OPTENT3(0,   "hd",   OPT_STRING, &cmdlineP->hd, 
+    OPTENT3(0,   "hd",   OPT_STRING, &cmdlineP->hd,
             &hdSpec,             0);
     OPTENT3(0,   "tl",   OPT_STRING, &cmdlineP->tl,
             &tlSpec,             0);
@@ -84,7 +82,7 @@ parseCommandLine(int argc, const char ** argv,
     opt.short_allowed = FALSE;  /* We have no short (old-fashioned) options */
     opt.allowNegNum = FALSE;  /* We have no parms that are negative numbers */
 
-    pm_optParseOptions3(&argc, (char **)argv, opt, sizeof(opt), 0);
+    pm_optParseOptions4(&argc, argv, opt, sizeof(opt), 0);
     free(option_def);
 
     if (!hdSpec)
@@ -113,7 +111,6 @@ parseCommandLine(int argc, const char ** argv,
 
 
 
-
 typedef enum {
 /* The types of object we handle */
     BDATA, IRED, IGREEN, IBLUE, ILUM, FRED, FGREEN, FBLUE, FLUM,
@@ -134,7 +131,7 @@ typedef union {
         char * bdat;   /* Binary data (text with newlines etc.) */
         unsigned int ndat;
     } binData;
-    
+
     struct Icdat {
         char icformat[MAXFORMAT+1];  /* Integer colors */
         unsigned int icolmin, icolmax;
@@ -144,7 +141,7 @@ typedef union {
         char fcformat[MAXFORMAT+1];  /* Float colors */
         double fcolmin, fcolmax;
     } fcolData;
-    
+
     struct Idat {
         char iformat[MAXFORMAT+1];   /* Integer data */
     } iData;
@@ -152,7 +149,7 @@ typedef union {
 
 
 /* Each object has a type and some data */
-typedef struct { 
+typedef struct {
     SkeletonObjectType objType;
     SkeletonObjectData odata;
 } SkeletonObject;
@@ -187,11 +184,11 @@ dumpSkeleton(SkeletonObject ** const skeletonPList,
 static void
 dumpAllSkeleton(SkeletonObject ** const bodySkeletonPList,
                 unsigned int      const bodyNskl,
-                SkeletonObject ** const headSkeletonPList, 
+                SkeletonObject ** const headSkeletonPList,
                 unsigned int      const headNskl,
                 SkeletonObject ** const tailSkeletonPList,
                 unsigned int      const tailNskl) {
-    
+
     pm_message("Body skeleton:");
     dumpSkeleton(bodySkeletonPList, bodyNskl);
 
@@ -240,7 +237,7 @@ writeFcol(FILE *           const ofP,
           double           const value) {
 
     struct Fcdat * const fcdataP = &objectP->odata.fcolData;
-    
+
     fprintf(ofP, fcdataP->fcformat,
             (double)
             (fcdataP->fcolmin
@@ -255,7 +252,7 @@ writeIdat(FILE *           const ofP,
           unsigned int     const value) {
 
     struct Idat * const idataP = &objectP->odata.iData;
-    
+
     fprintf(ofP, idataP->iformat, value);
 }
 
@@ -272,7 +269,7 @@ writeText(FILE *            const ofP,
           double            const red,
           double            const green,
           double            const blue) {
-    
+
     unsigned int i;
 
     for (i = 0; i < nObj; ++i) {
@@ -352,6 +349,7 @@ objClass(SkeletonObjectType const objType) {
 }
 
 
+
 /*----------------------------------------------------------------------------
   Format string validation
 
@@ -366,7 +364,7 @@ objClass(SkeletonObjectType const objType) {
 
   Documentation for parse_printf_format() is usually available in texinfo
   format on GNU/Linux systems.  As of Dec. 2014 there is no official man page.
-  
+
   Online documentation is available from:
   https://
   www.gnu.org/software/libc/manual/html_node/Parsing-a-Template-String.html
@@ -379,7 +377,7 @@ validateParsePrintfFlag(int                const printfConversion,
                         const char **      const errorP) {
 /*----------------------------------------------------------------------------
   Assuming 'printfConversion' is the value reported by parse_printf_format()
-  as the type of argument a format string requires, 
+  as the type of argument a format string requires,
   return an explanation of how it is incompatible with 'ctyp' as
   *errorP -- return null string if it is compatible.
 -----------------------------------------------------------------------------*/
@@ -403,7 +401,7 @@ validateParsePrintfFlag(int                const printfConversion,
     default:
         switch (printfConversion & ~PA_FLAG_MASK) {
         case PA_CHAR:
-            pm_message("Warning: char type conversion."); 
+            pm_message("Warning: char type conversion.");
         case PA_INT:
             if(objClass(ctyp) == OBJTYP_ICOLOR ||
                objClass(ctyp) == OBJTYP_INT )
@@ -496,7 +494,7 @@ validateFormatOne(char               const typeSpecifier,
     case '0': case '1': case '2': case '3': case '4': case '5':
     case '6': case '7': case '8': case '9':
         break;
-        
+
     case 'c': case 'C':
         pm_message("Warning: char type conversion: %%%c.", typeSpecifier);
     case 'i': case 'd': case 'u': case 'o': case 'x': case 'X':
@@ -599,12 +597,12 @@ validateFormat(const char *       const format,
 
     if (error)
         pm_error("Invalid format string '%s'.  %s", format, error);
-}              
-               
+}
+
 
 
 static SkeletonObject *
-newBinDataObj(unsigned int const nDat, 
+newBinDataObj(unsigned int const nDat,
               const char * const bdat) {
 /*----------------------------------------------------------------------------
   Create a binary data object.
@@ -787,7 +785,7 @@ newFcSkelFromReplString(const char *       const fcolorObjstr,
         retval = NULL;
 
     return retval;
-} 
+}
 
 
 
@@ -805,7 +803,7 @@ newISkelFromReplString(const char *       const intObjstr,
     int nOdata;
 
     nOdata = sscanf(intObjstr, "%s", formstr);
-    
+
     if (nOdata == 1)
         retval = newIdataObj(objType, formstr);
     else if (nOdata == EOF) {
@@ -815,7 +813,7 @@ newISkelFromReplString(const char *       const intObjstr,
         retval = NULL;
 
     return retval;
-} 
+}
 
 
 
@@ -842,7 +840,7 @@ newSkeletonFromReplString(const char * const objstr) {
     int conversionCt;
     char s1[MAX_OBJ_BUF];    /* Dry read. */
     char s2[MAX_OBJ_BUF];    /* Extra tailing characters. */
-    float f1, f2;            /* Dry read. */ 
+    float f1, f2;            /* Dry read. */
 
     typstr[0] = '\0';  /* initial value */
 
@@ -905,7 +903,7 @@ readThroughCloseParen(FILE * const ifP,
             if (chr == ')') {
                 gotEscSeq = true;
                 objstr[i] = '\0';
-	        } else
+                } else
                 objstr[i] = chr;
         }
     }
@@ -942,7 +940,7 @@ SkeletonBuffer_add(SkeletonBuffer * const bufferP,
         pm_error("Too many skeletons.  Max = %u", bufferP->capacity);
 
     bufferP->skeletonPList[bufferP->nSkeleton++] = skeletonP;
-}                   
+}
 
 
 
@@ -1050,7 +1048,7 @@ readSkeletonFile(const char *      const filename,
         /* A buffer for accumulating skeleton objects */
     Buffer buffer;
         /* A buffer for accumulating binary (literal; unsubstituted) data, on
-           its way to becoming a binary skeleton object. 
+           its way to becoming a binary skeleton object.
         */
     bool eof;
     const char * error;
@@ -1135,7 +1133,7 @@ convertIt(FILE *            const ifP,
           FILE *            const ofP,
           SkeletonObject ** const bodySkeletonPList,
           unsigned int      const bodyNskl,
-          SkeletonObject ** const headSkeletonPList, 
+          SkeletonObject ** const headSkeletonPList,
           unsigned int      const headNskl,
           SkeletonObject ** const tailSkeletonPList,
           unsigned int      const tailNskl) {
@@ -1154,7 +1152,7 @@ convertIt(FILE *            const ifP,
     dmaxval = (double)maxval;
 
     /* Write header */
-    writeText(ofP, headNskl, headSkeletonPList, 
+    writeText(ofP, headNskl, headSkeletonPList,
               cols, rows , 0, 0, 0.0, 0.0, 0.0);
 
     /* Write raster */
@@ -1175,7 +1173,7 @@ convertIt(FILE *            const ifP,
     }
 
     /* Write trailer */
-    writeText(ofP, tailNskl, tailSkeletonPList, 
+    writeText(ofP, tailNskl, tailSkeletonPList,
               cols, rows, 0, 0, 0.0, 0.0, 0.0);
 }
 
@@ -1184,7 +1182,7 @@ convertIt(FILE *            const ifP,
 int
 main(int           argc,
      const char ** argv) {
-    
+
     struct CmdlineInfo cmdline;
 
     unsigned int headNskl, bodyNskl, tailNskl;
@@ -1240,3 +1238,4 @@ main(int           argc,
 }
 
 
+
diff --git a/converter/ppm/ppmtoascii.c b/converter/ppm/ppmtoascii.c
index 6b0b04d7..b7c6669d 100644
--- a/converter/ppm/ppmtoascii.c
+++ b/converter/ppm/ppmtoascii.c
@@ -102,7 +102,6 @@ parseCommandLine(int argc, const char **argv,
                  struct cmdlineInfo * const cmdlineP) {
 
     optEntry * option_def;
-        /* Instructions to OptParseOptions3 on how to parse our options */
     optStruct3 opt;
 
     unsigned int option_def_index;
@@ -118,7 +117,7 @@ parseCommandLine(int argc, const char **argv,
     opt.short_allowed = false;  /* We have no short (old-fashioned) options */
     opt.allowNegNum = false;  /* We have no parms that are negative numbers */
 
-    pm_optParseOptions3(&argc, (char **)argv, opt, sizeof(opt), 0);
+    pm_optParseOptions4(&argc, argv, opt, sizeof(opt), 0);
         /* Uses and sets argc, argv, and some of *cmdlineP and others. */
 
     if (dim1x2Spec && dim2x4Spec)
@@ -164,7 +163,7 @@ ppmtoascii(pixel * const *    const pixels,
 
     for (row = 0; row < rows; row += cellHeight) {
         unsigned int col;
-        for (col = 0; col < cols; col += cellWidth)	{
+        for (col = 0; col < cols; col += cellWidth)     {
             unsigned int const sumthresh = cellWidth * cellHeight * 1.0 / 2;
 
             float sumr, sumg, sumb;
@@ -181,7 +180,7 @@ ppmtoascii(pixel * const *    const pixels,
                 for (subcol = 0; subcol < cellWidth; ++subcol) {
                     pixel color;
                     pixval value;
-                
+
                     if (row + subrow < rows && col + subcol < cols)
                         color = pixels[row + subrow][col + subcol];
                     else
@@ -225,7 +224,7 @@ main(int argc, const char ** argv) {
     parseCommandLine(argc, argv, &cmdline);
 
     ifP = pm_openr(cmdline.inputFileName);
-    
+
     pixels = ppm_readppm(ifP, &cols, &rows, &maxval);
 
     pm_close(ifP);
@@ -234,3 +233,6 @@ main(int argc, const char ** argv) {
 
     return 0;
 }
+
+
+
diff --git a/converter/ppm/ppmtobmp.c b/converter/ppm/ppmtobmp.c
index 41cee482..ed44b83a 100644
--- a/converter/ppm/ppmtobmp.c
+++ b/converter/ppm/ppmtobmp.c
@@ -17,6 +17,7 @@
 #define _BSD_SOURCE 1    /* Make sure strdup() is in string.h */
 #define _XOPEN_SOURCE 500  /* Make sure strdup() is in string.h */
 
+#include <stdbool.h>
 #include <assert.h>
 #include <string.h>
 
@@ -87,8 +88,6 @@ parseCommandLine(int argc, const char ** argv,
    in argv!
 -----------------------------------------------------------------------------*/
     optEntry * option_def;
-        /* Instructions to OptParseOptions3 on how to parse our options.
-         */
     optStruct3 opt;
 
     unsigned int windowsSpec, os2Spec, mapfileSpec;
@@ -106,10 +105,10 @@ parseCommandLine(int argc, const char ** argv,
             &mapfileSpec,             0);
 
     opt.opt_table = option_def;
-    opt.short_allowed = FALSE;  /* We have no short (old-fashioned) options */
-    opt.allowNegNum = FALSE;  /* We have no parms that are negative numbers */
+    opt.short_allowed = false;  /* We have no short (old-fashioned) options */
+    opt.allowNegNum = false;  /* We have no parms that are negative numbers */
 
-    pm_optParseOptions3(&argc, (char **)argv, opt, sizeof(opt), 0);
+    pm_optParseOptions4(&argc, argv, opt, sizeof(opt), 0);
 
     if (windowsSpec && os2Spec)
         pm_error("Can't specify both -windows and -os2 options.");
@@ -183,6 +182,7 @@ putLong(FILE * const fp, long const v) {
 }
 
 
+
 /*----------------------------------------------------------------------------
    BMP writing
 -----------------------------------------------------------------------------*/
diff --git a/converter/ppm/ppmtoeyuv.c b/converter/ppm/ppmtoeyuv.c
index f5ce1156..0cfe9b13 100644
--- a/converter/ppm/ppmtoeyuv.c
+++ b/converter/ppm/ppmtoeyuv.c
@@ -1,9 +1,9 @@
 /* Bryan got this from mm.ftp-cs.berkeley.edu from the package
-   mpeg-encode-1.5b-src under the name ppmtoeyuv.c on March 30, 2000.  
-   The file was dated January 19, 1995.  
+   mpeg-encode-1.5b-src under the name ppmtoeyuv.c on March 30, 2000.
+   The file was dated January 19, 1995.
 
    Bryan changed the program to take an argument as the input filename
-   and fixed a crash when the input image has an odd number of rows or 
+   and fixed a crash when the input image has an odd number of rows or
    columns.
 
    Then Bryan updated the program on March 15, 2001 to use the Netpbm
@@ -12,7 +12,7 @@
 
    There was no attached documentation except for this:  Encoder/Berkeley
    YUV format is merely the concatenation of Y, U, and V data in order.
-   Compare with Abekas YUV, which interlaces Y, U, and V data. 
+   Compare with Abekas YUV, which interlaces Y, U, and V data.
 
    Future enhancement: It may be useful to have an option to do the
    calculations without multiplication tables to save memory at the
@@ -43,7 +43,7 @@
  * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
  */
 
-/*  
+/*
  *  $Header: /n/picasso/users/keving/encode/src/RCS/readframe.c,v 1.1 1993/07/22 22:23:43 keving Exp keving $
  *  $Log: readframe.c,v $
  * Revision 1.1  1993/07/22  22:23:43  keving
@@ -56,6 +56,7 @@
  * HEADER FILES *
  *==============*/
 
+#include <stdbool.h>
 #include <stdio.h>
 #include <ctype.h>
 #include <string.h>
@@ -65,43 +66,47 @@
 #include "ppm.h"
 #include "mallocvar.h"
 
-typedef	unsigned char uint8;
+typedef unsigned char uint8;
 
 /* Multiplication tables */
 
 #define YUVMAXVAL 255
 #define HALFYUVMAXVAL 128
-/* multXXX are multiplication tables used in RGB-YCC calculations for 
+/* multXXX are multiplication tables used in RGB-YCC calculations for
    speed.  mult299[x] is x * .299, scaled to a maxval of 255.  These
    are malloc'ed and essentially constant.
 
    We use these tables because it is much faster to do a
    multiplication once for each possible sample value than once for
-   each pixel in the image.  
+   each pixel in the image.
 */
 static float *mult299, *mult587, *mult114;
 static float *mult16874, *mult33126, *mult5;
 static float *mult41869, *mult08131;
 
 static __inline__ float
-luminance(const pixel p) {
+luminance(pixel const p) {
     return mult299[PPM_GETR(p)]
-        + mult587[PPM_GETG(p)] 
+        + mult587[PPM_GETG(p)]
         + mult114[PPM_GETB(p)]
         ;
 }
 
+
+
 static __inline__ float
-chrominance_red(const pixel p) {
-    return mult5[PPM_GETR(p)] 
+chrominanceRed(pixel const p) {
+    return mult5[PPM_GETR(p)]
         + mult41869[PPM_GETG(p)]
         + mult08131[PPM_GETB(p)]
         ;
 }
 
+
+
 static __inline__ float
-chrominance_blue(const pixel p) {
-    return mult16874[PPM_GETR(p)] 
+chrominanceBlue(pixel const p) {
+    return mult16874[PPM_GETR(p)]
         + mult33126[PPM_GETG(p)]
         + mult5[PPM_GETB(p)]
         ;
@@ -110,9 +115,7 @@ chrominance_blue(const pixel p) {
 
 
 static void
-create_multiplication_tables(const pixval maxval) {
-
-    int index;
+createMultiplicationTables(pixval const maxval) {
 
     MALLOCARRAY_NOFAIL(mult299   , maxval+1);
     MALLOCARRAY_NOFAIL(mult587   , maxval+1);
@@ -125,7 +128,9 @@ create_multiplication_tables(const pixval maxval) {
 
     if (maxval == YUVMAXVAL) {
         /* fast path */
-        for ( index = 0; index <= maxval; index++ ) {
+        unsigned int index;
+
+        for (index = 0; index <= maxval; ++index) {
             mult299[index]   =  0.29900*index;
             mult587[index]   =  0.58700*index;
             mult114[index]   =  0.11400*index;
@@ -136,7 +141,8 @@ create_multiplication_tables(const pixval maxval) {
             mult33126[index] = -0.33126*index;
         }
     } else {
-        for ( index = 0; index <= maxval; index++ ) {
+        unsigned int index;
+        for (index = 0; index <= maxval; ++index) {
             mult299[index]   =  0.29900*index*(maxval/YUVMAXVAL);
             mult587[index]   =  0.58700*index*(maxval/YUVMAXVAL);
             mult114[index]   =  0.11400*index*(maxval/YUVMAXVAL);
@@ -146,14 +152,13 @@ create_multiplication_tables(const pixval maxval) {
             mult16874[index] = -0.16874*index*(maxval/YUVMAXVAL);
             mult33126[index] = -0.33126*index*(maxval/YUVMAXVAL);
         }
-        
     }
 }
 
 
 
 static void
-free_multiplication_tables(void) {
+freeMultiplicationTables(void) {
     free(mult299   );
     free(mult587   );
     free(mult114   );
@@ -170,31 +175,33 @@ free_multiplication_tables(void) {
  *
  * PPMtoYUV
  *
- *	convert PPM data into YUV data
- *	assumes that ydivisor = 1
+ *      convert PPM data into YUV data
+ *      assumes that ydivisor = 1
  *
- * RETURNS:	nothing
+ * RETURNS:     nothing
  *
  * SIDE EFFECTS:    none
  *
  * This function processes the input file in 4 pixel squares.  If the
  * Image does not have an even number of rows and columns, the rightmost
  * column or the bottom row gets ignored and output has one fewer row
- * or column than the input. 
+ * or column than the input.
  *
  *===========================================================================*/
-static void 
-PPMtoYUV(pixel ** const ppm_image, const int width, const int height,
-         uint8 *** const orig_yP, 
-         uint8 *** const orig_crP, 
-         uint8 *** const orig_cbP) {
+static void
+ppmToYuv(pixel **     const ppmImage,
+         unsigned int const width,
+         unsigned int const height,
+         uint8 ***    const orig_yP,
+         uint8 ***    const orig_crP,
+         uint8 ***    const orig_cbP) {
 
     int y;
     uint8 ** orig_y;
     uint8 ** orig_cr;
     uint8 ** orig_cb;
 
-    orig_y = *orig_yP;
+    orig_y  = *orig_yP;
     orig_cr = *orig_crP;
     orig_cb = *orig_cbP;
 
@@ -204,17 +211,17 @@ PPMtoYUV(pixel ** const ppm_image, const int width, const int height,
         const pixel *src0, *src1;
           /* Pair of contiguous rows of the ppm input image we are
              converting */
-        int x;
+        unsigned int x;
 
-        src0 = ppm_image[y];
-        src1 = ppm_image[y + 1];
+        src0 = ppmImage[y];
+        src1 = ppmImage[y + 1];
 
         dy0 = orig_y[y];
         dy1 = orig_y[y + 1];
         dcr = orig_cr[y / 2];
         dcb = orig_cb[y / 2];
 
-        for ( x = 0; x + 1 < width; x += 2) {
+        for (x = 0; x + 1 < width; x += 2) {
             dy0[x] = luminance(src0[x]);
             dy1[x] = luminance(src1[x]);
 
@@ -222,17 +229,17 @@ PPMtoYUV(pixel ** const ppm_image, const int width, const int height,
             dy1[x+1] = luminance(src1[x+1]);
 
             dcr[x/2] = ((
-                chrominance_red(src0[x]) +
-                chrominance_red(src1[x]) +
-                chrominance_red(src0[x+1]) +
-                chrominance_red(src1[x+1]) 
+                chrominanceRed(src0[x]) +
+                chrominanceRed(src1[x]) +
+                chrominanceRed(src0[x+1]) +
+                chrominanceRed(src1[x+1])
                 ) / 4) + HALFYUVMAXVAL;
 
             dcb[x/2] = ((
-                chrominance_blue(src0[x]) +
-                chrominance_blue(src1[x]) +
-                chrominance_blue(src0[x+1]) +
-                chrominance_blue(src1[x+1]) 
+                chrominanceBlue(src0[x]) +
+                chrominanceBlue(src1[x]) +
+                chrominanceBlue(src0[x+1]) +
+                chrominanceBlue(src1[x+1])
                 ) / 4) + HALFYUVMAXVAL;
         }
     }
@@ -240,74 +247,81 @@ PPMtoYUV(pixel ** const ppm_image, const int width, const int height,
 
 
 
-static void 
-WriteYUV(FILE *fpointer, const int width, const int height,
-         uint8 ** const orig_y, uint8 ** const orig_cr, uint8 ** const orig_cb)
-{
-    register int y;
+static void
+writeYUV(FILE *       const ofP,
+         unsigned int const width,
+         unsigned int const height,
+         uint8 **     const orig_y,
+         uint8 **     const orig_cr,
+         uint8 **     const orig_cb) {
+
+    unsigned int y;
 
-    for (y = 0; y < height; y++)                        /* Y */
-        fwrite(orig_y[y], 1, width, fpointer);
+    for (y = 0; y < height; ++y)                        /* Y */
+        fwrite(orig_y[y], 1, width, ofP);
 
-    for (y = 0; y < height / 2; y++)                    /* U */
-        fwrite(orig_cb[y], 1, width / 2, fpointer);
+    for (y = 0; y < height / 2; ++y)                    /* U */
+        fwrite(orig_cb[y], 1, width / 2, ofP);
 
-    for (y = 0; y < height / 2; y++)                    /* V */
-        fwrite(orig_cr[y], 1, width / 2, fpointer);
+    for (y = 0; y < height / 2; ++y)                    /* V */
+        fwrite(orig_cr[y], 1, width / 2, ofP);
 }
 
 
 
 static void
-AllocYUV(int       const width, 
+allocYUV(int       const width,
          int       const height,
-         uint8 *** const orig_yP, 
+         uint8 *** const orig_yP,
          uint8 *** const orig_crP,
          uint8 *** const orig_cbP) {
 
-    int y;
+    unsigned int y;
     uint8 ** orig_y;
     uint8 ** orig_cr;
     uint8 ** orig_cb;
 
     MALLOCARRAY_NOFAIL(*orig_yP, height);
     orig_y = *orig_yP;
-    for (y = 0; y < height; y++) 
+    for (y = 0; y < height; ++y)
         MALLOCARRAY_NOFAIL(orig_y[y], width);
 
     MALLOCARRAY_NOFAIL(*orig_crP, height / 2);
     orig_cr = *orig_crP;
-    for (y = 0; y < height / 2; y++) 
+    for (y = 0; y < height / 2; ++y)
         MALLOCARRAY_NOFAIL(orig_cr[y], width / 2);
 
     MALLOCARRAY_NOFAIL(*orig_cbP, height / 2);
     orig_cb = *orig_cbP;
-    for (y = 0; y < height / 2; y++) 
+    for (y = 0; y < height / 2; ++y)
         MALLOCARRAY_NOFAIL(orig_cb[y], width / 2);
 }
 
 
 
 static void
-FreeYUV(const int width, const int height,
-        uint8 ** const orig_y, uint8 ** const orig_cr, uint8 ** const orig_cb){
+freeYUV(unsigned int const width,
+        unsigned int const height,
+        uint8 **     const orig_y,
+        uint8 **     const orig_cr,
+        uint8 **     const orig_cb){
 
-    int y;
+    unsigned int y;
 
     if (orig_y) {
-       for (y = 0; y < height; y++)
+       for (y = 0; y < height; ++y)
            free(orig_y[y]);
        free(orig_y);
     }
 
     if (orig_cr) {
-       for (y = 0; y < height / 2; y++)
+       for (y = 0; y < height / 2; ++y)
            free(orig_cr[y]);
        free(orig_cr);
     }
 
     if (orig_cb) {
-       for (y = 0; y < height / 2; y++)
+       for (y = 0; y < height / 2; ++y)
            free(orig_cb[y]);
        free(orig_cb);
     }
@@ -316,81 +330,84 @@ FreeYUV(const int width, const int height,
 
 
 int
-main(int argc, char **argv) {
-    const char *input_filename;  /* NULL for stdin */
-    FILE * ifp;
+main(int argc, const char **argv) {
+
+    const char *inputFilename;  /* NULL for stdin */
+    FILE * ifP;
     int width, height;
     pixval maxval;
-    pixel **ppm_image;   /* malloc'ed */
+    pixel ** ppmImage;   /* malloc'ed */
     uint8 **orig_y, **orig_cr, **orig_cb;
-        /* orig_y is the height x width array of individual pixel luminances 
+        /* orig_y is the height x width array of individual pixel luminances
            orig_cr and orig_cb are the height/2 x width/2 arrays of average
            red and blue chrominance values over each 4 pixel square.
         */
     int eof;
 
-    /* The following are width, height, and maxval of the image we 
-       processed before this one.  Zero if there was no image before 
+    /* The following are width, height, and maxval of the image we
+       processed before this one.  Zero if there was no image before
        this one.
     */
-    int last_width, last_height;
-    pixval last_maxval;
+    int lastWidth, lastHeight;
+    pixval lastMaxval;
 
-    ppm_init(&argc, argv);
+    pm_proginit(&argc, argv);
 
-    if (argc > 2) {
+    if (argc-1 > 1) {
         pm_error("Program takes either one argument -- "
                 "the input filename -- or no arguments (input is stdin)");
         exit(1);
-    } else if (argc == 2)
-        input_filename = argv[1];
-    else input_filename = NULL;
+    } else if (argc-1 > 0)
+        inputFilename = argv[1];
+    else
+        inputFilename = "-";
 
-    if (input_filename == NULL) ifp = stdin;
-    else ifp = pm_openr(input_filename);
+    ifP = pm_openr(inputFilename);
 
-    eof = FALSE;
-    last_maxval = 0;  /* No previous maxval */
-    last_width = 0;	/* No previous width */
-    last_height = 0;	/* No previous height */
+    eof = false;  /* EOF not yet encountered */
+    lastMaxval = 0;  /* No previous maxval */
+    lastWidth = 0;      /* No previous width */
+    lastHeight = 0;     /* No previous height */
     orig_y = orig_cr = orig_cb = 0;
 
     while (!eof) {
-        ppm_image = ppm_readppm(ifp, &width, &height, &maxval);
+        ppmImage = ppm_readppm(ifP, &width, &height, &maxval);
 
-        if (width % 2 != 0) 
+        if (width % 2 != 0)
             pm_message("Input image has odd number of columns.  The rightmost "
                        "column will be omitted from the output.");
-        if (height % 2 != 0) 
+        if (height % 2 != 0)
             pm_message("Input image has odd number of rows.  The bottom "
                        "row will be omitted from the output.");
 
-        if (maxval != last_maxval) {
+        if (maxval != lastMaxval) {
             /* We're going to need all new multiplication tables. */
-            free_multiplication_tables();
-            create_multiplication_tables(maxval);
+            freeMultiplicationTables();
+            createMultiplicationTables(maxval);
         }
-        last_maxval = maxval;
-        
-        if (height != last_height || width != last_width) {
-            FreeYUV(width, height, orig_y, orig_cr, orig_cb);
+        lastMaxval = maxval;
+
+        if (height != lastHeight || width != lastWidth) {
+            freeYUV(width, height, orig_y, orig_cr, orig_cb);
             /* Need new YUV buffers for different size */
-            AllocYUV(width, height, &orig_y, &orig_cr, &orig_cb);
+            allocYUV(width, height, &orig_y, &orig_cr, &orig_cb);
         }
-        last_height = height;
-        last_width = width;
+        lastHeight = height;
+        lastWidth  = width;
 
-        PPMtoYUV(ppm_image, width, height, &orig_y, &orig_cr, &orig_cb);
+        ppmToYuv(ppmImage, width, height, &orig_y, &orig_cr, &orig_cb);
 
-        WriteYUV(stdout, (width/2)*2, (height/2)*2, orig_y, orig_cr, orig_cb);
+        writeYUV(stdout, (width/2)*2, (height/2)*2, orig_y, orig_cr, orig_cb);
 
-        ppm_freearray(ppm_image, height);
-        ppm_nextimage(ifp, &eof);
+        ppm_freearray(ppmImage, height);
+        ppm_nextimage(ifP, &eof);
     }
-    FreeYUV(width, height, orig_y, orig_cr, orig_cb);
-    free_multiplication_tables();
-    pm_close(ifp);
-        
+    freeYUV(width, height, orig_y, orig_cr, orig_cb);
+    freeMultiplicationTables();
+    pm_close(ifP);
+
     return 0;
 }
 
+
+
diff --git a/converter/ppm/ppmtogif.c b/converter/ppm/ppmtogif.c
index 8dd133b5..b50a934d 100644
--- a/converter/ppm/ppmtogif.c
+++ b/converter/ppm/ppmtogif.c
@@ -14,6 +14,7 @@
 #define _BSD_SOURCE   /* Make sure strdup() is in string.h */
 #define _XOPEN_SOURCE 500  /* Make sure strdup() is in string.h */
 
+#include <stdbool.h>
 #include <assert.h>
 #include <string.h>
 #include <stdio.h>
@@ -46,19 +47,19 @@ dirname(const char * const fileName) {
 
 
 
-struct cmdlineInfo {
+struct CmdlineInfo {
     /* All the information the user supplied in the command line,
        in a form easy for the program to use.
     */
-    const char *inputFileName;  /* Name of input file */
-    const char *alpha_filespec; /* Filespec of alpha file; NULL if none */
-    const char *alphacolor;     /* -alphacolor option value or default */
-    unsigned int interlace;     /* -interlace option value */
-    unsigned int sort;          /* -sort option value */
-    const char *mapfile;        /* -mapfile option value.  NULL if none. */
-    const char *transparent;    /* -transparent option value.  NULL if none. */
-    const char *comment;        /* -comment option value; NULL if none */
-    unsigned int nolzw;         /* -nolzw option */
+    const char * inputFileName;  /* Name of input file */
+    const char * alpha_filespec; /* Filespec of alpha file; NULL if none */
+    const char * alphacolor;     /* -alphacolor option value or default */
+    unsigned int interlace;      /* -interlace option value */
+    unsigned int sort;           /* -sort option value */
+    const char * mapfile;        /* -mapfile option value.  NULL if none. */
+    const char * transparent;    /* -transparent option value.  NULL if none.*/
+    const char * comment;        /* -comment option value; NULL if none */
+    unsigned int nolzw;          /* -nolzw option */
     unsigned int verbose;
 };
 
@@ -78,8 +79,8 @@ handleLatex2htmlHack(void) {
 
   So we issue a special error message just to trick latex2html into
   deciding that we have -interlace and -transparent options.  The function
-  is not documented in the man page.  We would like to see Latex2html 
-  either stop checking or check like configure programs usually do -- 
+  is not documented in the man page.  We would like to see Latex2html
+  either stop checking or check like configure programs usually do --
   try the option and see if you get success or failure.
 
   -Bryan 2001.11.14
@@ -93,7 +94,7 @@ handleLatex2htmlHack(void) {
 
 static void
 parseCommandLine(int argc, const char ** argv,
-                 struct cmdlineInfo * const cmdlineP) {
+                 struct CmdlineInfo * const cmdlineP) {
 /*----------------------------------------------------------------------------
    Parse the program arguments (given by argc and argv) into a form
    the program can deal with more easily -- a cmdline_info structure.
@@ -112,48 +113,48 @@ parseCommandLine(int argc, const char ** argv,
     MALLOCARRAY_NOFAIL(option_def, 100);
 
     option_def_index = 0;   /* incremented by OPTENT3 */
-    OPTENT3(0,   "interlace",   OPT_FLAG,   
+    OPTENT3(0,   "interlace",   OPT_FLAG,
             NULL,                       &cmdlineP->interlace, 0);
-    OPTENT3(0,   "sort",        OPT_FLAG,   
+    OPTENT3(0,   "sort",        OPT_FLAG,
             NULL,                       &cmdlineP->sort, 0);
-    OPTENT3(0,   "nolzw",       OPT_FLAG,   
+    OPTENT3(0,   "nolzw",       OPT_FLAG,
             NULL,                       &cmdlineP->nolzw, 0);
-    OPTENT3(0,   "mapfile",     OPT_STRING, 
+    OPTENT3(0,   "mapfile",     OPT_STRING,
             &cmdlineP->mapfile,        NULL, 0);
-    OPTENT3(0,   "transparent", OPT_STRING, 
+    OPTENT3(0,   "transparent", OPT_STRING,
             &cmdlineP->transparent,    NULL, 0);
-    OPTENT3(0,   "comment",     OPT_STRING, 
+    OPTENT3(0,   "comment",     OPT_STRING,
             &cmdlineP->comment,        NULL, 0);
-    OPTENT3(0,   "alpha",       OPT_STRING, 
+    OPTENT3(0,   "alpha",       OPT_STRING,
             &cmdlineP->alpha_filespec, NULL, 0);
-    OPTENT3(0,   "alphacolor",  OPT_STRING, 
+    OPTENT3(0,   "alphacolor",  OPT_STRING,
             &cmdlineP->alphacolor,     NULL, 0);
-    OPTENT3(0,   "h",           OPT_FLAG, 
+    OPTENT3(0,   "h",           OPT_FLAG,
             NULL,                       &latex2htmlhack, 0);
-    OPTENT3(0,   "verbose",     OPT_FLAG, 
+    OPTENT3(0,   "verbose",     OPT_FLAG,
             NULL,                       &cmdlineP->verbose, 0);
-    
+
     /* Set the defaults */
     cmdlineP->mapfile = NULL;
     cmdlineP->transparent = NULL;  /* no transparency */
     cmdlineP->comment = NULL;      /* no comment */
     cmdlineP->alpha_filespec = NULL;      /* no alpha file */
-    cmdlineP->alphacolor = "rgb:0/0/0";      
+    cmdlineP->alphacolor = "rgb:0/0/0";
         /* We could say "black" here, but then we depend on the color names
            database existing.
         */
 
     opt.opt_table = option_def;
-    opt.short_allowed = FALSE;  /* We have no short (old-fashioned) options */
-    opt.allowNegNum = FALSE;  /* We have no parms that are negative numbers */
+    opt.short_allowed = false;  /* We have no short (old-fashioned) options */
+    opt.allowNegNum = false;  /* We have no parms that are negative numbers */
 
-    pm_optParseOptions3(&argc, (char **)argv, opt, sizeof(opt), 0);
+    pm_optParseOptions4(&argc, argv, opt, sizeof(opt), 0);
         /* Uses and sets argc, argv, and some of *cmdlineP and others. */
 
-    if (latex2htmlhack) 
+    if (latex2htmlhack)
         handleLatex2htmlHack();
 
-    if (argc-1 == 0) 
+    if (argc-1 == 0)
         cmdlineP->inputFileName = "-";
     else if (argc-1 != 1)
         pm_error("Program takes zero or one argument (filename).  You "
@@ -206,7 +207,7 @@ openPnmremapStream(const char * const inputFileName,
 
 static const char *
 pamtogifCommand(const char *       const arg0,
-                struct cmdlineInfo const cmdline) {
+                struct CmdlineInfo const cmdline) {
 
     const char * const pamtogifName = "pamtogif";
 
@@ -252,7 +253,7 @@ pamtogifCommand(const char *       const arg0,
                 commentOpt,
                 cmdline.nolzw ? "-nolzw" : "",
                 cmdline.verbose ? "-verbose" : "");
-    
+
     pm_strfree(transparentOpt);
     pm_strfree(commentOpt);
 
@@ -264,7 +265,7 @@ pamtogifCommand(const char *       const arg0,
 static void
 feedPamtogifNoAlpha(struct pam * const inPamP,
                     FILE *       const pipeToPamtogif) {
-    
+
     unsigned int row;
     struct pam outPam;
     tuple * tuplerow;
@@ -273,7 +274,7 @@ feedPamtogifNoAlpha(struct pam * const inPamP,
 
     outPam = *inPamP;
     outPam.file = pipeToPamtogif;
-    
+
     pnm_writepaminit(&outPam);
 
     for (row = 0; row < inPamP->height; ++row) {
@@ -303,7 +304,7 @@ copyRasterWithAlpha(struct pam * const inPamP,
 
     for (row = 0; row < inPamP->height; ++row) {
         unsigned int col;
-            
+
         pnm_readpamrow(inPamP, tuplerow);
         pnm_readpamrow(alphaPamP, alpharow);
 
@@ -360,7 +361,7 @@ static void
 feedPamtogif(struct pam * const inPamP,
              const char * const alphaFilespec,
              FILE *       const pipeToPamtogif) {
-    
+
     if (alphaFilespec) {
         FILE * afP;
         struct pam alphaPam;
@@ -378,7 +379,7 @@ int
 main(int           argc,
      const char ** argv) {
 
-    struct cmdlineInfo cmdline;
+    struct CmdlineInfo cmdline;
     FILE * ifP;
     struct pam inPam;
     const char * command;
@@ -394,12 +395,12 @@ main(int           argc,
                            cmdline.verbose, &ifP);
     else
         ifP = pm_openr(cmdline.inputFileName);
-        
+
     command = pamtogifCommand(argv[0], cmdline);
 
     if (cmdline.verbose)
         pm_message("Executing shell command '%s'", command);
-    
+
     pipeToPamtogif = popen(command, "w");
 
     if (pipeToPamtogif == NULL)
@@ -421,3 +422,6 @@ main(int           argc,
 
     return 0;
 }
+
+
+
diff --git a/converter/ppm/ppmtoicr.c b/converter/ppm/ppmtoicr.c
index 1720f790..2c9fd3a1 100644
--- a/converter/ppm/ppmtoicr.c
+++ b/converter/ppm/ppmtoicr.c
@@ -12,11 +12,139 @@
 
 #include <stdbool.h>
 #include <assert.h>
+#include <string.h>
 #include "ppm.h"
+#include "pm_c_util.h"
+#include "shhopt.h"
+#include "mallocvar.h"
+#include "nstring.h"
 
 #define MAXCOLORCT 256
 #define CLUTCOLORCT 768
 
+/* The following are arbitrary limits.  We could not find an official
+   format specification for this.
+*/
+#define MAXSIZE 32767
+#define MAXDISP 1024
+#define MAXNAMELEN 80
+
+
+struct CmdlineInfo {
+    /* All the information the user supplied in the command line,
+       in a form easy for the program to use.
+    */
+    const char * inputFilename;
+    const char * windowname;  /* NULL means not specified */
+    unsigned int expand;
+    unsigned int display;
+};
+
+
+
+
+static void
+parseCommandLine(int argc, const char ** argv,
+                 struct CmdlineInfo * const cmdlineP) {
+/*----------------------------------------------------------------------------
+   Note that the file spec array we return is stored in the storage that
+   was passed to us as the argv array.
+-----------------------------------------------------------------------------*/
+    optEntry * option_def;
+    optStruct3 opt;
+
+    unsigned int option_def_index;
+    unsigned int windowNameSpec;
+    unsigned int rleSpec;
+    unsigned int expandSpec;
+    unsigned int displaySpec;
+
+    MALLOCARRAY(option_def, 100);
+
+    option_def_index = 0;   /* incremented by OPTENTRY */
+
+    OPTENT3(0,   "windowname",  OPT_STRING, &cmdlineP->windowname,
+            &windowNameSpec, 0);
+    OPTENT3(0,   "expand",      OPT_UINT,   &cmdlineP->expand,
+            &expandSpec,     0);
+    OPTENT3(0,   "display",     OPT_UINT,   &cmdlineP->display,
+            &displaySpec,    0);
+    OPTENT3(0,   "rle",         OPT_FLAG,   NULL,
+            &rleSpec,        0);
+
+    opt.opt_table = option_def;
+    opt.short_allowed = false;  /* We have no short (old-fashioned) options */
+    opt.allowNegNum = false;  /* We may have parms that are negative numbers */
+
+    pm_optParseOptions4(&argc, argv, opt, sizeof(opt), 0);
+        /* Uses and sets argc, argv, and some of *cmdlineP and others. */
+
+    if (!expandSpec)
+        cmdlineP->expand = 1;
+
+    if (!displaySpec)
+        cmdlineP->display = 0;
+
+    if (rleSpec)
+        pm_error("The -rle command line option no longer exists.");
+
+    if (cmdlineP->expand == 0)
+        pm_error("-expand value must be positive.");
+
+    if (cmdlineP->display > MAXDISP)
+        pm_error("-display value is too large.  Maximum is %u", MAXDISP);
+
+    if (argc-1 < 1) {
+        cmdlineP->inputFilename = "-";
+    } else
+        cmdlineP->inputFilename = argv[1];
+
+    if (argc-1 > 1)
+        pm_error("Program takes zero or one argument (filename).  You "
+                 "specified %u", argc-1);
+
+    if (windowNameSpec) {
+        if (strlen(cmdlineP->windowname) > MAXNAMELEN)
+            pm_error("-windowname value is too long.  (max %u chars)",
+                      MAXNAMELEN);
+        {
+            unsigned int i;
+            for (i = 0; cmdlineP->windowname[i]; ++i) {
+                if (!isprint (cmdlineP->windowname[i]))
+                    pm_error("-window option contains nonprintable character");
+                if (cmdlineP->windowname[i] =='^') {
+                    /* '^' terminates the window name string in ICR */
+                    pm_error("-windowname option value '%s' contains "
+                             "disallowed '^' character.",
+                             cmdlineP->windowname);
+                }
+            }
+        }
+    } else
+        cmdlineP->windowname = NULL;
+}
+
+
+
+static void
+validateComputableSize(unsigned int const cols,
+                       unsigned int const rows,
+                       unsigned int const expand) {
+/*----------------------------------------------------------------------------
+  We don't have any information on what the limit for these values should be.
+
+  The ICR protocol was used around 1990 when PC main memory was measured in
+  megabytes.
+-----------------------------------------------------------------------------*/
+
+    if (cols > MAXSIZE / expand)
+        pm_error("image width (%f) too large to be processed",
+                 (float) cols * expand);
+    if (rows > MAXSIZE / expand)
+        pm_error("image height (%f) too large to be processed",
+                 (float) rows * expand);
+}
+
 
 
 static void
@@ -130,70 +258,60 @@ sendOutPicture(pixel **        const pixels,
 
 
 
-int
+static const char *
+windowNameFmFileName(const char * const fileName) {
+
+    /* Use the input file name, with unprintable characters and '^'
+       replaced with '.'.  '^' terminates the window name string in
+       the output file.  Truncate if necessary.
+    */
+    char * windowName;  /* malloced */
+    unsigned int i;
+
+    windowName = malloc(MAXNAMELEN+1);
+    if (!windowName)
+        pm_error("Failed to get %u bytes of memory for window name "
+                 "buffer", MAXNAMELEN+1);
+
+    for (i = 0; i < MAXNAMELEN && fileName[i]; ++i) {
+        const char thisChar = fileName[i];
+
+        if (!isprint(thisChar) || thisChar =='^')
+            windowName[i] = '.';
+        else
+            windowName[i] = thisChar;
+    }
+    windowName[i] = '\0';
+
+    return windowName;
+}
+
+
+
+            int
 main(int argc, const char ** const argv) {
 
     FILE * ifP;
     int rows, cols;
     int colorCt;
-    int argn;
     pixval maxval;
     colorhist_vector chv;
     char rgb[CLUTCOLORCT];
-    const char * windowName;
-    int display, expand;
-    int winflag;
-    const char* const usage = "[-windowname windowname] [-expand expand] [-display display] [ppmfile]";
-    pixel** pixels;
+    pixel ** pixels;
     colorhash_table cht;
+    struct CmdlineInfo cmdline;
+    const char * windowName;
 
     pm_proginit(&argc, argv);
 
-    argn = 1;
-    windowName = "untitled";
-    winflag = 0;
-    expand = 1;
-    display = 0;
+    parseCommandLine(argc, argv, &cmdline);
 
-    while ( argn < argc && argv[argn][0] == '-' && argv[argn][1] != '\0' )
-    {
-        if ( pm_keymatch(argv[argn],"-windowname",2) && argn + 1 < argc )
-        {
-            ++argn;
-            windowName = argv[argn];
-            winflag = 1;
-        }
-        else if ( pm_keymatch(argv[argn],"-expand",2) && argn + 1 < argc )
-        {
-            ++argn;
-            if ( sscanf( argv[argn], "%d",&expand ) != 1 )
-                pm_usage( usage );
-        }
-        else if ( pm_keymatch(argv[argn],"-display",2) && argn + 1 < argc )
-        {
-            ++argn;
-            if ( sscanf( argv[argn], "%d",&display ) != 1 )
-                pm_usage( usage );
-        }
-        else
-            pm_usage( usage );
-    }
-
-    if ( argn < argc )
-    {
-        ifP = pm_openr( argv[argn] );
-        if ( ! winflag )
-            windowName = argv[argn];
-        ++argn;
-    }
-    else
-        ifP = stdin;
-
-    if ( argn != argc )
-        pm_usage( usage );
+    ifP = pm_openr(cmdline.inputFilename);
 
     pixels = ppm_readppm(ifP, &cols, &rows, &maxval);
 
+    validateComputableSize(cols, rows, cmdline.expand);
+
     pm_close(ifP);
 
     /* Figure out the colormap. */
@@ -213,17 +331,28 @@ main(int argc, const char ** const argv) {
     /************** Create a new window using ICR protocol *********/
     /* Format is "ESC^W;left;top;width;height;display;windowname"  */
 
-    pm_message("Creating window %s ...", windowName);
+    if (cmdline.windowname)
+        windowName = pm_strdup(cmdline.windowname);
+    else {
+        if (streq(cmdline.inputFilename, "-"))
+            windowName = pm_strdup("untitled");
+        else
+            windowName = windowNameFmFileName(cmdline.inputFilename);
+    }
+    pm_message("Creating window '%s' ...", windowName);
 
     printf("\033^W;%d;%d;%d;%d;%d;%s^",
-           0, 0, cols * expand, rows * expand, display, windowName);
+           0, 0, cols * cmdline.expand, rows * cmdline.expand,
+                 cmdline.display, windowName);
     fflush(stdout);
 
     /****************** Download the colormap.  ********************/
 
     downloadColormap(rgb, windowName);
 
-    sendOutPicture(pixels, rows, cols, cht, expand, windowName);
+    sendOutPicture(pixels, rows, cols, cht, cmdline.expand, windowName);
+
+    pm_strfree(windowName);
 
     return 0;
 }
diff --git a/converter/ppm/ppmtoilbm.c b/converter/ppm/ppmtoilbm.c
index 595aa3f4..c91315c3 100644
--- a/converter/ppm/ppmtoilbm.c
+++ b/converter/ppm/ppmtoilbm.c
@@ -73,7 +73,6 @@
 #include "pm_c_util.h"
 #include "mallocvar.h"
 #include "ppm.h"
-#include "ppmfloyd.h"
 #include "pbm.h"
 #include "runlength.h"
 #include "ilbm.h"
@@ -118,13 +117,13 @@
 static unsigned char *coded_rowbuf; /* buffer for uncompressed scanline */
 static unsigned char *compr_rowbuf; /* buffer for compressed scanline */
 static pixel **pixels;  /* PPM image (NULL for row-by-row operation) */
-static pixel *pixrow;   
+static pixel *pixrow;
     /* current row in PPM image (pointer into pixels array, or buffer
-       for row-by-row operation) 
+       for row-by-row operation)
     */
 
 static long viewportmodes = 0;
-static int slicesize = 1; 
+static int slicesize = 1;
     /* rows per slice for multipalette images - NOT USED */
 
 static unsigned char compmethod = DEF_COMPRESSION;   /* default compression */
@@ -155,9 +154,8 @@ static bodyblock *cur_block = &firstblock;
 static char *anno_chunk, *auth_chunk, *name_chunk, *text_chunk, *copyr_chunk;
 
 /* flags */
-static short compr_force = 0;   
+static short compr_force = 0;
     /* force compressed output, even if the image got larger  - NOT USED */
-static short floyd = 0;         /* apply floyd-steinberg error diffusion */
 static short gen_camg = 0;      /* write CAMG chunk */
 
 #define WORSTCOMPR(bytes)       ((bytes) + (bytes)/128 + 1)
@@ -346,6 +344,7 @@ writeTextChunks(void) {
 }
 
 
+
 static void
 writeCmap(pixel * const colormap,
           int     const colors,
@@ -360,7 +359,7 @@ writeCmap(pixel * const colormap,
     pm_writebiglong(stdout, cmapsize);
     if( maxval != MAXCOLVAL ) {
         int *table;
-        pm_message("maxval is not %d - automatically rescaling colors", 
+        pm_message("maxval is not %d - automatically rescaling colors",
                    MAXCOLVAL);
         table = makeValTable(maxval, MAXCOLVAL);
         for( i = 0; i < colors; i++ ) {
@@ -457,7 +456,7 @@ compressRow(unsigned int const bytes) {
                 &compressedByteCt);
             break;
         default:
-            pm_error("compressRow(): unknown compression method %d", 
+            pm_error("compressRow(): unknown compression method %d",
                      compmethod);
     }
     storeBodyrow(compr_rowbuf, compressedByteCt);
@@ -485,7 +484,7 @@ encodeRow(FILE *    const outfile,
     int plane, bytes;
     long retbytes = 0;
 
-    bytes = RowBytes(cols);
+    bytes = ilbm_rowByteCt(cols);
 
     /* Encode and write raw bytes in plane-interleaved form. */
     for( plane = 0; plane < nPlanes; plane++ ) {
@@ -551,35 +550,35 @@ reportTooManyColors(int         const ifmode,
                     int         const hamplanes,
                     DirectColor const dcol,
                     int         const deepbits) {
-    
+
     int const maxcolors = 1 << maxplanes;
 
     switch( ifmode ) {
     case MODE_HAM:
         pm_message("too many colors for %d planes - "
-                   "proceeding to write a HAM%d file", 
+                   "proceeding to write a HAM%d file",
                    maxplanes, hamplanes);
-        pm_message("if you want a non-HAM file, try doing a 'pnmquant %d'", 
+        pm_message("if you want a non-HAM file, try doing a 'pnmquant %d'",
                    maxcolors);
         break;
     case MODE_DCOL:
         pm_message("too many colors for %d planes - "
-                   "proceeding to write a %d:%d:%d direct color ILBM", 
+                   "proceeding to write a %d:%d:%d direct color ILBM",
                    maxplanes, dcol.r, dcol.g, dcol.b);
         pm_message("if you want a non-direct color file, "
                    "try doing a 'pnmquant %d'", maxcolors);
         break;
     case MODE_DEEP:
         pm_message("too many colors for %d planes - "
-                   "proceeding to write a %d-bit \'deep\' ILBM", 
+                   "proceeding to write a %d-bit \'deep\' ILBM",
                    maxplanes, deepbits*3);
         pm_message("if you want a non-deep file, "
-                   "try doing a 'pnmquant %d'", 
+                   "try doing a 'pnmquant %d'",
                    maxcolors);
         break;
     default:
         pm_error("too many colors for %d planes - "
-                 "try doing a 'pnmquant %d'", 
+                 "try doing a 'pnmquant %d'",
                  maxplanes, maxcolors);
         break;
     }
@@ -599,7 +598,7 @@ getIntVal(const char * const string,
         pm_error("option \"%s\" needs integer argument", option);
 
     if (val < bot || val > top)
-        pm_error("option \"%s\" argument value out of range (%d..%d)", 
+        pm_error("option \"%s\" argument value out of range (%d..%d)",
                  option, bot, top);
 
     return val;
@@ -613,10 +612,10 @@ getComprMethod(const char * const string) {
     int retval;
     if( pm_keymatch(string, "none", 1) || pm_keymatch(string, "0", 1) )
         retval = cmpNone;
-    else if( pm_keymatch(string, "byterun1", 1) || 
+    else if( pm_keymatch(string, "byterun1", 1) ||
              pm_keymatch(string, "1", 1) )
         retval = cmpByteRun1;
-    else 
+    else
         pm_error("unknown compression method: %s", string);
     return retval;
 }
@@ -631,12 +630,12 @@ getMaskType(const char * const string) {
     if( pm_keymatch(string, "none", 1) || pm_keymatch(string, "0", 1) )
         retval = mskNone;
     else
-    if( pm_keymatch(string, "plane", 1) || 
+    if( pm_keymatch(string, "plane", 1) ||
         pm_keymatch(string, "maskplane", 1) ||
         pm_keymatch(string, "1", 1) )
         retval = mskHasMask;
     else
-    if( pm_keymatch(string, "transparentcolor", 1) || 
+    if( pm_keymatch(string, "transparentcolor", 1) ||
         pm_keymatch(string, "2", 1) )
         retval = mskHasTransparentColor;
     else
@@ -665,7 +664,7 @@ getHammapMode(const char * const string) {
     else
     if( pm_keymatch(string, "rgb5", 4) )
         retval = HAMMODE_RGB5;
-    else 
+    else
         pm_error("unknown HAM colormap selection mode: %s", string);
     return retval;
 }
@@ -726,7 +725,7 @@ hcmp(const void * const a,
     const hentry * const vaP = a;
     const hentry * const vbP = b;
 
-    return(vbP->count - vaP->count);  
+    return(vbP->count - vaP->count);
 }
 
 
@@ -801,17 +800,17 @@ computeHamCmap(int   const cols,
                     if( dist <= maxdist ) {
                         unsigned int sum = hmap[i].count + hmap[col].count;
 
-                        hmap[i].r = ROUNDDIV(hmap[i].r * hmap[i].count + 
+                        hmap[i].r = ROUNDDIV(hmap[i].r * hmap[i].count +
                                              r * hmap[col].count, sum);
-                        hmap[i].g = ROUNDDIV(hmap[i].g * hmap[i].count + 
+                        hmap[i].g = ROUNDDIV(hmap[i].g * hmap[i].count +
                                              g * hmap[col].count, sum);
-                        hmap[i].b = ROUNDDIV(hmap[i].b * hmap[i].count + 
+                        hmap[i].b = ROUNDDIV(hmap[i].b * hmap[i].count +
                                              b * hmap[col].count, sum);
                         hmap[i].count = sum;
 
                         hmap[col] = hmap[i];    /* temp store */
-                        for( tmp = i-1; 
-                             tmp >= 0 && hmap[tmp].count < hmap[col].count; 
+                        for( tmp = i-1;
+                             tmp >= 0 && hmap[tmp].count < hmap[col].count;
                              tmp-- )
                             hmap[tmp+1] = hmap[tmp];
                         hmap[tmp+1] = hmap[col];
@@ -878,7 +877,6 @@ doHamBody(FILE *  const ifP,
 
     int col, row, i;
     rawtype *raw_rowbuf;
-    ppm_fs_info *fi = NULL;
     colorhash_table cht, cht2;
     long bodysize = 0;
     int *itoh;      /* table image -> ham */
@@ -898,9 +896,6 @@ doHamBody(FILE *  const ifP,
 
     itoh = makeValTable(maxval, hammaxval);
 
-    if( floyd )
-        fi = ppm_fs_init(cols, maxval, 0);
-
     for( row = 0; row < rows; row++ ) {
         int noprev;
         int spr, spg, spb;   /* scaled values of previous pixel */
@@ -909,9 +904,7 @@ doHamBody(FILE *  const ifP,
 
         noprev = 1;
         prow = nextPixrow(ifP, row);
-        for( col = ppm_fs_startrow(fi, prow); 
-             col < cols; 
-             col = ppm_fs_next(fi, col) ) {
+        for( col = 0; col < cols; ++col ) {
 
             pixel const p = prow[col];
 
@@ -930,15 +923,15 @@ doHamBody(FILE *  const ifP,
                 int ucr, ucg, ucb;  /* unscaled values of colormap entry */
 
                 if(  hammapmode == HAMMODE_GRAY ) {
-                    if( maxval <= 255 ) 
-                        /* Use fast approximation to 
+                    if( maxval <= 255 )
+                        /* Use fast approximation to
                            0.299 r + 0.587 g + 0.114 b. */
                         i = (int)ppm_fastlumin(p);
-                    else 
-                        /* Can't use fast approximation, 
-                           so fall back on floats. 
+                    else
+                        /* Can't use fast approximation,
+                           so fall back on floats.
                         */
-                        i = (int)(PPM_LUMIN(p) + 0.5); 
+                        i = (int)(PPM_LUMIN(p) + 0.5);
                             /* -IUW added '+ 0.5' */
                     i = itoh[i];
                 }
@@ -956,8 +949,8 @@ doHamBody(FILE *  const ifP,
                         }
                     }
                 }
-                ucr = PPM_GETR(colormap[i]); 
-                ucg = PPM_GETG(colormap[i]); 
+                ucr = PPM_GETR(colormap[i]);
+                ucg = PPM_GETG(colormap[i]);
                 ucb = PPM_GETB(colormap[i]);
 
                 if( noprev ) {  /* no previous pixel, must use colormap */
@@ -985,21 +978,21 @@ doHamBody(FILE *  const ifP,
                         (sb - scb)*(sb - scb);
 #endif
 
-                    if( di <= dr && di <= dg && di <= db ) {    
+                    if( di <= dr && di <= dg && di <= db ) {
                         /* prefer colormap lookup */
-                        raw_rowbuf[col] = i; 
+                        raw_rowbuf[col] = i;
                         upr = ucr;  upg = ucg;  upb = ucb;
                         spr = scr;  spg = scg;  spb = scb;
                     }
                     else
                     if( db <= dr && db <= dg ) {
-                        raw_rowbuf[col] = sb + hamcode_blue; 
+                        raw_rowbuf[col] = sb + hamcode_blue;
                         spb = sb;
                         upb = ub;
                     }
                     else
                     if( dr <= dg ) {
-                        raw_rowbuf[col] = sr + hamcode_red;  
+                        raw_rowbuf[col] = sr + hamcode_red;
                         spr = sr;
                         upr = ur;
                     }
@@ -1012,19 +1005,17 @@ doHamBody(FILE *  const ifP,
             }
             else {  /* prefect match in cmap */
                 raw_rowbuf[col] = i;    /* + (HAMCODE_CMAP << colbits) */
-                upr = PPM_GETR(colormap[i]); 
-                upg = PPM_GETG(colormap[i]); 
+                upr = PPM_GETR(colormap[i]);
+                upg = PPM_GETG(colormap[i]);
                 upb = PPM_GETB(colormap[i]);
-                spr = itoh[upr];            
-                spg = itoh[upg];            
+                spr = itoh[upr];
+                spg = itoh[upg];
                 spb = itoh[upb];
             }
-            ppm_fs_update3(fi, col, upr, upg, upb);
         }
         bodysize += encodeRow(ofP, raw_rowbuf, cols, nPlanes);
         if( maskmethod == mskHasMask )
             bodysize += encodeMaskrow(ofP, raw_rowbuf, cols);
-        ppm_fs_endrow(fi);
     }
     if( ofP && ODD(bodysize) )
         putByte(0);
@@ -1033,7 +1024,6 @@ doHamBody(FILE *  const ifP,
 
     /* clean up */
     free(raw_rowbuf);
-    ppm_fs_free(fi);
 
     return bodysize;
 }
@@ -1113,12 +1103,12 @@ ppmToHam(FILE *  const ifP,
             }
             break;
             case HAMMODE_RGB4:
-                colormap = computeHamCmap(cols, rows, maxval, hamcolors, 
+                colormap = computeHamCmap(cols, rows, maxval, hamcolors,
                                           &colors, 4);
                 cmapmaxval = 15;
                 break;
             case HAMMODE_RGB5:
-                colormap = computeHamCmap(cols, rows, maxval, 
+                colormap = computeHamCmap(cols, rows, maxval,
                                           hamcolors, &colors, 5);
                 cmapmaxval = 31;
                 break;
@@ -1129,7 +1119,7 @@ ppmToHam(FILE *  const ifP,
     else {
         hammapmode = HAMMODE_MAPFILE;
         if( colors > hamcolors ) {
-            pm_message("colormap too large - using first %d colors", 
+            pm_message("colormap too large - using first %d colors",
                        hamcolors);
             colors = hamcolors;
         }
@@ -1142,9 +1132,9 @@ ppmToHam(FILE *  const ifP,
         newcmap = ppm_allocrow(colors);
         table = makeValTable(cmapmaxval, maxval);
         for( i = 0; i < colors; i++ )
-            PPM_ASSIGN(newcmap[i], 
-                       table[PPM_GETR(colormap[i])], 
-                       table[PPM_GETG(colormap[i])], 
+            PPM_ASSIGN(newcmap[i],
+                       table[PPM_GETR(colormap[i])],
+                       table[PPM_GETG(colormap[i])],
                        table[PPM_GETB(colormap[i])]);
         free(table);
         ppm_freerow(colormap);
@@ -1156,18 +1146,18 @@ ppmToHam(FILE *  const ifP,
     nPlanes = hamplanes;
     cmapsize = colors * 3;
 
-    bodysize = oldsize = rows * TOTALPLANES(nPlanes) * RowBytes(cols);
+    bodysize = oldsize = rows * TOTALPLANES(nPlanes) * ilbm_rowByteCt(cols);
     if( DO_COMPRESS ) {
-        bodysize = doHamBody(ifP, NULL, cols, rows, maxval, 
+        bodysize = doHamBody(ifP, NULL, cols, rows, maxval,
                                hammaxval, nPlanes, colormap, colors);
-        /*bodysize = doHamBody(ifP, NULL, cols, 
+        /*bodysize = doHamBody(ifP, NULL, cols,
           rows, maxval, hammaxval, nPlanes, colbits, nocolor);*/
         if( bodysize > oldsize )
             pm_message("warning - %s compression increases BODY size "
-                       "by %ld%%", 
+                       "by %ld%%",
                        cmpNAME[compmethod], 100*(bodysize-oldsize)/oldsize);
         else
-            pm_message("BODY compression (%s): %ld%%", 
+            pm_message("BODY compression (%s): %ld%%",
                        cmpNAME[compmethod], 100*(oldsize-bodysize)/oldsize);
     }
 
@@ -1195,7 +1185,7 @@ ppmToHam(FILE *  const ifP,
     if( DO_COMPRESS )
         writeBodyRows();
     else
-        doHamBody(ifP, stdout, cols, rows, maxval, hammaxval, 
+        doHamBody(ifP, stdout, cols, rows, maxval, hammaxval,
                   nPlanes, colormap, colors);
 }
 
@@ -1210,7 +1200,7 @@ doDeepBody(FILE * const ifP,
            FILE * const ofP,
            int    const cols,
            int    const rows,
-           pixval const maxval, 
+           pixval const maxval,
            int    const bitspercolor) {
 
     int row, col;
@@ -1226,7 +1216,7 @@ doDeepBody(FILE * const ifP,
 
     newmaxval = pm_bitstomaxval(bitspercolor);
     if( maxval != newmaxval ) {
-        pm_message("maxval is not %d - automatically rescaling colors", 
+        pm_message("maxval is not %d - automatically rescaling colors",
                    newmaxval);
         table = makeValTable(maxval, newmaxval);
     }
@@ -1287,14 +1277,14 @@ ppmToDeep(FILE * const ifP,
 
     nPlanes = 3*bitspercolor;
 
-    bodysize = oldsize = rows * TOTALPLANES(nPlanes) * RowBytes(cols);
+    bodysize = oldsize = rows * TOTALPLANES(nPlanes) * ilbm_rowByteCt(cols);
     if( DO_COMPRESS ) {
         bodysize = doDeepBody(ifP, NULL, cols, rows, maxval, bitspercolor);
         if( bodysize > oldsize )
             pm_message("warning - %s compression increases BODY size by %ld%%",
                        cmpNAME[compmethod], 100*(bodysize-oldsize)/oldsize);
         else
-            pm_message("BODY compression (%s): %ld%%", 
+            pm_message("BODY compression (%s): %ld%%",
                        cmpNAME[compmethod], 100*(oldsize-bodysize)/oldsize);
     }
 
@@ -1335,7 +1325,7 @@ doDcolBody(FILE *        const ifP,
            FILE *        const ofP,
            int           const cols,
            int           const rows,
-           pixval        const maxval, 
+           pixval        const maxval,
            DirectColor * const dcol) {
 
     int row, col;
@@ -1400,15 +1390,15 @@ ppmToDcol(FILE *        const ifP,
 
     nPlanes = dcol->r + dcol->g + dcol->b;
 
-    bodysize = oldsize = rows * TOTALPLANES(nPlanes) * RowBytes(cols);
+    bodysize = oldsize = rows * TOTALPLANES(nPlanes) * ilbm_rowByteCt(cols);
     if( DO_COMPRESS ) {
         bodysize = doDcolBody(ifP, NULL, cols, rows, maxval, dcol);
         if( bodysize > oldsize )
             pm_message("warning - %s compression increases BODY size by %ld%%",
-                       cmpNAME[compmethod], 
+                       cmpNAME[compmethod],
                        100*(bodysize-oldsize)/oldsize);
         else
-            pm_message("BODY compression (%s): %ld%%", cmpNAME[compmethod], 
+            pm_message("BODY compression (%s): %ld%%", cmpNAME[compmethod],
                        100*(oldsize-bodysize)/oldsize);
     }
 
@@ -1467,35 +1457,30 @@ doStdBody(FILE *  const ifP,
     int row, col, i;
     pixel *pP;
     rawtype *raw_rowbuf;
-    ppm_fs_info *fi = NULL;
     long bodysize = 0;
     int usehash = 1;
     colorhash_table cht;
 
     MALLOCARRAY_NOFAIL(raw_rowbuf, cols);
     cht = ppm_colorrowtocolorhash(colormap, colors);
-    if( floyd )
-        fi = ppm_fs_init(cols, maxval, FS_ALTERNATE);
 
     for( row = 0; row < rows; row++ ) {
         pixel *prow;
         prow = nextPixrow(ifP, row);
 
-        for( col = ppm_fs_startrow(fi, prow); 
-             col < cols; 
-             col = ppm_fs_next(fi, col) ) {
+        for( col = 0; col < cols; ++col ) {
             pP = &prow[col];
 
-            if( maskmethod == mskHasTransparentColor && 
+            if( maskmethod == mskHasTransparentColor &&
                 maskrow[col] == PBM_WHITE )
                 i = transpIndex;
             else {
                 /* Check hash table to see if we have already matched
-                   this color. 
+                   this color.
                 */
                 i = ppm_lookupcolor(cht, pP);
                 if( i == -1 ) {
-                    i = ppm_findclosestcolor(colormap, colors, pP);    
+                    i = ppm_findclosestcolor(colormap, colors, pP);
                         /* No; search colormap for closest match. */
                     if( usehash ) {
                         if( ppm_addtocolorhash(cht, pP, i) < 0 ) {
@@ -1507,12 +1492,10 @@ doStdBody(FILE *  const ifP,
                 }
             }
             raw_rowbuf[col] = i;
-            ppm_fs_update(fi, col, &colormap[i]);
         }
         bodysize += encodeRow(ofP, raw_rowbuf, cols, nPlanes);
         if( maskmethod == mskHasMask )
             bodysize += encodeMaskrow(ofP, raw_rowbuf, cols);
-        ppm_fs_endrow(fi);
     }
     if( ofP && ODD(bodysize) )
         putByte(0);
@@ -1520,7 +1503,6 @@ doStdBody(FILE *  const ifP,
     /* clean up */
     ppm_freecolorhash(cht);
     free(raw_rowbuf);
-    ppm_fs_free(fi);
 
     return bodysize;
 }
@@ -1534,7 +1516,7 @@ ppmToStd(FILE *  const ifP,
          int     const maxval,
          pixel * const colormapArg,
          int     const colorsArg,
-         int     const cmapmaxvalArg, 
+         int     const cmapmaxvalArg,
          int     const maxcolors,
          int     const nPlanes) {
 
@@ -1550,7 +1532,7 @@ ppmToStd(FILE *  const ifP,
 
     if( maskmethod == mskHasTransparentColor ) {
         if( transpColor ) {
-            transpIndex = 
+            transpIndex =
                 ppm_addtocolorrow(colormap, &colors, maxcolors, transpColor);
         }
         else
@@ -1572,9 +1554,9 @@ ppmToStd(FILE *  const ifP,
         newcmap = ppm_allocrow(colors);
         table = makeValTable(cmapmaxval, maxval);
         for (i = 0; i < colors; ++i)
-            PPM_ASSIGN(newcmap[i], 
-                       table[PPM_GETR(colormap[i])], 
-                       table[PPM_GETG(colormap[i])], 
+            PPM_ASSIGN(newcmap[i],
+                       table[PPM_GETR(colormap[i])],
+                       table[PPM_GETG(colormap[i])],
                        table[PPM_GETB(colormap[i])]);
         free(table);
         colormap = newcmap;
@@ -1582,15 +1564,15 @@ ppmToStd(FILE *  const ifP,
     if( sortcmap )
         ppm_sortcolorrow(colormap, colors, PPM_STDSORT);
 
-    bodysize = oldsize = rows * TOTALPLANES(nPlanes) * RowBytes(cols);
+    bodysize = oldsize = rows * TOTALPLANES(nPlanes) * ilbm_rowByteCt(cols);
     if( DO_COMPRESS ) {
-        bodysize = doStdBody(ifP, NULL, cols, rows, maxval, colormap, 
+        bodysize = doStdBody(ifP, NULL, cols, rows, maxval, colormap,
                              colors, nPlanes);
         if( bodysize > oldsize )
             pm_message("warning - %s compression increases BODY size by %ld%%",
                        cmpNAME[compmethod], 100*(bodysize-oldsize)/oldsize);
         else
-            pm_message("BODY compression (%s): %ld%%", 
+            pm_message("BODY compression (%s): %ld%%",
                        cmpNAME[compmethod], 100*(oldsize-bodysize)/oldsize);
     }
 
@@ -1659,7 +1641,7 @@ ppmToRgb8(FILE * const ifP,
         for( col1 = 0; col1 < cols; col1 = col2 ) {
             col2 = col1 + 1;
             if( maskrow ) {
-                while( col2 < cols && PPM_EQUAL(pP[col1], pP[col2]) && 
+                while( col2 < cols && PPM_EQUAL(pP[col1], pP[col2]) &&
                        maskrow[col1] == maskrow[col2] )
                     col2++;
             }
@@ -1750,7 +1732,7 @@ ppmToRgbn(FILE * const ifP,
         for( col1 = 0; col1 < cols; col1 = col2 ) {
             col2 = col1 + 1;
             if( maskrow ) {
-                while( col2 < cols && PPM_EQUAL(pP[col1], pP[col2]) && 
+                while( col2 < cols && PPM_EQUAL(pP[col1], pP[col2]) &&
                        maskrow[col1] == maskrow[col2] )
                     col2++;
             }
@@ -1782,14 +1764,14 @@ ppmToRgbn(FILE * const ifP,
                 else {
                     ++compr_len;                  /* 3 bit repeat count = 0 */
                     if( count <= 255 )
-                        compr_row[compr_len++] = (unsigned char)count;  
+                        compr_row[compr_len++] = (unsigned char)count;
                             /* byte repeat count */
                     else {
-                        compr_row[compr_len++] = (unsigned char)0;   
+                        compr_row[compr_len++] = (unsigned char)0;
                             /* byte repeat count = 0 */
-                        compr_row[compr_len++] = (count >> 8) & 0xff; 
+                        compr_row[compr_len++] = (count >> 8) & 0xff;
                             /* word repeat count MSB */
-                        compr_row[compr_len++] = count & 0xff;    
+                        compr_row[compr_len++] = count & 0xff;
                             /* word repeat count LSB */
                     }
                 }
@@ -1878,6 +1860,7 @@ main(int argc, char ** argv) {
     pixval cmapmaxval;      /* maxval of colors in cmap */
     const char * mapfile;
     const char * transpname;
+    unsigned int defunctArgs = 0;
 
     ppm_init(&argc, argv);
 
@@ -1902,7 +1885,7 @@ main(int argc, char ** argv) {
         if( pm_keymatch(argv[argn], "-rgbn", 5) )
             forcemode = MODE_RGBN;
         else
-        if( pm_keymatch(argv[argn], "-maxplanes", 4) || 
+        if( pm_keymatch(argv[argn], "-maxplanes", 4) ||
             pm_keymatch(argv[argn], "-mp", 3) ) {
             if( ++argn >= argc )
                 pm_error("-maxplanes requires a value");
@@ -1910,7 +1893,7 @@ main(int argc, char ** argv) {
             fixplanes = 0;
         }
         else
-        if( pm_keymatch(argv[argn], "-fixplanes", 4) || 
+        if( pm_keymatch(argv[argn], "-fixplanes", 4) ||
             pm_keymatch(argv[argn], "-fp", 3) ) {
             if( ++argn >= argc )
                 pm_error("-fixplanes requires a value");
@@ -1935,7 +1918,7 @@ main(int argc, char ** argv) {
                     break;
                 default:
                     pm_error("This program does not know how to handle "
-                             "masking method '%s'", 
+                             "masking method '%s'",
                              mskNAME[maskmethod]);
             }
         }
@@ -2014,7 +1997,7 @@ main(int argc, char ** argv) {
         if( pm_keymatch(argv[argn], "-hambits", 5) ) {
             if( ++argn >= argc )
                 pm_usage("-hambits requires a value");
-            hamplanes = 
+            hamplanes =
                 getIntVal(argv[argn], argv[argn-1], 3, HAMMAXPLANES-2) +2;
         }
         else
@@ -2118,7 +2101,7 @@ main(int argc, char ** argv) {
                 forcemode = MODE_NONE;
         }
         else
-        if( pm_keymatch(argv[argn], "-dcbits", 4) || 
+        if( pm_keymatch(argv[argn], "-dcbits", 4) ||
             pm_keymatch(argv[argn], "-dcplanes", 4) ) {
             if( argc - argn < 4 )
                 pm_error("-dcbits requires 4 arguments");
@@ -2154,13 +2137,9 @@ main(int argc, char ** argv) {
             compmethod = getComprMethod(argv[argn]);
         }
         else
-        if( pm_keymatch(argv[argn], "-floyd", 3) || 
-            pm_keymatch(argv[argn], "-fs", 3) )
-            floyd = 1;
-        else
-        if( pm_keymatch(argv[argn], "-nofloyd", 5) || 
+        if( pm_keymatch(argv[argn], "-nofloyd", 5) ||
             pm_keymatch(argv[argn], "-nofs", 5) )
-            floyd = 0;
+            defunctArgs++;
         else
         if( pm_keymatch(argv[argn], "-annotation", 3) ) {
             if( ++argn >= argc )
@@ -2230,10 +2209,10 @@ main(int argc, char ** argv) {
         case MODE_CMAP:
             /* Figure out the colormap. */
             pm_message("computing colormap...");
-            colormap = ppm_mapfiletocolorrow(ifP, MAXCOLORS, &colors, 
+            colormap = ppm_mapfiletocolorrow(ifP, MAXCOLORS, &colors,
                                              &cmapmaxval);
             if (colormap == NULL)
-                pm_error("too many colors - try doing a 'pnmquant %d'", 
+                pm_error("too many colors - try doing a 'pnmquant %d'",
                          MAXCOLORS);
             pm_message("%d colors found", colors);
             break;
@@ -2241,11 +2220,11 @@ main(int argc, char ** argv) {
             if (mapfile)
                 initRead(ifP, &cols, &rows, &maxval, &format, 0);
             else {
-                initRead(ifP, &cols, &rows, &maxval, &format, 1);  
+                initRead(ifP, &cols, &rows, &maxval, &format, 1);
                     /* read file into memory */
                 pm_message("computing colormap...");
-                colormap = 
-                    ppm_computecolorrow(pixels, cols, rows, MAXCOLORS, 
+                colormap =
+                    ppm_computecolorrow(pixels, cols, rows, MAXCOLORS,
                                         &colors);
                 if (colormap) {
                     cmapmaxval = maxval;
@@ -2266,7 +2245,7 @@ main(int argc, char ** argv) {
 
         pm_message("reading colormap file...");
         mapfp = pm_openr(mapfile);
-        colormap = ppm_mapfiletocolorrow(mapfp, MAXCOLORS, &colors, 
+        colormap = ppm_mapfiletocolorrow(mapfp, MAXCOLORS, &colors,
                                          &cmapmaxval);
         pm_close(mapfp);
         if (colormap == NULL)
@@ -2274,6 +2253,7 @@ main(int argc, char ** argv) {
         if (colors == 0)
             pm_error("empty colormap??");
         pm_message("%d colors found in colormap", colors);
+        nPlanes = pm_maxvaltobits(colors-1);
     }
 
     if (maskmethod != mskNone) {
@@ -2295,17 +2275,19 @@ main(int argc, char ** argv) {
 
     if (mode != MODE_CMAP) {
         unsigned int i;
-        MALLOCARRAY_NOFAIL(coded_rowbuf, RowBytes(cols));
-        for (i = 0; i < RowBytes(cols); ++i)
+        MALLOCARRAY_NOFAIL(coded_rowbuf, ilbm_rowByteCt(cols));
+        for (i = 0; i < ilbm_rowByteCt(cols); ++i)
             coded_rowbuf[i] = 0;
         if (DO_COMPRESS)
-            pm_rlenc_allocoutbuf(&compr_rowbuf, RowBytes(cols), PM_RLE_PACKBITS);
+            pm_rlenc_allocoutbuf(&compr_rowbuf,
+                                 ilbm_rowByteCt(cols),
+                                 PM_RLE_PACKBITS);
     }
-    
+
     switch (mode) {
         case MODE_HAM:
             viewportmodes |= vmHAM;
-            ppmToHam(ifP, cols, rows, maxval, 
+            ppmToHam(ifP, cols, rows, maxval,
                      colormap, colors, cmapmaxval, hamplanes);
             break;
         case MODE_DEEP:
@@ -2324,9 +2306,7 @@ main(int argc, char ** argv) {
             ppmToCmap(colormap, colors, cmapmaxval);
             break;
         default:
-            if (mapfile == NULL)
-                floyd = 0;          /* would only slow down conversion */
-            ppmToStd(ifP, cols, rows, maxval, colormap, colors, 
+            ppmToStd(ifP, cols, rows, maxval, colormap, colors,
                      cmapmaxval, MAXCOLORS, nPlanes);
             break;
     }
diff --git a/converter/ppm/ppmtoleaf.c b/converter/ppm/ppmtoleaf.c
index dcff0985..dc73dc48 100644
--- a/converter/ppm/ppmtoleaf.c
+++ b/converter/ppm/ppmtoleaf.c
@@ -11,7 +11,7 @@
  *
  * Known problems: pgms are not converted to leaf grayscales; they are
  * converted to 8-bit color images with all gray for colors.
- * 
+ *
  */
 
 #include <stdio.h>
@@ -31,7 +31,7 @@ static int
 colorstobpp(unsigned int const colors) {
 
     int bpp;
-    
+
     if (colors <= 2)
         bpp = 1;
     else if (colors <= 256)
@@ -49,15 +49,14 @@ GetPixel(int const x,
          int const y) {
 
     int color;
-    
+
     color = ppm_lookupcolor(cht, &pixels[y][x]);
-    
+
     return color;
 }
 
 
 
-
 static void
 leaf_writeimg(unsigned int const width,
               unsigned int const height,
@@ -70,52 +69,52 @@ leaf_writeimg(unsigned int const width,
     */
 
     /* NOTE: byte order in ileaf img file fmt is big-endian, always! */
-    
+
     /* magic */
     fputc(0x89, stdout);
     fputc(0x4f, stdout);
     fputc(0x50, stdout);
     fputc(0x53, stdout);
-    
+
     /* version 4 */
     fputc(0x00, stdout);
     fputc(0x04, stdout);
-    
+
     /* h resolution: pixels/inch: say 75=screen resolution */
     fputc(0x00, stdout);
     fputc(75, stdout);
-    
+
     /* v resolution: pixels/inch: say 75=screen resolution */
     fputc(0x00, stdout);
     fputc(75, stdout);
-    
+
     /* unique id, could be anything */
     fputc(0x01, stdout);
     fputc(0x02, stdout);
     fputc(0x03, stdout);
     fputc(0x04, stdout);
-    
+
     /* x offset, always zero */
     fputc(0x00, stdout);
     fputc(0x00, stdout);
-    
+
     /* y offset, always zero */
     fputc(0x00, stdout);
     fputc(0x00, stdout);
-    
+
     /* dimensions 64k x 64k max */
     fputc((unsigned char)((width >> 8) & 0x00ff), stdout);
     fputc((unsigned char)(width  & 0x00ff), stdout);
     fputc((unsigned char)((height >> 8) & 0x00ff), stdout);
     fputc((unsigned char)(height  & 0x00ff), stdout);
-    
+
     /* depth */
     fputc(0x00, stdout);
     fputc((unsigned char)depth, stdout);
-    
+
     /* compressed, 0=uncompressed, 1=compressed */
     fputc(0x00, stdout);
-    
+
     /* format, mono/gray = 0x20000000, RGB=0x29000000 */
     if (depth == 1)
         fputc(0x20, stdout);
@@ -125,7 +124,7 @@ leaf_writeimg(unsigned int const width,
     fputc(0x00, stdout);
     fputc(0x00, stdout);
     fputc(0x00, stdout);
-    
+
     /* colormap size */
     if (depth == 8) {
         unsigned int i;
@@ -139,10 +138,10 @@ leaf_writeimg(unsigned int const width,
             fputc((unsigned char) Green[i]*255/maxval, stdout);
         for (i = 0; i < 256; ++i)
             fputc((unsigned char) Blue[i]*255/maxval, stdout);
-    
+
         for (row=0; row < height; ++row) {
             unsigned int col;
-            for (col = 0; col < width; ++col) 
+            for (col = 0; col < width; ++col)
                 fputc(GetPixel(col, row), stdout);
             if ((width % 2) != 0)
                 fputc(0x00, stdout); /* pad to 2-bytes */
@@ -180,18 +179,18 @@ leaf_writeimg(unsigned int const width,
 
         fputc(0x00, stdout);
         fputc(0x00, stdout);
-        
+
         for (row = 0; row < height; ++row) {
             unsigned int col;
-            for (col = 0; col < width; ++col) 
+            for (col = 0; col < width; ++col)
                 fputc(pixels[row][col].r * 255 / maxval, stdout);
             if (width % 2 != 0)
                 fputc(0x00, stdout); /* pad to 2-bytes */
-            for (col = 0; col < width; ++col) 
+            for (col = 0; col < width; ++col)
                 fputc(pixels[row][col].g * 255 / maxval, stdout);
             if (width % 2 != 0)
                 fputc(0x00, stdout); /* pad to 2-bytes */
-            for (col = 0; col < width; ++col) 
+            for (col = 0; col < width; ++col)
                 fputc(pixels[row][col].b * 255 / maxval, stdout);
             if (width % 2 != 0)
                 fputc(0x00, stdout); /* pad to 2-bytes */
@@ -212,24 +211,24 @@ main(int argc, const char * argv[]) {
     pixval maxval;
     colorhist_vector chv;
     const char * const usage = "[ppmfile]";
-    
+
     pm_proginit(&argc, argv);
-    
+
     argn = 1;
-    
+
     if (argn < argc) {
         ifP = pm_openr(argv[argn]);
         argn++;
     } else
         ifP = stdin;
-    
+
     if (argn != argc)
         pm_usage(usage);
-    
+
     pixels = ppm_readppm(ifP, &cols, &rows, &maxval);
-    
+
     pm_close(ifP);
-    
+
     /* Figure out the colormap. */
     pm_message("Computing colormap...");
     chv = ppm_computecolorhist(pixels, cols, rows, MAXCOLORS, &colors);
@@ -237,14 +236,14 @@ main(int argc, const char * argv[]) {
         unsigned int i;
 
         pm_message("... Done.  %u colors found.", colors);
-    
+
         for (i = 0; i < colors; ++i) {
             Red[i]   = (int) PPM_GETR( chv[i].color);
             Green[i] = (int) PPM_GETG( chv[i].color);
             Blue[i]  = (int) PPM_GETB( chv[i].color);
         }
         BitsPerPixel = colorstobpp(colors);
-    
+
         /* And make a hash table for fast lookup. */
         cht = ppm_colorhisttocolorhash(chv, colors);
         ppm_freecolorhist(chv);
@@ -252,8 +251,11 @@ main(int argc, const char * argv[]) {
         BitsPerPixel = 24;
         pm_message("  ... Done.  24-bit true color %u color image.", colors);
     }
-    
+
     leaf_writeimg(cols, rows, BitsPerPixel, colors, maxval);
-    
+
     return 0;
 }
+
+
+
diff --git a/converter/ppm/ppmtolj.c b/converter/ppm/ppmtolj.c
index 7ed814ed..e2e03ac5 100644
--- a/converter/ppm/ppmtolj.c
+++ b/converter/ppm/ppmtolj.c
@@ -10,13 +10,12 @@
 ** implied warranty.
 */
 
+#include <stdbool.h>
+#include <limits.h>
 #include <string.h>
 
 #include "ppm.h"
 
-static int compress_row_delta (unsigned char *op, unsigned char *prev_op, 
-                               unsigned char *cp, int bufsize);
-
 #define C_RESET                 "\033E"
 #define C_PRESENTATION          "\033*r%dF"
 #define C_PRESENTATION_LOGICAL  0
@@ -44,103 +43,269 @@ static int compress_row_delta (unsigned char *op, unsigned char *prev_op,
 #define C_Y_OFFSET              "\033*b%dY"
 
 
+
+static void
+printHeader(FILE *       const ofP,
+            int          const resets,
+            bool         const floating,
+            int          const resolution,
+            unsigned int const rows,
+            unsigned int const cols,
+            int          const mode,
+            int          const gamma) {
+
+    char const CID[6] =  { 0, 3, 0, 8, 8, 8 };
+        /*data for the configure image data command*/
+
+    if (resets & 0x1) {
+        /* Printer reset. */
+        fprintf(ofP, C_RESET);
+    }
+
+    if (!floating) {
+        /* Ensure top margin is zero */
+        fprintf(ofP, "\033&l0E");
+    }
+
+    /*Set Presentation mode*/
+    fprintf(ofP, C_PRESENTATION, C_PRESENTATION_PHYSICAL);
+    /* Set the resolution */
+    fprintf(ofP, C_RESOLUTION, resolution);
+    /* Set raster height*/
+    fprintf(ofP, C_IMAGE_HEIGHT, rows);
+    /* Set raster width*/
+    fprintf(ofP, C_IMAGE_WIDTH, cols);
+    /* set left margin to current x pos*/
+    /*(void) fprintf(ofP, C_LEFT_MARGIN, 1);*/
+    /* set the correct color mode */
+    fprintf(ofP, C_CONFIG_IMAGE_DATA);
+    fwrite(CID, 1, 6, ofP);
+    /* Start raster graphics */
+    fprintf(ofP, C_BEGIN_RASTER, C_BEGIN_RASTER_CUR);  /*posscale);*/
+    /* set Y offset to 0 */
+    fprintf(ofP, C_Y_OFFSET, 0);
 /*
- * delta encoding. 
- */
-/*
-op row buffer
-prev_op     previous row buffer
-bufsize     length of row
-cp          buffer for compressed data
+    if (xoff)
+        fprintf(ofP, C_MOVE_X, xoff);
+    if (yoff)
+        fprintf(ofP, C_MOVE_Y, yoff);
 */
+    /* Set raster compression */
+    fprintf(ofP, C_TRANS_MODE, mode);
+
+    if (gamma)
+        fprintf(ofP, C_GAMMA,   gamma);
+}
+
+
+
 static int
-compress_row_delta(op, prev_op, cp, bufsize)
-unsigned char *op, *prev_op, *cp;
-int bufsize;
-{
-    int burstStart, burstEnd, burstCode, mustBurst, ptr, skip, skipped, code;
-    int deltaBufferIndex = 0;
-    if (memcmp(op, prev_op , bufsize/*rowBufferIndex*/) == 0) 
+compressRowDelta(unsigned char * const op,
+                 unsigned char * const prevOp,
+                 unsigned char * const cp,
+                 unsigned int    const bufsize) {
+/*----------------------------------------------------------------------------
+
+  delta encoding.
+
+
+  op:      row buffer
+  prevOp:  previous row buffer
+  bufsize: length of row
+  cp:       buffer for compressed data
+-----------------------------------------------------------------------------*/
+    int burstStart, burstEnd, burstCode, ptr, skipped, code;
+    bool mustBurst;
+    int deltaBufferIndex;
+
+    if (memcmp(op, prevOp , bufsize/*rowBufferIndex*/) == 0)
         return 0; /* exact match, no deltas required */
 
-    ptr = 0;
-    skipped = 0;
-    burstStart = -1;
-    burstEnd = -1;
-    mustBurst = 0;
-    while (ptr < bufsize/*rowBufferIndex*/) 
-    {
-        skip = 0;
-        if (ptr == 0 || skipped == 30 || op[ptr] != prev_op[ptr] ||
-            (burstStart != -1 && ptr == bufsize - 1)) 
-        {
+    deltaBufferIndex = 0;  /* initial value */
+    ptr = 0;               /* initial value */
+    skipped = 0;           /* initial value */
+    burstStart = -1;       /* initial value */
+    burstEnd = -1;         /* initial value */
+    mustBurst = false;     /* initial value */
+
+    while (ptr < bufsize/*rowBufferIndex*/) {
+        bool mustSkip;
+
+        mustSkip = false;  /* initial assumption */
+
+        if (ptr == 0 || skipped == 30 || op[ptr] != prevOp[ptr] ||
+            (burstStart != -1 && ptr == bufsize - 1)) {
             /* we want to output this byte... */
-            if (burstStart == -1) 
-            {
+            if (burstStart == -1) {
                 burstStart = ptr;
             }
-            if (ptr - burstStart == 7 || ptr == bufsize - 1) 
-            {
+            if (ptr - burstStart == 7 || ptr == bufsize - 1) {
                 /* we have to output it now... */
                 burstEnd = ptr;
-                mustBurst = 1;
+                mustBurst = true;
             }
-        } 
-        else 
-        {
+        } else {
             /* duplicate byte, we can skip it */
-            if (burstStart != -1) 
+            if (burstStart != -1)
             {
                 burstEnd = ptr - 1;
-                mustBurst = 1;
+                mustBurst = true;
             }
-            skip = 1;
+            mustSkip = true;
         }
-        if (mustBurst) 
-        {
+        if (mustBurst) {
             burstCode = burstEnd - burstStart; /* 0-7 means 1-8 bytes follow */
             code = (burstCode << 5) | skipped;
             cp[deltaBufferIndex++] = (char) code;
-            memcpy(cp+deltaBufferIndex, op+burstStart, burstCode + 1);
+            memcpy(cp + deltaBufferIndex, op + burstStart, burstCode + 1);
             deltaBufferIndex += burstCode + 1;
             burstStart = -1;
             burstEnd = -1;
-            mustBurst = 0;
+            mustBurst = false;
             skipped = 0;
         }
-        if (skip) 
-        {
-            skipped ++;
-        }
-        ptr ++;
+        if (mustSkip)
+            ++skipped;
+        ++ptr;
     }
     return deltaBufferIndex;
 }
 
 
-int main(int argc, char *argv[]) {
+
+static void
+printTrailer(FILE * const ofP,
+             int    const resets) {
+
+    fprintf(ofP, C_END_RASTER, C_END_RASTER_UNUSED);
+
+    if (resets & 0x2) {
+        /* Printer reset. */
+        fprintf(ofP, C_RESET);
+    }
+}
+
+
+
+static void
+printRaster(FILE *       const ifP,
+            unsigned int const rows,
+            unsigned int const cols,
+            int          const maxval,
+            int          const format,
+            int          const mode,
+            FILE *       const ofP) {
+
+    unsigned char * obuf; /* malloc'ed */
+    unsigned char * cbuf; /* malloc'ed */
+    unsigned char * previousObuf;  /* malloc'ed */
+    unsigned int uncompOutRowSz;
+    unsigned int outRowSz;
+    int currentmode;
     pixel * pixelrow;
-    FILE *ifp;
-    int argn, rows, cols, r, c, k;
-    pixval maxval;
-    unsigned char *obuf, *op, *cbuf, *previous_obuf;
-    int format;
-    int gamma = 0;
-    int mode = C_TRANS_MODE_STD;
-    int currentmode = 0;
-    int floating = 0;  /* suppress the ``ESC & l 0 E'' ? */
-    int resets = 3;    /* bit mask for when to emit printer reset seq */
+    unsigned int row;
 
-    int resolution = C_RESOLUTION_300DPI;
+    pixelrow = ppm_allocrow(cols);
 
-    char CID[6] =  { 0, 3, 0, 8, 8, 8 }; 
-        /*data for the configure image data command*/
+    if (cols > UINT_MAX/6) {
+        /* We may need a row buffer of up to cols * 6 bytes for compression */
+        pm_error("Image is uncomputably wide (%u columns)", cols);
+    }
+
+    obuf = (unsigned char *) pm_allocrow(cols * 3, sizeof(unsigned char));
+    cbuf = (unsigned char *) pm_allocrow(cols * 6, sizeof(unsigned char));
+
+    if (mode == C_TRANS_MODE_DELTA) {
+        previousObuf =
+            (unsigned char *) pm_allocrow(cols * 3, sizeof(unsigned char));
+        memset(previousObuf, 0, cols * 3);
+    } else
+        previousObuf = NULL;
+
+    currentmode = mode;  /* initial value */
+
+    for (row = 0; row < rows; ++row) {
+        unsigned int col;
+        const unsigned char * op;
+
+        ppm_readppmrow(ifP, pixelrow, cols, maxval, format);
+
+        /* get a row of data with 3 bytes per pixel */
+        for (col = 0; col < cols; ++col) {
+            obuf[3*col + 0] = (PPM_GETR(pixelrow[col])*255)/maxval;
+            obuf[3*col + 1] = (PPM_GETG(pixelrow[col])*255)/maxval;
+            obuf[3*col + 2] = (PPM_GETB(pixelrow[col])*255)/maxval;
+        }
+        uncompOutRowSz = 3 * cols;
+
+        /*compress the row if required*/
+        switch (mode) {
+        case C_TRANS_MODE_STD: /*no compression*/
+            op = obuf;
+            outRowSz = uncompOutRowSz;
+            break;
+        case C_TRANS_MODE_DELTA: {   /*delta compression*/
+            int const deltasize =
+                compressRowDelta(obuf, previousObuf, cbuf, uncompOutRowSz);
+
+            int newmode;
+
+            newmode = 0;  /* initial value */
+
+            if (deltasize >= uncompOutRowSz) {
+                /*normal is best?*/
+                op = obuf;
+                outRowSz = uncompOutRowSz;
+            } else {
+                /*delta is best*/
+                op = cbuf;
+                outRowSz = deltasize;
+                newmode = C_TRANS_MODE_DELTA;
+            }
+            memcpy(previousObuf, obuf, cols*3);
+
+            if (currentmode != newmode) {
+                fprintf(ofP, C_TRANS_MODE, newmode);
+                currentmode = newmode;
+            }
+        }
+        }
+        fprintf(ofP, C_SEND_ROW, outRowSz);
+        fwrite(op, 1, outRowSz, ofP);
+    }
+    free(cbuf);
+    free(obuf);
+    if (previousObuf)
+        free(previousObuf);
+    ppm_freerow(pixelrow);
+}
+
+
+
+int
+main(int argc, const char **argv) {
+    FILE * ifP;
+    int argn, rows, cols;
+    pixval maxval;
+    int format;
+    int gamma;
+    int mode;
+    bool floating;
+        /* suppress the ``ESC & l 0 E'' ? */
+    int resets;
+        /* bit mask for when to emit printer reset seq */
+    int resolution;
 
     const char * const usage = "[-noreset][-float][-delta][-gamma <val>] [-resolution N] "
         "[ppmfile]\n\tresolution = [75|100|150|300|600] (dpi)";
 
-    ppm_init( &argc, argv );
+    pm_proginit(&argc, argv);
 
+    gamma = 0; /* initial value */
+    mode = C_TRANS_MODE_STD;  /* initial value */
+    resolution = C_RESOLUTION_300DPI;  /* initial value */
+    floating = false;  /* initial value */
+    resets = 0x3;  /* initial value */
     argn = 1;
     while ( argn < argc && argv[argn][0] == '-' && argv[argn][1] != '\0' )
     {
@@ -159,9 +324,9 @@ int main(int argc, char *argv[]) {
         else if (pm_keymatch(argv[argn],"-delta",2))
             mode = C_TRANS_MODE_DELTA;
         else if (pm_keymatch(argv[argn],"-float",2))
-            floating = 1;
+            floating = true;
         else if (pm_keymatch(argv[argn],"-noreset",2))
-            resets = 0;
+            resets = 0x0;
 
         else
             pm_usage( usage );
@@ -170,128 +335,28 @@ int main(int argc, char *argv[]) {
 
     if ( argn < argc )
     {
-        ifp = pm_openr( argv[argn] );
+        ifP = pm_openr( argv[argn] );
         ++argn;
     }
     else
-        ifp = stdin;
+        ifP = stdin;
 
     if ( argn != argc )
         pm_usage( usage );
 
-    ppm_readppminit( ifp, &cols, &rows, &maxval, &format );
-    pixelrow = ppm_allocrow( cols );
+    ppm_readppminit(ifP, &cols, &rows, &maxval, &format);
 
-    obuf = (unsigned char *) pm_allocrow(cols * 3, sizeof(unsigned char));
-    cbuf = (unsigned char *) pm_allocrow(cols * 6, sizeof(unsigned char));
-    if (mode == C_TRANS_MODE_DELTA)
-    {
-        previous_obuf = 
-            (unsigned char *) pm_allocrow(cols * 3, sizeof(unsigned char));
-        memset(previous_obuf, 0, cols * 3);
-    }
+    printHeader(stdout, resets, floating, resolution, rows, cols,
+                mode, gamma);
 
-    if(resets & 1)
-    {
-        /* Printer reset. */
-        printf(C_RESET);
-    }
+    printRaster(ifP, rows, cols, maxval, format, mode, stdout);
 
-    if(!floating)
-    {
-        /* Ensure top margin is zero */
-        printf("\033&l0E");
-    }
+    printTrailer(stdout, resets);
 
-    /*Set Presentation mode*/
-    (void) printf(C_PRESENTATION, C_PRESENTATION_PHYSICAL);
-    /* Set the resolution */
-    (void) printf(C_RESOLUTION, resolution);
-    /* Set raster height*/
-    (void) printf(C_IMAGE_HEIGHT, rows);
-    /* Set raster width*/
-    (void) printf(C_IMAGE_WIDTH, cols);
-    /* set left margin to current x pos*/
-    /*(void) printf(C_LEFT_MARGIN, 1);*/
-    /* set the correct color mode */
-    (void) printf(C_CONFIG_IMAGE_DATA);
-    (void) fwrite(CID, 1, 6, stdout);
-    /* Start raster graphics */
-    (void) printf(C_BEGIN_RASTER, C_BEGIN_RASTER_CUR);  /*posscale);*/
-    /* set Y offset to 0 */
-    (void) printf(C_Y_OFFSET, 0);
-/*  
-    if (xoff)
-        (void) printf(C_MOVE_X, xoff);
-    if (yoff)
-        (void) printf(C_MOVE_Y, yoff);
-*/
-    /* Set raster compression */
-    (void) printf(C_TRANS_MODE, mode);
-    currentmode = mode;
-    
-    if(gamma)
-        (void) printf(C_GAMMA,   gamma);
-    
-    for (r = 0; r < rows; r++)
-    {
-        ppm_readppmrow(ifp, pixelrow, cols, maxval, format);
-
-        /* get a row of data with 3 bytes per pixel */
-        for (c = 0, op = &obuf[-1]; c < cols; c++)
-        {
-            ++op;
-            *op = (PPM_GETR(pixelrow[c])*255)/maxval;
-            ++op;
-            *op = (PPM_GETG(pixelrow[c])*255)/maxval;
-            ++op;
-            *op = (PPM_GETB(pixelrow[c])*255)/maxval;
-        }
-        ++op;
-        k = op - obuf; /*size of row*/
-        /*compress the row if required*/
-        if(mode == C_TRANS_MODE_STD)
-        {/*no compression*/
-            op = obuf;
-        }
+    pm_close(ifP);
 
-        if(mode ==  C_TRANS_MODE_DELTA)
-        {/*delta compression*/
-            int newmode = 0;
-            int deltasize = 
-                compress_row_delta(obuf, previous_obuf, cbuf, cols*3);
-            if(deltasize >= k)/*normal is best?*/
-            {
-                op = obuf;
-            }
-            else /*delta is best*/
-            {
-                k = deltasize;
-                op = cbuf;
-                newmode = C_TRANS_MODE_DELTA;
-            }
-            memcpy(previous_obuf, obuf, cols*3);
-
-            if(currentmode != newmode)
-            {
-                (void) printf(C_TRANS_MODE, newmode);
-                currentmode = newmode;
-            }
-        }
+    return 0;
+}
 
-        (void) printf(C_SEND_ROW, k);
-        (void) fwrite(op, 1, k, stdout);
-        
-    }
 
-    (void) printf(C_END_RASTER, C_END_RASTER_UNUSED);
-    if(resets & 2)
-    {
-        /* Printer reset. */
-        printf(C_RESET);
-    }
-    pm_close( ifp );
-    ppm_freerow(pixelrow);
 
-    return 0;
-}
diff --git a/converter/ppm/ppmtomitsu.c b/converter/ppm/ppmtomitsu.c
index 50b790d6..8fb7cddd 100644
--- a/converter/ppm/ppmtomitsu.c
+++ b/converter/ppm/ppmtomitsu.c
@@ -20,6 +20,7 @@
 ** implied warranty.
 */
 
+#include <stdbool.h>
 #include <assert.h>
 #include <string.h>
 #include <stdio.h>
@@ -35,28 +36,84 @@
 #define HASHSIZE 2048
 #define myhash(x) ((PPM_GETR(x)*3 + PPM_GETG(x)*5 + PPM_GETB(x)*7) % HASHSIZE)
 
-typedef struct hashinfo {
+typedef struct Hashinfo {
         pixel     color;
         long      flag;
-        struct hashinfo * next;
-} hashinfo;
+        struct Hashinfo * next;
+} Hashinfo;
 
-#define cmd(arg)           fputc((arg), stdout)
-#define datum(arg)         fputc((char)(arg), stdout)
-#define data(arg,num)      fwrite((arg), sizeof(char), (num), stdout)
+
+
+static struct Mediasize
+mediaSize(const char * const media,
+          bool         const dpi300) {
+
+    struct Mediasize medias;
+
+    if (TOUPPER(media[0]) == 'A') {
+        switch (TOUPPER(media[1])) {
+        case 'S':
+            medias = MSize_AS;
+            break;
+        case '4':
+            if (TOUPPER(media[2]) == 'S')
+                medias = MSize_A4S;
+            else
+                medias = MSize_A4;
+            break;
+        default:
+            medias = MSize_A;
+        }
+    } else
+        medias = MSize_User;
+
+    if (dpi300) {
+        medias.maxcols *= 2;
+        medias.maxrows *= 2;
+    }
+
+    return medias;
+}
 
 
 
 static void
-check_and_rotate(int              const cols,
-                 int              const rows,
-                 int              const enlarge,
-                 struct mediasize const medias) {
+cmd(char const arg) {
+
+    fputc(arg, stdout);
+}
+
+
+
+static void
+datum(unsigned char const arg) {
+
+    fputc(arg, stdout);
+}
+
+
+
+static void
+data(unsigned char * const arg,
+     size_t          const len) {
+
+    fwrite((unsigned char *)arg, 1, len, stdout);
+}
+
+
+
+static void
+checkAndRotate(int              const cols,
+               int              const rows,
+               int              const enlarge,
+               struct Mediasize const medias) {
 
     if (cols > rows) {
         ROTATEIMG(DOROTATE);                        /* rotate image */
         if (enlarge * rows > medias.maxcols || enlarge * cols > medias.maxrows)
-            pm_error("Image too large, MaxPixels = %u x %u",
+            pm_error("Image too large (%u x %u).  "
+                     "Size of output media: %u x %u",
+                     enlarge*rows, enlarge*cols,
                      medias.maxrows, medias.maxcols);
         HPIXELS(cols);
         VPIXELS(rows);
@@ -66,7 +123,9 @@ check_and_rotate(int              const cols,
     } else {
         ROTATEIMG(DONTROTATE);
         if (enlarge * rows > medias.maxrows || enlarge * cols > medias.maxcols)
-            pm_error("Image too large, MaxPixels = %u x %u",
+            pm_error("Image too large (%u x %u).  "
+                     "Size of output media: %u x %u",
+                     enlarge*rows, enlarge*cols,
                      medias.maxrows, medias.maxcols);
         HPIXELS(cols);
         VPIXELS(rows);
@@ -83,7 +142,7 @@ lineputinit(int              const cols,
             int              const sharpness,
             int              const enlarge,
             int              const copy,
-            struct mediasize const medias) {
+            struct Mediasize const medias) {
     ONLINE;
     CLRMEM;
     MEDIASIZE(medias);
@@ -132,7 +191,7 @@ lineputinit(int              const cols,
     default:
         SHARPNESS(SP_USER);
     }
-    check_and_rotate(cols, rows, enlarge, medias);
+    checkAndRotate(cols, rows, enlarge, medias);
     DATASTART;
 }
 
@@ -142,7 +201,7 @@ static void
 lookuptableinit(int              const sharpness,
                 int              const enlarge,
                 int              const copy,
-                struct mediasize const medias) {
+                struct Mediasize const medias) {
 
     ONLINE;
     CLRMEM;
@@ -200,10 +259,10 @@ static void
 lookuptabledata(int              const cols,
                 int              const rows,
                 int              const enlarge,
-                struct mediasize const medias) {
+                struct Mediasize const medias) {
 
     DONELOOKUPTABLE;
-    check_and_rotate(cols, rows, enlarge, medias);
+    checkAndRotate(cols, rows, enlarge, medias);
     DATASTART;
 }
 
@@ -215,7 +274,7 @@ frametransferinit(int              const cols,
                   int              const sharpness,
                   int              const enlarge,
                   int              const copy,
-                  struct mediasize const medias) {
+                  struct Mediasize const medias) {
 
     ONLINE;
     CLRMEM;
@@ -265,7 +324,7 @@ frametransferinit(int              const cols,
     default:
         SHARPNESS(SP_USER);
     }
-    check_and_rotate(cols, rows, enlarge, medias);
+    checkAndRotate(cols, rows, enlarge, medias);
 }
 
 
@@ -273,14 +332,14 @@ frametransferinit(int              const cols,
 static void
 doLookupTableColors(colorhist_vector const table,
                     unsigned int     const nColor,
-                    hashinfo *       const colorhashtable) {
+                    Hashinfo *       const colorhashtable) {
 
     unsigned int colval;
     for (colval = 0; colval < nColor; ++colval) {
-        struct hashinfo * const hashchain =
+        struct Hashinfo * const hashchain =
             &colorhashtable[myhash((table[colval]).color)];
 
-        struct hashinfo * hashrun;
+        struct Hashinfo * hashrun;
 
         cmd('$');
         datum(colval);
@@ -310,13 +369,13 @@ doLookupTableColors(colorhist_vector const table,
 static void
 doLookupTableGrays(colorhist_vector const table,
                    unsigned int     const nColor,
-                   hashinfo *       const colorhashtable) {
+                   Hashinfo *       const colorhashtable) {
 
     unsigned int colval;
     for (colval = 0; colval < nColor; ++colval) {
-        struct hashinfo * const hashchain =
+        struct Hashinfo * const hashchain =
             &colorhashtable[myhash((table[colval]).color)];
-        struct hashinfo * hashrun;
+        struct Hashinfo * hashrun;
 
         cmd('$');
         datum(colval);
@@ -352,8 +411,8 @@ generateLookupTable(colorhist_vector const table,
                     int              const sharpness,
                     int              const enlarge,
                     int              const copy,
-                    struct mediasize const medias,
-                    hashinfo **      const colorhashtableP) {
+                    struct Mediasize const medias,
+                    Hashinfo **      const colorhashtableP) {
 /*----------------------------------------------------------------------------
    Write to the output file the palette (color lookup table) indicated by
    'table' and generate a hash table to use with it: *colorhashtableP.
@@ -361,7 +420,7 @@ generateLookupTable(colorhist_vector const table,
    Also write the various properties 'sharpness', 'enlarge', 'copy', and
    'medias' to the output file.
 -----------------------------------------------------------------------------*/
-    hashinfo * colorhashtable;
+    Hashinfo * colorhashtable;
 
     lookuptableinit(sharpness, enlarge, copy, medias);
 
@@ -394,7 +453,7 @@ static void
 writeColormapRaster(pixel **         const pixels,
                     unsigned int     const cols,
                     unsigned int     const rows,
-                    hashinfo *       const colorhashtable) {
+                    Hashinfo *       const colorhashtable) {
 /*----------------------------------------------------------------------------
    Write a colormapped raster: write the pixels pixels[][] (dimensions cols x
    rows) as indices into the colormap (palette; lookup table) indicated by
@@ -407,9 +466,9 @@ writeColormapRaster(pixel **         const pixels,
 
         for (col = 0; col < cols; ++col) {
             pixel * const pixrow = pixels[row];
-            struct hashinfo * const hashchain =
+            struct Hashinfo * const hashchain =
                 &colorhashtable[myhash(pixrow[col])];
-            struct hashinfo * p;
+            struct Hashinfo * p;
 
             p = hashchain;
             while (!PPM_EQUAL((p->color), pixrow[col])) {
@@ -429,13 +488,13 @@ useLookupTable(pixel **         const pixels,
                int              const sharpness,
                int              const enlarge,
                int              const copy,
-               struct mediasize const medias,
+               struct Mediasize const medias,
                unsigned int     const cols,
                unsigned int     const rows,
                int              const format,
                unsigned int     const nColor) {
 
-    hashinfo * colorhashtable;
+    Hashinfo * colorhashtable;
 
     pm_message("found %u colors - using the lookuptable-method", nColor);
 
@@ -523,7 +582,7 @@ useNoLookupTable(pixel **         const pixels,
                  int              const sharpness,
                  int              const enlarge,
                  int              const copy,
-                 struct mediasize const medias,
+                 struct Mediasize const medias,
                  unsigned int     const cols,
                  unsigned int     const rows,
                  int              const format) {
@@ -553,7 +612,7 @@ doTiny(FILE *           const ifP,
        int              const sharpness,
        int              const enlarge,
        int              const copy,
-       struct mediasize const medias) {
+       struct Mediasize const medias) {
 
     pixel * pixelrow;
     unsigned char * redrow;
@@ -596,26 +655,28 @@ doTiny(FILE *           const ifP,
 
 
 int
-main(int argc, char * argv[]) {
-    FILE * ifP;
+main(int argc, const char ** argv) {
+
+    FILE *           ifP;
     int              argn;
     bool             dpi300;
+    bool             tiny;
     int              cols, rows, format;
     pixval           maxval;
-    int              sharpness, enlarge, copy, tiny;
-    struct mediasize medias;
+    int              sharpness, enlarge, copy;
+    struct Mediasize medias;
     char             media[16];
     const char * const usage = "[-sharpness <1-4>] [-enlarge <1-3>] [-media <a,a4,as,a4s>] [-copy <1-9>] [-tiny] [-dpi300] [ppmfile]";
 
-    ppm_init(&argc, argv);
+    pm_proginit(&argc, argv);
 
-    dpi300 = FALSE;
+    dpi300 = false;
     argn = 1;
     sharpness = 32;
     enlarge   = 1;
     copy      = 1;
     memset(media, '\0', 16);
-    tiny      = FALSE;
+    tiny      = false;
 
     /* check for flags */
     while (argn < argc && argv[argn][0] == '-' && argv[argn][1] != '\0') {
@@ -648,9 +709,9 @@ main(int argc, char * argv[]) {
             pm_usage(usage);
         }
     else if (pm_keymatch(argv[argn], "-dpi300", 2))
-        dpi300 = TRUE;
+        dpi300 = true;
     else if (pm_keymatch(argv[argn], "-tiny", 2))
-        tiny = TRUE;
+        tiny = true;
     else
         pm_usage(usage);
     ++argn;
@@ -666,28 +727,7 @@ main(int argc, char * argv[]) {
     if (argn != argc)
         pm_usage(usage);
 
-    if (TOUPPER(media[0]) == 'A')
-        switch (TOUPPER(media[1])) {
-        case 'S':
-            medias = MSize_AS;
-            break;
-        case '4':
-            if(TOUPPER(media[2]) == 'S')
-                medias = MSize_A4S;
-            else {
-                medias = MSize_A4;
-            }
-            break;
-        default:
-            medias = MSize_A;
-        }
-    else
-        medias = MSize_User;
-
-    if (dpi300) {
-        medias.maxcols *= 2;
-        medias.maxrows *= 2;
-    }
+    medias = mediaSize(media, dpi300);
 
     ppm_readppminit(ifP, &cols, &rows, &maxval, &format);
 
@@ -721,3 +761,6 @@ main(int argc, char * argv[]) {
     pm_close(ifP);
     return 0;
 }
+
+
+
diff --git a/converter/ppm/ppmtomitsu.test b/converter/ppm/ppmtomitsu.test
deleted file mode 100644
index f574d927..00000000
--- a/converter/ppm/ppmtomitsu.test
+++ /dev/null
@@ -1,12 +0,0 @@
-echo Test 1.  Should print 3110813682 101562
-./ppmtomitsu ../../testimg.ppm | cksum 
-echo Test 2.  Should print 239186803 34399
-pnmquant 100 ../../testimg.ppm | ./ppmtomitsu | cksum 
-echo Test 3.  Should print 3201293405 310
-./ppmtomitsu ../../testgrid.pbm | cksum 
-echo Test 4.  Should print 3354679572 752
-./ppmtomitsu -tiny ../../testgrid.pbm | cksum 
-echo Test 5.  Should print 3999654426 101549
-./ppmtomitsu -tiny ../../testimg.ppm | cksum 
-echo Test 2.  Should print 3078685526 101549
-pnmquant 100 ../../testimg.ppm | ./ppmtomitsu -tiny | cksum 
diff --git a/converter/ppm/ppmtompeg/bframe.c b/converter/ppm/ppmtompeg/bframe.c
index f5009d6c..8bce3e14 100644
--- a/converter/ppm/ppmtompeg/bframe.c
+++ b/converter/ppm/ppmtompeg/bframe.c
@@ -94,7 +94,7 @@ extern Block **dct, **dctr, **dctb;
 
 static void
 zeroMotion(motion * const motionP) {
-    
+
     motionP->fwd.y = motionP->fwd.x = motionP->bwd.y = motionP->bwd.x = 0;
 }
 
@@ -114,7 +114,6 @@ halfMotion(motion const motion) {
 
 
 
-
 /*===========================================================================*
  *
  *  compute the block resulting from motion compensation
@@ -218,14 +217,14 @@ ComputeBDiffDCTs(MpegFrame * const current,
                  int *       const patternP) {
 
     Block motionBlock;
-    
+
     if (*patternP & 0x20) {
         boolean significantDiff;
         ComputeBMotionBlock(prev, next, by, bx, mode, motion,
                             &motionBlock, LUM_BLOCK);
         ComputeDiffDCTBlock(current->y_blocks[by][bx], dct[by][bx],
                             motionBlock, &significantDiff);
-        if (!significantDiff) 
+        if (!significantDiff)
             *patternP ^=  0x20;
     }
 
@@ -235,7 +234,7 @@ ComputeBDiffDCTs(MpegFrame * const current,
                             &motionBlock, LUM_BLOCK);
         ComputeDiffDCTBlock(current->y_blocks[by][bx+1], dct[by][bx+1],
                             motionBlock, &significantDiff);
-        if (!significantDiff) 
+        if (!significantDiff)
             *patternP ^=  0x10;
     }
 
@@ -348,7 +347,7 @@ ComputeBlockColorDiff(Block current,
 
     unsigned int y;
     int diffTotal;
-    
+
     diffTotal = 0;
 
     for (y = 0; y < 8; ++y) {
@@ -433,13 +432,12 @@ MotionSufficient(MpegFrame *      const curr,
                         &mColorBlock, CB_BLOCK);
     colorErr += ComputeBlockColorDiff(curr->cr_blocks[by/2][bx/2],
                                       mColorBlock);
-    
+
     return (colorErr < 256); /* lumErr checked above */
 }
 
 
 
-
 struct stats {
     int IBlocks;
     int BBlocks;
@@ -464,7 +462,7 @@ initializeStats(struct stats * const statsP) {
 
 
 static void
-checkSpecifics(MpegFrame *      const curr, 
+checkSpecifics(MpegFrame *      const curr,
                int              const mbAddress,
                int              const QScale,
                boolean *        const skipItP,
@@ -519,9 +517,9 @@ checkSpecifics(MpegFrame *      const curr,
 
 static void
 makeNonSkipBlock(int              const y,
-                 int              const x, 
-                 MpegFrame *      const curr, 
-                 MpegFrame *      const prev, 
+                 int              const x,
+                 MpegFrame *      const curr,
+                 MpegFrame *      const prev,
                  MpegFrame *      const next,
                  bool             const specificsOn,
                  int              const mbAddress,
@@ -556,7 +554,7 @@ makeNonSkipBlock(int              const y,
                                  &motion, mode);
         }
         /* STEP 2:  INTRA OR NON-INTRA CODING */
-        if (IntraPBAllowed && 
+        if (IntraPBAllowed &&
             DoBIntraCode(curr, prev, next, y, x, mode, motion)) {
             /* output I-block inside a B-frame */
             ++statsP->IBlocks;
@@ -565,7 +563,7 @@ makeNonSkipBlock(int              const y,
             dct_data[y][x].useMotion = NO_MOTION;
             *oldModeP = MOTION_FORWARD;
             /* calculate forward dct's */
-            if (collect_quant && (collect_quant_detailed & 1)) 
+            if (collect_quant && (collect_quant_detailed & 1))
                 fprintf(collect_quant_fp, "l\n");
             mp_fwd_dct_block2(curr->y_blocks[y][x], dct[y][x]);
             mp_fwd_dct_block2(curr->y_blocks[y][x+1], dct[y][x+1]);
@@ -574,9 +572,9 @@ makeNonSkipBlock(int              const y,
             if (collect_quant && (collect_quant_detailed & 1)) {
                 fprintf(collect_quant_fp, "c\n");
             }
-            mp_fwd_dct_block2(curr->cb_blocks[y>>1][x>>1], 
+            mp_fwd_dct_block2(curr->cb_blocks[y>>1][x>>1],
                               dctb[y>>1][x>>1]);
-            mp_fwd_dct_block2(curr->cr_blocks[y>>1][x>>1], 
+            mp_fwd_dct_block2(curr->cr_blocks[y>>1][x>>1],
                               dctr[y>>1][x>>1]);
 
         } else { /* dct P/Bi/B block */
@@ -608,9 +606,9 @@ makeNonSkipBlock(int              const y,
             default:
                 pm_error("INTERNAL ERROR:  Illegal mode: %d", mode);
             }
-        
+
             ComputeBDiffDCTs(curr, prev, next, y, x, mode, motion, &pattern);
-        
+
             dct_data[y][x].pattern = pattern;
             dct_data[y][x].useMotion = MOTION;
             if ( computeMVHist ) {
@@ -622,7 +620,7 @@ makeNonSkipBlock(int              const y,
                 assert(motion.bwd.y + searchRangeB + 1 >= 0);
                 assert(motion.bwd.x + searchRangeB + 1 <= 2*searchRangeB + 2);
                 assert(motion.bwd.y + searchRangeB + 1 <= 2*searchRangeB + 2);
-                
+
                 ++bfmvHistogram[motion.fwd.x + searchRangeB + 1]
                     [motion.fwd.y + searchRangeB + 1];
                 ++bbmvHistogram[motion.bwd.x + searchRangeB + 1]
@@ -649,9 +647,9 @@ makeNonSkipBlock(int              const y,
  *
  *===========================================================================*/
 void
-GenBFrame(BitBucket * const bb, 
-          MpegFrame * const curr, 
-          MpegFrame * const prev, 
+GenBFrame(BitBucket * const bb,
+          MpegFrame * const curr,
+          MpegFrame * const prev,
           MpegFrame * const next) {
 
     FlatBlock fba[6], fb[6];
@@ -704,7 +702,7 @@ GenBFrame(BitBucket * const bb,
     if (bitstreamMode == FIXED_RATE) {
         targetRateControl(curr);
     }
- 
+
     QScale = GetBQScale();
     Mhead_GenPictureHeader(bb, B_FRAME, curr->id, fCodeB);
     /* Check for Qscale change */
@@ -751,7 +749,7 @@ GenBFrame(BitBucket * const bb,
     mbAddress = 0;
 
     /* Start with zero motion assumption */
-    zeroMotion(&motion); 
+    zeroMotion(&motion);
     zeroMotion(&oldMotion);
     zeroMotion(&motionRem);
     zeroMotion(&motionQuot);
@@ -759,7 +757,7 @@ GenBFrame(BitBucket * const bb,
     /* find motion vectors and do dcts */
     /* In this first loop, all MVs are in half-pixel scope, (if FULL
        is set then they will be multiples of 2).  This is not true in
-       the second loop. 
+       the second loop.
     */
     for (y = 0;  y < lastBlockY;  y += 2) {
         for (x = 0;  x < lastBlockX;  x += 2) {
@@ -772,14 +770,14 @@ GenBFrame(BitBucket * const bb,
                     currentBlock.l[iy][ix] = (int16)curr->orig_y[fy+iy][fx+ix];
                 }
             }
-        
+
             if (slicePos == 0) {
                 zeroMotion(&oldMotion);
                 oldMode = MOTION_FORWARD;
                 lastIntra = TRUE;
             }
 
-            /* STEP 1:  Select Forward, Backward, or Interpolated motion 
+            /* STEP 1:  Select Forward, Backward, or Interpolated motion
                vectors */
             /* see if old motion is good enough */
             /* but force last block to be non-skipped */
@@ -795,7 +793,7 @@ GenBFrame(BitBucket * const bb,
                  (! lastIntra) &&
                  (BSkipBlocks) ) {
                 make_skip_block =
-                    MotionSufficient(curr, &currentBlock, 
+                    MotionSufficient(curr, &currentBlock,
                                      prev, next, y, x, oldMode, oldMotion);
             } else
                 make_skip_block = FALSE;
@@ -830,7 +828,7 @@ GenBFrame(BitBucket * const bb,
     if ( (slicePos == 0) && (mbAddress != 0) ) {
       if (specificsOn) {
         /* Make sure no slice Qscale change */
-        newQScale = 
+        newQScale =
             SpecLookup(curr->id,1,mbAddress/blocksPerSlice, &info, QScale);
         if (newQScale != -1) QScale = newQScale;
       }
@@ -858,7 +856,7 @@ GenBFrame(BitBucket * const bb,
         QScale = newQScale;
       }
     }
- 
+
     if (specificsOn) {
       newQScale = SpecLookup(curr->id, 2, mbAddress, &info, QScale);
       if (newQScale != -1) {
@@ -871,12 +869,12 @@ GenBFrame(BitBucket * const bb,
       mbAddrInc = 1;
       stats.IBits += (bb->cumulativeBits - stats.totalBits);
       stats.totalBits = bb->cumulativeBits;
-          
+
       /* reset because intra-coded */
       zeroMotion(&oldMotion);
       oldMode = MOTION_FORWARD;
       lastIntra = TRUE;
-          
+
       if ( printSNR ) {
         /* need to decode block we just encoded */
         /* and reverse the DCT transform */
@@ -896,14 +894,14 @@ GenBFrame(BitBucket * const bb,
     } else if (dct_data[y][x].useMotion == SKIP) {
       ++stats.Skipped;
       mbAddrInc++;
-          
+
       /* decode skipped block */
       if (printSNR) {
           struct motion motion;
-        
+
           for (idx = 0; idx < 6; ++idx)
-              memset((char *)dec[idx], 0, sizeof(Block)); 
-        
+              memset((char *)dec[idx], 0, sizeof(Block));
+
           if (pixelFullSearch) {
               motion.fwd.y = 2 * oldMotion.fwd.y;
               motion.fwd.x = 2 * oldMotion.fwd.x;
@@ -911,7 +909,7 @@ GenBFrame(BitBucket * const bb,
               motion.bwd.x = 2 * oldMotion.bwd.x;
           } else
               motion = oldMotion;
-          
+
           /* now add the motion block */
           AddBMotionBlock(dec[0], prev->decoded_y,
                           next->decoded_y, y, x, mode, motion);
@@ -927,7 +925,7 @@ GenBFrame(BitBucket * const bb,
           AddBMotionBlock(dec[5], prev->decoded_cr,
                           next->decoded_cr, y/2, x/2, mode,
                           halfMotion(motion));
-        
+
           /* now, unblockify */
           BlockToData(curr->decoded_y, dec[0], y, x);
           BlockToData(curr->decoded_y, dec[1], y, x+1);
@@ -937,9 +935,9 @@ GenBFrame(BitBucket * const bb,
           BlockToData(curr->decoded_cr, dec[5], y/2, x/2);
       }
     } else   /* B block */ {
-        int const fCode = fCodeB;   
+        int const fCode = fCodeB;
         int pattern;
-        
+
         pattern = dct_data[y][x].pattern;
         motion.fwd.y = dct_data[y][x].fmotionY;
         motion.fwd.x = dct_data[y][x].fmotionX;
@@ -948,7 +946,7 @@ GenBFrame(BitBucket * const bb,
 
         if (pixelFullSearch)
             motion = halfMotion(motion);
-          
+
         /* create flat blocks and update pattern if necessary */
     calc_blocks:
         /* Note DoQuant references QScale, overflowChange, overflowValue,
@@ -962,7 +960,7 @@ GenBFrame(BitBucket * const bb,
 
         motionForward  = (dct_data[y][x].mode != MOTION_BACKWARD);
         motionBackward = (dct_data[y][x].mode != MOTION_FORWARD);
-        
+
         /* Encode Vectors */
         if (motionForward) {
             /* transform the fMotion vector into the appropriate values */
@@ -974,7 +972,7 @@ GenBFrame(BitBucket * const bb,
                                FORW_F, fCode);
             oldMotion.fwd = motion.fwd;
         }
-          
+
         if (motionBackward) {
             /* transform the bMotion vector into the appropriate values */
             offsetY = motion.bwd.y - oldMotion.bwd.y;
@@ -984,9 +982,9 @@ GenBFrame(BitBucket * const bb,
                                BACK_F, fCode);
             oldMotion.bwd = motion.bwd;
         }
-          
+
         oldMode = dct_data[y][x].mode;
-          
+
         if (printSNR) { /* Need to decode */
             if (pixelFullSearch) {
                 motion.fwd.x *= 2; motion.fwd.y *= 2;
@@ -1030,7 +1028,7 @@ GenBFrame(BitBucket * const bb,
         y_dc_pred = cr_dc_pred = cb_dc_pred = 128;
         lastIntra = FALSE;
         mode = dct_data[y][x].mode;
-        
+
         /*      DBG_PRINT(("MB Header(%d,%d)\n", x, y));  */
         Mhead_GenMBHeader(
             bb, 3 /* pict_code_type */, mbAddrInc /* addr_incr */,
@@ -1049,7 +1047,7 @@ GenBFrame(BitBucket * const bb,
             pattern /* mb_pattern */, FALSE /* mb_intra */);
 
         mbAddrInc = 1;
-          
+
         /* now output the difference */
         {
             unsigned int x;
@@ -1058,7 +1056,7 @@ GenBFrame(BitBucket * const bb,
                     Mpost_RLEHuffPBlock(fba[x], bb);
             }
         }
-          
+
         switch (mode) {
         case MOTION_FORWARD:
             bframeStats.BFOBits += (bb->cumulativeBits - stats.totalBits);
@@ -1072,10 +1070,10 @@ GenBFrame(BitBucket * const bb,
         default:
             pm_error("PROGRAMMER ERROR:  Illegal mode: %d", mode);
       }
-      
+
       stats.BBits += (bb->cumulativeBits - stats.totalBits);
       stats.totalBits = bb->cumulativeBits;
-    
+
       if (overflowChange) {
         /* undo an overflow-caused Qscale change */
         overflowChange = FALSE;
@@ -1091,7 +1089,7 @@ GenBFrame(BitBucket * const bb,
       rc_blockStart = bb->cumulativeBits;
       MB_RateOut(TYPE_BFRAME);
     }
-    
+
       }
     }
 
@@ -1100,22 +1098,22 @@ GenBFrame(BitBucket * const bb,
       totalSNR += snr[0];
       totalPSNR += psnr[0];
     }
-    
+
     Mhead_GenSliceEnder(bb);
     /*   Rate Control  */
     if (bitstreamMode == FIXED_RATE) {
       updateRateControl(TYPE_BFRAME);
     }
-    
+
     endTime = time_elapsed();
     totalTime += (endTime-startTime);
-    
+
     if ( showBitRatePerFrame ) {
       /* ASSUMES 30 FRAMES PER SECOND */
       fprintf(bitRateFile, "%5d\t%8d\n", curr->id,
           30*(bb->cumulativeBits-totalFrameBits));
     }
-    
+
     if ( frameSummary && !realQuiet) {
       fprintf(stdout, "FRAME %d (B):  "
               "I BLOCKS: %5d;  B BLOCKS: %5d   SKIPPED: %5d (%ld seconds)\n",
@@ -1127,7 +1125,7 @@ GenBFrame(BitBucket * const bb,
             curr->id, snr[0], snr[1], snr[2],
             psnr[0], psnr[1], psnr[2]);
     }
-    
+
     bframeStats.FrameBits += (bb->cumulativeBits-totalFrameBits);
     bframeStats.BIBlocks += stats.IBlocks;
     bframeStats.BBBlocks += stats.BBlocks;
@@ -1156,6 +1154,7 @@ SetBQScale(qB)
 }
 
 
+
 /*===========================================================================*
  *
  * GetBQScale
@@ -1174,6 +1173,7 @@ GetBQScale()
 }
 
 
+
 /*===========================================================================*
  *
  * ResetBFrameStats
@@ -1208,8 +1208,8 @@ BFrameTotalTime(void) {
 
 
 void
-ShowBFrameSummary(unsigned int const inputFrameBits, 
-                  unsigned int const totalBits, 
+ShowBFrameSummary(unsigned int const inputFrameBits,
+                  unsigned int const totalBits,
                   FILE *       const fpointer) {
 
     if (bframeStats.Frames > 0) {
@@ -1234,13 +1234,13 @@ ShowBFrameSummary(unsigned int const inputFrameBits,
                     "  B types:   %5d     (%4d bpb) "
                     "forw  %5d (%4d bpb) back   %5d (%4d bpb) bi\n",
                     bframeStats.BFOBlocks,
-                    (bframeStats.BFOBlocks==0) ? 
+                    (bframeStats.BFOBlocks==0) ?
                         0 : bframeStats.BFOBits/bframeStats.BFOBlocks,
                     bframeStats.BBABlocks,
-                    (bframeStats.BBABlocks==0) ? 
+                    (bframeStats.BBABlocks==0) ?
                         0 : bframeStats.BBABits/bframeStats.BBABlocks,
                     bframeStats.BINBlocks,
-                    (bframeStats.BINBlocks==0) ? 
+                    (bframeStats.BINBlocks==0) ?
                         0 : bframeStats.BINBits/bframeStats.BINBlocks);
         } else
             fprintf(fpointer, "  B Blocks:  %5d\n", 0);
@@ -1251,7 +1251,7 @@ ShowBFrameSummary(unsigned int const inputFrameBits,
                 "(%5d bpf)     (%2.1f%% of total)\n",
                 bframeStats.Frames, bframeStats.FrameBits,
                 bframeStats.FrameBits/bframeStats.Frames,
-                100.0*(float)bframeStats.FrameBits/(float)totalBits);        
+                100.0*(float)bframeStats.FrameBits/(float)totalBits);
         fprintf(fpointer, "  Compression:  %3d:1     (%9.4f bpp)\n",
                 bframeStats.Frames*inputFrameBits/bframeStats.FrameBits,
                 24.0*(float)bframeStats.FrameBits/
@@ -1312,7 +1312,7 @@ ComputeBMotionLumBlock(MpegFrame * const prev,
 
         ComputeMotionLumBlock(prev, by, bx, motion.fwd, &prevBlock);
         ComputeMotionLumBlock(next, by, bx, motion.bwd, &nextBlock);
-        
+
         for (y = 0; y < 16; ++y) {
             unsigned int x;
             for (x = 0; x < 16; ++x)
@@ -1326,6 +1326,7 @@ ComputeBMotionLumBlock(MpegFrame * const prev,
 }
 
 
+
 /*===========================================================================*
  *
  *  estimate the seconds to compute a B-frame
@@ -1344,3 +1345,4 @@ EstimateSecondsPerBFrame() {
 }
 
 
+
diff --git a/converter/ppm/ppmtompeg/bitio.c b/converter/ppm/ppmtompeg/bitio.c
index 3812bc39..b95f1ce1 100644
--- a/converter/ppm/ppmtompeg/bitio.c
+++ b/converter/ppm/ppmtompeg/bitio.c
@@ -106,10 +106,10 @@ Dump(BitBucket * const bbPtr) {
         for (i = 0; i <= ptr->currword; ++i)
             buffer[i] = pm_bigendFromUint32(ptr->bits[i]);
 
-        nitems = fwrite(buffer, sizeof(buffer[0]), ptr->currword + 1, 
+        nitems = fwrite(buffer, sizeof(buffer[0]), ptr->currword + 1,
                         bbPtr->filePtr);
         if (nitems != ptr->currword+1) {
-            fprintf(stderr, 
+            fprintf(stderr,
                     "Whoa!  Trouble writing %u words (wrote %u words)!  "
                     "Game over, dude!\n",
                     ptr->currword+1, nitems);
@@ -133,6 +133,7 @@ Dump(BitBucket * const bbPtr) {
 }
 
 
+
 /*=====================*
  * EXPORTED PROCEDURES *
  *=====================*/
@@ -170,7 +171,7 @@ Bitio_New(FILE * const filePtr) {
     bbPtr->firstPtr->bitsleft = MAXBITS_PER_BUCKET;
     bbPtr->firstPtr->bitsleftcur = 32;
     bbPtr->firstPtr->currword = 0;
-    memset((char *)bbPtr->firstPtr->bits, 0, 
+    memset((char *)bbPtr->firstPtr->bits, 0,
            sizeof(uint32) * WORDS_PER_BUCKET);
 
     return bbPtr;
@@ -182,7 +183,7 @@ BitBucket *
 Bitio_New_Filename(const char * const fileName) {
 
     FILE * outputFile;
-    
+
     outputFile = fopen(fileName, "wb");
     if (outputFile == NULL)
         pm_error("Could not open output file '%s'.  "
@@ -217,6 +218,7 @@ Bitio_Free(BitBucket * const bbPtr) {
 }
 
 
+
 /*===========================================================================*
  *
  * Bitio_Write
@@ -232,14 +234,14 @@ Bitio_Free(BitBucket * const bbPtr) {
  *
  *===========================================================================*/
 void
-Bitio_Write(BitBucket * const bbPtr, 
-            uint32      const bits_arg, 
+Bitio_Write(BitBucket * const bbPtr,
+            uint32      const bits_arg,
             int         const nbits) {
 
     register struct bitBucket *lastPtr, *newPtr;
     register int delta;
     uint32 bits;
-    
+
     bits=bits_arg;
     assert(nbits <= 32 && nbits >= 0);
 
@@ -261,7 +263,7 @@ Bitio_Write(BitBucket * const bbPtr,
          * there's not enough room in the current bucket, so we're
          * going to have to allocate another bucket
          */
-        newPtr = lastPtr->nextPtr = (struct bitBucket *) 
+        newPtr = lastPtr->nextPtr = (struct bitBucket *)
             malloc(sizeof(struct bitBucket));
         ERRCHK(newPtr, "malloc");
         newPtr->nextPtr = NULL;
@@ -302,7 +304,7 @@ Bitio_Write(BitBucket * const bbPtr,
              */
             lastPtr->bits[lastPtr->currword] |= (bits >> delta);
             lastPtr->currword++;
-            lastPtr->bits[lastPtr->currword] = 
+            lastPtr->bits[lastPtr->currword] =
                 (bits & lower_mask[delta]) << (32 - delta);
             lastPtr->bitsleftcur = 32 - delta;
         } else {
@@ -318,6 +320,7 @@ Bitio_Write(BitBucket * const bbPtr,
 }
 
 
+
 /*===========================================================================*
  *
  * Bitio_Flush
@@ -371,12 +374,12 @@ Bitio_Flush(BitBucket * const bbPtr) {
             if (nitems != numWords) {
                 if (ferror(bbPtr->filePtr))
                     pm_error("Error writing %u words to flush a bit bucket.  "
-                             "fwrite() gives errno %d (%s)", 
+                             "fwrite() gives errno %d (%s)",
                              numWords, errno, strerror(errno));
                 else
                     pm_error("Problem writing %u words "
                              "to flush a bit bucket.  "
-                             "Only %d words transferred.", 
+                             "Only %d words transferred.",
                              numWords, nitems);
             }
 
@@ -439,7 +442,7 @@ Bitio_Close(BitBucket * const bbPtr) {
  *
  *===========================================================================*/
 void
-Bitio_WriteToSocket(BitBucket * const bbPtr, 
+Bitio_WriteToSocket(BitBucket * const bbPtr,
                     int         const socket) {
 
     struct bitBucket *ptr, *tempPtr;
@@ -516,6 +519,7 @@ Bitio_WriteToSocket(BitBucket * const bbPtr,
 }
 
 
+
 /*===========================================================================*
  *
  * Bitio_BytePad
@@ -534,3 +538,6 @@ Bitio_BytePad(BitBucket * const bbPtr) {
         Bitio_Write(bbPtr, 0, lastPtrPtr->bitsleftcur % 8);
     }
 }
+
+
+
diff --git a/converter/ppm/ppmtompeg/block.c b/converter/ppm/ppmtompeg/block.c
index 913518c4..db8dc277 100644
--- a/converter/ppm/ppmtompeg/block.c
+++ b/converter/ppm/ppmtompeg/block.c
@@ -42,6 +42,8 @@ halfVector(vector const v) {
     return half;
 }
 
+
+
 /*===========================*
  * COMPUTE DCT OF DIFFERENCE *
  *===========================*/
@@ -106,7 +108,7 @@ ComputeDiffDCTs(MpegFrame * const current,
                 int         const bx,
                 vector      const m,
                 int *       const patternP) {
-    
+
     Block motionBlock;
 
     if (collect_quant && (collect_quant_detailed & 1))
@@ -203,14 +205,14 @@ computePrevFyFx(MpegFrame * const prevFrame,
         if (yHalf) {
             if (m.y < 0)
                 --*fyP;
-        
+
             *prevP = prevFrame->halfBoth;
         } else
             *prevP = prevFrame->halfX;
     } else if (yHalf) {
         if (m.y < 0)
             --*fyP;
-        
+
         *prevP = prevFrame->halfY;
     } else
         *prevP = prevFrame->ref_y;
@@ -263,7 +265,7 @@ ComputeMotionBlock(uint8 ** const prev,
 
         if (m.x < 0)
             --fx;
-    
+
         for (y = 0; y < 8; ++y) {
             int16 * const destPtr = (*motionBlockP)[y];
             uint8 * const srcPtr  = &(prev[fy+y][fx]);
@@ -278,7 +280,7 @@ ComputeMotionBlock(uint8 ** const prev,
         unsigned int y;
         if (m.x < 0)
             --fx;
-        
+
         for (y = 0; y < 8; ++y) {
             int16 * const destPtr = (*motionBlockP)[y];
             uint8 * const srcPtr  = &(prev[fy+y][fx]);
@@ -361,6 +363,7 @@ ComputeMotionLumBlock(MpegFrame * const prevFrame,
 }
 
 
+
 /*=======================*
  * BASIC ERROR FUNCTIONS *
  *=======================*/
@@ -410,7 +413,7 @@ LumBlockMAD(const LumBlock * const currentBlockP,
  *  return the MAD of the currentBlock and the motion-compensated block
  *      (without TUNEing)
  *
- *  (by, bx) is the location of the block in the frame 
+ *  (by, bx) is the location of the block in the frame
  *  (block number coordinates).  'm' is the motion of the block in pixels.
  *  The moved block must be wholly within the frame.
  *
@@ -452,7 +455,7 @@ LumMotionError(const LumBlock * const currentBlockP,
             const int32 * const cacross = currentBlockP->l[y];
             uint8 *       const across  = &prev[fy+y][fx];
             unsigned int x;
-            
+
             for (x = 0; x < 16; ++x) {
                 int32 const localDiff = across[x]-cacross[x];
                 diff += ABS(localDiff);
@@ -461,14 +464,14 @@ LumMotionError(const LumBlock * const currentBlockP,
                 return diff;
         }
         break;
-      
+
     case LOCAL_DCT: {
         Block     dctdiff[4], dctquant[4];
         FlatBlock quant;
         int x, i, tmp;
         int distortion=0, datarate=0;
         int pq = GetPQScale();
-      
+
         for (y = 0;  y < 16;  ++y) {
             const int32 * const cacross = currentBlockP->l[y];
             uint8 * const across = &(prev[fy+y][fx]);
@@ -489,7 +492,7 @@ LumMotionError(const LumBlock * const currentBlockP,
                 datarate += CalcRLEHuffLength(quant);
             }
         }
-      
+
         /* Calculate distortion */
         for (y = 0;  y < 16;  ++y) {
             const int32 * const cacross = currentBlockP->l[y];
@@ -510,12 +513,12 @@ LumMotionError(const LumBlock * const currentBlockP,
         extern int32 niqtable[];
         int pq = niqtable[0]*GetPQScale();
         unsigned int y;
-        
+
         for (y = 0; y < 16; ++y) {
             const int32 * const cacross = currentBlockP->l[y];
             uint8 * const across = &(prev[fy+y][fx]);
             unsigned int x;
-            
+
             for (x = 0; x < 16; ++x) {
                 int32 const localDiff = across[x]-cacross[x];
                 diff += localDiff;
@@ -598,7 +601,7 @@ LumAddMotionError(const LumBlock * const currentBlockP,
         if (diff > bestSoFar)
             return diff;
     }
-    
+
     /* This is what's happening:
      *
      *  ComputeMotionLumBlock(prevFrame, by, bx, my, mx, lumMotionBlock);
@@ -691,6 +694,7 @@ AddMotionBlock(Block          block,
 }
 
 
+
 /*===========================================================================*
  *
  *  adds the motion-compensated B-frame block to the given block
@@ -734,6 +738,7 @@ AddBMotionBlock(Block          block,
 }
 
 
+
 /*===========================================================================*
  *
  *  copies the given block into the appropriate data area
@@ -764,6 +769,7 @@ BlockToData(uint8 ** const data,
 }
 
 
+
 /*===========================================================================*
  *
  *  copies data into appropriate blocks
@@ -834,6 +840,7 @@ BlockifyFrame(MpegFrame * const frameP) {
 }
 
 
+
 /*===========================================================================*
  *                                       *
  * UNUSED PROCEDURES                                 *
@@ -855,7 +862,7 @@ BlockifyFrame(MpegFrame * const frameP) {
  * but leave it here anyway for clarity
  *
  * (startY, startX) = (0,0) for A....(0,1) for B...(1,0) for C...(1,1) for D
- *  
+ *
  */
 void
 ComputeSubSampledMotionLumBlock(MpegFrame * const prevFrame,
@@ -889,7 +896,7 @@ ComputeSubSampledMotionLumBlock(MpegFrame * const prevFrame,
         if ( my < 0 ) {
         fy--;
         }
-        
+
         prev = prevFrame->halfBoth;
     } else {
         prev = prevFrame->halfX;
@@ -925,6 +932,7 @@ ComputeSubSampledMotionLumBlock(MpegFrame * const prevFrame,
 }
 
 
+
 /*===========================================================================*
  *
  *  return the MAD of the currentBlock and the motion-compensated block,
@@ -974,7 +982,7 @@ LumMotionErrorSubSampled(LumBlock    const currentBlock,
         if ( my < 0 ) {
         fy--;
         }
-        
+
         prev = prevFrame->halfBoth;
     } else {
         prev = prevFrame->halfX;
@@ -1021,6 +1029,7 @@ LumMotionErrorSubSampled(LumBlock    const currentBlock,
 }
 
 
+
 #endif /* UNUSED_PROCEDURES */
 /*
  * Copyright (c) 1995 The Regents of the University of California.
diff --git a/converter/ppm/ppmtompeg/bsearch.c b/converter/ppm/ppmtompeg/bsearch.c
index b825ef72..6d13ab34 100644
--- a/converter/ppm/ppmtompeg/bsearch.c
+++ b/converter/ppm/ppmtompeg/bsearch.c
@@ -116,6 +116,7 @@ SetBSearchAlg(const char * const alg) {
 }
 
 
+
 /*===========================================================================*
  *
  * BSearchName
@@ -256,6 +257,7 @@ FindBestMatchExhaust(const LumBlock * const blockP,
 }
 
 
+
 /*===========================================================================*
  *
  * FindBestMatchTwoLevel
@@ -587,6 +589,7 @@ FindBestMatchSubSample(const LumBlock * const blockP,
 }
 
 
+
 /*===========================================================================*
  *
  * FindBestMatch
@@ -775,6 +778,7 @@ BMotionSearchSimple(const LumBlock * const currentBlockP,
 }
 
 
+
 /*===========================================================================*
  *
  * BMotionSearchCross2
@@ -863,6 +867,7 @@ BMotionSearchCross2(const LumBlock * const currentBlockP,
 }
 
 
+
 /*===========================================================================*
  *
  * BMotionSearchExhaust
@@ -1027,6 +1032,7 @@ BMotionSearch(const LumBlock * const currentBlockP,
 }
 
 
+
 /*===========================================================================*
  *                                       *
  * UNUSED PROCEDURES                                 *
@@ -1085,4 +1091,5 @@ ValidBMotion(by, bx, mode, fmy, fmx, bmy, bmx)
 }
 
 
+
 #endif /* UNUSED_PROCEDURES */
diff --git a/converter/ppm/ppmtompeg/combine.c b/converter/ppm/ppmtompeg/combine.c
index c00f9c71..afc3572d 100644
--- a/converter/ppm/ppmtompeg/combine.c
+++ b/converter/ppm/ppmtompeg/combine.c
@@ -112,7 +112,7 @@ appendSpecifiedGopFiles(struct inputSource * const inputSourceP,
 
             ifP = fopen(fileName, "rb");
             if (ifP == NULL)
-                pm_message("ERROR:  Couldn't read file '%s'.  retry %u", 
+                pm_message("ERROR:  Couldn't read file '%s'.  retry %u",
                            fileName, nAttempts);
         }
         if (ifP) {
@@ -125,7 +125,7 @@ appendSpecifiedGopFiles(struct inputSource * const inputSourceP,
         pm_strfree(fileName);
         pm_strfree(inputFileName);
     }
-} 
+}
 
 
 
@@ -135,20 +135,20 @@ appendDefaultGopFiles(const char * const outputFileName,
 
     unsigned int fileSeq;
     bool endOfFiles;
-    
+
     for (fileSeq = 0, endOfFiles = FALSE; !endOfFiles; ++fileSeq) {
         const char * fileName;
         FILE * ifP;
 
         pm_asprintf(&fileName, "%s.gop.%u", outputFileName, fileSeq);
-        
+
         ifP = fopen(fileName, "rb");
         if (ifP == NULL)
             endOfFiles = TRUE;
         else {
             if (!realQuiet)
                 pm_message("appending file:  %s", fileName);
-            
+
             AppendFile(ofP, ifP);
         }
         pm_strfree(fileName);
@@ -159,7 +159,7 @@ appendDefaultGopFiles(const char * const outputFileName,
 
 void
 GOPsToMPEG(struct inputSource * const inputSourceP,
-           const char *         const outputFileName, 
+           const char *         const outputFileName,
            FILE *               const ofP) {
 /*----------------------------------------------------------------------------
    Combine individual GOPs (one per file) into a single MPEG sequence file.
@@ -174,13 +174,13 @@ GOPsToMPEG(struct inputSource * const inputSourceP,
         if (Fsize_x == 0 || Fsize_y == 0)
             Fsize_Note(0, x, y);
     }
-    
+
     bb = Bitio_New(ofP);
 
     Mhead_GenSequenceHeader(bb, Fsize_x, Fsize_y, /* pratio */ aspectRatio,
                             /* pict_rate */ frameRate, /* bit_rate */ -1,
                             /* buf_size */ -1, /*c_param_flag */ 1,
-                            /* iq_matrix */ customQtable, 
+                            /* iq_matrix */ customQtable,
                             /* niq_matrix */ customNIQtable,
                             /* ext_data */ NULL, /* ext_data_size */ 0,
                             /* user_data */ NULL, /* user_data_size */ 0);
@@ -228,16 +228,16 @@ makeGOPHeader(FILE *       const outputFileP,
                        tc_hrs, tc_min, tc_sec, tc_pict,
                        closed, /* broken_link */ 0,
                        /* ext_data */ NULL, /* ext_data_size */ 0,
-                       /* user_data */ NULL, 
+                       /* user_data */ NULL,
                        /* user_data_size */ 0);
     Bitio_Flush(bbP);
     SetGOPStartTime(frameNumber);
-}        
+}
 
 
 
 void
-FramesToMPEG(FILE *               const outputFile, 
+FramesToMPEG(FILE *               const outputFile,
              void *               const inputHandle,
              fileAcquisitionFn          acquireInputFile,
              fileDispositionFn          disposeInputFile) {
@@ -292,7 +292,7 @@ FramesToMPEG(FILE *               const outputFile,
     frameNumber = 0;
 
     makeGOPHeader(outputFile, totalFramesSent, frameNumber, seqWithinGop);
-    
+
     while (inputLeft) {
         if (FType_Type(frameNumber) != 'b') {
             pastRefNum = futureRefNum;
@@ -318,7 +318,7 @@ FramesToMPEG(FILE *               const outputFile,
                 /* now, output the B-frames */
                 if (pastRefNum != -1) {
                     unsigned int bNum;
-                    
+
                     for (bNum = pastRefNum+1; bNum < futureRefNum; ++bNum) {
                         acquireInputFile(inputHandle, bNum, &inputFile);
 
@@ -326,7 +326,7 @@ FramesToMPEG(FILE *               const outputFile,
                             AppendFile(outputFile, inputFile);
 
                             disposeInputFile(inputHandle, bNum);
-            
+
                             ++seqWithinGop;
                             IncrementTCTime();
                         }
diff --git a/converter/ppm/ppmtompeg/file.c b/converter/ppm/ppmtompeg/file.c
index 223170a4..bc097452 100644
--- a/converter/ppm/ppmtompeg/file.c
+++ b/converter/ppm/ppmtompeg/file.c
@@ -121,7 +121,7 @@ ChangeDirectory(ClientData nulldata, Tcl_Interp *interp, int argc,
         fprintf(stderr, "can't open '%s'\n", currentPath);
         return TCL_OK;  /* shouldn't, really */
     }
-    
+
     return TCL_OK;
 }
 
@@ -164,7 +164,7 @@ ListDirectory(ClientData nulldata, Tcl_Interp *interp, int argc,
     while ((dp = readdir(dfd)) != NULL) {
         strcpy(restPtr, dp->d_name);
         stat(fullName, &stbuf);
-        
+
         if (dp->d_name[0] != '.') {
             if (S_ISDIR(stbuf.st_mode)) {
                 sprintf(fileName[fileCount], "%s/", dp->d_name);
@@ -263,7 +263,7 @@ SetBrowseGlob(ClientData nulldata, Tcl_Interp *interp,
         return TCL_OK;
     }
 
-    Tcl_AppendResult(interp, 
+    Tcl_AppendResult(interp,
                      "wrong args: should be \"", argv[0]," string\"",
                      NULL);
     return TCL_ERROR;
@@ -301,3 +301,6 @@ MatchesGlob(char *string, char *glob) {
 
     return TRUE;
 }
+
+
+
diff --git a/converter/ppm/ppmtompeg/frame.c b/converter/ppm/ppmtompeg/frame.c
index f91f2cc6..81c1ff9f 100644
--- a/converter/ppm/ppmtompeg/frame.c
+++ b/converter/ppm/ppmtompeg/frame.c
@@ -12,7 +12,7 @@
  *  Frame_AllocYCC                               *
  *  Frame_AllocDecoded                           *
  *  Frame_AllocHalf                                  *
- *  Frame_Resize                                     * 
+ *  Frame_Resize                                     *
  *                                       *
  *===========================================================================*/
 
@@ -52,7 +52,7 @@
  *===========*/
 
 /* The maximum number of B-Frames allowed between reference frames. */
-#define  B_FRAME_RUN  16    
+#define  B_FRAME_RUN  16
 
 /*==================*
  * GLOBAL VARIABLES *
@@ -64,13 +64,13 @@ static unsigned int numOfFrames;
 
 /*====================================================
 * Resize_Array_Width
-*    
+*
 *   This function will resize any array width up
 * or down in size.  The algorithm is based on the
 * least common multiple approach more commonly
 * used in audio frequency adjustments.
 *=====================================================*/
-static void 
+static void
 Resize_Array_Width(uint8 ** const inarray,
                    int      const in_x,
                    int      const in_y,
@@ -86,7 +86,7 @@ Resize_Array_Width(uint8 ** const inarray,
     uint8 pointA,pointB;
     double slope,diff;
 #endif
-    
+
     for (i = 0; i < in_y; ++i) {     /* For each row */
         unsigned int j;
         inptr = &inarray[i][0];
@@ -106,7 +106,7 @@ Resize_Array_Width(uint8 ** const inarray,
                     in_total = in_total - out_x;
                     --inptr;
                 }
-            } else {  
+            } else {
 #ifdef DOING_INTERPOLATION
                 pointA = *inptr;
 #endif
@@ -124,10 +124,10 @@ Resize_Array_Width(uint8 ** const inarray,
                 } else {
                     *outptr = (pointB -
                                (uint8)(slope*(((float)(out_x)) - diff)));
-                } 
+                }
 #endif
                 /* Non-Interpolative solution */
-                *outptr = *inptr;  
+                *outptr = *inptr;
 
                 ++outptr;
                 out_total = out_total + in_x;
@@ -153,7 +153,7 @@ Resize_Array_Width(uint8 ** const inarray,
 * Same as Resize_array_Width except pointer
 * manipulation must change.
 *===============================*/
-static void 
+static void
 Resize_Array_Height(uint8 ** const inarray,
                     int      const in_x,
                     int      const in_y,
@@ -176,7 +176,7 @@ Resize_Array_Height(uint8 ** const inarray,
         out_total = 0;
         k = 0;
         for(j=0; j < out_y; ++j){  /* for each output value */
-            if (in_total == out_total) {  
+            if (in_total == out_total) {
                 outarray[j][i] = inarray[k][i];
                 out_total=out_total+in_y;
                 while(in_total < out_total){
@@ -187,7 +187,7 @@ Resize_Array_Height(uint8 ** const inarray,
                     in_total = in_total - out_y;
                     --k;
                 }
-            } else {  
+            } else {
 #ifdef DOING_INTERPOLATION
                 pointA = inarray[k][i];
                 if (k != (in_y - 1)) {
@@ -210,7 +210,7 @@ Resize_Array_Height(uint8 ** const inarray,
                     in_total = in_total - out_y;
                     --k;
                 }
-            } 
+            }
         }
     }
 }
@@ -220,7 +220,7 @@ Resize_Array_Height(uint8 ** const inarray,
 /*========================================================
 * Resize_Width
 *======================================================*/
-static void  
+static void
 Resize_Width(MpegFrame * const omfrw,
              MpegFrame * const mfrw,
              int         const in_x,
@@ -274,12 +274,12 @@ Resize_Width(MpegFrame * const omfrw,
             free(mfrw->orig_y[i]);
         }
         free(mfrw->orig_y);
-        
+
         for (i = 0; i < in_y / 2; ++i) {
             free(mfrw->orig_cr[i]);
         }
         free(mfrw->orig_cr);
-        
+
         for (i = 0; i < in_y / 2; ++i) {
             free(mfrw->orig_cb[i]);
         }
@@ -300,9 +300,9 @@ Resize_Height(MpegFrame * const omfrh,
               int         const in_x,
               int         const in_y,
               int         const out_y) {
-    
-    unsigned int y; 
-    
+
+    unsigned int y;
+
     Fsize_y = out_y;
 
     /* Allocate new frame memory */
@@ -347,12 +347,12 @@ Resize_Height(MpegFrame * const omfrh,
             free(mfrh->orig_y[i]);
         }
         free(mfrh->orig_y);
-        
+
     for (i = 0; i < in_y / 2; ++i) {
         free(mfrh->orig_cr[i]);
     }
     free(mfrh->orig_cr);
-    
+
     for (i = 0; i < in_y / 2; ++i) {
         free(mfrh->orig_cb[i]);
     }
@@ -386,8 +386,8 @@ Frame_Init(unsigned int const numOfFramesRequested) {
     for (idx = 0; idx < numOfFrames; ++idx) {
         MALLOCVAR(frameMemory[idx]);
         frameMemory[idx]->inUse = FALSE;
-        frameMemory[idx]->orig_y = NULL;    
-        frameMemory[idx]->y_blocks = NULL; 
+        frameMemory[idx]->orig_y = NULL;
+        frameMemory[idx]->y_blocks = NULL;
         frameMemory[idx]->decoded_y = NULL;
         frameMemory[idx]->halfX = NULL;
         frameMemory[idx]->next = NULL;
@@ -395,6 +395,7 @@ Frame_Init(unsigned int const numOfFramesRequested) {
 }
 
 
+
 /*===========================================================================*
  *
  * FreeFrame
@@ -458,11 +459,11 @@ FreeFrame(MpegFrame * const frameP) {
             for ( i = 0; i < Fsize_y; ++i )
                 free(frameP->halfX[i]);
             free(frameP->halfX);
-            
+
             for (i = 0; i < Fsize_y-1; ++i)
                 free(frameP->halfY[i]);
             free(frameP->halfY);
-            
+
             for (i = 0; i < Fsize_y-1; ++i)
                 free(frameP->halfBoth[i]);
             free(frameP->halfBoth);
@@ -495,6 +496,7 @@ Frame_Exit(void) {
 }
 
 
+
 /*===========================================================================*
  *
  * Frame_Free
@@ -542,7 +544,7 @@ GetUnusedFrame() {
                 "See the man page for help.\n");
         exit(1);
     }
-    return frameMemory[idx]; 
+    return frameMemory[idx];
 }
 
 
@@ -638,7 +640,7 @@ Frame_AllocBlocks(MpegFrame * const frameP) {
             MALLOCARRAY(frameP->y_blocks[i], dctx);
             ERRCHK(frameP->y_blocks[i], "malloc");
         }
-    
+
         MALLOCARRAY(frameP->cr_blocks, dcty / 2);
         ERRCHK(frameP->cr_blocks, "malloc");
         MALLOCARRAY(frameP->cb_blocks, dcty / 2);
@@ -672,7 +674,7 @@ Frame_AllocYCC(MpegFrame * const frameP) {
         /* already allocated */
     } else {
         unsigned int y;
-    
+
         DBG_PRINT(("ycc_calc:\n"));
         /*
          * first, allocate tons of memory
@@ -755,7 +757,7 @@ Frame_AllocHalf(MpegFrame * const frameP) {
  *
  *  allocate memory for decoded frame for the given frame, if required
  *  if makeReference == TRUE, then makes it reference frame
- * 
+ *
  * RETURNS: nothing
  *
  * SIDE EFFECTS:    none
@@ -781,14 +783,14 @@ Frame_AllocDecoded(MpegFrame * const frameP,
             MALLOCARRAY(frameP->decoded_y[y], Fsize_x);
             ERRCHK(frameP->decoded_y[y], "malloc");
         }
-        
+
         MALLOCARRAY(frameP->decoded_cr, Fsize_y / 2);
         ERRCHK(frameP->decoded_cr, "malloc");
         for (y = 0; y < (Fsize_y / 2); ++y) {
             MALLOCARRAY(frameP->decoded_cr[y], Fsize_x / 2);
             ERRCHK(frameP->decoded_cr[y], "malloc");
         }
-        
+
         MALLOCARRAY(frameP->decoded_cb, Fsize_y / 2);
         ERRCHK(frameP->decoded_cb, "malloc");
         for (y = 0; y < (Fsize_y / 2); ++y) {
@@ -810,7 +812,7 @@ Frame_AllocDecoded(MpegFrame * const frameP,
  *
  * Frame_Resize                  by James Boucher
  *                Boston University Multimedia Communications Lab
- *  
+ *
  *     This function takes the mf input frame, read in READFrame(),
  * and resizes all the input component arrays to the output
  * dimensions specified in the parameter file as OUT_SIZE.
@@ -828,11 +830,11 @@ Frame_Resize(MpegFrame * const omf,
     MpegFrame * frameAP;  /* intermediate frame */
 
     MALLOCVAR_NOFAIL(frameAP);
-    
+
     if (insize_x != outsize_x && insize_y != outsize_y) {
         Resize_Width(frameAP, mf, insize_x, insize_y, outsize_x);
         Resize_Height(omf, frameAP, outsize_x, insize_y, outsize_y);
-    } else 
+    } else
         if (insize_x ==outsize_x && insize_y != outsize_y) {
             Resize_Height(omf, mf, insize_x, insize_y, outsize_y);
         } else
@@ -842,5 +844,7 @@ Frame_Resize(MpegFrame * const omf,
                 exit(1);
 
     free(frameAP);
-    free(mf);
 }
+
+
+
diff --git a/converter/ppm/ppmtompeg/frametype.c b/converter/ppm/ppmtompeg/frametype.c
index debefcdc..ff45564b 100644
--- a/converter/ppm/ppmtompeg/frametype.c
+++ b/converter/ppm/ppmtompeg/frametype.c
@@ -1,18 +1,18 @@
 /*===========================================================================*
- * frametype.c								     *
- *									     *
- *	procedures to keep track of frame types (I, P, B)		     *
- *									     *
- * EXPORTED PROCEDURES:							     *
- *	FType_Type						             *
- *	FType_FutureRef						             *
- *	FType_PastRef						             *
- *									     *
- * SYNOPSIS								     *
- *	FType_Type	returns the type of the given numbered frame	     *
- *	FType_FutureRef	returns the number of the future reference frame     *
- *	FType_PastRef	returns the number of the past reference frame	     *
- *									     *
+ * frametype.c                                                               *
+ *                                                                           *
+ *      procedures to keep track of frame types (I, P, B)                    *
+ *                                                                           *
+ * EXPORTED PROCEDURES:                                                      *
+ *      FType_Type                                                           *
+ *      FType_FutureRef                                                      *
+ *      FType_PastRef                                                        *
+ *                                                                           *
+ * SYNOPSIS                                                                  *
+ *      FType_Type      returns the type of the given numbered frame         *
+ *      FType_FutureRef returns the number of the future reference frame     *
+ *      FType_PastRef   returns the number of the past reference frame       *
+ *                                                                           *
  * 00.12.07 change malloc from frameTable to calloc to fix bug
  *===========================================================================*/
 
@@ -72,9 +72,9 @@ extern char * framePattern;
  *
  * FType_Type
  *
- *	returns the type of the given numbered frame
+ *      returns the type of the given numbered frame
  *
- * RETURNS:	the type
+ * RETURNS:     the type
  *
  * SIDE EFFECTS:    none
  *
@@ -161,9 +161,9 @@ FType_FutureRef(unsigned int const currFrameNum) {
  *
  * FType_PastRef
  *
- *	returns the number of the past reference frame
+ *      returns the number of the past reference frame
  *
- * RETURNS:	the number
+ * RETURNS:     the number
  *
  * SIDE EFFECTS:    none
  *
@@ -172,8 +172,8 @@ int
 FType_PastRef(currFrameNum)
     int currFrameNum;
 {
-    int	    index;
-    int	    pastIndex;
+    int     index;
+    int     pastIndex;
 
     if (use_cache) {
       return frameTable[currFrameNum].prev->number;
@@ -182,18 +182,19 @@ FType_PastRef(currFrameNum)
       pastIndex = frameTable[index].prev->number;
 
       return currFrameNum -
-	(((index-pastIndex)+framePatternLen) % framePatternLen);
+        (((index-pastIndex)+framePatternLen) % framePatternLen);
     }
 }
 
 
+
 /*===========================================================================*
  *
  * SetFramePattern
  *
- *	set the IPB pattern; calls ComputeFrameTable to set up table
+ *      set the IPB pattern; calls ComputeFrameTable to set up table
  *
- * RETURNS:	nothing
+ * RETURNS:     nothing
  *
  * SIDE EFFECTS:    framePattern, framePatternLen, frameTable
  *
@@ -264,8 +265,8 @@ ComputeFrameTable(unsigned int const numFramesArg) {
   'numFrames' == 0 means number of frames is not known at this time.
 -----------------------------------------------------------------------------*/
     int index;
-    FrameTable	*lastIP, *firstB, *secondIP;
-    FrameTable	*ptr;
+    FrameTable  *lastIP, *firstB, *secondIP;
+    FrameTable  *ptr;
     char typ;
     int table_size;
 
@@ -286,14 +287,14 @@ ComputeFrameTable(unsigned int const numFramesArg) {
         typ = FType_Type(index);
         frameTable[index].typ = typ;
         switch( typ ) {
-	    case 'i':
+            case 'i':
             ptr = firstB;
             while ( ptr != NULL ) {
                 ptr->next = &(frameTable[index]);
                 ptr = ptr->nextOutput;
             }
             frameTable[index].nextOutput = firstB;
-            frameTable[index].prev = lastIP;	/* for freeing */
+            frameTable[index].prev = lastIP;    /* for freeing */
             if ( lastIP != NULL ) {
                 lastIP->next = &(frameTable[index]);
                 if ( secondIP == NULL ) {
@@ -303,7 +304,7 @@ ComputeFrameTable(unsigned int const numFramesArg) {
             lastIP = &(frameTable[index]);
             firstB = NULL;
             break;
-	    case 'p':
+            case 'p':
             ptr = firstB;
             while ( ptr != NULL ) {
                 ptr->next = &(frameTable[index]);
@@ -320,7 +321,7 @@ ComputeFrameTable(unsigned int const numFramesArg) {
             lastIP = &(frameTable[index]);
             firstB = NULL;
             break;
-	    case 'b':
+            case 'b':
             if ( (index+1 == framePatternLen) ||
                  (FType_Type(index+1) != 'b') ) {
                 frameTable[index].nextOutput = NULL;
@@ -332,11 +333,11 @@ ComputeFrameTable(unsigned int const numFramesArg) {
                 firstB = &(frameTable[index]);
             }
             break;
-	    default:
-	        fprintf(stderr, "Programmer Error in ComputeFrameTable (%d)\n",
+            default:
+                fprintf(stderr, "Programmer Error in ComputeFrameTable (%d)\n",
                     framePattern[index]);
-	        exit(1);
-	        break;
+                exit(1);
+                break;
         }
     }
 
diff --git a/converter/ppm/ppmtompeg/fsize.c b/converter/ppm/ppmtompeg/fsize.c
index 3808405c..83b383e4 100644
--- a/converter/ppm/ppmtompeg/fsize.c
+++ b/converter/ppm/ppmtompeg/fsize.c
@@ -1,17 +1,17 @@
 /*===========================================================================*
- * fsize.c								     *
- *									     *
- *	procedures to keep track of frame size				     *
- *									     *
- * EXPORTED PROCEDURES:							     *
- *	Fsize_Reset							     *
- *	Fsize_Note							     *
- *	Fsize_Validate							     *
- *									     *
- * EXPORTED VARIABLES:							     *
- *	Fsize_x								     *
- *	Fsize_y								     *
- *									     *
+ * fsize.c                                                                   *
+ *                                                                           *
+ *      procedures to keep track of frame size                               *
+ *                                                                           *
+ * EXPORTED PROCEDURES:                                                      *
+ *      Fsize_Reset                                                          *
+ *      Fsize_Note                                                           *
+ *      Fsize_Validate                                                       *
+ *                                                                           *
+ * EXPORTED VARIABLES:                                                       *
+ *      Fsize_x                                                              *
+ *      Fsize_y                                                              *
+ *                                                                           *
  *===========================================================================*/
 
 /*
@@ -60,9 +60,9 @@ int Fsize_y = 0;
  *
  * Fsize_Reset
  *
- *	reset the frame size to 0
+ *      reset the frame size to 0
  *
- * RETURNS:	nothing
+ * RETURNS:     nothing
  *
  * SIDE EFFECTS:    Fsize_x, Fsize_y
  *
@@ -78,9 +78,9 @@ Fsize_Reset(void) {
  *
  * Fsize_Validate
  *
- *	make sure that the x, y values are 16-pixel aligned
+ *      make sure that the x, y values are 16-pixel aligned
  *
- * RETURNS:	modifies the x, y values to 16-pixel alignment
+ * RETURNS:     modifies the x, y values to 16-pixel alignment
  *
  * SIDE EFFECTS:    none
  *
@@ -94,13 +94,14 @@ Fsize_Validate(int * const xP,
 }
 
 
+
 /*===========================================================================*
  *
  * Fsize_Note
  *
- *	note the given frame size and modify the global values as appropriate
+ *      note the given frame size and modify the global values as appropriate
  *
- * RETURNS:	nothing
+ * RETURNS:     nothing
  *
  * SIDE EFFECTS:    Fsize_x, Fsize_y
  *
@@ -122,13 +123,16 @@ Fsize_Note(int          const id,
 
 #ifdef BLEAH
     if (Fsize_x == 0) {
-	Fsize_x = width;
-	Fsize_y = height;
-	Fsize_Validate(&Fsize_x, &Fsize_y);
+        Fsize_x = width;
+        Fsize_y = height;
+        Fsize_Validate(&Fsize_x, &Fsize_y);
     } else if (width < Fsize_x || height < Fsize_y) {
-	fprintf(stderr, "Frame %d: wrong size: (%d,%d).  Should be greater or equal to: (%d,%d)\n",
-		id, width, height, Fsize_x, Fsize_y);
-	exit(1);
+        fprintf(stderr, "Frame %d: wrong size: (%d,%d).  Should be greater or equal to: (%d,%d)\n",
+                id, width, height, Fsize_x, Fsize_y);
+        exit(1);
     }
 #endif
 }
+
+
+
diff --git a/converter/ppm/ppmtompeg/gethostname.c b/converter/ppm/ppmtompeg/gethostname.c
index 649fff91..dedb3129 100644
--- a/converter/ppm/ppmtompeg/gethostname.c
+++ b/converter/ppm/ppmtompeg/gethostname.c
@@ -26,3 +26,6 @@ GetHostName(void) {
 
     return strdup(utsname.nodename);
 }
+
+
+
diff --git a/converter/ppm/ppmtompeg/gethostname_win32.c b/converter/ppm/ppmtompeg/gethostname_win32.c
index e37fbb37..2e03476d 100644
--- a/converter/ppm/ppmtompeg/gethostname_win32.c
+++ b/converter/ppm/ppmtompeg/gethostname_win32.c
@@ -30,6 +30,8 @@ pushString(push_string_t *p, const char *fmt, ...)
     va_end(args);
 }
 
+
+
 #if _WIN32_WINNT < 0x0600
 /*
  * Reference available here:
@@ -90,13 +92,13 @@ get_string_version(push_string_t *str)
     if( !(bOsVersionInfoEx = GetVersionEx ((OSVERSIONINFO *) &osvi)) )
     {
         osvi.dwOSVersionInfoSize = sizeof (OSVERSIONINFO);
-        if (! GetVersionEx ( (OSVERSIONINFO *) &osvi) ) 
+        if (! GetVersionEx ( (OSVERSIONINFO *) &osvi) )
             return FALSE;
     }
 
     /* Call GetNativeSystemInfo if available; GetSystemInfo otherwise. */
     pGNSI = (PGNSI)
-            GetProcAddress(GetModuleHandle(TEXT("kernel32.dll")), 
+            GetProcAddress(GetModuleHandle(TEXT("kernel32.dll")),
             "GetNativeSystemInfo");
     if (NULL != pGNSI)
         pGNSI(&si);
@@ -254,7 +256,7 @@ get_string_version(push_string_t *str)
             pushString(str, "Microsoft Windows 2000 ");
             if (osvi.wProductType == VER_NT_WORKSTATION)
                 pushString(str, "Professional ");
-            else 
+            else
             if (osvi.wSuiteMask & VER_SUITE_DATACENTER)
                 pushString(str, "Datacenter Server ");
             else
@@ -288,7 +290,7 @@ get_string_version(push_string_t *str)
             }
         }
         /* Test for specific product on Windows NT 4.0 SP5 and earlier */
-        else  
+        else
         {
             HKEY hKey;
             TCHAR szProductType[BUFSIZE];
@@ -321,9 +323,9 @@ get_string_version(push_string_t *str)
         }
 
         /* Display service pack (if any) and build number. */
-        if (osvi.dwMajorVersion == 4 && 
+        if (osvi.dwMajorVersion == 4 &&
             lstrcmpi(osvi.szCSDVersion, TEXT("Service Pack 6")) == 0)
-        { 
+        {
             HKEY hKey;
             LONG lRet;
 
@@ -332,7 +334,7 @@ get_string_version(push_string_t *str)
                 TEXT("SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Hotfix\\Q246009"),
                 0, KEY_QUERY_VALUE, &hKey );
             if( lRet == ERROR_SUCCESS )
-                pushString(str, "Service Pack 6a (Build %d)\n", osvi.dwBuildNumber & 0xFFFF );         
+                pushString(str, "Service Pack 6a (Build %d)\n", osvi.dwBuildNumber & 0xFFFF );
             else
                 /* Windows NT 4.0 prior to SP6a */
                 pushString(str, "%s (Build %d)\n", osvi.szCSDVersion, osvi.dwBuildNumber & 0xFFFF);
@@ -358,7 +360,7 @@ get_string_version(push_string_t *str)
             pushString(str, "Microsoft Windows 98");
             if (osvi.szCSDVersion[1]=='A' || osvi.szCSDVersion[1]=='B')
                 pushString(str, " SE");
-        } 
+        }
         else
         if (osvi.dwMajorVersion == 4 && osvi.dwMinorVersion == 90)
             pushString(str, "Microsoft Windows Millennium Edition\n");
@@ -368,9 +370,11 @@ get_string_version(push_string_t *str)
         pushString(str, "Microsoft Win32s\n");
         break;
     }
-    return TRUE; 
+    return TRUE;
 }
 
+
+
 const char *
 GetHostName(void)
 {
@@ -389,6 +393,8 @@ GetHostName(void)
     return (const char *)_strdup(str.str);
 }
 
+
+
 #ifdef GETHOSTNAME_LOCAL_DEBUG
 int WINAPI WinMain(HINSTANCE hCurInst, HINSTANCE hPrevInst,
                    LPSTR lpsCmdLine, int nCmdShow)
diff --git a/converter/ppm/ppmtompeg/headers/all.h b/converter/ppm/ppmtompeg/headers/all.h
index 8f095d8e..242ffe98 100644
--- a/converter/ppm/ppmtompeg/headers/all.h
+++ b/converter/ppm/ppmtompeg/headers/all.h
@@ -1,8 +1,8 @@
 /*===========================================================================*
- * all.h								     *
- *									     *
- *	stuff included from ALL source files				     *
- *									     *
+ * all.h                                                                     *
+ *                                                                           *
+ *      stuff included from ALL source files                                 *
+ *                                                                           *
  *===========================================================================*/
 
 /*
@@ -26,7 +26,7 @@
  * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
  */
 
-/*  
+/*
  *  $Header: /u/smoot/md/mpeg_encode/headers/RCS/all.h,v 1.9 1995/06/05 21:11:06 smoot Exp $
  *  $Log: all.h,v $
  * Revision 1.9  1995/06/05  21:11:06  smoot
diff --git a/converter/ppm/ppmtompeg/headers/bitio.h b/converter/ppm/ppmtompeg/headers/bitio.h
index 931bcdd9..c74116f5 100644
--- a/converter/ppm/ppmtompeg/headers/bitio.h
+++ b/converter/ppm/ppmtompeg/headers/bitio.h
@@ -1,8 +1,8 @@
 /*===========================================================================*
- * bitio.h								     *
- *									     *
- *	bitwise input/output						     *
- *									     *
+ * bitio.h                                                                   *
+ *                                                                           *
+ *      bitwise input/output                                                 *
+ *                                                                           *
  *===========================================================================*/
 
 /*
@@ -26,7 +26,7 @@
  * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
  */
 
-/*  
+/*
  *  $Header: /n/charlie-brown/project/mm/mpeg/mpeg_dist/mpeg_encode/headers/RCS/bitio.h,v 1.8 1995/01/19 23:54:37 eyhung Exp $
  *  $Log: bitio.h,v $
  * Revision 1.8  1995/01/19  23:54:37  eyhung
@@ -70,9 +70,9 @@
  *===========*/
 
 #define WORDS_PER_BUCKET 128
-#define MAXBITS_PER_BUCKET	(WORDS_PER_BUCKET * 32)
-#define	MAX_BUCKETS	128
-#define MAX_BITS	MAX_BUCKETS*MAXBITS_PER_BUCKET
+#define MAXBITS_PER_BUCKET      (WORDS_PER_BUCKET * 32)
+#define MAX_BUCKETS     128
+#define MAX_BITS        MAX_BUCKETS*MAXBITS_PER_BUCKET
 
 
 /*=======================*
@@ -87,8 +87,8 @@ typedef struct bitBucket {
 
 typedef struct _BitBucket {
     int totalbits;
-    int	cumulativeBits;
-    int	bitsWritten;
+    int cumulativeBits;
+    int bitsWritten;
     FILE    *filePtr;
     ActualBucket *firstPtr;
     ActualBucket *lastPtr;
@@ -99,20 +99,20 @@ typedef struct _BitBucket {
  * MACROS *
  *========*/
 
-#define	SET_ITH_BIT(bits, i)	(bits |= (1 << (i)))
-#define	GET_ITH_BIT(bits, i)	(bits & (1 << (i)))
+#define SET_ITH_BIT(bits, i)    (bits |= (1 << (i)))
+#define GET_ITH_BIT(bits, i)    (bits & (1 << (i)))
 
 
 /*===============================*
  * EXTERNAL PROCEDURE prototypes *
  *===============================*/
 
-void	    
+void
 Bitio_Free(BitBucket * const bbPtr);
 
 void
-Bitio_Write(BitBucket * const bbPtr, 
-            uint32      const bits, 
+Bitio_Write(BitBucket * const bbPtr,
+            uint32      const bits,
             int         const nbits);
 
 void
@@ -131,7 +131,7 @@ void
 Bitio_Close(BitBucket * const bbPtr);
 
 void
-Bitio_WriteToSocket(BitBucket * const bbPtr, 
+Bitio_WriteToSocket(BitBucket * const bbPtr,
                     int         const socket);
 
 #endif /* BIT_IO_INCLUDED */
diff --git a/converter/ppm/ppmtompeg/headers/byteorder.h b/converter/ppm/ppmtompeg/headers/byteorder.h
index e2d8030c..9376b576 100644
--- a/converter/ppm/ppmtompeg/headers/byteorder.h
+++ b/converter/ppm/ppmtompeg/headers/byteorder.h
@@ -1,8 +1,8 @@
 /*===========================================================================*
- * byteorder.h								     *
- *									     *
- *	stuff to handle different byte order				     *
- *									     *
+ * byteorder.h                                                               *
+ *                                                                           *
+ *      stuff to handle different byte order                                 *
+ *                                                                           *
  *===========================================================================*/
 
 /*
@@ -26,7 +26,7 @@
  * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
  */
 
-/*  
+/*
  *  $Header: /u/smoot/md/mpeg_encode/headers/RCS/byteorder.h,v 1.3 1995/01/19 23:54:39 eyhung Exp $
  *  $Log: byteorder.h,v $
  * Revision 1.3  1995/01/19  23:54:39  eyhung
@@ -60,17 +60,17 @@
      * constant; thus, this is not for general use, but works with bitio.c
      */
 #define htonl(x)    \
-    ((((unsigned char *)(&x))[0] << 24) |	\
-     (((unsigned char *)(&x))[1] << 16) |	\
-     (((unsigned char *)(&x))[2] << 8) |	\
+    ((((unsigned char *)(&x))[0] << 24) |       \
+     (((unsigned char *)(&x))[1] << 16) |       \
+     (((unsigned char *)(&x))[2] << 8) |        \
      (((unsigned char *)(&x))[3]))
 #define ntohl(x)    htonl(x)
 #define htons(x)    \
-    ((((unsigned char *)(&x))[0] << 8) |	\
+    ((((unsigned char *)(&x))[0] << 8) |        \
      ((unsigned char *)(&x))[1])
 #define ntohs(x)    htons(x)
 #else
-    /* let in.h handle it, if possible */		   
+    /* let in.h handle it, if possible */
 #include <sys/types.h>
 #if !defined(WIN32) || defined(__CYGWIN__)
 #include <netinet/in.h>
diff --git a/converter/ppm/ppmtompeg/headers/combine.h b/converter/ppm/ppmtompeg/headers/combine.h
index e28c6dee..c99d9dbe 100644
--- a/converter/ppm/ppmtompeg/headers/combine.h
+++ b/converter/ppm/ppmtompeg/headers/combine.h
@@ -2,7 +2,7 @@ struct inputSource;
 
 void
 GOPsToMPEG(struct inputSource * const inputSourceP,
-           const char *         const outputFileName, 
+           const char *         const outputFileName,
            FILE *               const outputFilePtr);
 
 typedef void (*fileAcquisitionFn)(void *       const handle,
@@ -14,7 +14,7 @@ typedef void (*fileDispositionFn)(void *       const handle,
                                   unsigned int const frameNumber);
 
 void
-FramesToMPEG(FILE *               const outputFile, 
+FramesToMPEG(FILE *               const outputFile,
              void *               const inputHandle,
              fileAcquisitionFn          acquireInputFile,
              fileDispositionFn          disposeInputFile);
diff --git a/converter/ppm/ppmtompeg/headers/dct.h b/converter/ppm/ppmtompeg/headers/dct.h
index 3b824cf0..3c4780cd 100644
--- a/converter/ppm/ppmtompeg/headers/dct.h
+++ b/converter/ppm/ppmtompeg/headers/dct.h
@@ -1,8 +1,8 @@
 /*===========================================================================*
- * dct.h								     *
- *									     *
- *	DCT procedures							     *
- *									     *
+ * dct.h                                                                     *
+ *                                                                           *
+ *      DCT procedures                                                       *
+ *                                                                           *
  *===========================================================================*/
 
 /*
@@ -43,7 +43,7 @@ typedef DCTELEM DCTBLOCK[DCTSIZE2];
 typedef DCTELEM DCTBLOCK_2D[DCTSIZE][DCTSIZE];
 
 
-/*  
+/*
  *  from mfwddct.c:
  */
 void init_fdct (void);
diff --git a/converter/ppm/ppmtompeg/headers/frame.h b/converter/ppm/ppmtompeg/headers/frame.h
index e1f587a2..993359bc 100644
--- a/converter/ppm/ppmtompeg/headers/frame.h
+++ b/converter/ppm/ppmtompeg/headers/frame.h
@@ -1,8 +1,8 @@
 /*===========================================================================*
- * frame.h								     *
- *									     *
- *	basic frames procedures						     *
- *									     *
+ * frame.h                                                                   *
+ *                                                                           *
+ *      basic frames procedures                                              *
+ *                                                                           *
  *===========================================================================*/
 
 /*
@@ -40,9 +40,9 @@
 /*===========*
  * CONSTANTS *
  *===========*/
-#define TYPE_IFRAME	2
-#define TYPE_PFRAME	3
-#define TYPE_BFRAME	4
+#define TYPE_IFRAME     2
+#define TYPE_PFRAME     3
+#define TYPE_BFRAME     4
 
 
 /*=======================*
@@ -54,11 +54,11 @@ typedef struct mpegFrame {
     char    inputFileName[256];
     int id;           /* the frame number -- starts at 0 */
     bool inUse;
-	   /* this frame is currently being used (if not, any data here can be
+           /* this frame is currently being used (if not, any data here can be
           thrashed)
        */
 
-    /*  
+    /*
      *  now, the YCrCb data.  All pixel information is stored in unsigned
      *  8-bit pieces.  We separate y, cr, and cb because cr and cb are
      *  subsampled by a factor of 2.
@@ -68,16 +68,16 @@ typedef struct mpegFrame {
     uint8_t **orig_y, **orig_cr, **orig_cb;
 
     /* now, the decoded data -- relevant only if
-     *	    referenceFrame == DECODED_FRAME
+     *      referenceFrame == DECODED_FRAME
      *
-     * if decoded_y is NULL, then decoded_cr, decoded_cb are undefined 
+     * if decoded_y is NULL, then decoded_cr, decoded_cb are undefined
      */
     uint8_t **decoded_y, **decoded_cr, **decoded_cb;
 
     /* reference data */
     uint8_t **ref_y, **ref_cr, **ref_cb;
 
-    /*  
+    /*
      *  these are the Blocks which will ultimately compose MacroBlocks.
      *  A Block is in a format that mp_fwddct() can crunch.
      *  if y_blocks is NULL, then cr_blocks, cb_blocks are undefined
@@ -92,8 +92,8 @@ typedef struct mpegFrame {
     bool   halfComputed;        /* TRUE iff half-pixels already computed */
 
     struct mpegFrame *next;  /* points to the next B-frame to be encoded, if
-		       * stdin is used as the input. 
-		       */
+                       * stdin is used as the input.
+                       */
 } MpegFrame;
 
 
diff --git a/converter/ppm/ppmtompeg/headers/frames.h b/converter/ppm/ppmtompeg/headers/frames.h
index 2ec11d69..88638690 100644
--- a/converter/ppm/ppmtompeg/headers/frames.h
+++ b/converter/ppm/ppmtompeg/headers/frames.h
@@ -1,8 +1,8 @@
 /*===========================================================================*
- * frames.h                                  
- *                                       
- *  stuff dealing with frames                        
- *                                       
+ * frames.h
+ *
+ *  stuff dealing with frames
+ *
  *===========================================================================*/
 
 #ifndef FRAMES_INCLUDED
@@ -72,7 +72,7 @@ typedef struct FrameTableStruct {
     int number;
 
     int bFrameNumber;       /* actual frame number, if a b-frame */
-    
+
 } FrameTable;
 
 
@@ -125,6 +125,8 @@ MotionToFrameCoord(int   const by,
     *xP = bx * DCTSIZE + mx;
 }
 
+
+
 #define COORD_IN_FRAME(fy,fx, type)                 \
     ((type == LUM_BLOCK) ?                      \
      ((fy >= 0) && (fx >= 0) && (fy < Fsize_y) && (fx < Fsize_x)) : \
@@ -175,6 +177,7 @@ encodeMotionVector(int      const x,
 }
 
 
+
 #define DoQuant(bit, src, dest)                                         \
   if (pattern & bit) {                                                  \
     switch (Mpost_QuantZigBlock(src, dest, QScale, FALSE)) {            \
@@ -234,13 +237,13 @@ float
 BFrameTotalTime(void);
 
 void
-ShowPFrameSummary(unsigned int const inputFrameBits, 
-                  unsigned int const totalBits, 
+ShowPFrameSummary(unsigned int const inputFrameBits,
+                  unsigned int const totalBits,
                   FILE *       const fpointer);
 
 void
-ShowBFrameSummary(unsigned int const inputFrameBits, 
-                  unsigned int const totalBits, 
+ShowBFrameSummary(unsigned int const inputFrameBits,
+                  unsigned int const totalBits,
                   FILE *       const fpointer);
 
 /*==================*
@@ -291,7 +294,7 @@ extern int TIME_RATE;
  * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
  */
 
-/*  
+/*
  *  $Header: /n/picasso/project/mpeg/mpeg_dist/mpeg_encode/headers/RCS/frames.h,v 1.13 1995/08/15 23:43:04 smoot Exp $
  *  $Log: frames.h,v $
  *  Revision 1.13  1995/08/15 23:43:04  smoot
diff --git a/converter/ppm/ppmtompeg/headers/frametype.h b/converter/ppm/ppmtompeg/headers/frametype.h
index 33b604e6..3e319c40 100644
--- a/converter/ppm/ppmtompeg/headers/frametype.h
+++ b/converter/ppm/ppmtompeg/headers/frametype.h
@@ -7,7 +7,7 @@ FType_Type(unsigned int const frameNum);
 unsigned int
 FType_FutureRef(unsigned int const currFrameNum);
 
-int	FType_PastRef (int currFrameNum);
+int     FType_PastRef (int currFrameNum);
 
 void SetFramePattern(const char * const pattern);
 
diff --git a/converter/ppm/ppmtompeg/headers/fsize.h b/converter/ppm/ppmtompeg/headers/fsize.h
index 6a1c910e..5f57e4f2 100644
--- a/converter/ppm/ppmtompeg/headers/fsize.h
+++ b/converter/ppm/ppmtompeg/headers/fsize.h
@@ -1,8 +1,8 @@
 /*===========================================================================*
- * fsize.h								     *
- *									     *
- *	procedures to deal with frame size				     *
- *									     *
+ * fsize.h                                                                   *
+ *                                                                           *
+ *      procedures to deal with frame size                                   *
+ *                                                                           *
  *===========================================================================*/
 
 /*
diff --git a/converter/ppm/ppmtompeg/headers/general.h b/converter/ppm/ppmtompeg/headers/general.h
index 59c33c73..45d3db17 100644
--- a/converter/ppm/ppmtompeg/headers/general.h
+++ b/converter/ppm/ppmtompeg/headers/general.h
@@ -1,8 +1,8 @@
 /*===========================================================================*
- * general.h								     *
- *									     *
- *	very general stuff						     *
- *									     *
+ * general.h                                                                 *
+ *                                                                           *
+ *      very general stuff                                                   *
+ *                                                                           *
  *===========================================================================*/
 
 /*
@@ -26,7 +26,7 @@
  * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
  */
 
-/*  
+/*
  *  $Header: /n/picasso/project/mpeg/mpeg_dist/mpeg_encode/headers/RCS/general.h,v 1.7 1995/08/04 23:34:13 smoot Exp $
  *  $Log: general.h,v $
  *  Revision 1.7  1995/08/04 23:34:13  smoot
@@ -62,7 +62,7 @@
  * if your /usr/include headers do not have these, then pass -DMISSING_PROTOS
  * to your compiler
  *
- */ 
+ */
 #ifdef MISSING_PROTOS
 int fprintf();
 int fwrite();
@@ -114,7 +114,7 @@ int pclose();
 typedef int boolean;
 
 /* In the following, we need the "signed" in order to make these typedefs
-   match those in AIX system header files.  Otherwise, compile fails on 
+   match those in AIX system header files.  Otherwise, compile fails on
    AIX.  2000.09.11.
 */
 typedef unsigned char uint8;
@@ -139,10 +139,10 @@ typedef signed short int16;
 */
 
     /* LONG_32 should only be defined iff
-     *	    1) long's are 32 bits and
-     *	    2) int's are not
+     *      1) long's are 32 bits and
+     *      2) int's are not
      */
-#ifdef LONG_32		
+#ifdef LONG_32
 typedef unsigned long uint32;
 typedef long int32;
 #else
diff --git a/converter/ppm/ppmtompeg/headers/huff.h b/converter/ppm/ppmtompeg/headers/huff.h
index a6379248..8b46a8b8 100644
--- a/converter/ppm/ppmtompeg/headers/huff.h
+++ b/converter/ppm/ppmtompeg/headers/huff.h
@@ -19,18 +19,18 @@
  * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
  */
 
-/*  
+/*
  *  $Header: /n/charlie-brown/project/mm/mpeg/mpeg_dist/mpeg_encode/headers/RCS/huff.h,v 1.3 1995/01/19 23:54:51 eyhung Exp $
  */
 
-/*  
+/*
  *  THIS FILE WAS ORIGINALLY MACHINE GENERATED
  */
 
 #include "general.h"
 
-#define HUFF_MAXRUN	32
-#define HUFF_MAXLEVEL	41
+#define HUFF_MAXRUN     32
+#define HUFF_MAXLEVEL   41
 
 extern int huff_maxlevel[];
 extern uint32 *huff_table[];
diff --git a/converter/ppm/ppmtompeg/headers/iframe.h b/converter/ppm/ppmtompeg/headers/iframe.h
index c4f77c74..fb8d508c 100644
--- a/converter/ppm/ppmtompeg/headers/iframe.h
+++ b/converter/ppm/ppmtompeg/headers/iframe.h
@@ -19,7 +19,7 @@ int
 GetIQScale(void);
 
 void
-GenIFrame(BitBucket * const bb, 
+GenIFrame(BitBucket * const bb,
           MpegFrame * const current);
 
 void
@@ -30,8 +30,8 @@ IFrameTotalTime(void);
 
 
 void
-ShowIFrameSummary(unsigned int const inputFrameBits, 
-                  unsigned int const totalBits, 
+ShowIFrameSummary(unsigned int const inputFrameBits,
+                  unsigned int const totalBits,
                   FILE *       const fpointer);
 
 void
diff --git a/converter/ppm/ppmtompeg/headers/mheaders.h b/converter/ppm/ppmtompeg/headers/mheaders.h
index edd9552d..43df26a5 100644
--- a/converter/ppm/ppmtompeg/headers/mheaders.h
+++ b/converter/ppm/ppmtompeg/headers/mheaders.h
@@ -1,8 +1,8 @@
 /*===========================================================================*
- * mheaders.h								     *
- *									     *
- *	MPEG headers							     *
- *									     *
+ * mheaders.h                                                                *
+ *                                                                           *
+ *      MPEG headers                                                         *
+ *                                                                           *
  *===========================================================================*/
 
 /*
@@ -26,7 +26,7 @@
  * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
  */
 
-/*  
+/*
  *  $Header: /n/picasso/project/mm/mpeg/mpeg_dist/mpeg_encode/headers/RCS/mheaders.h,v 1.4 1995/03/27 19:29:24 smoot Exp $
  *  $Log: mheaders.h,v $
  * Revision 1.4  1995/03/27  19:29:24  smoot
@@ -61,40 +61,40 @@
  * EXTERNAL PROCEDURE prototypes *
  *===============================*/
 
-void	SetGOPStartTime (int index);
+void    SetGOPStartTime (int index);
 
 void
-Mhead_GenSequenceHeader(BitBucket *   const bbPtr, 
-                        uint32        const hsize, 
+Mhead_GenSequenceHeader(BitBucket *   const bbPtr,
+                        uint32        const hsize,
                         uint32        const vsize,
-                        int32         const pratio, 
-                        int32         const pict_rate, 
+                        int32         const pratio,
+                        int32         const pict_rate,
                         int32         const bit_rate_arg,
-                        int32         const buf_size_arg, 
-                        int32         const c_param_flag_arg, 
-                        const int32 * const iq_matrix, 
+                        int32         const buf_size_arg,
+                        int32         const c_param_flag_arg,
+                        const int32 * const iq_matrix,
                         const int32 * const niq_matrix,
-                        uint8 *       const ext_data, 
-                        int32         const ext_data_size, 
+                        uint8 *       const ext_data,
+                        int32         const ext_data_size,
                         uint8 *       const user_data,
                         int32         const user_data_size);
 
-void	Mhead_GenSequenceEnder (BitBucket *bbPtr);
-void	Mhead_GenGOPHeader (BitBucket *bbPtr,
-	   int32 drop_frame_flag,
+void    Mhead_GenSequenceEnder (BitBucket *bbPtr);
+void    Mhead_GenGOPHeader (BitBucket *bbPtr,
+           int32 drop_frame_flag,
            int32 tc_hrs, int32 tc_min,
            int32 tc_sec, int32 tc_pict,
            int32 closed_gop, int32 broken_link,
            uint8 *ext_data, int32 ext_data_size,
            uint8 *user_data, int32 user_data_size);
-void	Mhead_GenPictureHeader (BitBucket *bbPtr, int frameType,
-					    int pictCount, int f_code);
-void	Mhead_GenSliceHeader (BitBucket *bbPtr, uint32 slicenum,
-					  uint32 qscale, uint8 *extra_info,
-					  uint32 extra_info_size);
-void	Mhead_GenSliceEnder (BitBucket *bbPtr);
-void	Mhead_GenMBHeader (BitBucket *bbPtr,
-	  uint32 pict_code_type, uint32 addr_incr,
+void    Mhead_GenPictureHeader (BitBucket *bbPtr, int frameType,
+                                            int pictCount, int f_code);
+void    Mhead_GenSliceHeader (BitBucket *bbPtr, uint32 slicenum,
+                                          uint32 qscale, uint8 *extra_info,
+                                          uint32 extra_info_size);
+void    Mhead_GenSliceEnder (BitBucket *bbPtr);
+void    Mhead_GenMBHeader (BitBucket *bbPtr,
+          uint32 pict_code_type, uint32 addr_incr,
           uint32 q_scale,
           uint32 forw_f_code, uint32 back_f_code,
           uint32 horiz_forw_r, uint32 vert_forw_r,
diff --git a/converter/ppm/ppmtompeg/headers/motion_search.h b/converter/ppm/ppmtompeg/headers/motion_search.h
index d00509c4..0cb5370b 100644
--- a/converter/ppm/ppmtompeg/headers/motion_search.h
+++ b/converter/ppm/ppmtompeg/headers/motion_search.h
@@ -40,7 +40,7 @@ if ( stepSize == 2 ) { \
     rightMY++;      \
     rightMX++;      \
     }
-    
+
 #define VALID_MOTION(m)   \
 (((m).y >= leftMY) && ((m).y < rightMY) &&   \
  ((m).x >= leftMX) && ((m).x < rightMX) )
@@ -50,9 +50,9 @@ if ( stepSize == 2 ) { \
  * EXTERNAL PROCEDURE prototypes *
  *===============================*/
 
-void 
+void
 SetPSearchAlg(const char * const alg);
-void 
+void
 SetBSearchAlg(const char * const alg);
 const char *
 BSearchName(void);
@@ -94,9 +94,9 @@ PTwoLevelSearch(const LumBlock * const currentBlockP,
                 int              const searchRange);
 void
 PMotionSearch(const LumBlock * const currentBlockP,
-              MpegFrame *      const prev, 
+              MpegFrame *      const prev,
               int              const by,
-              int              const bx, 
+              int              const bx,
               vector *         const motionP);
 
 void
@@ -129,7 +129,7 @@ extern int psearchAlg;
  * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
  */
 
-/*  
+/*
  *  $Header: /n/picasso/project/mpeg/mpeg_dist/mpeg_encode/headers/RCS/search.h,v 1.6 1995/08/15 23:43:36 smoot Exp $
  *  $Log: search.h,v $
  *  Revision 1.6  1995/08/15 23:43:36  smoot
diff --git a/converter/ppm/ppmtompeg/headers/mpeg.h b/converter/ppm/ppmtompeg/headers/mpeg.h
index fbfaaf2c..d258cde4 100644
--- a/converter/ppm/ppmtompeg/headers/mpeg.h
+++ b/converter/ppm/ppmtompeg/headers/mpeg.h
@@ -1,8 +1,8 @@
 /*===========================================================================*
- * mpeg.h								     *
- *									     *
- *	no comment							     *
- *									     *
+ * mpeg.h                                                                    *
+ *                                                                           *
+ *      no comment                                                           *
+ *                                                                           *
  *===========================================================================*/
 
 /*
@@ -47,13 +47,13 @@ enum frameContext {CONTEXT_WHOLESTREAM, CONTEXT_GOP, CONTEXT_JUSTFRAMES};
 
 void
 GenMPEGStream(struct inputSource * const inputSourceP,
-              enum frameContext    const context, 
-              unsigned int         const frameStart, 
-              unsigned int         const frameEnd, 
-              int32                const qtable[], 
-              int32                const niqtable[], 
+              enum frameContext    const context,
+              unsigned int         const frameStart,
+              unsigned int         const frameEnd,
+              int32                const qtable[],
+              int32                const niqtable[],
               bool                 const childProcess,
-              FILE *               const ofp, 
+              FILE *               const ofp,
               const char *         const outputFileName,
               bool                 const wantVbvUnderflowWarning,
               bool                 const wantVbvOverflowWarning,
@@ -61,38 +61,38 @@ GenMPEGStream(struct inputSource * const inputSourceP,
               unsigned int *       const totalBitsP);
 
 void
-PrintStartStats(time_t               const startTime, 
+PrintStartStats(time_t               const startTime,
                 bool                 const specificFrames,
-                unsigned int         const firstFrame, 
+                unsigned int         const firstFrame,
                 unsigned int         const lastFrame,
                 struct inputSource * const inputSourceP);
 
 void
 PrintEndStats(time_t       const startTime,
               time_t       const endTime,
-              unsigned int const inputFrameBits, 
+              unsigned int const inputFrameBits,
               unsigned int const totalBits);
 
 void
-ComputeGOPFrames(int            const whichGOP, 
-                 unsigned int * const firstFrameP, 
-                 unsigned int * const lastFrameP, 
+ComputeGOPFrames(int            const whichGOP,
+                 unsigned int * const firstFrameP,
+                 unsigned int * const lastFrameP,
                  unsigned int   const numFrames);
 
-extern void	IncrementTCTime (void);
+extern void     IncrementTCTime (void);
 void SetReferenceFrameType(const char * const type);
 
 boolean
 NonLocalRefFrame(int     const id);
 
 void
-ReadDecodedRefFrame(MpegFrame *  const frameP, 
+ReadDecodedRefFrame(MpegFrame *  const frameP,
                     unsigned int const frameNumber);
 
 void
 SetBitRateFileName(const char * const fileName);
 
-extern void	SetFrameRate (void);
+extern void     SetFrameRate (void);
 
 
 /*==================*
@@ -100,11 +100,11 @@ extern void	SetFrameRate (void);
  *==================*/
 
 extern MpegFrame *frameMemory[3];
-extern int32	  tc_hrs, tc_min, tc_sec, tc_pict, tc_extra;
-extern int	  totalFramesSent;
-extern int	  gopSize;
-extern char	 *framePattern;
-extern int	  framePatternLen;
+extern int32      tc_hrs, tc_min, tc_sec, tc_pict, tc_extra;
+extern int        totalFramesSent;
+extern int        gopSize;
+extern char      *framePattern;
+extern int        framePatternLen;
 extern int32 qtable[];
 extern int32 niqtable[];
 extern int32 *customQtable;
diff --git a/converter/ppm/ppmtompeg/headers/mproto.h b/converter/ppm/ppmtompeg/headers/mproto.h
index 5b003b2e..22b3ba2b 100644
--- a/converter/ppm/ppmtompeg/headers/mproto.h
+++ b/converter/ppm/ppmtompeg/headers/mproto.h
@@ -1,8 +1,8 @@
 /*===========================================================================*
- * mproto.h								     *
- *									     *
- *	basically a lot of miscellaneous prototypes			     *
- *									     *
+ * mproto.h                                                                  *
+ *                                                                           *
+ *      basically a lot of miscellaneous prototypes                          *
+ *                                                                           *
  *===========================================================================*/
 
 /*
@@ -26,7 +26,7 @@
  * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
  */
 
-/*  
+/*
  *  $Header: /n/picasso/project/mm/mpeg/mpeg_dist/mpeg_encode/headers/RCS/mproto.h,v 1.12 1995/03/29 20:14:29 smoot Exp $
  *  $Log: mproto.h,v $
  * Revision 1.12  1995/03/29  20:14:29  smoot
@@ -82,7 +82,7 @@ typedef DCTELEM DCTBLOCK[DCTSIZE2];
  * EXTERNAL PROCEDURE prototypes *
  *===============================*/
 
-/*  
+/*
  *  from mbasic.c:
  */
 void mp_reset (void);
@@ -90,13 +90,13 @@ void mp_free (MpegFrame *mf);
 MpegFrame *mp_new (int fnumber, char type, MpegFrame *oldFrame);
 void mp_ycc_calc (MpegFrame *mf);
 void mp_dct_blocks (MpegFrame *mf);
-void	AllocDecoded (MpegFrame *frame);
+void    AllocDecoded (MpegFrame *frame);
 
-/*  
+/*
  *  from moutput.c:
  */
 boolean mp_quant_zig_block (Block in, FlatBlock out, int qscale, int iblock);
-void	UnQuantZig (FlatBlock in, Block out, int qscale, boolean iblock);
+void    UnQuantZig (FlatBlock in, Block out, int qscale, boolean iblock);
 void mp_rle_huff_block (FlatBlock in, BitBucket *out);
 void mp_rle_huff_pblock (FlatBlock in, BitBucket *out);
 void mp_create_blocks (MpegFrame *mf);
@@ -104,12 +104,12 @@ void mp_create_blocks (MpegFrame *mf);
 
 
 
-void	ReadEYUV (MpegFrame * mf, FILE *fpointer, int width,
-			    int height);
-boolean	ReadPPM (MpegFrame *mf, FILE *fpointer);
+void    ReadEYUV (MpegFrame * mf, FILE *fpointer, int width,
+                            int height);
+boolean ReadPPM (MpegFrame *mf, FILE *fpointer);
 void PPMtoYCC (MpegFrame * mf);
 
-void	ComputeHalfPixelData (MpegFrame *frame);
+void    ComputeHalfPixelData (MpegFrame *frame);
 void mp_validate_size (int *x, int *y);
 void AllocYCC (MpegFrame * mf);
 
diff --git a/converter/ppm/ppmtompeg/headers/mtypes.h b/converter/ppm/ppmtompeg/headers/mtypes.h
index a44ce680..bf56a110 100644
--- a/converter/ppm/ppmtompeg/headers/mtypes.h
+++ b/converter/ppm/ppmtompeg/headers/mtypes.h
@@ -1,7 +1,7 @@
 /*===========================================================================*
  * mtypes.h
  *
- *	MPEG data types
+ *      MPEG data types
  *
  *===========================================================================*/
 
@@ -18,12 +18,12 @@
  * CONSTANTS *
  *===========*/
 
-#define TYPE_BOGUS	0   /* for the header of the circular list */
-#define TYPE_VIRGIN	1
+#define TYPE_BOGUS      0   /* for the header of the circular list */
+#define TYPE_VIRGIN     1
 
-#define STATUS_EMPTY	0
-#define STATUS_LOADED	1
-#define STATUS_WRITTEN	2
+#define STATUS_EMPTY    0
+#define STATUS_LOADED   1
+#define STATUS_WRITTEN  2
 
 
 typedef struct vector {
@@ -40,15 +40,15 @@ typedef struct motion {
  * TYPE DEFINITIONS *
  *==================*/
 
-/*  
+/*
  *  your basic Block type
  */
 typedef int16_t Block[DCTSIZE][DCTSIZE];
 typedef int16_t FlatBlock[DCTSIZE_SQ];
-typedef	struct {
+typedef struct {
     int32_t l[2*DCTSIZE][2*DCTSIZE];
 } LumBlock;
-typedef	int32_t ChromBlock[DCTSIZE][DCTSIZE];
+typedef int32_t ChromBlock[DCTSIZE][DCTSIZE];
 
 /*========*
  * MACROS *
diff --git a/converter/ppm/ppmtompeg/headers/opts.h b/converter/ppm/ppmtompeg/headers/opts.h
index 1756334e..887c9723 100644
--- a/converter/ppm/ppmtompeg/headers/opts.h
+++ b/converter/ppm/ppmtompeg/headers/opts.h
@@ -23,7 +23,7 @@
  * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
  */
 
-/*  
+/*
  *  $Header: /n/picasso/project/mpeg/mpeg_dist/mpeg_encode/headers/RCS/opts.h,v 1.3 1995/08/15 23:43:43 smoot Exp $
  *  $Log: opts.h,v $
  *  Revision 1.3  1995/08/15 23:43:43  smoot
@@ -109,10 +109,10 @@ extern int LaplaceNum, LaplaceCnum;
 extern boolean BSkipBlocks;
 
 /* Procedures Prototypes */
-int	GetIQScale (void);
-int	GetPQScale (void);
-int	GetBQScale (void);
-void	Tune_Init (void);
+int     GetIQScale (void);
+int     GetPQScale (void);
+int     GetBQScale (void);
+void    Tune_Init (void);
 int     CalcRLEHuffLength (FlatBlock in);
 void    ParseTuneParam(const char * const charPtr);
 int     mse (Block blk1, Block blk2);
diff --git a/converter/ppm/ppmtompeg/headers/parallel.h b/converter/ppm/ppmtompeg/headers/parallel.h
index 0a31fac2..b5407cea 100644
--- a/converter/ppm/ppmtompeg/headers/parallel.h
+++ b/converter/ppm/ppmtompeg/headers/parallel.h
@@ -1,8 +1,8 @@
 /*===========================================================================*
- * parallel.h          
- *                     
- *  parallel encoding  
- *                     
+ * parallel.h
+ *
+ *  parallel encoding
+ *
  *===========================================================================*/
 
 /*
@@ -42,33 +42,33 @@ struct inputSource;
 
 void
 MasterServer(struct inputSource * const inputSourceP,
-             const char *         const paramFileName, 
+             const char *         const paramFileName,
              const char *         const outputFileName);
 
 void
-NotifyMasterDone(const char * const hostName, 
-                 int          const portNum, 
-                 int          const machineNumber, 
-                 unsigned int const seconds, 
+NotifyMasterDone(const char * const hostName,
+                 int          const portNum,
+                 int          const machineNumber,
+                 unsigned int const seconds,
                  boolean *    const moreWorkToDoP,
                  int *        const frameStartP,
                  int *        const frameEndP);
 
 void
 IoServer(struct inputSource * const inputSourceP,
-         const char *         const parallelHostName, 
+         const char *         const parallelHostName,
          int                  const portNum);
 
 void
-CombineServer(int          const numInputFiles, 
-              const char * const masterHostName, 
+CombineServer(int          const numInputFiles,
+              const char * const masterHostName,
               int          const masterPortNum,
               const char*  const outputFileName);
 
 void
-DecodeServer(int          const numInputFiles, 
-             const char * const decodeFileName, 
-             const char * const parallelHostName, 
+DecodeServer(int          const numInputFiles,
+             const char * const decodeFileName,
+             const char * const parallelHostName,
              int          const portNum);
 
 void
@@ -91,20 +91,20 @@ SetIOConvert(boolean const separate);
 void
 SetRemoteShell(const char * const shell);
 
-void 
+void
 NotifyDecodeServerReady(int const id);
 
-void 
+void
 WaitForDecodedFrame(int id);
 
-void 
+void
 SendDecodedFrame(MpegFrame * const frameP);
 
-void 
+void
 GetRemoteDecodedRefFrame(MpegFrame * const frameP,
                          int         const frameNumber);
 
-void 
+void
 SetParallelPerfect(boolean val);
 
 
diff --git a/converter/ppm/ppmtompeg/headers/param.h b/converter/ppm/ppmtompeg/headers/param.h
index 46a544b3..103f03b5 100644
--- a/converter/ppm/ppmtompeg/headers/param.h
+++ b/converter/ppm/ppmtompeg/headers/param.h
@@ -33,7 +33,7 @@ struct params {
 
 
 void
-ReadParamFile(const char *         const fileName, 
+ReadParamFile(const char *         const fileName,
               majorProgramFunction const function,
               struct params *      const paramP);
 
diff --git a/converter/ppm/ppmtompeg/headers/postdct.h b/converter/ppm/ppmtompeg/headers/postdct.h
index 3f3b51fe..e426f05a 100644
--- a/converter/ppm/ppmtompeg/headers/postdct.h
+++ b/converter/ppm/ppmtompeg/headers/postdct.h
@@ -1,8 +1,8 @@
 /*===========================================================================*
- * postdct.h								     *
- *									     *
- *	MPEG post-DCT processing					     *
- *									     *
+ * postdct.h                                                                 *
+ *                                                                           *
+ *      MPEG post-DCT processing                                             *
+ *                                                                           *
  *===========================================================================*/
 
 /*
@@ -30,10 +30,10 @@
 
 
 int     Mpost_QuantZigBlock (Block in, FlatBlock out, int qscale, int iblock);
-void	Mpost_UnQuantZigBlock (FlatBlock in, Block out,
+void    Mpost_UnQuantZigBlock (FlatBlock in, Block out,
                                int qscale, boolean iblock);
-void	Mpost_RLEHuffIBlock (FlatBlock in, BitBucket *out);
-void	Mpost_RLEHuffPBlock (FlatBlock in, BitBucket *out);
+void    Mpost_RLEHuffIBlock (FlatBlock in, BitBucket *out);
+void    Mpost_RLEHuffPBlock (FlatBlock in, BitBucket *out);
 
 #define MPOST_ZERO 0
 #define MPOST_NON_ZERO 1
diff --git a/converter/ppm/ppmtompeg/headers/psocket.h b/converter/ppm/ppmtompeg/headers/psocket.h
index 214f5dce..26e11db2 100644
--- a/converter/ppm/ppmtompeg/headers/psocket.h
+++ b/converter/ppm/ppmtompeg/headers/psocket.h
@@ -22,8 +22,8 @@ WriteBytes(int             const fd,
            unsigned int    const nbyte);
 
 void
-ConnectToSocket(const char *      const machineName, 
-                int               const portNum, 
+ConnectToSocket(const char *      const machineName,
+                int               const portNum,
                 struct hostent ** const hostEnt,
                 int *             const socketFdP,
                 const char **     const errorP);
diff --git a/converter/ppm/ppmtompeg/headers/rate.h b/converter/ppm/ppmtompeg/headers/rate.h
index a5f5076f..d11a4b77 100644
--- a/converter/ppm/ppmtompeg/headers/rate.h
+++ b/converter/ppm/ppmtompeg/headers/rate.h
@@ -1,22 +1,22 @@
 /*===========================================================================*
- * rate.h								     *
- *									     *
- *	Procedures concerned with rate control
- *									     *
- * EXPORTED PROCEDURES:							     *
+ * rate.h                                                                    *
+ *                                                                           *
+ *      Procedures concerned with rate control
+ *                                                                           *
+ * EXPORTED PROCEDURES:                                                      *
  *  getRateMode()
  *  setBitRate()
  *  getBitRate()
  *  setBufferSize()
  *  getBufferSize()
- *	initRateControl()
- *	targetRateControl()
- * 	updateRateControl()
- *	MB_RateOut()
- *									     *
+ *      initRateControl()
+ *      targetRateControl()
+ *      updateRateControl()
+ *      MB_RateOut()
+ *                                                                           *
  *===========================================================================*/
 
-/* 	COPYRIGHT INFO HERE	*/
+/*      COPYRIGHT INFO HERE     */
 
 #define VARIABLE_RATE 0
 #define FIXED_RATE 1
@@ -41,7 +41,7 @@ extern int rc_quantOverride;
  *
  * initRateControl
  *
- *	initialize the allocation parameters.
+ *      initialize the allocation parameters.
  *===========================================================================*/
 int
 initRateControl(bool const wantUnderflowWarning,
@@ -64,7 +64,7 @@ targetRateControl(MpegFrame * const frameP);
  * MB_RateOut
  *
  *      Prints out sampling of MB rate control data.  Every "nth" block
- *	stats are printed, with "n" controlled by global RC_MB_SAMPLE_RATE
+ *      stats are printed, with "n" controlled by global RC_MB_SAMPLE_RATE
  *
  * RETURNS:     nothing
  *===========================================================================*/
@@ -137,7 +137,7 @@ extern void SetRateControl (char *charPtr);
  *
  * RETURNS:     nothing
  *===========================================================================*/
-extern void 
+extern void
 setBufferSize(const char * const charPtr);
 
 
@@ -164,7 +164,7 @@ extern int getBufferSize (void);
  *
  * SIDE EFFECTS:   global variables
  *===========================================================================*/
-extern void 
+extern void
 setBitRate(const char * const charPtr);
 
 
diff --git a/converter/ppm/ppmtompeg/headers/readframe.h b/converter/ppm/ppmtompeg/headers/readframe.h
index 3a6876b1..3c203e8a 100644
--- a/converter/ppm/ppmtompeg/headers/readframe.h
+++ b/converter/ppm/ppmtompeg/headers/readframe.h
@@ -1,8 +1,8 @@
 /*===========================================================================*
- * readframe.h								     *
- *									     *
- *	stuff dealing with reading frames				     *
- *									     *
+ * readframe.h                                                               *
+ *                                                                           *
+ *      stuff dealing with reading frames                                    *
+ *                                                                           *
  *===========================================================================*/
 
 /*
@@ -32,15 +32,15 @@
  * CONSTANTS *
  *===========*/
 
-#define	PPM_FILE_TYPE	    0
-#define YUV_FILE_TYPE	    2
-#define ANY_FILE_TYPE	    3
-#define BASE_FILE_TYPE	    4
-#define PNM_FILE_TYPE	    5
-#define SUB4_FILE_TYPE	    6
-#define JPEG_FILE_TYPE	    7
+#define PPM_FILE_TYPE       0
+#define YUV_FILE_TYPE       2
+#define ANY_FILE_TYPE       3
+#define BASE_FILE_TYPE      4
+#define PNM_FILE_TYPE       5
+#define SUB4_FILE_TYPE      6
+#define JPEG_FILE_TYPE      7
 #define JMOVIE_FILE_TYPE    8
-#define Y_FILE_TYPE	    9
+#define Y_FILE_TYPE         9
 
 
 struct inputSource;
@@ -52,7 +52,7 @@ ReadFrameFile(MpegFrame *  const frameP,
               bool *       const eofP);
 
 void
-ReadFrame(MpegFrame *          const frameP, 
+ReadFrame(MpegFrame *          const frameP,
           struct inputSource * const inputSourceP,
           unsigned int         const frameNumber,
           const char *         const conversion,
@@ -62,8 +62,8 @@ FILE *
 ReadIOConvert(struct inputSource * const inputSourceP,
               unsigned int         const frameNumber);
 
-extern void	SetFileType(const char * const conversion);
-extern void	SetFileFormat(const char * const format);
-extern void	SetResize(bool const set);
+extern void     SetFileType(const char * const conversion);
+extern void     SetFileFormat(const char * const format);
+extern void     SetResize(bool const set);
 
-extern int	baseFormat;
+extern int      baseFormat;
diff --git a/converter/ppm/ppmtompeg/headers/rgbtoycc.h b/converter/ppm/ppmtompeg/headers/rgbtoycc.h
index 52159963..d7aa017c 100644
--- a/converter/ppm/ppmtompeg/headers/rgbtoycc.h
+++ b/converter/ppm/ppmtompeg/headers/rgbtoycc.h
@@ -1,8 +1,8 @@
 /*===========================================================================*
- * rgbtoycc.h								     *
- *									     *
- *	Procedures to convert from RGB space to YUV space		     *
- *									     *
+ * rgbtoycc.h                                                                *
+ *                                                                           *
+ *      Procedures to convert from RGB space to YUV space                    *
+ *                                                                           *
  *===========================================================================*/
 
 /*
diff --git a/converter/ppm/ppmtompeg/headers/specifics.h b/converter/ppm/ppmtompeg/headers/specifics.h
index 4f5c7074..552193d8 100644
--- a/converter/ppm/ppmtompeg/headers/specifics.h
+++ b/converter/ppm/ppmtompeg/headers/specifics.h
@@ -1,5 +1,3 @@
-
-
 /*===========*
  * TYPES     *
  *===========*/
@@ -19,7 +17,7 @@ typedef struct detail_def {
 }  Slice_Specifics;
 
 typedef struct fsl_def {
-  int framenum; 
+  int framenum;
   int frametype;
   char qscale;
   Slice_Specifics *slc;
@@ -28,8 +26,8 @@ typedef struct fsl_def {
 } FrameSpecList;
 
 
-void	Specifics_Init (void);
+void    Specifics_Init (void);
 int     SpecLookup (int fn, int typ, int num,
-			    BlockMV **info, int start_qs);
+                            BlockMV **info, int start_qs);
 int SpecTypeLookup (int fn);
 
diff --git a/converter/ppm/ppmtompeg/huff.c b/converter/ppm/ppmtompeg/huff.c
index f2be16ef..565a2f0e 100644
--- a/converter/ppm/ppmtompeg/huff.c
+++ b/converter/ppm/ppmtompeg/huff.c
@@ -19,24 +19,38 @@
  * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
  */
 
-/*  
+/*
  *  $Header: /n/charlie-brown/project/mm/mpeg/mpeg_dist/mpeg_encode/RCS/huff.c,v 1.6 1995/01/19 23:07:39 eyhung Exp $
  */
 
-/*  
+/*
  *  THIS FILE WAS ORIGINALLY MACHINE GENERATED
  */
 #include "general.h"
 #include "mtypes.h"
 #include "huff.h"
 
-int huff_maxlevel[32] = { 41, 19, 6, 5, 4, 4, 4, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2 };
+int huff_maxlevel[32] = { 41, 19, 6, 5, 4, 4, 4, 3, 3, 3, 3, 3, 3, 3,
+                           3, 3, 3, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
+                           2, 2, 2 };
+
+uint32 huff_table0[41] = { 0x0, 0x6, 0x8, 0xa, 0xc, 0x4c, 0x42, 0x14,
+                           0x3a, 0x30, 0x26, 0x20, 0x34, 0x32, 0x30,
+                           0x2e, 0x3e, 0x3c, 0x3a, 0x38, 0x36, 0x34,
+                           0x32, 0x30, 0x2e, 0x2c, 0x2a, 0x28, 0x26,
+                           0x24, 0x22, 0x20, 0x30, 0x2e, 0x2c, 0x2a,
+                           0x28, 0x26, 0x24, 0x22, 0x20 };
+
+int huff_bits0[41] = { 0, 3, 5, 6, 8, 9, 9, 11, 13, 13, 13, 13, 14, 14,
+                      14, 14, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
+                      15, 15, 15, 16, 16, 16, 16, 16, 16, 16, 16, 16 };
 
-uint32 huff_table0[41] = { 0x0, 0x6, 0x8, 0xa, 0xc, 0x4c, 0x42, 0x14, 0x3a, 0x30, 0x26, 0x20, 0x34, 0x32, 0x30, 0x2e, 0x3e, 0x3c, 0x3a, 0x38, 0x36, 0x34, 0x32, 0x30, 0x2e, 0x2c, 0x2a, 0x28, 0x26, 0x24, 0x22, 0x20, 0x30, 0x2e, 0x2c, 0x2a, 0x28, 0x26, 0x24, 0x22, 0x20 };
-int huff_bits0[41] = { 0, 3, 5, 6, 8, 9, 9, 11, 13, 13, 13, 13, 14, 14, 14, 14, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 16, 16, 16, 16, 16, 16, 16, 16, 16 };
+uint32 huff_table1[19] = { 0x0, 0x6, 0xc, 0x4a, 0x18, 0x36, 0x2c,
+                          0x2a, 0x3e, 0x3c, 0x3a, 0x38, 0x36, 0x34,
+                          0x32, 0x26, 0x24, 0x22, 0x20 };
 
-uint32 huff_table1[19] = { 0x0, 0x6, 0xc, 0x4a, 0x18, 0x36, 0x2c, 0x2a, 0x3e, 0x3c, 0x3a, 0x38, 0x36, 0x34, 0x32, 0x26, 0x24, 0x22, 0x20 };
-int huff_bits1[19] = { 0, 4, 7, 9, 11, 13, 14, 14, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17 };
+int huff_bits1[19] = { 0, 4, 7, 9, 11, 13, 14, 14, 16, 16, 16, 16, 16,
+                      16, 16, 17, 17, 17, 17 };
 
 uint32 huff_table2[6] = { 0x0, 0xa, 0x8, 0x16, 0x28, 0x28 };
 int huff_bits2[6] = { 0, 5, 8, 11, 13, 14 };
@@ -128,5 +142,18 @@ int huff_bits30[2] = { 0, 17 };
 uint32 huff_table31[2] = { 0x0, 0x36 };
 int huff_bits31[2] = { 0, 17 };
 
-uint32 *huff_table[32] = { huff_table0, huff_table1, huff_table2, huff_table3, huff_table4, huff_table5, huff_table6, huff_table7, huff_table8, huff_table9, huff_table10, huff_table11, huff_table12, huff_table13, huff_table14, huff_table15, huff_table16, huff_table17, huff_table18, huff_table19, huff_table20, huff_table21, huff_table22, huff_table23, huff_table24, huff_table25, huff_table26, huff_table27, huff_table28, huff_table29, huff_table30, huff_table31 };
-int *huff_bits[32] = { huff_bits0, huff_bits1, huff_bits2, huff_bits3, huff_bits4, huff_bits5, huff_bits6, huff_bits7, huff_bits8, huff_bits9, huff_bits10, huff_bits11, huff_bits12, huff_bits13, huff_bits14, huff_bits15, huff_bits16, huff_bits17, huff_bits18, huff_bits19, huff_bits20, huff_bits21, huff_bits22, huff_bits23, huff_bits24, huff_bits25, huff_bits26, huff_bits27, huff_bits28, huff_bits29, huff_bits30, huff_bits31 };
+uint32 *huff_table[32] = { huff_table0, huff_table1, huff_table2,
+    huff_table3, huff_table4, huff_table5, huff_table6, huff_table7,
+    huff_table8, huff_table9, huff_table10, huff_table11, huff_table12,
+    huff_table13, huff_table14, huff_table15, huff_table16, huff_table17,
+    huff_table18, huff_table19, huff_table20, huff_table21, huff_table22,
+    huff_table23, huff_table24, huff_table25, huff_table26, huff_table27,
+    huff_table28, huff_table29, huff_table30, huff_table31 };
+
+int *huff_bits[32] = { huff_bits0, huff_bits1, huff_bits2, huff_bits3,
+    huff_bits4, huff_bits5, huff_bits6, huff_bits7, huff_bits8, huff_bits9,
+    huff_bits10, huff_bits11, huff_bits12, huff_bits13, huff_bits14,
+    huff_bits15, huff_bits16, huff_bits17, huff_bits18, huff_bits19,
+    huff_bits20, huff_bits21, huff_bits22, huff_bits23, huff_bits24,
+    huff_bits25, huff_bits26, huff_bits27, huff_bits28, huff_bits29,
+    huff_bits30, huff_bits31 };
diff --git a/converter/ppm/ppmtompeg/iframe.c b/converter/ppm/ppmtompeg/iframe.c
index 66f5ea3b..2bc50196 100644
--- a/converter/ppm/ppmtompeg/iframe.c
+++ b/converter/ppm/ppmtompeg/iframe.c
@@ -239,7 +239,7 @@ void
 SetBlocksPerSlice(void) {
 
     int     totalBlocks;
-    
+
     totalBlocks = (Fsize_y>>4)*(Fsize_x>>4);
 
     if ( slicesPerFrame > totalBlocks ) {
@@ -296,7 +296,7 @@ CalcDistortion(MpegFrame * const current,
     Block decblk;
     FlatBlock fblk;
     int datarate = 0;
-  
+
     for (qscale = 1; qscale < 32; qscale ++) {
         distort = 0;
         datarate = 0;
@@ -361,7 +361,7 @@ CalcDistortion(MpegFrame * const current,
  *
  *===========================================================================*/
 void
-GenIFrame(BitBucket * const bb, 
+GenIFrame(BitBucket * const bb,
           MpegFrame * const current) {
 
     int x, y;
@@ -391,25 +391,25 @@ GenIFrame(BitBucket * const bb,
             lastIFrame = current->id;
         } else {
             /* ASSUMES 30 FRAMES PER SECOND */
-    
+
             if (! realQuiet) {
                 fprintf(stdout, "I-to-I (frames %5d to %5d) bitrate:  %8d\n",
                         lastIFrame, current->id-1,
                         ((bb->cumulativeBits-lastNumBits)*30)/
                         (current->id-lastIFrame));
             }
-    
+
             fprintf(bitRateFile, "I-to-I (frames %5d to %5d) bitrate:  %8d\n",
                     lastIFrame, current->id-1,
                     ((bb->cumulativeBits-lastNumBits)*30)/
                     (current->id-lastIFrame));
-            lastNumBits = bb->cumulativeBits;       
+            lastNumBits = bb->cumulativeBits;
             lastIFrame = current->id;
         }
     }
-    
+
     startTime = time_elapsed();
-    
+
     Frame_AllocBlocks(current);
     BlockifyFrame(current);
 
@@ -435,13 +435,13 @@ GenIFrame(BitBucket * const bb,
         }
     }
     Mhead_GenSliceHeader(bb, 1, QScale, NULL, 0);
-    
+
     if ( referenceFrame == DECODED_FRAME ) {
         Frame_AllocDecoded(current, TRUE);
     } else if ( printSNR ) {
         Frame_AllocDecoded(current, FALSE);
     }
-    
+
     y_dc_pred = cr_dc_pred = cb_dc_pred = 128;
     totalBits = bb->cumulativeBits;
     mbAddress = 0;
@@ -449,24 +449,24 @@ GenIFrame(BitBucket * const bb,
     /* DCT the macroblocks */
     for (y = 0;  y < (Fsize_y >> 3);  y += 2) {
         for (x = 0;  x < (Fsize_x >> 3);  x += 2) {
-            if (collect_quant && (collect_quant_detailed & 1)) 
+            if (collect_quant && (collect_quant_detailed & 1))
                 fprintf(collect_quant_fp, "l\n");
             if (DoLaplace) {LaplaceCnum = 0;}
             mp_fwd_dct_block2(current->y_blocks[y][x], dct[y][x]);
             mp_fwd_dct_block2(current->y_blocks[y][x+1], dct[y][x+1]);
             mp_fwd_dct_block2(current->y_blocks[y+1][x], dct[y+1][x]);
             mp_fwd_dct_block2(current->y_blocks[y+1][x+1], dct[y+1][x+1]);
-            if (collect_quant && (collect_quant_detailed & 1)) 
+            if (collect_quant && (collect_quant_detailed & 1))
                 fprintf(collect_quant_fp, "c\n");
             if (DoLaplace) {LaplaceCnum = 1;}
-            mp_fwd_dct_block2(current->cb_blocks[y>>1][x>>1], 
+            mp_fwd_dct_block2(current->cb_blocks[y>>1][x>>1],
                               dctb[y>>1][x>>1]);
             if (DoLaplace) {LaplaceCnum = 2;}
-            mp_fwd_dct_block2(current->cr_blocks[y>>1][x>>1], 
+            mp_fwd_dct_block2(current->cr_blocks[y>>1][x>>1],
                               dctr[y>>1][x>>1]);
         }
     }
-    
+
     if (DoLaplace)
         CalcLambdas();
 
@@ -474,13 +474,13 @@ GenIFrame(BitBucket * const bb,
         for (x = 0;  x < (Fsize_x >> 3);  x += 2) {
             /* Check for Qscale change */
             if (specificsOn) {
-                newQScale = 
+                newQScale =
                     SpecLookup(current->id, 2, mbAddress, &info, QScale);
                 if (newQScale != -1) {
                     QScale = newQScale;
                 }
             }
-    
+
             /*  Determine if new Qscale needed for Rate Control purposes  */
             if (bitstreamMode == FIXED_RATE) {
                 rc_blockStart = bb->cumulativeBits;
@@ -493,20 +493,20 @@ GenIFrame(BitBucket * const bb,
                     QScale = newQScale;
                 }
             }
-    
+
             if ( (mbAddress % blocksPerSlice == 0) && (mbAddress != 0) ) {
                 /* create a new slice */
                 if (specificsOn) {
                     /* Make sure no slice Qscale change */
                     newQScale = SpecLookup(current->id, 1,
-                                           mbAddress/blocksPerSlice, &info, 
+                                           mbAddress/blocksPerSlice, &info,
                                            QScale);
                     if (newQScale != -1) QScale = newQScale;
                 }
                 Mhead_GenSliceEnder(bb);
                 Mhead_GenSliceHeader(bb, 1+(y>>1), QScale, NULL, 0);
                 y_dc_pred = cr_dc_pred = cb_dc_pred = 128;
-      
+
                 GEN_I_BLOCK(I_FRAME, current, bb, 1+(x>>1), QScale);
             } else {
                 GEN_I_BLOCK(I_FRAME, current, bb, 1, QScale);
@@ -515,23 +515,23 @@ GenIFrame(BitBucket * const bb,
             if (WriteDistortionNumbers) {
                 CalcDistortion(current, y, x);
             }
-    
+
             if ( decodeRefFrames ) {
                 /* now, reverse the DCT transform */
                 LaplaceCnum = 0;
                 for ( index = 0; index < 6; index++ ) {
                     if (!DoLaplace) {
-                        Mpost_UnQuantZigBlock(fb[index], dec[index], QScale, 
+                        Mpost_UnQuantZigBlock(fb[index], dec[index], QScale,
                                               TRUE);
                     } else {
                         if (index == 4) {LaplaceCnum = 1;}
                         if (index == 5) {LaplaceCnum = 2;}
-                        Mpost_UnQuantZigBlockLaplace(fb[index], dec[index], 
+                        Mpost_UnQuantZigBlockLaplace(fb[index], dec[index],
                                                      QScale, TRUE);
                     }
-                    mpeg_jrevdct((int16 *)dec[index]);      
+                    mpeg_jrevdct((int16 *)dec[index]);
                 }
-      
+
                 /* now, unblockify */
                 BlockToData(current->decoded_y, dec[0], y, x);
                 BlockToData(current->decoded_y, dec[1], y, x+1);
@@ -540,7 +540,7 @@ GenIFrame(BitBucket * const bb,
                 BlockToData(current->decoded_cb, dec[4], y>>1, x>>1);
                 BlockToData(current->decoded_cr, dec[5], y>>1, x>>1);
             }
-    
+
             numBlocks++;
             mbAddress++;
             /*   Rate Control */
@@ -551,43 +551,43 @@ GenIFrame(BitBucket * const bb,
             }
         }
     }
-    
+
     if ( printSNR ) {
         BlockComputeSNR(current,snr,psnr);
         totalSNR += snr[0];
         totalPSNR += psnr[0];
     }
-    
+
     numBits += (bb->cumulativeBits-totalBits);
-    
+
     DBG_PRINT(("End of frame\n"));
-    
+
     Mhead_GenSliceEnder(bb);
     /*   Rate Control  */
     if (bitstreamMode == FIXED_RATE) {
         updateRateControl(TYPE_IFRAME);
     }
-    
+
     endTime = time_elapsed();
     totalTime += (endTime-startTime);
-    
+
     numFrameBits += (bb->cumulativeBits-totalFrameBits);
-    
+
     if ( showBitRatePerFrame ) {
         /* ASSUMES 30 FRAMES PER SECOND */
         fprintf(bitRateFile, "%5d\t%8d\n", current->id,
                 30*(bb->cumulativeBits-totalFrameBits));
     }
-    
+
     if ( frameSummary && !realQuiet ) {
-        
+
         /* ASSUMES 30 FRAMES PER SECOND */
-        fprintf(stdout, 
-                "FRAME %d (I):  %ld seconds  (%d bits/s output)\n", 
+        fprintf(stdout,
+                "FRAME %d (I):  %ld seconds  (%d bits/s output)\n",
                 current->id, (long)((endTime-startTime)/TIME_RATE),
                 30*(bb->cumulativeBits-totalFrameBits));
         if ( printSNR ) {
-            fprintf(stdout, 
+            fprintf(stdout,
                     "FRAME %d:  SNR:  %.1f\t%.1f\t%.1f\t"
                     "PSNR:  %.1f\t%.1f\t%.1f\n",
                         current->id, snr[0], snr[1], snr[2],
@@ -628,8 +628,8 @@ IFrameTotalTime(void) {
 
 
 void
-ShowIFrameSummary(unsigned int const inputFrameBits, 
-                  unsigned int const totalBits, 
+ShowIFrameSummary(unsigned int const inputFrameBits,
+                  unsigned int const totalBits,
                   FILE *       const fpointer) {
 /*----------------------------------------------------------------------------
    Print out statistics on all I frames.
@@ -697,12 +697,12 @@ EncodeYDC(int32       const dc_term,
 
     ydiff = (dc_term - (*pred_term));
     if (ydiff > 255) {
-#ifdef BLEAH 
+#ifdef BLEAH
       fprintf(stdout, "TRUNCATED\n");
 #endif
     ydiff = 255;
     } else if (ydiff < -255) {
-#ifdef BLEAH 
+#ifdef BLEAH
       fprintf(stdout, "TRUNCATED\n");
 #endif
     ydiff = -255;
@@ -753,12 +753,12 @@ EncodeCDC(int32       const dc_term,
     cdiff = (dc_term - (*pred_term));
     if (cdiff > 255) {
 #ifdef BLEAH
-        fprintf(stdout, "TRUNCATED\n"); 
+        fprintf(stdout, "TRUNCATED\n");
 #endif
         cdiff = 255;
     } else if (cdiff < -255) {
 #ifdef BLEAH
-        fprintf(stdout, "TRUNCATED\n"); 
+        fprintf(stdout, "TRUNCATED\n");
 #endif
         cdiff = -255;
     }
@@ -789,21 +789,21 @@ BlockComputeSNR(MpegFrame * const current,
     int32 varDiff[3];
     double    ratio[3];
     double    total[3];
-    uint8 **origY=current->orig_y, **origCr=current->orig_cr, 
+    uint8 **origY=current->orig_y, **origCr=current->orig_cr,
         **origCb=current->orig_cb;
-    uint8 **newY=current->decoded_y, **newCr=current->decoded_cr, 
+    uint8 **newY=current->decoded_y, **newCr=current->decoded_cr,
         **newCb=current->decoded_cb;
     static int32       **SignalY,  **NoiseY;
     static int32       **SignalCb, **NoiseCb;
     static int32       **SignalCr, **NoiseCr;
     static short   ySize[3], xSize[3];
     static boolean needs_init=TRUE;
-  
+
     /* Init */
     if (needs_init) {
         int ysz = (Fsize_y>>3) * sizeof(int32 *);
         int xsz = (Fsize_x>>3);
-    
+
         needs_init = FALSE;
         for (y=0; y<3; y++) {
             varDiff[y] = ratio[y] = total[y] = 0.0;
@@ -817,7 +817,7 @@ BlockComputeSNR(MpegFrame * const current,
         NoiseCb  = (int32 **) malloc(ysz);
         SignalCr = (int32 **) malloc(ysz);
         NoiseCr  = (int32 **) malloc(ysz);
-        if (SignalY == NULL || NoiseY == NULL || SignalCr == NULL || 
+        if (SignalY == NULL || NoiseY == NULL || SignalCr == NULL ||
             NoiseCb == NULL || SignalCb == NULL || NoiseCr == NULL) {
             fprintf(stderr, "Out of memory in BlockComputeSNR\n");
             exit(-1);
@@ -840,7 +840,7 @@ BlockComputeSNR(MpegFrame * const current,
             memset((char *) &SignalCr[y][0], 0, (xSize[0]>>3) * 4);
         }
     }
-  
+
     /* find all the signal and noise */
     for (y = 0; y < ySize[0]; y++) {
         for (x = 0; x < xSize[0]; x++) {
@@ -863,7 +863,7 @@ BlockComputeSNR(MpegFrame * const current,
             tempInt = origCr[y][x];
             SignalCr[y>>3][x>>3] += tempInt*tempInt;
         }}
-  
+
     /* Now sum up that noise */
     for(y=0; y<Fsize_y>>4; y++){
         for(x=0; x<Fsize_x>>4; x++){
@@ -874,7 +874,7 @@ BlockComputeSNR(MpegFrame * const current,
         }
         if (printMSE) puts("");
     }
-  
+
     /* Now look at those ratios! */
     for(y=0; y<Fsize_y>>4; y++){
         for(x=0; x<Fsize_x>>4; x++){
@@ -882,7 +882,7 @@ BlockComputeSNR(MpegFrame * const current,
             ratio[1] += (double)SignalCb[y][x]/(double)varDiff[1];
             ratio[2] += (double)SignalCr[y][x]/(double)varDiff[2];
         }}
-  
+
     for (x=0; x<3; x++) {
         snr[x] = 10.0 * log10(ratio[x]);
         psnr[x] = 20.0 * log10(255.0/sqrt((double)varDiff[x]/
@@ -983,3 +983,6 @@ int32 time_elapsed(void) {
     return timeBuffer.tms_utime + timeBuffer.tms_stime;
 #endif
 }
+
+
+
diff --git a/converter/ppm/ppmtompeg/input.c b/converter/ppm/ppmtompeg/input.c
index 4266d39b..83aa387c 100644
--- a/converter/ppm/ppmtompeg/input.c
+++ b/converter/ppm/ppmtompeg/input.c
@@ -1,16 +1,16 @@
 /*===========================================================================*
- * input.c              
- *                      
+ * input.c
+ *
  *  Stuff for getting the raw frame input for the program
- *                                    
+ *
  *===========================================================================*/
 
 /* COPYRIGHT INFORMATION IS AT THE END OF THIS FILE */
 
 #define _XOPEN_SOURCE 1
-    /* This makes sure popen() is in stdio.h.  In GNU libc 2.1.3, 
+    /* This makes sure popen() is in stdio.h.  In GNU libc 2.1.3,
      _POSIX_C_SOURCE = 2 is sufficient, but on AIX 4.3, the higher level
-     _XOPEN_SOURCE is required.  2000.09.09 
+     _XOPEN_SOURCE is required.  2000.09.09
     */
 
 
@@ -31,7 +31,7 @@
 #include "jpeg.h"
 #include "input.h"
 
-extern boolean realQuiet;	/* TRUE = no messages to stdout */
+extern boolean realQuiet;       /* TRUE = no messages to stdout */
 
 struct InputFileEntry {
     char    left[256];
@@ -57,11 +57,11 @@ GetNthInputFileName(struct inputSource * const inputSourceP,
 /*----------------------------------------------------------------------------
    Return the file name of the Nth input file.
 -----------------------------------------------------------------------------*/
-    static int	lastN = 0, lastMapN = 0, lastSoFar = 0;
-    int	    mapN;
+    static int  lastN = 0, lastMapN = 0, lastSoFar = 0;
+    int     mapN;
     int     index;
-    int	    soFar;
-    int	    numPadding;
+    int     soFar;
+    int     numPadding;
     struct InputFileEntry * mapNEntryP;
 
     assert(!inputSourceP->stdinUsed);
@@ -84,7 +84,7 @@ GetNthInputFileName(struct inputSource * const inputSourceP,
     }
 
     mapN = index;
-    
+
     mapNEntryP = inputSourceP->inputFileEntries[mapN];
 
     index = mapNEntryP->startID + mapNEntryP->skip*(n - soFar);
@@ -93,7 +93,7 @@ GetNthInputFileName(struct inputSource * const inputSourceP,
 
     if (numPadding != -1) {
         char    numBuffer[33];
-        int	    loop;
+        int         loop;
 
         sprintf(numBuffer, "%32d", index);
         for (loop = 32-numPadding; loop < 32; ++loop) {
@@ -159,26 +159,26 @@ ReadNthFrame(struct inputSource * const inputSourceP,
 void
 JM2JPEG(struct inputSource * const inputSourceP) {
     char full_path[1024];
-    char inter_file[1024]; 
+    char inter_file[1024];
     int ci;
-    
+
     for(ci = 0; ci < inputSourceP->numInputFileEntries; ci++) {
         inter_file[0] = '\0';
         full_path[0] = '\0';
         strcpy(full_path, currentPath);
-    
+
         if (!inputSource.stdinUsed) {
             strcat(full_path, "/");
             strcat(full_path, inputSourceP->inputFileEntries[ci]->left);
             strcpy(inter_file,full_path);
-    
+
             if (!realQuiet)
                 fprintf(stdout, "Extracting JPEG's in the JMOVIE from %s\n",
                         full_path);
-    
+
             JMovie2JPEG(full_path,
                         inter_file,
-                        inputSourceP->inputFileEntries[ci]->startID, 
+                        inputSourceP->inputFileEntries[ci]->startID,
                         inputSourceP->inputFileEntries[ci]->endID);
         } else
             pm_error("ERROR: Cannot use JMovie format on Standard Input");
@@ -200,7 +200,7 @@ SkipSpacesTabs(const char * const start) {
 
 
 static void
-processGlob(const char *            const input, 
+processGlob(const char *            const input,
             struct InputFileEntry * const inputFileEntryP) {
 
     const char *globPtr;
@@ -208,10 +208,10 @@ processGlob(const char *            const input,
     char    left[256], right[256];
     char    leftNumText[256], rightNumText[256];
     char    skipNumText[256];
-    int	    leftNum, rightNum;
-    int	    skipNum;
+    int     leftNum, rightNum;
+    int     skipNum;
     boolean padding;
-    int	    numPadding = 0;
+    int     numPadding = 0;
 
     inputFileEntryP->glob = TRUE;
     inputFileEntryP->repeat = FALSE;
@@ -229,13 +229,13 @@ processGlob(const char *            const input,
     *charPtr = '\0';
 
     if (*globPtr == '\0') {
-        fprintf(stderr, 
+        fprintf(stderr,
                 "WARNING: expanding non-star regular expression\n");
         inputFileEntryP->repeat = TRUE;
         globPtr = input;
         charPtr = left;
         /* recopy left of whitespace */
-        while ( (*globPtr != '\0') && (*globPtr != '*') && 
+        while ( (*globPtr != '\0') && (*globPtr != '*') &&
                 (*globPtr != ' ')  && (*globPtr != '\t')) {
             *charPtr = *globPtr;
             charPtr++;
@@ -256,11 +256,11 @@ processGlob(const char *            const input,
         }
         *charPtr = '\0';
     }
-      
+
     globPtr = SkipSpacesTabs(globPtr);
 
     if ( *globPtr != '[' ) {
-        fprintf(stderr, 
+        fprintf(stderr,
                 "ERROR:  "
                 "Invalid input file expansion expression (no '[')\n");
         exit(1);
@@ -277,7 +277,7 @@ processGlob(const char *            const input,
     *charPtr = '\0';
 
     if ( *globPtr != '-' ) {
-        fprintf(stderr, 
+        fprintf(stderr,
                 "ERROR:  "
                 "Invalid input file expansion expression (no '-')\n");
         exit(1);
@@ -293,7 +293,7 @@ processGlob(const char *            const input,
     }
     *charPtr = '\0';
     if ( atoi(rightNumText) < atoi(leftNumText) ) {
-        fprintf(stderr, 
+        fprintf(stderr,
                 "ERROR:  "
                 "Beginning of input range is higher than end.\n");
         exit(1);
@@ -302,7 +302,7 @@ processGlob(const char *            const input,
 
     if ( *globPtr != ']' ) {
         if ( *globPtr != '+' ) {
-            fprintf(stderr, 
+            fprintf(stderr,
                     "ERROR:  "
                     "Invalid input file expansion expression "
                     "(no ']')\n");
@@ -320,7 +320,7 @@ processGlob(const char *            const input,
         *charPtr = '\0';
 
         if ( *globPtr != ']' ) {
-            fprintf(stderr, 
+            fprintf(stderr,
                     "ERROR:  Invalid input file expansion expression "
                     "(no ']')\n");
             exit(1);
@@ -344,7 +344,7 @@ processGlob(const char *            const input,
     inputFileEntryP->startID = leftNum;
     inputFileEntryP->endID = rightNum;
     inputFileEntryP->skip = skipNum;
-    inputFileEntryP->numFiles = 
+    inputFileEntryP->numFiles =
         (rightNum-leftNum+1)/skipNum;
     strcpy(inputFileEntryP->left, left);
     strcpy(inputFileEntryP->right, right);
@@ -357,7 +357,7 @@ processGlob(const char *            const input,
 
 
 
-static void processJmovie(const char *            const input, 
+static void processJmovie(const char *            const input,
                           struct InputFileEntry * const inputFileEntryP) {
     FILE    *jmovie;
     char    full_path[1024];
@@ -365,19 +365,19 @@ static void processJmovie(const char *            const input,
     inputFileEntryP->glob = TRUE;
     full_path[0] = '\0';
     strcpy(full_path, currentPath);
-    
+
     strcat(full_path, "/");
     strcat(full_path, input);
-    jmovie = fopen(input, "rb"); 
-    
+    jmovie = fopen(input, "rb");
+
     if (jmovie == NULL) {
-        perror (input); 
+        perror (input);
         exit (1);
     }
-    
+
     fseek (jmovie, (8*sizeof(char)), 0);
     fseek (jmovie, (2*sizeof(int)), 1);
-    
+
     if (fread(&(inputFileEntryP->numFiles),
               sizeof(int), 1, jmovie) != 1) {
         perror ("Error in reading number of frames in JMOVIE");
@@ -391,11 +391,11 @@ static void processJmovie(const char *            const input,
     inputFileEntryP->endID = (inputFileEntryP->numFiles-1);
     inputFileEntryP->skip = 1;
     if (! realQuiet) {
-        fprintf (stdout, 
-                 "Encoding all %d frames from JMOVIE.\n", 
+        fprintf (stdout,
+                 "Encoding all %d frames from JMOVIE.\n",
                  inputFileEntryP->endID);
     }
-} 
+}
 
 
 
@@ -415,6 +415,7 @@ processSimpleFileName(const char *            const input,
 }
 
 
+
 #define INPUT_ENTRY_BLOCK_SIZE   128
 
 void
@@ -428,19 +429,19 @@ AddInputFiles(struct inputSource * const inputSourceP,
     if (currentIndex >= inputSourceP->ifArraySize) {
         /* Get more space */
         inputSourceP->ifArraySize += INPUT_ENTRY_BLOCK_SIZE;
-        REALLOCARRAY_NOFAIL(inputSourceP->inputFileEntries, 
+        REALLOCARRAY_NOFAIL(inputSourceP->inputFileEntries,
                             inputSourceP->ifArraySize);
     }
     MALLOCVAR_NOFAIL(inputSourceP->inputFileEntries[currentIndex]);
     currentEntryP = inputSourceP->inputFileEntries[currentIndex];
 
-    if (input[strlen(input)-1] == ']') 
+    if (input[strlen(input)-1] == ']')
         processGlob(input, currentEntryP);
     else {
         strcpy(currentEntryP->left, input);
-        if (baseFormat == JMOVIE_FILE_TYPE) 
+        if (baseFormat == JMOVIE_FILE_TYPE)
             processJmovie(input, currentEntryP);
-        else 
+        else
             processSimpleFileName(input, currentEntryP);
     }
     inputSourceP->numInputFiles += currentEntryP->numFiles;
@@ -472,7 +473,7 @@ CreateInputSource(struct inputSource ** const inputSourcePP) {
     inputSourceP->ifArraySize = 1;
     inputSourceP->numInputFiles = 0;
     MALLOCARRAY_NOFAIL(inputSourceP->inputFileEntries, 1);
-    
+
     *inputSourcePP = inputSourceP;
 }
 
diff --git a/converter/ppm/ppmtompeg/jpeg.c b/converter/ppm/ppmtompeg/jpeg.c
index 4540f6f0..6680404b 100644
--- a/converter/ppm/ppmtompeg/jpeg.c
+++ b/converter/ppm/ppmtompeg/jpeg.c
@@ -339,7 +339,6 @@ JMovie2JPEG(const char * const infilename,
 
 
 
-
 /*===========================================================================*
  *
  * ReadJPEG  contributed by James Arthur Boucher of Boston University's
diff --git a/converter/ppm/ppmtompeg/jrevdct.c b/converter/ppm/ppmtompeg/jrevdct.c
index dd1f9fff..f46051bc 100644
--- a/converter/ppm/ppmtompeg/jrevdct.c
+++ b/converter/ppm/ppmtompeg/jrevdct.c
@@ -16,7 +16,7 @@
  * The advantage of this method is that no data path contains more than one
  * multiplication; this allows a very simple and accurate implementation in
  * scaled fixed-point arithmetic, with a minimal number of shifts.
- * 
+ *
  * I've made lots of modifications to attempt to take advantage of the
  * sparse nature of the DCT matrices we're getting.  Although the logic
  * is cumbersome, it's straightforward and the resulting code is much
@@ -85,10 +85,10 @@
 #ifdef EIGHT_BIT_SAMPLES
 #define PASS1_BITS  2
 #else
-#define PASS1_BITS  1		/* lose a little precision to avoid overflow */
+#define PASS1_BITS  1           /* lose a little precision to avoid overflow */
 #endif
 
-#define ONE	((int32) 1)
+#define ONE     ((int32) 1)
 
 #define CONST_SCALE (ONE << CONST_BITS)
 
@@ -99,7 +99,7 @@
  */
 
 /* Actually FIX is no longer used, we precomputed them all */
-#define FIX(x)	((int32) ((x) * CONST_SCALE + 0.5)) 
+#define FIX(x)  ((int32) ((x) * CONST_SCALE + 0.5))
 
 /* Descale and correctly round an int32 value that's scaled by N bits.
  * We assume RIGHT_SHIFT rounds towards minus infinity, so adding
@@ -120,22 +120,22 @@
  */
 
 #ifdef EIGHT_BIT_SAMPLES
-#ifdef SHORTxSHORT_32		/* may work if 'int' is 32 bits */
+#ifdef SHORTxSHORT_32           /* may work if 'int' is 32 bits */
 #define MULTIPLY(var,const)  (((INT16) (var)) * ((INT16) (const)))
 #endif
-#ifdef SHORTxLCONST_32		/* known to work with Microsoft C 6.0 */
+#ifdef SHORTxLCONST_32          /* known to work with Microsoft C 6.0 */
 #define MULTIPLY(var,const)  (((INT16) (var)) * ((int32) (const)))
 #endif
 #endif
 
-#ifndef MULTIPLY		/* default definition */
+#ifndef MULTIPLY                /* default definition */
 #define MULTIPLY(var,const)  ((var) * (const))
 #endif
 
 
-/* 
+/*
   Unlike our decoder where we approximate the FIXes, we need to use exact
-ones here or successive P-frames will drift too much with Reference frame coding 
+ones here or successive P-frames will drift too much with Reference frame coding
 */
 #define FIX_0_211164243 1730
 #define FIX_0_275899380 2260
@@ -179,6 +179,8 @@ mpeg_jrevdct(data)
   else mpeg_jrevdct_quick(data);
 }
 
+
+
 /*
  * Perform the inverse DCT on one block of coefficients.
  */
@@ -194,7 +196,7 @@ mpeg_jrevdct_quick(data)
   register DCTELEM *dataptr;
   int rowctr;
   SHIFT_TEMPS
-   
+
   /* Pass 1: process rows. */
   /* Note results are scaled up by sqrt(8) compared to a true IDCT; */
   /* furthermore, we scale the results by 2**PASS1_BITS. */
@@ -217,17 +219,17 @@ mpeg_jrevdct_quick(data)
     if ((d1 == 0) && (idataptr[1] | idataptr[2] | idataptr[3]) == 0) {
       /* AC terms all zero */
       if (d0) {
-	  /* Compute a 32 bit value to assign. */
-	  DCTELEM dcval = (DCTELEM) (d0 << PASS1_BITS);
-	  register int v = (dcval & 0xffff) | ((dcval << 16) & 0xffff0000);
-	  
-	  idataptr[0] = v;
-	  idataptr[1] = v;
-	  idataptr[2] = v;
-	  idataptr[3] = v;
+          /* Compute a 32 bit value to assign. */
+          DCTELEM dcval = (DCTELEM) (d0 << PASS1_BITS);
+          register int v = (dcval & 0xffff) | ((dcval << 16) & 0xffff0000);
+
+          idataptr[0] = v;
+          idataptr[1] = v;
+          idataptr[2] = v;
+          idataptr[3] = v;
       }
-      
-      dataptr += DCTSIZE;	/* advance pointer to next row */
+
+      dataptr += DCTSIZE;       /* advance pointer to next row */
       continue;
     }
     d2 = dataptr[2];
@@ -241,180 +243,180 @@ mpeg_jrevdct_quick(data)
     /* The rotator is sqrt(2)*c(-6). */
 {
     if (d6) {
-	if (d4) {
-	    if (d2) {
-		if (d0) {
-		    /* d0 != 0, d2 != 0, d4 != 0, d6 != 0 */
-		    z1 = MULTIPLY(d2 + d6, FIX_0_541196100);
-		    tmp2 = z1 + MULTIPLY(-d6, FIX_1_847759065);
-		    tmp3 = z1 + MULTIPLY(d2, FIX_0_765366865);
-
-		    tmp0 = (d0 + d4) << CONST_BITS;
-		    tmp1 = (d0 - d4) << CONST_BITS;
-
-		    tmp10 = tmp0 + tmp3;
-		    tmp13 = tmp0 - tmp3;
-		    tmp11 = tmp1 + tmp2;
-		    tmp12 = tmp1 - tmp2;
-		} else {
-		    /* d0 == 0, d2 != 0, d4 != 0, d6 != 0 */
-		    z1 = MULTIPLY(d2 + d6, FIX_0_541196100);
-		    tmp2 = z1 + MULTIPLY(-d6, FIX_1_847759065);
-		    tmp3 = z1 + MULTIPLY(d2, FIX_0_765366865);
-
-		    tmp0 = d4 << CONST_BITS;
-
-		    tmp10 = tmp0 + tmp3;
-		    tmp13 = tmp0 - tmp3;
-		    tmp11 = tmp2 - tmp0;
-		    tmp12 = -(tmp0 + tmp2);
-		}
-	    } else {
-		if (d0) {
-		    /* d0 != 0, d2 == 0, d4 != 0, d6 != 0 */
-		    tmp2 = MULTIPLY(-d6, FIX_1_306562965);
-		    tmp3 = MULTIPLY(d6, FIX_0_541196100);
-
-		    tmp0 = (d0 + d4) << CONST_BITS;
-		    tmp1 = (d0 - d4) << CONST_BITS;
-
-		    tmp10 = tmp0 + tmp3;
-		    tmp13 = tmp0 - tmp3;
-		    tmp11 = tmp1 + tmp2;
-		    tmp12 = tmp1 - tmp2;
-		} else {
-		    /* d0 == 0, d2 == 0, d4 != 0, d6 != 0 */
-		    tmp2 = MULTIPLY(-d6, FIX_1_306562965);
-		    tmp3 = MULTIPLY(d6, FIX_0_541196100);
-
-		    tmp0 = d4 << CONST_BITS;
-
-		    tmp10 = tmp0 + tmp3;
-		    tmp13 = tmp0 - tmp3;
-		    tmp11 = tmp2 - tmp0;
-		    tmp12 = -(tmp0 + tmp2);
-		}
-	    }
-	} else {
-	    if (d2) {
-		if (d0) {
-		    /* d0 != 0, d2 != 0, d4 == 0, d6 != 0 */
-		    z1 = MULTIPLY(d2 + d6, FIX_0_541196100);
-		    tmp2 = z1 + MULTIPLY(-d6, FIX_1_847759065);
-		    tmp3 = z1 + MULTIPLY(d2, FIX_0_765366865);
-
-		    tmp0 = d0 << CONST_BITS;
-
-		    tmp10 = tmp0 + tmp3;
-		    tmp13 = tmp0 - tmp3;
-		    tmp11 = tmp0 + tmp2;
-		    tmp12 = tmp0 - tmp2;
-		} else {
-		    /* d0 == 0, d2 != 0, d4 == 0, d6 != 0 */
-		    z1 = MULTIPLY(d2 + d6, FIX_0_541196100);
-		    tmp2 = z1 + MULTIPLY(-d6, FIX_1_847759065);
-		    tmp3 = z1 + MULTIPLY(d2, FIX_0_765366865);
-
-		    tmp10 = tmp3;
-		    tmp13 = -tmp3;
-		    tmp11 = tmp2;
-		    tmp12 = -tmp2;
-		}
-	    } else {
-		if (d0) {
-		    /* d0 != 0, d2 == 0, d4 == 0, d6 != 0 */
-		    tmp2 = MULTIPLY(-d6, FIX_1_306562965);
-		    tmp3 = MULTIPLY(d6, FIX_0_541196100);
-
-		    tmp0 = d0 << CONST_BITS;
-
-		    tmp10 = tmp0 + tmp3;
-		    tmp13 = tmp0 - tmp3;
-		    tmp11 = tmp0 + tmp2;
-		    tmp12 = tmp0 - tmp2;
-		} else {
-		    /* d0 == 0, d2 == 0, d4 == 0, d6 != 0 */
-		    tmp2 = MULTIPLY(-d6, FIX_1_306562965);
-		    tmp3 = MULTIPLY(d6, FIX_0_541196100);
-
-		    tmp10 = tmp3;
-		    tmp13 = -tmp3;
-		    tmp11 = tmp2;
-		    tmp12 = -tmp2;
-		}
-	    }
-	}
+        if (d4) {
+            if (d2) {
+                if (d0) {
+                    /* d0 != 0, d2 != 0, d4 != 0, d6 != 0 */
+                    z1 = MULTIPLY(d2 + d6, FIX_0_541196100);
+                    tmp2 = z1 + MULTIPLY(-d6, FIX_1_847759065);
+                    tmp3 = z1 + MULTIPLY(d2, FIX_0_765366865);
+
+                    tmp0 = (d0 + d4) << CONST_BITS;
+                    tmp1 = (d0 - d4) << CONST_BITS;
+
+                    tmp10 = tmp0 + tmp3;
+                    tmp13 = tmp0 - tmp3;
+                    tmp11 = tmp1 + tmp2;
+                    tmp12 = tmp1 - tmp2;
+                } else {
+                    /* d0 == 0, d2 != 0, d4 != 0, d6 != 0 */
+                    z1 = MULTIPLY(d2 + d6, FIX_0_541196100);
+                    tmp2 = z1 + MULTIPLY(-d6, FIX_1_847759065);
+                    tmp3 = z1 + MULTIPLY(d2, FIX_0_765366865);
+
+                    tmp0 = d4 << CONST_BITS;
+
+                    tmp10 = tmp0 + tmp3;
+                    tmp13 = tmp0 - tmp3;
+                    tmp11 = tmp2 - tmp0;
+                    tmp12 = -(tmp0 + tmp2);
+                }
+            } else {
+                if (d0) {
+                    /* d0 != 0, d2 == 0, d4 != 0, d6 != 0 */
+                    tmp2 = MULTIPLY(-d6, FIX_1_306562965);
+                    tmp3 = MULTIPLY(d6, FIX_0_541196100);
+
+                    tmp0 = (d0 + d4) << CONST_BITS;
+                    tmp1 = (d0 - d4) << CONST_BITS;
+
+                    tmp10 = tmp0 + tmp3;
+                    tmp13 = tmp0 - tmp3;
+                    tmp11 = tmp1 + tmp2;
+                    tmp12 = tmp1 - tmp2;
+                } else {
+                    /* d0 == 0, d2 == 0, d4 != 0, d6 != 0 */
+                    tmp2 = MULTIPLY(-d6, FIX_1_306562965);
+                    tmp3 = MULTIPLY(d6, FIX_0_541196100);
+
+                    tmp0 = d4 << CONST_BITS;
+
+                    tmp10 = tmp0 + tmp3;
+                    tmp13 = tmp0 - tmp3;
+                    tmp11 = tmp2 - tmp0;
+                    tmp12 = -(tmp0 + tmp2);
+                }
+            }
+        } else {
+            if (d2) {
+                if (d0) {
+                    /* d0 != 0, d2 != 0, d4 == 0, d6 != 0 */
+                    z1 = MULTIPLY(d2 + d6, FIX_0_541196100);
+                    tmp2 = z1 + MULTIPLY(-d6, FIX_1_847759065);
+                    tmp3 = z1 + MULTIPLY(d2, FIX_0_765366865);
+
+                    tmp0 = d0 << CONST_BITS;
+
+                    tmp10 = tmp0 + tmp3;
+                    tmp13 = tmp0 - tmp3;
+                    tmp11 = tmp0 + tmp2;
+                    tmp12 = tmp0 - tmp2;
+                } else {
+                    /* d0 == 0, d2 != 0, d4 == 0, d6 != 0 */
+                    z1 = MULTIPLY(d2 + d6, FIX_0_541196100);
+                    tmp2 = z1 + MULTIPLY(-d6, FIX_1_847759065);
+                    tmp3 = z1 + MULTIPLY(d2, FIX_0_765366865);
+
+                    tmp10 = tmp3;
+                    tmp13 = -tmp3;
+                    tmp11 = tmp2;
+                    tmp12 = -tmp2;
+                }
+            } else {
+                if (d0) {
+                    /* d0 != 0, d2 == 0, d4 == 0, d6 != 0 */
+                    tmp2 = MULTIPLY(-d6, FIX_1_306562965);
+                    tmp3 = MULTIPLY(d6, FIX_0_541196100);
+
+                    tmp0 = d0 << CONST_BITS;
+
+                    tmp10 = tmp0 + tmp3;
+                    tmp13 = tmp0 - tmp3;
+                    tmp11 = tmp0 + tmp2;
+                    tmp12 = tmp0 - tmp2;
+                } else {
+                    /* d0 == 0, d2 == 0, d4 == 0, d6 != 0 */
+                    tmp2 = MULTIPLY(-d6, FIX_1_306562965);
+                    tmp3 = MULTIPLY(d6, FIX_0_541196100);
+
+                    tmp10 = tmp3;
+                    tmp13 = -tmp3;
+                    tmp11 = tmp2;
+                    tmp12 = -tmp2;
+                }
+            }
+        }
     } else {
-	if (d4) {
-	    if (d2) {
-		if (d0) {
-		    /* d0 != 0, d2 != 0, d4 != 0, d6 == 0 */
-		    tmp2 = MULTIPLY(d2, FIX_0_541196100);
-		    tmp3 = MULTIPLY(d2, FIX_1_306562965);
-
-		    tmp0 = (d0 + d4) << CONST_BITS;
-		    tmp1 = (d0 - d4) << CONST_BITS;
-
-		    tmp10 = tmp0 + tmp3;
-		    tmp13 = tmp0 - tmp3;
-		    tmp11 = tmp1 + tmp2;
-		    tmp12 = tmp1 - tmp2;
-		} else {
-		    /* d0 == 0, d2 != 0, d4 != 0, d6 == 0 */
-		    tmp2 = MULTIPLY(d2, FIX_0_541196100);
-		    tmp3 = MULTIPLY(d2, FIX_1_306562965);
-
-		    tmp0 = d4 << CONST_BITS;
-
-		    tmp10 = tmp0 + tmp3;
-		    tmp13 = tmp0 - tmp3;
-		    tmp11 = tmp2 - tmp0;
-		    tmp12 = -(tmp0 + tmp2);
-		}
-	    } else {
-		if (d0) {
-		    /* d0 != 0, d2 == 0, d4 != 0, d6 == 0 */
-		    tmp10 = tmp13 = (d0 + d4) << CONST_BITS;
-		    tmp11 = tmp12 = (d0 - d4) << CONST_BITS;
-		} else {
-		    /* d0 == 0, d2 == 0, d4 != 0, d6 == 0 */
-		    tmp10 = tmp13 = d4 << CONST_BITS;
-		    tmp11 = tmp12 = -tmp10;
-		}
-	    }
-	} else {
-	    if (d2) {
-		if (d0) {
-		    /* d0 != 0, d2 != 0, d4 == 0, d6 == 0 */
-		    tmp2 = MULTIPLY(d2, FIX_0_541196100);
-		    tmp3 = MULTIPLY(d2, FIX_1_306562965);
-
-		    tmp0 = d0 << CONST_BITS;
-
-		    tmp10 = tmp0 + tmp3;
-		    tmp13 = tmp0 - tmp3;
-		    tmp11 = tmp0 + tmp2;
-		    tmp12 = tmp0 - tmp2;
-		} else {
-		    /* d0 == 0, d2 != 0, d4 == 0, d6 == 0 */
-		    tmp2 = MULTIPLY(d2, FIX_0_541196100);
-		    tmp3 = MULTIPLY(d2, FIX_1_306562965);
-
-		    tmp10 = tmp3;
-		    tmp13 = -tmp3;
-		    tmp11 = tmp2;
-		    tmp12 = -tmp2;
-		}
-	    } else {
-		if (d0) {
-		    /* d0 != 0, d2 == 0, d4 == 0, d6 == 0 */
-		    tmp10 = tmp13 = tmp11 = tmp12 = d0 << CONST_BITS;
-		} else {
-		    /* d0 == 0, d2 == 0, d4 == 0, d6 == 0 */
-		    tmp10 = tmp13 = tmp11 = tmp12 = 0;
-		}
-	    }
-	}
+        if (d4) {
+            if (d2) {
+                if (d0) {
+                    /* d0 != 0, d2 != 0, d4 != 0, d6 == 0 */
+                    tmp2 = MULTIPLY(d2, FIX_0_541196100);
+                    tmp3 = MULTIPLY(d2, FIX_1_306562965);
+
+                    tmp0 = (d0 + d4) << CONST_BITS;
+                    tmp1 = (d0 - d4) << CONST_BITS;
+
+                    tmp10 = tmp0 + tmp3;
+                    tmp13 = tmp0 - tmp3;
+                    tmp11 = tmp1 + tmp2;
+                    tmp12 = tmp1 - tmp2;
+                } else {
+                    /* d0 == 0, d2 != 0, d4 != 0, d6 == 0 */
+                    tmp2 = MULTIPLY(d2, FIX_0_541196100);
+                    tmp3 = MULTIPLY(d2, FIX_1_306562965);
+
+                    tmp0 = d4 << CONST_BITS;
+
+                    tmp10 = tmp0 + tmp3;
+                    tmp13 = tmp0 - tmp3;
+                    tmp11 = tmp2 - tmp0;
+                    tmp12 = -(tmp0 + tmp2);
+                }
+            } else {
+                if (d0) {
+                    /* d0 != 0, d2 == 0, d4 != 0, d6 == 0 */
+                    tmp10 = tmp13 = (d0 + d4) << CONST_BITS;
+                    tmp11 = tmp12 = (d0 - d4) << CONST_BITS;
+                } else {
+                    /* d0 == 0, d2 == 0, d4 != 0, d6 == 0 */
+                    tmp10 = tmp13 = d4 << CONST_BITS;
+                    tmp11 = tmp12 = -tmp10;
+                }
+            }
+        } else {
+            if (d2) {
+                if (d0) {
+                    /* d0 != 0, d2 != 0, d4 == 0, d6 == 0 */
+                    tmp2 = MULTIPLY(d2, FIX_0_541196100);
+                    tmp3 = MULTIPLY(d2, FIX_1_306562965);
+
+                    tmp0 = d0 << CONST_BITS;
+
+                    tmp10 = tmp0 + tmp3;
+                    tmp13 = tmp0 - tmp3;
+                    tmp11 = tmp0 + tmp2;
+                    tmp12 = tmp0 - tmp2;
+                } else {
+                    /* d0 == 0, d2 != 0, d4 == 0, d6 == 0 */
+                    tmp2 = MULTIPLY(d2, FIX_0_541196100);
+                    tmp3 = MULTIPLY(d2, FIX_1_306562965);
+
+                    tmp10 = tmp3;
+                    tmp13 = -tmp3;
+                    tmp11 = tmp2;
+                    tmp12 = -tmp2;
+                }
+            } else {
+                if (d0) {
+                    /* d0 != 0, d2 == 0, d4 == 0, d6 == 0 */
+                    tmp10 = tmp13 = tmp11 = tmp12 = d0 << CONST_BITS;
+                } else {
+                    /* d0 == 0, d2 == 0, d4 == 0, d6 == 0 */
+                    tmp10 = tmp13 = tmp11 = tmp12 = 0;
+                }
+            }
+        }
       }
 
     /* Odd part per figure 8; the matrix is unitary and hence its
@@ -422,259 +424,259 @@ mpeg_jrevdct_quick(data)
      */
 
     if (d7) {
-	if (d5) {
-	    if (d3) {
-		if (d1) {
-		    /* d1 != 0, d3 != 0, d5 != 0, d7 != 0 */
-		    z1 = d7 + d1;
-		    z2 = d5 + d3;
-		    z3 = d7 + d3;
-		    z4 = d5 + d1;
-		    z5 = MULTIPLY(z3 + z4, FIX_1_175875602);
-		    
-		    tmp0 = MULTIPLY(d7, FIX_0_298631336); 
-		    tmp1 = MULTIPLY(d5, FIX_2_053119869);
-		    tmp2 = MULTIPLY(d3, FIX_3_072711026);
-		    tmp3 = MULTIPLY(d1, FIX_1_501321110);
-		    z1 = MULTIPLY(-z1, FIX_0_899976223);
-		    z2 = MULTIPLY(-z2, FIX_2_562915447);
-		    z3 = MULTIPLY(-z3, FIX_1_961570560);
-		    z4 = MULTIPLY(-z4, FIX_0_390180644);
-		    
-		    z3 += z5;
-		    z4 += z5;
-		    
-		    tmp0 += z1 + z3;
-		    tmp1 += z2 + z4;
-		    tmp2 += z2 + z3;
-		    tmp3 += z1 + z4;
-		} else {
-		    /* d1 == 0, d3 != 0, d5 != 0, d7 != 0 */
-		    z2 = d5 + d3;
-		    z3 = d7 + d3;
-		    z5 = MULTIPLY(z3 + d5, FIX_1_175875602);
-		    
-		    tmp0 = MULTIPLY(d7, FIX_0_298631336); 
-		    tmp1 = MULTIPLY(d5, FIX_2_053119869);
-		    tmp2 = MULTIPLY(d3, FIX_3_072711026);
-		    z1 = MULTIPLY(-d7, FIX_0_899976223);
-		    z2 = MULTIPLY(-z2, FIX_2_562915447);
-		    z3 = MULTIPLY(-z3, FIX_1_961570560);
-		    z4 = MULTIPLY(-d5, FIX_0_390180644);
-		    
-		    z3 += z5;
-		    z4 += z5;
-		    
-		    tmp0 += z1 + z3;
-		    tmp1 += z2 + z4;
-		    tmp2 += z2 + z3;
-		    tmp3 = z1 + z4;
-		}
-	    } else {
-		if (d1) {
-		    /* d1 != 0, d3 == 0, d5 != 0, d7 != 0 */
-		    z1 = d7 + d1;
-		    z4 = d5 + d1;
-		    z5 = MULTIPLY(d7 + z4, FIX_1_175875602);
-		    
-		    tmp0 = MULTIPLY(d7, FIX_0_298631336); 
-		    tmp1 = MULTIPLY(d5, FIX_2_053119869);
-		    tmp3 = MULTIPLY(d1, FIX_1_501321110);
-		    z1 = MULTIPLY(-z1, FIX_0_899976223);
-		    z2 = MULTIPLY(-d5, FIX_2_562915447);
-		    z3 = MULTIPLY(-d7, FIX_1_961570560);
-		    z4 = MULTIPLY(-z4, FIX_0_390180644);
-		    
-		    z3 += z5;
-		    z4 += z5;
-		    
-		    tmp0 += z1 + z3;
-		    tmp1 += z2 + z4;
-		    tmp2 = z2 + z3;
-		    tmp3 += z1 + z4;
-		} else {
-		    /* d1 == 0, d3 == 0, d5 != 0, d7 != 0 */
-		    tmp0 = MULTIPLY(-d7, FIX_0_601344887); 
-		    z1 = MULTIPLY(-d7, FIX_0_899976223);
-		    z3 = MULTIPLY(-d7, FIX_1_961570560);
-		    tmp1 = MULTIPLY(-d5, FIX_0_509795579);
-		    z2 = MULTIPLY(-d5, FIX_2_562915447);
-		    z4 = MULTIPLY(-d5, FIX_0_390180644);
-		    z5 = MULTIPLY(d5 + d7, FIX_1_175875602);
-		    
-		    z3 += z5;
-		    z4 += z5;
-		    
-		    tmp0 += z3;
-		    tmp1 += z4;
-		    tmp2 = z2 + z3;
-		    tmp3 = z1 + z4;
-		}
-	    }
-	} else {
-	    if (d3) {
-		if (d1) {
-		    /* d1 != 0, d3 != 0, d5 == 0, d7 != 0 */
-		    z1 = d7 + d1;
-		    z3 = d7 + d3;
-		    z5 = MULTIPLY(z3 + d1, FIX_1_175875602);
-		    
-		    tmp0 = MULTIPLY(d7, FIX_0_298631336); 
-		    tmp2 = MULTIPLY(d3, FIX_3_072711026);
-		    tmp3 = MULTIPLY(d1, FIX_1_501321110);
-		    z1 = MULTIPLY(-z1, FIX_0_899976223);
-		    z2 = MULTIPLY(-d3, FIX_2_562915447);
-		    z3 = MULTIPLY(-z3, FIX_1_961570560);
-		    z4 = MULTIPLY(-d1, FIX_0_390180644);
-		    
-		    z3 += z5;
-		    z4 += z5;
-		    
-		    tmp0 += z1 + z3;
-		    tmp1 = z2 + z4;
-		    tmp2 += z2 + z3;
-		    tmp3 += z1 + z4;
-		} else {
-		    /* d1 == 0, d3 != 0, d5 == 0, d7 != 0 */
-		    z3 = d7 + d3;
-		    
-		    tmp0 = MULTIPLY(-d7, FIX_0_601344887); 
-		    z1 = MULTIPLY(-d7, FIX_0_899976223);
-		    tmp2 = MULTIPLY(d3, FIX_0_509795579);
-		    z2 = MULTIPLY(-d3, FIX_2_562915447);
-		    z5 = MULTIPLY(z3, FIX_1_175875602);
-		    z3 = MULTIPLY(-z3, FIX_0_785694958);
-		    
-		    tmp0 += z3;
-		    tmp1 = z2 + z5;
-		    tmp2 += z3;
-		    tmp3 = z1 + z5;
-		}
-	    } else {
-		if (d1) {
-		    /* d1 != 0, d3 == 0, d5 == 0, d7 != 0 */
-		    z1 = d7 + d1;
-		    z5 = MULTIPLY(z1, FIX_1_175875602);
-
-		    z1 = MULTIPLY(z1, FIX_0_275899380);
-		    z3 = MULTIPLY(-d7, FIX_1_961570560);
-		    tmp0 = MULTIPLY(-d7, FIX_1_662939225); 
-		    z4 = MULTIPLY(-d1, FIX_0_390180644);
-		    tmp3 = MULTIPLY(d1, FIX_1_111140466);
-
-		    tmp0 += z1;
-		    tmp1 = z4 + z5;
-		    tmp2 = z3 + z5;
-		    tmp3 += z1;
-		} else {
-		    /* d1 == 0, d3 == 0, d5 == 0, d7 != 0 */
-		    tmp0 = MULTIPLY(-d7, FIX_1_387039845);
-		    tmp1 = MULTIPLY(d7, FIX_1_175875602);
-		    tmp2 = MULTIPLY(-d7, FIX_0_785694958);
-		    tmp3 = MULTIPLY(d7, FIX_0_275899380);
-		}
-	    }
-	}
+        if (d5) {
+            if (d3) {
+                if (d1) {
+                    /* d1 != 0, d3 != 0, d5 != 0, d7 != 0 */
+                    z1 = d7 + d1;
+                    z2 = d5 + d3;
+                    z3 = d7 + d3;
+                    z4 = d5 + d1;
+                    z5 = MULTIPLY(z3 + z4, FIX_1_175875602);
+
+                    tmp0 = MULTIPLY(d7, FIX_0_298631336);
+                    tmp1 = MULTIPLY(d5, FIX_2_053119869);
+                    tmp2 = MULTIPLY(d3, FIX_3_072711026);
+                    tmp3 = MULTIPLY(d1, FIX_1_501321110);
+                    z1 = MULTIPLY(-z1, FIX_0_899976223);
+                    z2 = MULTIPLY(-z2, FIX_2_562915447);
+                    z3 = MULTIPLY(-z3, FIX_1_961570560);
+                    z4 = MULTIPLY(-z4, FIX_0_390180644);
+
+                    z3 += z5;
+                    z4 += z5;
+
+                    tmp0 += z1 + z3;
+                    tmp1 += z2 + z4;
+                    tmp2 += z2 + z3;
+                    tmp3 += z1 + z4;
+                } else {
+                    /* d1 == 0, d3 != 0, d5 != 0, d7 != 0 */
+                    z2 = d5 + d3;
+                    z3 = d7 + d3;
+                    z5 = MULTIPLY(z3 + d5, FIX_1_175875602);
+
+                    tmp0 = MULTIPLY(d7, FIX_0_298631336);
+                    tmp1 = MULTIPLY(d5, FIX_2_053119869);
+                    tmp2 = MULTIPLY(d3, FIX_3_072711026);
+                    z1 = MULTIPLY(-d7, FIX_0_899976223);
+                    z2 = MULTIPLY(-z2, FIX_2_562915447);
+                    z3 = MULTIPLY(-z3, FIX_1_961570560);
+                    z4 = MULTIPLY(-d5, FIX_0_390180644);
+
+                    z3 += z5;
+                    z4 += z5;
+
+                    tmp0 += z1 + z3;
+                    tmp1 += z2 + z4;
+                    tmp2 += z2 + z3;
+                    tmp3 = z1 + z4;
+                }
+            } else {
+                if (d1) {
+                    /* d1 != 0, d3 == 0, d5 != 0, d7 != 0 */
+                    z1 = d7 + d1;
+                    z4 = d5 + d1;
+                    z5 = MULTIPLY(d7 + z4, FIX_1_175875602);
+
+                    tmp0 = MULTIPLY(d7, FIX_0_298631336);
+                    tmp1 = MULTIPLY(d5, FIX_2_053119869);
+                    tmp3 = MULTIPLY(d1, FIX_1_501321110);
+                    z1 = MULTIPLY(-z1, FIX_0_899976223);
+                    z2 = MULTIPLY(-d5, FIX_2_562915447);
+                    z3 = MULTIPLY(-d7, FIX_1_961570560);
+                    z4 = MULTIPLY(-z4, FIX_0_390180644);
+
+                    z3 += z5;
+                    z4 += z5;
+
+                    tmp0 += z1 + z3;
+                    tmp1 += z2 + z4;
+                    tmp2 = z2 + z3;
+                    tmp3 += z1 + z4;
+                } else {
+                    /* d1 == 0, d3 == 0, d5 != 0, d7 != 0 */
+                    tmp0 = MULTIPLY(-d7, FIX_0_601344887);
+                    z1 = MULTIPLY(-d7, FIX_0_899976223);
+                    z3 = MULTIPLY(-d7, FIX_1_961570560);
+                    tmp1 = MULTIPLY(-d5, FIX_0_509795579);
+                    z2 = MULTIPLY(-d5, FIX_2_562915447);
+                    z4 = MULTIPLY(-d5, FIX_0_390180644);
+                    z5 = MULTIPLY(d5 + d7, FIX_1_175875602);
+
+                    z3 += z5;
+                    z4 += z5;
+
+                    tmp0 += z3;
+                    tmp1 += z4;
+                    tmp2 = z2 + z3;
+                    tmp3 = z1 + z4;
+                }
+            }
+        } else {
+            if (d3) {
+                if (d1) {
+                    /* d1 != 0, d3 != 0, d5 == 0, d7 != 0 */
+                    z1 = d7 + d1;
+                    z3 = d7 + d3;
+                    z5 = MULTIPLY(z3 + d1, FIX_1_175875602);
+
+                    tmp0 = MULTIPLY(d7, FIX_0_298631336);
+                    tmp2 = MULTIPLY(d3, FIX_3_072711026);
+                    tmp3 = MULTIPLY(d1, FIX_1_501321110);
+                    z1 = MULTIPLY(-z1, FIX_0_899976223);
+                    z2 = MULTIPLY(-d3, FIX_2_562915447);
+                    z3 = MULTIPLY(-z3, FIX_1_961570560);
+                    z4 = MULTIPLY(-d1, FIX_0_390180644);
+
+                    z3 += z5;
+                    z4 += z5;
+
+                    tmp0 += z1 + z3;
+                    tmp1 = z2 + z4;
+                    tmp2 += z2 + z3;
+                    tmp3 += z1 + z4;
+                } else {
+                    /* d1 == 0, d3 != 0, d5 == 0, d7 != 0 */
+                    z3 = d7 + d3;
+
+                    tmp0 = MULTIPLY(-d7, FIX_0_601344887);
+                    z1 = MULTIPLY(-d7, FIX_0_899976223);
+                    tmp2 = MULTIPLY(d3, FIX_0_509795579);
+                    z2 = MULTIPLY(-d3, FIX_2_562915447);
+                    z5 = MULTIPLY(z3, FIX_1_175875602);
+                    z3 = MULTIPLY(-z3, FIX_0_785694958);
+
+                    tmp0 += z3;
+                    tmp1 = z2 + z5;
+                    tmp2 += z3;
+                    tmp3 = z1 + z5;
+                }
+            } else {
+                if (d1) {
+                    /* d1 != 0, d3 == 0, d5 == 0, d7 != 0 */
+                    z1 = d7 + d1;
+                    z5 = MULTIPLY(z1, FIX_1_175875602);
+
+                    z1 = MULTIPLY(z1, FIX_0_275899380);
+                    z3 = MULTIPLY(-d7, FIX_1_961570560);
+                    tmp0 = MULTIPLY(-d7, FIX_1_662939225);
+                    z4 = MULTIPLY(-d1, FIX_0_390180644);
+                    tmp3 = MULTIPLY(d1, FIX_1_111140466);
+
+                    tmp0 += z1;
+                    tmp1 = z4 + z5;
+                    tmp2 = z3 + z5;
+                    tmp3 += z1;
+                } else {
+                    /* d1 == 0, d3 == 0, d5 == 0, d7 != 0 */
+                    tmp0 = MULTIPLY(-d7, FIX_1_387039845);
+                    tmp1 = MULTIPLY(d7, FIX_1_175875602);
+                    tmp2 = MULTIPLY(-d7, FIX_0_785694958);
+                    tmp3 = MULTIPLY(d7, FIX_0_275899380);
+                }
+            }
+        }
     } else {
-	if (d5) {
-	    if (d3) {
-		if (d1) {
-		    /* d1 != 0, d3 != 0, d5 != 0, d7 == 0 */
-		    z2 = d5 + d3;
-		    z4 = d5 + d1;
-		    z5 = MULTIPLY(d3 + z4, FIX_1_175875602);
-		    
-		    tmp1 = MULTIPLY(d5, FIX_2_053119869);
-		    tmp2 = MULTIPLY(d3, FIX_3_072711026);
-		    tmp3 = MULTIPLY(d1, FIX_1_501321110);
-		    z1 = MULTIPLY(-d1, FIX_0_899976223);
-		    z2 = MULTIPLY(-z2, FIX_2_562915447);
-		    z3 = MULTIPLY(-d3, FIX_1_961570560);
-		    z4 = MULTIPLY(-z4, FIX_0_390180644);
-		    
-		    z3 += z5;
-		    z4 += z5;
-		    
-		    tmp0 = z1 + z3;
-		    tmp1 += z2 + z4;
-		    tmp2 += z2 + z3;
-		    tmp3 += z1 + z4;
-		} else {
-		    /* d1 == 0, d3 != 0, d5 != 0, d7 == 0 */
-		    z2 = d5 + d3;
-		    
-		    z5 = MULTIPLY(z2, FIX_1_175875602);
-		    tmp1 = MULTIPLY(d5, FIX_1_662939225);
-		    z4 = MULTIPLY(-d5, FIX_0_390180644);
-		    z2 = MULTIPLY(-z2, FIX_1_387039845);
-		    tmp2 = MULTIPLY(d3, FIX_1_111140466);
-		    z3 = MULTIPLY(-d3, FIX_1_961570560);
-		    
-		    tmp0 = z3 + z5;
-		    tmp1 += z2;
-		    tmp2 += z2;
-		    tmp3 = z4 + z5;
-		}
-	    } else {
-		if (d1) {
-		    /* d1 != 0, d3 == 0, d5 != 0, d7 == 0 */
-		    z4 = d5 + d1;
-		    
-		    z5 = MULTIPLY(z4, FIX_1_175875602);
-		    z1 = MULTIPLY(-d1, FIX_0_899976223);
-		    tmp3 = MULTIPLY(d1, FIX_0_601344887);
-		    tmp1 = MULTIPLY(-d5, FIX_0_509795579);
-		    z2 = MULTIPLY(-d5, FIX_2_562915447);
-		    z4 = MULTIPLY(z4, FIX_0_785694958);
-		    
-		    tmp0 = z1 + z5;
-		    tmp1 += z4;
-		    tmp2 = z2 + z5;
-		    tmp3 += z4;
-		} else {
-		    /* d1 == 0, d3 == 0, d5 != 0, d7 == 0 */
-		    tmp0 = MULTIPLY(d5, FIX_1_175875602);
-		    tmp1 = MULTIPLY(d5, FIX_0_275899380);
-		    tmp2 = MULTIPLY(-d5, FIX_1_387039845);
-		    tmp3 = MULTIPLY(d5, FIX_0_785694958);
-		}
-	    }
-	} else {
-	    if (d3) {
-		if (d1) {
-		    /* d1 != 0, d3 != 0, d5 == 0, d7 == 0 */
-		    z5 = d1 + d3;
-		    tmp3 = MULTIPLY(d1, FIX_0_211164243);
-		    tmp2 = MULTIPLY(-d3, FIX_1_451774981);
-		    z1 = MULTIPLY(d1, FIX_1_061594337);
-		    z2 = MULTIPLY(-d3, FIX_2_172734803);
-		    z4 = MULTIPLY(z5, FIX_0_785694958);
-		    z5 = MULTIPLY(z5, FIX_1_175875602);
-		    
-		    tmp0 = z1 - z4;
-		    tmp1 = z2 + z4;
-		    tmp2 += z5;
-		    tmp3 += z5;
-		} else {
-		    /* d1 == 0, d3 != 0, d5 == 0, d7 == 0 */
-		    tmp0 = MULTIPLY(-d3, FIX_0_785694958);
-		    tmp1 = MULTIPLY(-d3, FIX_1_387039845);
-		    tmp2 = MULTIPLY(-d3, FIX_0_275899380);
-		    tmp3 = MULTIPLY(d3, FIX_1_175875602);
-		}
-	    } else {
-		if (d1) {
-		    /* d1 != 0, d3 == 0, d5 == 0, d7 == 0 */
-		    tmp0 = MULTIPLY(d1, FIX_0_275899380);
-		    tmp1 = MULTIPLY(d1, FIX_0_785694958);
-		    tmp2 = MULTIPLY(d1, FIX_1_175875602);
-		    tmp3 = MULTIPLY(d1, FIX_1_387039845);
-		} else {
-		    /* d1 == 0, d3 == 0, d5 == 0, d7 == 0 */
-		    tmp0 = tmp1 = tmp2 = tmp3 = 0;
-		}
-	    }
-	}
+        if (d5) {
+            if (d3) {
+                if (d1) {
+                    /* d1 != 0, d3 != 0, d5 != 0, d7 == 0 */
+                    z2 = d5 + d3;
+                    z4 = d5 + d1;
+                    z5 = MULTIPLY(d3 + z4, FIX_1_175875602);
+
+                    tmp1 = MULTIPLY(d5, FIX_2_053119869);
+                    tmp2 = MULTIPLY(d3, FIX_3_072711026);
+                    tmp3 = MULTIPLY(d1, FIX_1_501321110);
+                    z1 = MULTIPLY(-d1, FIX_0_899976223);
+                    z2 = MULTIPLY(-z2, FIX_2_562915447);
+                    z3 = MULTIPLY(-d3, FIX_1_961570560);
+                    z4 = MULTIPLY(-z4, FIX_0_390180644);
+
+                    z3 += z5;
+                    z4 += z5;
+
+                    tmp0 = z1 + z3;
+                    tmp1 += z2 + z4;
+                    tmp2 += z2 + z3;
+                    tmp3 += z1 + z4;
+                } else {
+                    /* d1 == 0, d3 != 0, d5 != 0, d7 == 0 */
+                    z2 = d5 + d3;
+
+                    z5 = MULTIPLY(z2, FIX_1_175875602);
+                    tmp1 = MULTIPLY(d5, FIX_1_662939225);
+                    z4 = MULTIPLY(-d5, FIX_0_390180644);
+                    z2 = MULTIPLY(-z2, FIX_1_387039845);
+                    tmp2 = MULTIPLY(d3, FIX_1_111140466);
+                    z3 = MULTIPLY(-d3, FIX_1_961570560);
+
+                    tmp0 = z3 + z5;
+                    tmp1 += z2;
+                    tmp2 += z2;
+                    tmp3 = z4 + z5;
+                }
+            } else {
+                if (d1) {
+                    /* d1 != 0, d3 == 0, d5 != 0, d7 == 0 */
+                    z4 = d5 + d1;
+
+                    z5 = MULTIPLY(z4, FIX_1_175875602);
+                    z1 = MULTIPLY(-d1, FIX_0_899976223);
+                    tmp3 = MULTIPLY(d1, FIX_0_601344887);
+                    tmp1 = MULTIPLY(-d5, FIX_0_509795579);
+                    z2 = MULTIPLY(-d5, FIX_2_562915447);
+                    z4 = MULTIPLY(z4, FIX_0_785694958);
+
+                    tmp0 = z1 + z5;
+                    tmp1 += z4;
+                    tmp2 = z2 + z5;
+                    tmp3 += z4;
+                } else {
+                    /* d1 == 0, d3 == 0, d5 != 0, d7 == 0 */
+                    tmp0 = MULTIPLY(d5, FIX_1_175875602);
+                    tmp1 = MULTIPLY(d5, FIX_0_275899380);
+                    tmp2 = MULTIPLY(-d5, FIX_1_387039845);
+                    tmp3 = MULTIPLY(d5, FIX_0_785694958);
+                }
+            }
+        } else {
+            if (d3) {
+                if (d1) {
+                    /* d1 != 0, d3 != 0, d5 == 0, d7 == 0 */
+                    z5 = d1 + d3;
+                    tmp3 = MULTIPLY(d1, FIX_0_211164243);
+                    tmp2 = MULTIPLY(-d3, FIX_1_451774981);
+                    z1 = MULTIPLY(d1, FIX_1_061594337);
+                    z2 = MULTIPLY(-d3, FIX_2_172734803);
+                    z4 = MULTIPLY(z5, FIX_0_785694958);
+                    z5 = MULTIPLY(z5, FIX_1_175875602);
+
+                    tmp0 = z1 - z4;
+                    tmp1 = z2 + z4;
+                    tmp2 += z5;
+                    tmp3 += z5;
+                } else {
+                    /* d1 == 0, d3 != 0, d5 == 0, d7 == 0 */
+                    tmp0 = MULTIPLY(-d3, FIX_0_785694958);
+                    tmp1 = MULTIPLY(-d3, FIX_1_387039845);
+                    tmp2 = MULTIPLY(-d3, FIX_0_275899380);
+                    tmp3 = MULTIPLY(d3, FIX_1_175875602);
+                }
+            } else {
+                if (d1) {
+                    /* d1 != 0, d3 == 0, d5 == 0, d7 == 0 */
+                    tmp0 = MULTIPLY(d1, FIX_0_275899380);
+                    tmp1 = MULTIPLY(d1, FIX_0_785694958);
+                    tmp2 = MULTIPLY(d1, FIX_1_175875602);
+                    tmp3 = MULTIPLY(d1, FIX_1_387039845);
+                } else {
+                    /* d1 == 0, d3 == 0, d5 == 0, d7 == 0 */
+                    tmp0 = tmp1 = tmp2 = tmp3 = 0;
+                }
+            }
+        }
     }
 }
     /* Final output stage: inputs are tmp10..tmp13, tmp0..tmp3 */
@@ -688,7 +690,7 @@ mpeg_jrevdct_quick(data)
     dataptr[3] = (DCTELEM) DESCALE(tmp13 + tmp0, CONST_BITS-PASS1_BITS);
     dataptr[4] = (DCTELEM) DESCALE(tmp13 - tmp0, CONST_BITS-PASS1_BITS);
 
-    dataptr += DCTSIZE;		/* advance pointer to next row */
+    dataptr += DCTSIZE;         /* advance pointer to next row */
   }
 
   /* Pass 2: process columns. */
@@ -717,468 +719,469 @@ mpeg_jrevdct_quick(data)
     /* Even part: reverse the even part of the forward DCT. */
     /* The rotator is sqrt(2)*c(-6). */
     if (d6) {
-	if (d4) {
-	    if (d2) {
-		if (d0) {
-		    /* d0 != 0, d2 != 0, d4 != 0, d6 != 0 */
-		    z1 = MULTIPLY(d2 + d6, FIX_0_541196100);
-		    tmp2 = z1 + MULTIPLY(-d6, FIX_1_847759065);
-		    tmp3 = z1 + MULTIPLY(d2, FIX_0_765366865);
-
-		    tmp0 = (d0 + d4) << CONST_BITS;
-		    tmp1 = (d0 - d4) << CONST_BITS;
-
-		    tmp10 = tmp0 + tmp3;
-		    tmp13 = tmp0 - tmp3;
-		    tmp11 = tmp1 + tmp2;
-		    tmp12 = tmp1 - tmp2;
-		} else {
-		    /* d0 == 0, d2 != 0, d4 != 0, d6 != 0 */
-		    z1 = MULTIPLY(d2 + d6, FIX_0_541196100);
-		    tmp2 = z1 + MULTIPLY(-d6, FIX_1_847759065);
-		    tmp3 = z1 + MULTIPLY(d2, FIX_0_765366865);
-
-		    tmp0 = d4 << CONST_BITS;
-
-		    tmp10 = tmp0 + tmp3;
-		    tmp13 = tmp0 - tmp3;
-		    tmp11 = tmp2 - tmp0;
-		    tmp12 = -(tmp0 + tmp2);
-		}
-	    } else {
-		if (d0) {
-		    /* d0 != 0, d2 == 0, d4 != 0, d6 != 0 */
-		    tmp2 = MULTIPLY(-d6, FIX_1_306562965);
-		    tmp3 = MULTIPLY(d6, FIX_0_541196100);
-
-		    tmp0 = (d0 + d4) << CONST_BITS;
-		    tmp1 = (d0 - d4) << CONST_BITS;
-
-		    tmp10 = tmp0 + tmp3;
-		    tmp13 = tmp0 - tmp3;
-		    tmp11 = tmp1 + tmp2;
-		    tmp12 = tmp1 - tmp2;
-		} else {
-		    /* d0 == 0, d2 == 0, d4 != 0, d6 != 0 */
-		    tmp2 = MULTIPLY(-d6, FIX_1_306562965);
-		    tmp3 = MULTIPLY(d6, FIX_0_541196100);
-
-		    tmp0 = d4 << CONST_BITS;
-
-		    tmp10 = tmp0 + tmp3;
-		    tmp13 = tmp0 - tmp3;
-		    tmp11 = tmp2 - tmp0;
-		    tmp12 = -(tmp0 + tmp2);
-		}
-	    }
-	} else {
-	    if (d2) {
-		if (d0) {
-		    /* d0 != 0, d2 != 0, d4 == 0, d6 != 0 */
-		    z1 = MULTIPLY(d2 + d6, FIX_0_541196100);
-		    tmp2 = z1 + MULTIPLY(-d6, FIX_1_847759065);
-		    tmp3 = z1 + MULTIPLY(d2, FIX_0_765366865);
-
-		    tmp0 = d0 << CONST_BITS;
-
-		    tmp10 = tmp0 + tmp3;
-		    tmp13 = tmp0 - tmp3;
-		    tmp11 = tmp0 + tmp2;
-		    tmp12 = tmp0 - tmp2;
-		} else {
-		    /* d0 == 0, d2 != 0, d4 == 0, d6 != 0 */
-		    z1 = MULTIPLY(d2 + d6, FIX_0_541196100);
-		    tmp2 = z1 + MULTIPLY(-d6, FIX_1_847759065);
-		    tmp3 = z1 + MULTIPLY(d2, FIX_0_765366865);
-
-		    tmp10 = tmp3;
-		    tmp13 = -tmp3;
-		    tmp11 = tmp2;
-		    tmp12 = -tmp2;
-		}
-	    } else {
-		if (d0) {
-		    /* d0 != 0, d2 == 0, d4 == 0, d6 != 0 */
-		    tmp2 = MULTIPLY(-d6, FIX_1_306562965);
-		    tmp3 = MULTIPLY(d6, FIX_0_541196100);
-
-		    tmp0 = d0 << CONST_BITS;
-
-		    tmp10 = tmp0 + tmp3;
-		    tmp13 = tmp0 - tmp3;
-		    tmp11 = tmp0 + tmp2;
-		    tmp12 = tmp0 - tmp2;
-		} else {
-		    /* d0 == 0, d2 == 0, d4 == 0, d6 != 0 */
-		    tmp2 = MULTIPLY(-d6, FIX_1_306562965);
-		    tmp3 = MULTIPLY(d6, FIX_0_541196100);
-
-		    tmp10 = tmp3;
-		    tmp13 = -tmp3;
-		    tmp11 = tmp2;
-		    tmp12 = -tmp2;
-		}
-	    }
-	}
+        if (d4) {
+            if (d2) {
+                if (d0) {
+                    /* d0 != 0, d2 != 0, d4 != 0, d6 != 0 */
+                    z1 = MULTIPLY(d2 + d6, FIX_0_541196100);
+                    tmp2 = z1 + MULTIPLY(-d6, FIX_1_847759065);
+                    tmp3 = z1 + MULTIPLY(d2, FIX_0_765366865);
+
+                    tmp0 = (d0 + d4) << CONST_BITS;
+                    tmp1 = (d0 - d4) << CONST_BITS;
+
+                    tmp10 = tmp0 + tmp3;
+                    tmp13 = tmp0 - tmp3;
+                    tmp11 = tmp1 + tmp2;
+                    tmp12 = tmp1 - tmp2;
+                } else {
+                    /* d0 == 0, d2 != 0, d4 != 0, d6 != 0 */
+                    z1 = MULTIPLY(d2 + d6, FIX_0_541196100);
+                    tmp2 = z1 + MULTIPLY(-d6, FIX_1_847759065);
+                    tmp3 = z1 + MULTIPLY(d2, FIX_0_765366865);
+
+                    tmp0 = d4 << CONST_BITS;
+
+                    tmp10 = tmp0 + tmp3;
+                    tmp13 = tmp0 - tmp3;
+                    tmp11 = tmp2 - tmp0;
+                    tmp12 = -(tmp0 + tmp2);
+                }
+            } else {
+                if (d0) {
+                    /* d0 != 0, d2 == 0, d4 != 0, d6 != 0 */
+                    tmp2 = MULTIPLY(-d6, FIX_1_306562965);
+                    tmp3 = MULTIPLY(d6, FIX_0_541196100);
+
+                    tmp0 = (d0 + d4) << CONST_BITS;
+                    tmp1 = (d0 - d4) << CONST_BITS;
+
+                    tmp10 = tmp0 + tmp3;
+                    tmp13 = tmp0 - tmp3;
+                    tmp11 = tmp1 + tmp2;
+                    tmp12 = tmp1 - tmp2;
+                } else {
+                    /* d0 == 0, d2 == 0, d4 != 0, d6 != 0 */
+                    tmp2 = MULTIPLY(-d6, FIX_1_306562965);
+                    tmp3 = MULTIPLY(d6, FIX_0_541196100);
+
+                    tmp0 = d4 << CONST_BITS;
+
+                    tmp10 = tmp0 + tmp3;
+                    tmp13 = tmp0 - tmp3;
+                    tmp11 = tmp2 - tmp0;
+                    tmp12 = -(tmp0 + tmp2);
+                }
+            }
+        } else {
+            if (d2) {
+                if (d0) {
+                    /* d0 != 0, d2 != 0, d4 == 0, d6 != 0 */
+                    z1 = MULTIPLY(d2 + d6, FIX_0_541196100);
+                    tmp2 = z1 + MULTIPLY(-d6, FIX_1_847759065);
+                    tmp3 = z1 + MULTIPLY(d2, FIX_0_765366865);
+
+                    tmp0 = d0 << CONST_BITS;
+
+                    tmp10 = tmp0 + tmp3;
+                    tmp13 = tmp0 - tmp3;
+                    tmp11 = tmp0 + tmp2;
+                    tmp12 = tmp0 - tmp2;
+                } else {
+                    /* d0 == 0, d2 != 0, d4 == 0, d6 != 0 */
+                    z1 = MULTIPLY(d2 + d6, FIX_0_541196100);
+                    tmp2 = z1 + MULTIPLY(-d6, FIX_1_847759065);
+                    tmp3 = z1 + MULTIPLY(d2, FIX_0_765366865);
+
+                    tmp10 = tmp3;
+                    tmp13 = -tmp3;
+                    tmp11 = tmp2;
+                    tmp12 = -tmp2;
+                }
+            } else {
+                if (d0) {
+                    /* d0 != 0, d2 == 0, d4 == 0, d6 != 0 */
+                    tmp2 = MULTIPLY(-d6, FIX_1_306562965);
+                    tmp3 = MULTIPLY(d6, FIX_0_541196100);
+
+                    tmp0 = d0 << CONST_BITS;
+
+                    tmp10 = tmp0 + tmp3;
+                    tmp13 = tmp0 - tmp3;
+                    tmp11 = tmp0 + tmp2;
+                    tmp12 = tmp0 - tmp2;
+                } else {
+                    /* d0 == 0, d2 == 0, d4 == 0, d6 != 0 */
+                    tmp2 = MULTIPLY(-d6, FIX_1_306562965);
+                    tmp3 = MULTIPLY(d6, FIX_0_541196100);
+
+                    tmp10 = tmp3;
+                    tmp13 = -tmp3;
+                    tmp11 = tmp2;
+                    tmp12 = -tmp2;
+                }
+            }
+        }
     } else {
-	if (d4) {
-	    if (d2) {
-		if (d0) {
-		    /* d0 != 0, d2 != 0, d4 != 0, d6 == 0 */
-		    tmp2 = MULTIPLY(d2, FIX_0_541196100);
-		    tmp3 = MULTIPLY(d2, FIX_1_306562965);
-
-		    tmp0 = (d0 + d4) << CONST_BITS;
-		    tmp1 = (d0 - d4) << CONST_BITS;
-
-		    tmp10 = tmp0 + tmp3;
-		    tmp13 = tmp0 - tmp3;
-		    tmp11 = tmp1 + tmp2;
-		    tmp12 = tmp1 - tmp2;
-		} else {
-		    /* d0 == 0, d2 != 0, d4 != 0, d6 == 0 */
-		    tmp2 = MULTIPLY(d2, FIX_0_541196100);
-		    tmp3 = MULTIPLY(d2, FIX_1_306562965);
-
-		    tmp0 = d4 << CONST_BITS;
-
-		    tmp10 = tmp0 + tmp3;
-		    tmp13 = tmp0 - tmp3;
-		    tmp11 = tmp2 - tmp0;
-		    tmp12 = -(tmp0 + tmp2);
-		}
-	    } else {
-		if (d0) {
-		    /* d0 != 0, d2 == 0, d4 != 0, d6 == 0 */
-		    tmp10 = tmp13 = (d0 + d4) << CONST_BITS;
-		    tmp11 = tmp12 = (d0 - d4) << CONST_BITS;
-		} else {
-		    /* d0 == 0, d2 == 0, d4 != 0, d6 == 0 */
-		    tmp10 = tmp13 = d4 << CONST_BITS;
-		    tmp11 = tmp12 = -tmp10;
-		}
-	    }
-	} else {
-	    if (d2) {
-		if (d0) {
-		    /* d0 != 0, d2 != 0, d4 == 0, d6 == 0 */
-		    tmp2 = MULTIPLY(d2, FIX_0_541196100);
-		    tmp3 = MULTIPLY(d2, FIX_1_306562965);
-
-		    tmp0 = d0 << CONST_BITS;
-
-		    tmp10 = tmp0 + tmp3;
-		    tmp13 = tmp0 - tmp3;
-		    tmp11 = tmp0 + tmp2;
-		    tmp12 = tmp0 - tmp2;
-		} else {
-		    /* d0 == 0, d2 != 0, d4 == 0, d6 == 0 */
-		    tmp2 = MULTIPLY(d2, FIX_0_541196100);
-		    tmp3 = MULTIPLY(d2, FIX_1_306562965);
-
-		    tmp10 = tmp3;
-		    tmp13 = -tmp3;
-		    tmp11 = tmp2;
-		    tmp12 = -tmp2;
-		}
-	    } else {
-		if (d0) {
-		    /* d0 != 0, d2 == 0, d4 == 0, d6 == 0 */
-		    tmp10 = tmp13 = tmp11 = tmp12 = d0 << CONST_BITS;
-		} else {
-		    /* d0 == 0, d2 == 0, d4 == 0, d6 == 0 */
-		    tmp10 = tmp13 = tmp11 = tmp12 = 0;
-		}
-	    }
-	}
+        if (d4) {
+            if (d2) {
+                if (d0) {
+                    /* d0 != 0, d2 != 0, d4 != 0, d6 == 0 */
+                    tmp2 = MULTIPLY(d2, FIX_0_541196100);
+                    tmp3 = MULTIPLY(d2, FIX_1_306562965);
+
+                    tmp0 = (d0 + d4) << CONST_BITS;
+                    tmp1 = (d0 - d4) << CONST_BITS;
+
+                    tmp10 = tmp0 + tmp3;
+                    tmp13 = tmp0 - tmp3;
+                    tmp11 = tmp1 + tmp2;
+                    tmp12 = tmp1 - tmp2;
+                } else {
+                    /* d0 == 0, d2 != 0, d4 != 0, d6 == 0 */
+                    tmp2 = MULTIPLY(d2, FIX_0_541196100);
+                    tmp3 = MULTIPLY(d2, FIX_1_306562965);
+
+                    tmp0 = d4 << CONST_BITS;
+
+                    tmp10 = tmp0 + tmp3;
+                    tmp13 = tmp0 - tmp3;
+                    tmp11 = tmp2 - tmp0;
+                    tmp12 = -(tmp0 + tmp2);
+                }
+            } else {
+                if (d0) {
+                    /* d0 != 0, d2 == 0, d4 != 0, d6 == 0 */
+                    tmp10 = tmp13 = (d0 + d4) << CONST_BITS;
+                    tmp11 = tmp12 = (d0 - d4) << CONST_BITS;
+                } else {
+                    /* d0 == 0, d2 == 0, d4 != 0, d6 == 0 */
+                    tmp10 = tmp13 = d4 << CONST_BITS;
+                    tmp11 = tmp12 = -tmp10;
+                }
+            }
+        } else {
+            if (d2) {
+                if (d0) {
+                    /* d0 != 0, d2 != 0, d4 == 0, d6 == 0 */
+                    tmp2 = MULTIPLY(d2, FIX_0_541196100);
+                    tmp3 = MULTIPLY(d2, FIX_1_306562965);
+
+                    tmp0 = d0 << CONST_BITS;
+
+                    tmp10 = tmp0 + tmp3;
+                    tmp13 = tmp0 - tmp3;
+                    tmp11 = tmp0 + tmp2;
+                    tmp12 = tmp0 - tmp2;
+                } else {
+                    /* d0 == 0, d2 != 0, d4 == 0, d6 == 0 */
+                    tmp2 = MULTIPLY(d2, FIX_0_541196100);
+                    tmp3 = MULTIPLY(d2, FIX_1_306562965);
+
+                    tmp10 = tmp3;
+                    tmp13 = -tmp3;
+                    tmp11 = tmp2;
+                    tmp12 = -tmp2;
+                }
+            } else {
+                if (d0) {
+                    /* d0 != 0, d2 == 0, d4 == 0, d6 == 0 */
+                    tmp10 = tmp13 = tmp11 = tmp12 = d0 << CONST_BITS;
+                } else {
+                    /* d0 == 0, d2 == 0, d4 == 0, d6 == 0 */
+                    tmp10 = tmp13 = tmp11 = tmp12 = 0;
+                }
+            }
+        }
     }
 
     /* Odd part per figure 8; the matrix is unitary and hence its
      * transpose is its inverse.  i0..i3 are y7,y5,y3,y1 respectively.
      */
     if (d7) {
-	if (d5) {
-	    if (d3) {
-		if (d1) {
-		    /* d1 != 0, d3 != 0, d5 != 0, d7 != 0 */
-		    z1 = d7 + d1;
-		    z2 = d5 + d3;
-		    z3 = d7 + d3;
-		    z4 = d5 + d1;
-		    z5 = MULTIPLY(z3 + z4, FIX_1_175875602);
-		    
-		    tmp0 = MULTIPLY(d7, FIX_0_298631336); 
-		    tmp1 = MULTIPLY(d5, FIX_2_053119869);
-		    tmp2 = MULTIPLY(d3, FIX_3_072711026);
-		    tmp3 = MULTIPLY(d1, FIX_1_501321110);
-		    z1 = MULTIPLY(-z1, FIX_0_899976223);
-		    z2 = MULTIPLY(-z2, FIX_2_562915447);
-		    z3 = MULTIPLY(-z3, FIX_1_961570560);
-		    z4 = MULTIPLY(-z4, FIX_0_390180644);
-		    
-		    z3 += z5;
-		    z4 += z5;
-		    
-		    tmp0 += z1 + z3;
-		    tmp1 += z2 + z4;
-		    tmp2 += z2 + z3;
-		    tmp3 += z1 + z4;
-		} else {
-		    /* d1 == 0, d3 != 0, d5 != 0, d7 != 0 */
-		    z1 = d7;
-		    z2 = d5 + d3;
-		    z3 = d7 + d3;
-		    z5 = MULTIPLY(z3 + d5, FIX_1_175875602);
-		    
-		    tmp0 = MULTIPLY(d7, FIX_0_298631336); 
-		    tmp1 = MULTIPLY(d5, FIX_2_053119869);
-		    tmp2 = MULTIPLY(d3, FIX_3_072711026);
-		    z1 = MULTIPLY(-d7, FIX_0_899976223);
-		    z2 = MULTIPLY(-z2, FIX_2_562915447);
-		    z3 = MULTIPLY(-z3, FIX_1_961570560);
-		    z4 = MULTIPLY(-d5, FIX_0_390180644);
-		    
-		    z3 += z5;
-		    z4 += z5;
-		    
-		    tmp0 += z1 + z3;
-		    tmp1 += z2 + z4;
-		    tmp2 += z2 + z3;
-		    tmp3 = z1 + z4;
-		}
-	    } else {
-		if (d1) {
-		    /* d1 != 0, d3 == 0, d5 != 0, d7 != 0 */
-		    z1 = d7 + d1;
-		    z2 = d5;
-		    z3 = d7;
-		    z4 = d5 + d1;
-		    z5 = MULTIPLY(z3 + z4, FIX_1_175875602);
-		    
-		    tmp0 = MULTIPLY(d7, FIX_0_298631336); 
-		    tmp1 = MULTIPLY(d5, FIX_2_053119869);
-		    tmp3 = MULTIPLY(d1, FIX_1_501321110);
-		    z1 = MULTIPLY(-z1, FIX_0_899976223);
-		    z2 = MULTIPLY(-d5, FIX_2_562915447);
-		    z3 = MULTIPLY(-d7, FIX_1_961570560);
-		    z4 = MULTIPLY(-z4, FIX_0_390180644);
-		    
-		    z3 += z5;
-		    z4 += z5;
-		    
-		    tmp0 += z1 + z3;
-		    tmp1 += z2 + z4;
-		    tmp2 = z2 + z3;
-		    tmp3 += z1 + z4;
-		} else {
-		    /* d1 == 0, d3 == 0, d5 != 0, d7 != 0 */
-		    tmp0 = MULTIPLY(-d7, FIX_0_601344887); 
-		    z1 = MULTIPLY(-d7, FIX_0_899976223);
-		    z3 = MULTIPLY(-d7, FIX_1_961570560);
-		    tmp1 = MULTIPLY(-d5, FIX_0_509795579);
-		    z2 = MULTIPLY(-d5, FIX_2_562915447);
-		    z4 = MULTIPLY(-d5, FIX_0_390180644);
-		    z5 = MULTIPLY(d5 + d7, FIX_1_175875602);
-		    
-		    z3 += z5;
-		    z4 += z5;
-		    
-		    tmp0 += z3;
-		    tmp1 += z4;
-		    tmp2 = z2 + z3;
-		    tmp3 = z1 + z4;
-		}
-	    }
-	} else {
-	    if (d3) {
-		if (d1) {
-		    /* d1 != 0, d3 != 0, d5 == 0, d7 != 0 */
-		    z1 = d7 + d1;
-		    z3 = d7 + d3;
-		    z5 = MULTIPLY(z3 + d1, FIX_1_175875602);
-		    
-		    tmp0 = MULTIPLY(d7, FIX_0_298631336); 
-		    tmp2 = MULTIPLY(d3, FIX_3_072711026);
-		    tmp3 = MULTIPLY(d1, FIX_1_501321110);
-		    z1 = MULTIPLY(-z1, FIX_0_899976223);
-		    z2 = MULTIPLY(-d3, FIX_2_562915447);
-		    z3 = MULTIPLY(-z3, FIX_1_961570560);
-		    z4 = MULTIPLY(-d1, FIX_0_390180644);
-		    
-		    z3 += z5;
-		    z4 += z5;
-		    
-		    tmp0 += z1 + z3;
-		    tmp1 = z2 + z4;
-		    tmp2 += z2 + z3;
-		    tmp3 += z1 + z4;
-		} else {
-		    /* d1 == 0, d3 != 0, d5 == 0, d7 != 0 */
-		    z3 = d7 + d3;
-		    
-		    tmp0 = MULTIPLY(-d7, FIX_0_601344887); 
-		    z1 = MULTIPLY(-d7, FIX_0_899976223);
-		    tmp2 = MULTIPLY(d3, FIX_0_509795579);
-		    z2 = MULTIPLY(-d3, FIX_2_562915447);
-		    z5 = MULTIPLY(z3, FIX_1_175875602);
-		    z3 = MULTIPLY(-z3, FIX_0_785694958);
-		    
-		    tmp0 += z3;
-		    tmp1 = z2 + z5;
-		    tmp2 += z3;
-		    tmp3 = z1 + z5;
-		}
-	    } else {
-		if (d1) {
-		    /* d1 != 0, d3 == 0, d5 == 0, d7 != 0 */
-		    z1 = d7 + d1;
-		    z5 = MULTIPLY(z1, FIX_1_175875602);
-
-		    z1 = MULTIPLY(z1, FIX_0_275899380);
-		    z3 = MULTIPLY(-d7, FIX_1_961570560);
-		    tmp0 = MULTIPLY(-d7, FIX_1_662939225); 
-		    z4 = MULTIPLY(-d1, FIX_0_390180644);
-		    tmp3 = MULTIPLY(d1, FIX_1_111140466);
-
-		    tmp0 += z1;
-		    tmp1 = z4 + z5;
-		    tmp2 = z3 + z5;
-		    tmp3 += z1;
-		} else {
-		    /* d1 == 0, d3 == 0, d5 == 0, d7 != 0 */
-		    tmp0 = MULTIPLY(-d7, FIX_1_387039845);
-		    tmp1 = MULTIPLY(d7, FIX_1_175875602);
-		    tmp2 = MULTIPLY(-d7, FIX_0_785694958);
-		    tmp3 = MULTIPLY(d7, FIX_0_275899380);
-		}
-	    }
-	}
+        if (d5) {
+            if (d3) {
+                if (d1) {
+                    /* d1 != 0, d3 != 0, d5 != 0, d7 != 0 */
+                    z1 = d7 + d1;
+                    z2 = d5 + d3;
+                    z3 = d7 + d3;
+                    z4 = d5 + d1;
+                    z5 = MULTIPLY(z3 + z4, FIX_1_175875602);
+
+                    tmp0 = MULTIPLY(d7, FIX_0_298631336);
+                    tmp1 = MULTIPLY(d5, FIX_2_053119869);
+                    tmp2 = MULTIPLY(d3, FIX_3_072711026);
+                    tmp3 = MULTIPLY(d1, FIX_1_501321110);
+                    z1 = MULTIPLY(-z1, FIX_0_899976223);
+                    z2 = MULTIPLY(-z2, FIX_2_562915447);
+                    z3 = MULTIPLY(-z3, FIX_1_961570560);
+                    z4 = MULTIPLY(-z4, FIX_0_390180644);
+
+                    z3 += z5;
+                    z4 += z5;
+
+                    tmp0 += z1 + z3;
+                    tmp1 += z2 + z4;
+                    tmp2 += z2 + z3;
+                    tmp3 += z1 + z4;
+                } else {
+                    /* d1 == 0, d3 != 0, d5 != 0, d7 != 0 */
+                    z1 = d7;
+                    z2 = d5 + d3;
+                    z3 = d7 + d3;
+                    z5 = MULTIPLY(z3 + d5, FIX_1_175875602);
+
+                    tmp0 = MULTIPLY(d7, FIX_0_298631336);
+                    tmp1 = MULTIPLY(d5, FIX_2_053119869);
+                    tmp2 = MULTIPLY(d3, FIX_3_072711026);
+                    z1 = MULTIPLY(-d7, FIX_0_899976223);
+                    z2 = MULTIPLY(-z2, FIX_2_562915447);
+                    z3 = MULTIPLY(-z3, FIX_1_961570560);
+                    z4 = MULTIPLY(-d5, FIX_0_390180644);
+
+                    z3 += z5;
+                    z4 += z5;
+
+                    tmp0 += z1 + z3;
+                    tmp1 += z2 + z4;
+                    tmp2 += z2 + z3;
+                    tmp3 = z1 + z4;
+                }
+            } else {
+                if (d1) {
+                    /* d1 != 0, d3 == 0, d5 != 0, d7 != 0 */
+                    z1 = d7 + d1;
+                    z2 = d5;
+                    z3 = d7;
+                    z4 = d5 + d1;
+                    z5 = MULTIPLY(z3 + z4, FIX_1_175875602);
+
+                    tmp0 = MULTIPLY(d7, FIX_0_298631336);
+                    tmp1 = MULTIPLY(d5, FIX_2_053119869);
+                    tmp3 = MULTIPLY(d1, FIX_1_501321110);
+                    z1 = MULTIPLY(-z1, FIX_0_899976223);
+                    z2 = MULTIPLY(-d5, FIX_2_562915447);
+                    z3 = MULTIPLY(-d7, FIX_1_961570560);
+                    z4 = MULTIPLY(-z4, FIX_0_390180644);
+
+                    z3 += z5;
+                    z4 += z5;
+
+                    tmp0 += z1 + z3;
+                    tmp1 += z2 + z4;
+                    tmp2 = z2 + z3;
+                    tmp3 += z1 + z4;
+                } else {
+                    /* d1 == 0, d3 == 0, d5 != 0, d7 != 0 */
+                    tmp0 = MULTIPLY(-d7, FIX_0_601344887);
+                    z1 = MULTIPLY(-d7, FIX_0_899976223);
+                    z3 = MULTIPLY(-d7, FIX_1_961570560);
+                    tmp1 = MULTIPLY(-d5, FIX_0_509795579);
+                    z2 = MULTIPLY(-d5, FIX_2_562915447);
+                    z4 = MULTIPLY(-d5, FIX_0_390180644);
+                    z5 = MULTIPLY(d5 + d7, FIX_1_175875602);
+
+                    z3 += z5;
+                    z4 += z5;
+
+                    tmp0 += z3;
+                    tmp1 += z4;
+                    tmp2 = z2 + z3;
+                    tmp3 = z1 + z4;
+                }
+            }
+        } else {
+            if (d3) {
+                if (d1) {
+                    /* d1 != 0, d3 != 0, d5 == 0, d7 != 0 */
+                    z1 = d7 + d1;
+                    z3 = d7 + d3;
+                    z5 = MULTIPLY(z3 + d1, FIX_1_175875602);
+
+                    tmp0 = MULTIPLY(d7, FIX_0_298631336);
+                    tmp2 = MULTIPLY(d3, FIX_3_072711026);
+                    tmp3 = MULTIPLY(d1, FIX_1_501321110);
+                    z1 = MULTIPLY(-z1, FIX_0_899976223);
+                    z2 = MULTIPLY(-d3, FIX_2_562915447);
+                    z3 = MULTIPLY(-z3, FIX_1_961570560);
+                    z4 = MULTIPLY(-d1, FIX_0_390180644);
+
+                    z3 += z5;
+                    z4 += z5;
+
+                    tmp0 += z1 + z3;
+                    tmp1 = z2 + z4;
+                    tmp2 += z2 + z3;
+                    tmp3 += z1 + z4;
+                } else {
+                    /* d1 == 0, d3 != 0, d5 == 0, d7 != 0 */
+                    z3 = d7 + d3;
+
+                    tmp0 = MULTIPLY(-d7, FIX_0_601344887);
+                    z1 = MULTIPLY(-d7, FIX_0_899976223);
+                    tmp2 = MULTIPLY(d3, FIX_0_509795579);
+                    z2 = MULTIPLY(-d3, FIX_2_562915447);
+                    z5 = MULTIPLY(z3, FIX_1_175875602);
+                    z3 = MULTIPLY(-z3, FIX_0_785694958);
+
+                    tmp0 += z3;
+                    tmp1 = z2 + z5;
+                    tmp2 += z3;
+                    tmp3 = z1 + z5;
+                }
+            } else {
+                if (d1) {
+                    /* d1 != 0, d3 == 0, d5 == 0, d7 != 0 */
+                    z1 = d7 + d1;
+                    z5 = MULTIPLY(z1, FIX_1_175875602);
+
+                    z1 = MULTIPLY(z1, FIX_0_275899380);
+                    z3 = MULTIPLY(-d7, FIX_1_961570560);
+                    tmp0 = MULTIPLY(-d7, FIX_1_662939225);
+                    z4 = MULTIPLY(-d1, FIX_0_390180644);
+                    tmp3 = MULTIPLY(d1, FIX_1_111140466);
+
+                    tmp0 += z1;
+                    tmp1 = z4 + z5;
+                    tmp2 = z3 + z5;
+                    tmp3 += z1;
+                } else {
+                    /* d1 == 0, d3 == 0, d5 == 0, d7 != 0 */
+                    tmp0 = MULTIPLY(-d7, FIX_1_387039845);
+                    tmp1 = MULTIPLY(d7, FIX_1_175875602);
+                    tmp2 = MULTIPLY(-d7, FIX_0_785694958);
+                    tmp3 = MULTIPLY(d7, FIX_0_275899380);
+                }
+            }
+        }
     } else {
-	if (d5) {
-	    if (d3) {
-		if (d1) {
-		    /* d1 != 0, d3 != 0, d5 != 0, d7 == 0 */
-		    z2 = d5 + d3;
-		    z4 = d5 + d1;
-		    z5 = MULTIPLY(d3 + z4, FIX_1_175875602);
-		    
-		    tmp1 = MULTIPLY(d5, FIX_2_053119869);
-		    tmp2 = MULTIPLY(d3, FIX_3_072711026);
-		    tmp3 = MULTIPLY(d1, FIX_1_501321110);
-		    z1 = MULTIPLY(-d1, FIX_0_899976223);
-		    z2 = MULTIPLY(-z2, FIX_2_562915447);
-		    z3 = MULTIPLY(-d3, FIX_1_961570560);
-		    z4 = MULTIPLY(-z4, FIX_0_390180644);
-		    
-		    z3 += z5;
-		    z4 += z5;
-		    
-		    tmp0 = z1 + z3;
-		    tmp1 += z2 + z4;
-		    tmp2 += z2 + z3;
-		    tmp3 += z1 + z4;
-		} else {
-		    /* d1 == 0, d3 != 0, d5 != 0, d7 == 0 */
-		    z2 = d5 + d3;
-		    
-		    z5 = MULTIPLY(z2, FIX_1_175875602);
-		    tmp1 = MULTIPLY(d5, FIX_1_662939225);
-		    z4 = MULTIPLY(-d5, FIX_0_390180644);
-		    z2 = MULTIPLY(-z2, FIX_1_387039845);
-		    tmp2 = MULTIPLY(d3, FIX_1_111140466);
-		    z3 = MULTIPLY(-d3, FIX_1_961570560);
-		    
-		    tmp0 = z3 + z5;
-		    tmp1 += z2;
-		    tmp2 += z2;
-		    tmp3 = z4 + z5;
-		}
-	    } else {
-		if (d1) {
-		    /* d1 != 0, d3 == 0, d5 != 0, d7 == 0 */
-		    z4 = d5 + d1;
-		    
-		    z5 = MULTIPLY(z4, FIX_1_175875602);
-		    z1 = MULTIPLY(-d1, FIX_0_899976223);
-		    tmp3 = MULTIPLY(d1, FIX_0_601344887);
-		    tmp1 = MULTIPLY(-d5, FIX_0_509795579);
-		    z2 = MULTIPLY(-d5, FIX_2_562915447);
-		    z4 = MULTIPLY(z4, FIX_0_785694958);
-		    
-		    tmp0 = z1 + z5;
-		    tmp1 += z4;
-		    tmp2 = z2 + z5;
-		    tmp3 += z4;
-		} else {
-		    /* d1 == 0, d3 == 0, d5 != 0, d7 == 0 */
-		    tmp0 = MULTIPLY(d5, FIX_1_175875602);
-		    tmp1 = MULTIPLY(d5, FIX_0_275899380);
-		    tmp2 = MULTIPLY(-d5, FIX_1_387039845);
-		    tmp3 = MULTIPLY(d5, FIX_0_785694958);
-		}
-	    }
-	} else {
-	    if (d3) {
-		if (d1) {
-		    /* d1 != 0, d3 != 0, d5 == 0, d7 == 0 */
-		    z5 = d1 + d3;
-		    tmp3 = MULTIPLY(d1, FIX_0_211164243);
-		    tmp2 = MULTIPLY(-d3, FIX_1_451774981);
-		    z1 = MULTIPLY(d1, FIX_1_061594337);
-		    z2 = MULTIPLY(-d3, FIX_2_172734803);
-		    z4 = MULTIPLY(z5, FIX_0_785694958);
-		    z5 = MULTIPLY(z5, FIX_1_175875602);
-		    
-		    tmp0 = z1 - z4;
-		    tmp1 = z2 + z4;
-		    tmp2 += z5;
-		    tmp3 += z5;
-		} else {
-		    /* d1 == 0, d3 != 0, d5 == 0, d7 == 0 */
-		    tmp0 = MULTIPLY(-d3, FIX_0_785694958);
-		    tmp1 = MULTIPLY(-d3, FIX_1_387039845);
-		    tmp2 = MULTIPLY(-d3, FIX_0_275899380);
-		    tmp3 = MULTIPLY(d3, FIX_1_175875602);
-		}
-	    } else {
-		if (d1) {
-		    /* d1 != 0, d3 == 0, d5 == 0, d7 == 0 */
-		    tmp0 = MULTIPLY(d1, FIX_0_275899380);
-		    tmp1 = MULTIPLY(d1, FIX_0_785694958);
-		    tmp2 = MULTIPLY(d1, FIX_1_175875602);
-		    tmp3 = MULTIPLY(d1, FIX_1_387039845);
-		} else {
-		    /* d1 == 0, d3 == 0, d5 == 0, d7 == 0 */
-		    tmp0 = tmp1 = tmp2 = tmp3 = 0;
-		}
-	    }
-	}
+        if (d5) {
+            if (d3) {
+                if (d1) {
+                    /* d1 != 0, d3 != 0, d5 != 0, d7 == 0 */
+                    z2 = d5 + d3;
+                    z4 = d5 + d1;
+                    z5 = MULTIPLY(d3 + z4, FIX_1_175875602);
+
+                    tmp1 = MULTIPLY(d5, FIX_2_053119869);
+                    tmp2 = MULTIPLY(d3, FIX_3_072711026);
+                    tmp3 = MULTIPLY(d1, FIX_1_501321110);
+                    z1 = MULTIPLY(-d1, FIX_0_899976223);
+                    z2 = MULTIPLY(-z2, FIX_2_562915447);
+                    z3 = MULTIPLY(-d3, FIX_1_961570560);
+                    z4 = MULTIPLY(-z4, FIX_0_390180644);
+
+                    z3 += z5;
+                    z4 += z5;
+
+                    tmp0 = z1 + z3;
+                    tmp1 += z2 + z4;
+                    tmp2 += z2 + z3;
+                    tmp3 += z1 + z4;
+                } else {
+                    /* d1 == 0, d3 != 0, d5 != 0, d7 == 0 */
+                    z2 = d5 + d3;
+
+                    z5 = MULTIPLY(z2, FIX_1_175875602);
+                    tmp1 = MULTIPLY(d5, FIX_1_662939225);
+                    z4 = MULTIPLY(-d5, FIX_0_390180644);
+                    z2 = MULTIPLY(-z2, FIX_1_387039845);
+                    tmp2 = MULTIPLY(d3, FIX_1_111140466);
+                    z3 = MULTIPLY(-d3, FIX_1_961570560);
+
+                    tmp0 = z3 + z5;
+                    tmp1 += z2;
+                    tmp2 += z2;
+                    tmp3 = z4 + z5;
+                }
+            } else {
+                if (d1) {
+                    /* d1 != 0, d3 == 0, d5 != 0, d7 == 0 */
+                    z4 = d5 + d1;
+
+                    z5 = MULTIPLY(z4, FIX_1_175875602);
+                    z1 = MULTIPLY(-d1, FIX_0_899976223);
+                    tmp3 = MULTIPLY(d1, FIX_0_601344887);
+                    tmp1 = MULTIPLY(-d5, FIX_0_509795579);
+                    z2 = MULTIPLY(-d5, FIX_2_562915447);
+                    z4 = MULTIPLY(z4, FIX_0_785694958);
+
+                    tmp0 = z1 + z5;
+                    tmp1 += z4;
+                    tmp2 = z2 + z5;
+                    tmp3 += z4;
+                } else {
+                    /* d1 == 0, d3 == 0, d5 != 0, d7 == 0 */
+                    tmp0 = MULTIPLY(d5, FIX_1_175875602);
+                    tmp1 = MULTIPLY(d5, FIX_0_275899380);
+                    tmp2 = MULTIPLY(-d5, FIX_1_387039845);
+                    tmp3 = MULTIPLY(d5, FIX_0_785694958);
+                }
+            }
+        } else {
+            if (d3) {
+                if (d1) {
+                    /* d1 != 0, d3 != 0, d5 == 0, d7 == 0 */
+                    z5 = d1 + d3;
+                    tmp3 = MULTIPLY(d1, FIX_0_211164243);
+                    tmp2 = MULTIPLY(-d3, FIX_1_451774981);
+                    z1 = MULTIPLY(d1, FIX_1_061594337);
+                    z2 = MULTIPLY(-d3, FIX_2_172734803);
+                    z4 = MULTIPLY(z5, FIX_0_785694958);
+                    z5 = MULTIPLY(z5, FIX_1_175875602);
+
+                    tmp0 = z1 - z4;
+                    tmp1 = z2 + z4;
+                    tmp2 += z5;
+                    tmp3 += z5;
+                } else {
+                    /* d1 == 0, d3 != 0, d5 == 0, d7 == 0 */
+                    tmp0 = MULTIPLY(-d3, FIX_0_785694958);
+                    tmp1 = MULTIPLY(-d3, FIX_1_387039845);
+                    tmp2 = MULTIPLY(-d3, FIX_0_275899380);
+                    tmp3 = MULTIPLY(d3, FIX_1_175875602);
+                }
+            } else {
+                if (d1) {
+                    /* d1 != 0, d3 == 0, d5 == 0, d7 == 0 */
+                    tmp0 = MULTIPLY(d1, FIX_0_275899380);
+                    tmp1 = MULTIPLY(d1, FIX_0_785694958);
+                    tmp2 = MULTIPLY(d1, FIX_1_175875602);
+                    tmp3 = MULTIPLY(d1, FIX_1_387039845);
+                } else {
+                    /* d1 == 0, d3 == 0, d5 == 0, d7 == 0 */
+                    tmp0 = tmp1 = tmp2 = tmp3 = 0;
+                }
+            }
+        }
     }
 
     /* Final output stage: inputs are tmp10..tmp13, tmp0..tmp3 */
 
     dataptr[DCTSIZE*0] = (DCTELEM) DESCALE(tmp10 + tmp3,
-					   CONST_BITS+PASS1_BITS+3);
+                                           CONST_BITS+PASS1_BITS+3);
     dataptr[DCTSIZE*7] = (DCTELEM) DESCALE(tmp10 - tmp3,
-					   CONST_BITS+PASS1_BITS+3);
+                                           CONST_BITS+PASS1_BITS+3);
     dataptr[DCTSIZE*1] = (DCTELEM) DESCALE(tmp11 + tmp2,
-					   CONST_BITS+PASS1_BITS+3);
+                                           CONST_BITS+PASS1_BITS+3);
     dataptr[DCTSIZE*6] = (DCTELEM) DESCALE(tmp11 - tmp2,
-					   CONST_BITS+PASS1_BITS+3);
+                                           CONST_BITS+PASS1_BITS+3);
     dataptr[DCTSIZE*2] = (DCTELEM) DESCALE(tmp12 + tmp1,
-					   CONST_BITS+PASS1_BITS+3);
+                                           CONST_BITS+PASS1_BITS+3);
     dataptr[DCTSIZE*5] = (DCTELEM) DESCALE(tmp12 - tmp1,
-					   CONST_BITS+PASS1_BITS+3);
+                                           CONST_BITS+PASS1_BITS+3);
     dataptr[DCTSIZE*3] = (DCTELEM) DESCALE(tmp13 + tmp0,
-					   CONST_BITS+PASS1_BITS+3);
+                                           CONST_BITS+PASS1_BITS+3);
     dataptr[DCTSIZE*4] = (DCTELEM) DESCALE(tmp13 - tmp0,
-					   CONST_BITS+PASS1_BITS+3);
-    
-    dataptr++;			/* advance pointer to next column */
+                                           CONST_BITS+PASS1_BITS+3);
+
+    dataptr++;                  /* advance pointer to next column */
   }
 }
 
 
+
 /* here is the reference one, in case of problems with the normal one */
 
 /* idctref.c, Inverse Discrete Fourier Transform, double precision          */
@@ -1222,7 +1225,7 @@ static double itrans_coef[8][8];
 
 void init_idctref() {
 /*----------------------------------------------------------------------------
-   initialize DCT coefficient matrix 
+   initialize DCT coefficient matrix
 -----------------------------------------------------------------------------*/
     unsigned int freq;
 
@@ -1258,7 +1261,7 @@ int16 *block;
       tmp[8*i+j] = partial_product;
     }
 
-  /* Transpose operation is integrated into address mapping by switching 
+  /* Transpose operation is integrated into address mapping by switching
      loop order of i and j */
 
   for (j=0; j<8; j++)
@@ -1273,3 +1276,6 @@ int16 *block;
       block[8*i+j] = (v<-256) ? -256 : ((v>255) ? 255 : v);
     }
 }
+
+
+
diff --git a/converter/ppm/ppmtompeg/memory.c b/converter/ppm/ppmtompeg/memory.c
index f117994a..8c272707 100644
--- a/converter/ppm/ppmtompeg/memory.c
+++ b/converter/ppm/ppmtompeg/memory.c
@@ -44,28 +44,35 @@
  *
  */
 
-long	totalMemory = 0;
-long	maxMemory = 0;
+long    totalMemory = 0;
+long    maxMemory = 0;
 
 
-char	*MemAlloc(size_t size)
+char    *MemAlloc(size_t size)
 {
     totalMemory += (long)size;
     if ( totalMemory > maxMemory )
     {
-	maxMemory = totalMemory;
+        maxMemory = totalMemory;
     }
 
     return malloc(size);
 }
 
-void	MemFree(char *ptr, long bytes)
+
+
+void    MemFree(char *ptr, long bytes)
 {
     totalMemory -= bytes;
     free(ptr);
 }
 
-void	PrintMaxMemory(void)
+
+
+void    PrintMaxMemory(void)
 {
     fprintf(stdout, "MMMMM-----MAX MEMORY-----MMMMM = %ld\n", maxMemory);
 }
+
+
+
diff --git a/converter/ppm/ppmtompeg/mfwddct.c b/converter/ppm/ppmtompeg/mfwddct.c
index 9381e51c..1355ef91 100644
--- a/converter/ppm/ppmtompeg/mfwddct.c
+++ b/converter/ppm/ppmtompeg/mfwddct.c
@@ -1,4 +1,3 @@
-
 /*
  * mfwddct.c (derived from jfwddct.c, which carries the following info)
  *
@@ -51,10 +50,10 @@
 #ifdef EIGHT_BIT_SAMPLES
 #define LG2_DCT_SCALE 16
 #else
-#define LG2_DCT_SCALE 15	/* lose a little precision to avoid overflow */
+#define LG2_DCT_SCALE 15        /* lose a little precision to avoid overflow */
 #endif
 
-#define ONE	((int32) 1)
+#define ONE     ((int32) 1)
 
 #define DCT_SCALE (ONE << LG2_DCT_SCALE)
 
@@ -66,7 +65,7 @@
 #define OVERSHIFT(x)  ((x) <<= LG2_OVERSCALE)
 
 /* Scale a fractional constant by DCT_SCALE */
-#define FIX(x)	((int32) ((x) * DCT_SCALE + 0.5))
+#define FIX(x)  ((int32) ((x) * DCT_SCALE + 0.5))
 
 /* Scale a fractional constant by DCT_SCALE/OVERSCALE */
 /* Such a constant can be multiplied with an overscaled input */
@@ -81,7 +80,7 @@
 
 /* Take a value scaled by DCT_SCALE and round to integer scaled by OVERSCALE */
 #define UNFIXO(x)  RIGHT_SHIFT((x) + (ONE << (LG2_DCT_SCALE-1-LG2_OVERSCALE)),\
-			       LG2_DCT_SCALE-LG2_OVERSCALE)
+                               LG2_DCT_SCALE-LG2_OVERSCALE)
 
 /* Here are the constants we need */
 /* SIN_i_j is sine of i*pi/j, scaled by DCT_SCALE */
@@ -162,11 +161,11 @@ Block block, dest;
         s += trans_coef[i][k] * tmp[8*k+j];
 
       if (collect_quant) {
-	fprintf(collect_quant_fp, "%d %f\n", 8*i+j, s);
-      } 
+        fprintf(collect_quant_fp, "%d %f\n", 8*i+j, s);
+      }
       if (DoLaplace) {
-	L1[LaplaceCnum][i*8+j] += s*s;
-	L2[LaplaceCnum][i*8+j] += s;
+        L1[LaplaceCnum][i*8+j] += s*s;
+        L2[LaplaceCnum][i*8+j] += s;
       }
 
 
@@ -206,8 +205,8 @@ mp_fwd_dct_fast(data2d, dest2d)
  */
 
 {
-    int16 *data = (int16 *) data2d;	/* this algorithm wants
-					 * a 1-d array */
+    int16 *data = (int16 *) data2d;     /* this algorithm wants
+                                         * a 1-d array */
     int16 *dest = (int16 *) dest2d;
     int pass, rowctr;
     register int16 *inptr, *outptr;
@@ -216,15 +215,15 @@ mp_fwd_dct_fast(data2d, dest2d)
 
 #ifdef ndef
     {
-	int y;
-
-	printf("fwd_dct (beforehand):\n");
-	for (y = 0; y < 8; y++)
-	    printf("%4d %4d %4d %4d %4d %4d %4d %4d\n",
-		   data2d[y][0], data2d[y][1],
-		   data2d[y][2], data2d[y][3],
-		   data2d[y][4], data2d[y][5],
-		   data2d[y][6], data2d[y][7]);
+        int y;
+
+        printf("fwd_dct (beforehand):\n");
+        for (y = 0; y < 8; y++)
+            printf("%4d %4d %4d %4d %4d %4d %4d %4d\n",
+                   data2d[y][0], data2d[y][1],
+                   data2d[y][2], data2d[y][3],
+                   data2d[y][4], data2d[y][5],
+                   data2d[y][6], data2d[y][7]);
     }
 #endif
 
@@ -238,95 +237,96 @@ mp_fwd_dct_fast(data2d, dest2d)
      * array indexing.
      */
 
-    inptr = data;		/* initialize pointers for first pass */
+    inptr = data;               /* initialize pointers for first pass */
     outptr = workspace;
     for (pass = 1; pass >= 0; pass--) {
-	for (rowctr = DCTSIZE - 1; rowctr >= 0; rowctr--) {
-	    /*
-	     * many tmps have nonoverlapping lifetime -- flashy
-	     * register colorers should be able to do this lot
-	     * very well
-	     */
-	    int32 tmp0, tmp1, tmp2, tmp3, tmp4, tmp5, tmp6, tmp7;
-	    int32 tmp10, tmp11, tmp12, tmp13;
-	    int32 tmp14, tmp15, tmp16, tmp17;
-	    int32 tmp25, tmp26;
-	    /* SHIFT_TEMPS */
-
-	    /* temp0 through tmp7:  -512 to +512 */
-	    /* if I-block, then -256 to +256 */
-	    tmp0 = inptr[7] + inptr[0];
-	    tmp1 = inptr[6] + inptr[1];
-	    tmp2 = inptr[5] + inptr[2];
-	    tmp3 = inptr[4] + inptr[3];
-	    tmp4 = inptr[3] - inptr[4];
-	    tmp5 = inptr[2] - inptr[5];
-	    tmp6 = inptr[1] - inptr[6];
-	    tmp7 = inptr[0] - inptr[7];
-
-	    /* tmp10 through tmp13:  -1024 to +1024 */
-	    /* if I-block, then -512 to +512 */
-	    tmp10 = tmp3 + tmp0;
-	    tmp11 = tmp2 + tmp1;
-	    tmp12 = tmp1 - tmp2;
-	    tmp13 = tmp0 - tmp3;
-
-	    outptr[0] = (int16) UNFIXH((tmp10 + tmp11) * SIN_1_4);
-	    outptr[DCTSIZE * 4] =
+        for (rowctr = DCTSIZE - 1; rowctr >= 0; rowctr--) {
+            /*
+             * many tmps have nonoverlapping lifetime -- flashy
+             * register colorers should be able to do this lot
+             * very well
+             */
+            int32 tmp0, tmp1, tmp2, tmp3, tmp4, tmp5, tmp6, tmp7;
+            int32 tmp10, tmp11, tmp12, tmp13;
+            int32 tmp14, tmp15, tmp16, tmp17;
+            int32 tmp25, tmp26;
+            /* SHIFT_TEMPS */
+
+            /* temp0 through tmp7:  -512 to +512 */
+            /* if I-block, then -256 to +256 */
+            tmp0 = inptr[7] + inptr[0];
+            tmp1 = inptr[6] + inptr[1];
+            tmp2 = inptr[5] + inptr[2];
+            tmp3 = inptr[4] + inptr[3];
+            tmp4 = inptr[3] - inptr[4];
+            tmp5 = inptr[2] - inptr[5];
+            tmp6 = inptr[1] - inptr[6];
+            tmp7 = inptr[0] - inptr[7];
+
+            /* tmp10 through tmp13:  -1024 to +1024 */
+            /* if I-block, then -512 to +512 */
+            tmp10 = tmp3 + tmp0;
+            tmp11 = tmp2 + tmp1;
+            tmp12 = tmp1 - tmp2;
+            tmp13 = tmp0 - tmp3;
+
+            outptr[0] = (int16) UNFIXH((tmp10 + tmp11) * SIN_1_4);
+            outptr[DCTSIZE * 4] =
             (int16) UNFIXH((tmp10 - tmp11) * COS_1_4);
-	    outptr[DCTSIZE * 2] =
+            outptr[DCTSIZE * 2] =
             (int16) UNFIXH(tmp13 * COS_1_8 + tmp12 * SIN_1_8);
-	    outptr[DCTSIZE * 6] =
+            outptr[DCTSIZE * 6] =
             (int16) UNFIXH(tmp13 * SIN_1_8 - tmp12 * COS_1_8);
 
-	    tmp16 = UNFIXO((tmp6 + tmp5) * SIN_1_4);
-	    tmp15 = UNFIXO((tmp6 - tmp5) * COS_1_4);
+            tmp16 = UNFIXO((tmp6 + tmp5) * SIN_1_4);
+            tmp15 = UNFIXO((tmp6 - tmp5) * COS_1_4);
 
-	    OVERSHIFT(tmp4);
-	    OVERSHIFT(tmp7);
+            OVERSHIFT(tmp4);
+            OVERSHIFT(tmp7);
 
-	    /*
-	     * tmp4, tmp7, tmp15, tmp16 are overscaled by
-	     * OVERSCALE
-	     */
+            /*
+             * tmp4, tmp7, tmp15, tmp16 are overscaled by
+             * OVERSCALE
+             */
 
-	    tmp14 = tmp4 + tmp15;
-	    tmp25 = tmp4 - tmp15;
-	    tmp26 = tmp7 - tmp16;
-	    tmp17 = tmp7 + tmp16;
+            tmp14 = tmp4 + tmp15;
+            tmp25 = tmp4 - tmp15;
+            tmp26 = tmp7 - tmp16;
+            tmp17 = tmp7 + tmp16;
 
-	    outptr[DCTSIZE] =
+            outptr[DCTSIZE] =
             (int16) UNFIXH(tmp17 * OCOS_1_16 + tmp14 * OSIN_1_16);
-	    outptr[DCTSIZE * 7] =
+            outptr[DCTSIZE * 7] =
             (int16) UNFIXH(tmp17 * OCOS_7_16 - tmp14 * OSIN_7_16);
-	    outptr[DCTSIZE * 5] =
+            outptr[DCTSIZE * 5] =
             (int16) UNFIXH(tmp26 * OCOS_5_16 + tmp25 * OSIN_5_16);
-	    outptr[DCTSIZE * 3] =
+            outptr[DCTSIZE * 3] =
             (int16) UNFIXH(tmp26 * OCOS_3_16 - tmp25 * OSIN_3_16);
 
-	    inptr += DCTSIZE;	/* advance inptr to next row */
-	    outptr++;		/* advance outptr to next column */
-	}
-	/* end of pass; in case it was pass 1, set up for pass 2 */
-	inptr = workspace;
-	outptr = dest;
+            inptr += DCTSIZE;   /* advance inptr to next row */
+            outptr++;           /* advance outptr to next column */
+        }
+        /* end of pass; in case it was pass 1, set up for pass 2 */
+        inptr = workspace;
+        outptr = dest;
     }
 #ifdef ndef
     {
-	int y;
-
-	printf("fwd_dct (afterward):\n");
-	for (y = 0; y < 8; y++)
-	    printf("%4d %4d %4d %4d %4d %4d %4d %4d\n",
-		   dest2d[y][0], dest2d[y][1],
-		   dest2d[y][2], dest2d[y][3],
-		   dest2d[y][4], dest2d[y][5],
-		   dest2d[y][6], dest2d[y][7]);
+        int y;
+
+        printf("fwd_dct (afterward):\n");
+        for (y = 0; y < 8; y++)
+            printf("%4d %4d %4d %4d %4d %4d %4d %4d\n",
+                   dest2d[y][0], dest2d[y][1],
+                   dest2d[y][2], dest2d[y][3],
+                   dest2d[y][4], dest2d[y][5],
+                   dest2d[y][6], dest2d[y][7]);
     }
 #endif
 }
 
 
+
 extern boolean pureDCT;
 void
 mp_fwd_dct_block2(data, dest)
@@ -349,6 +349,8 @@ mp_fwd_dct_block2(data, dest)
   else mp_fwd_dct_fast(data, dest);
 }
 
+
+
 /* Modifies from the MPEG2 verification coder */
 /* fdctref.c, forward discrete cosine transform, double precision           */
 
diff --git a/converter/ppm/ppmtompeg/mheaders.c b/converter/ppm/ppmtompeg/mheaders.c
index 98e1b063..54dada83 100644
--- a/converter/ppm/ppmtompeg/mheaders.c
+++ b/converter/ppm/ppmtompeg/mheaders.c
@@ -1,17 +1,17 @@
 /*===========================================================================*
- * mheaders.c								     *
- *									     *
- *	Procedures to generate MPEG headers				     *
- *									     *
- * EXPORTED PROCEDURES:							     *
- *	Mhead_GenPictureHeader						     *
- *	Mhead_GenSequenceHeader						     *
- *	Mhead_GenSequenceEnder						     *
- *	Mhead_GenGOPHeader						     *
- *	Mhead_GenSliceHeader						     *
- *	Mhead_GenSliceEnder						     *
- *	Mhead_GenMBHeader						     *
- *									     *
+ * mheaders.c                                                                *
+ *                                                                           *
+ *      Procedures to generate MPEG headers                                  *
+ *                                                                           *
+ * EXPORTED PROCEDURES:                                                      *
+ *      Mhead_GenPictureHeader                                               *
+ *      Mhead_GenSequenceHeader                                              *
+ *      Mhead_GenSequenceEnder                                               *
+ *      Mhead_GenGOPHeader                                                   *
+ *      Mhead_GenSliceHeader                                                 *
+ *      Mhead_GenSliceEnder                                                  *
+ *      Mhead_GenMBHeader                                                    *
+ *                                                                           *
  *===========================================================================*/
 
 /*
@@ -254,7 +254,7 @@ static uint32 mbPatTable[][2] = {
     {0x4, 8},
     {0x4, 9},
     {0x7, 3},
-    {0xa, 5},	/* grrr... 61, 62, 63 added - Kevin */
+    {0xa, 5},   /* grrr... 61, 62, 63 added - Kevin */
     {0x8, 5},
     {0xc, 6}
 };
@@ -270,9 +270,9 @@ static uint32 mbPatTable[][2] = {
 #define PICT_START_CODE 0x00000100
 #define SLICE_BASE_CODE 0x00000100
 
-#define SEQ_END_CODE	0x000001b7
+#define SEQ_END_CODE    0x000001b7
 
-/* not static anymore because information is used for computing frame rate 
+/* not static anymore because information is used for computing frame rate
  * and for statistics */
 const double VidRateNum[9]={1.0, 23.976, 24.0, 25.0, 29.97, 30.0,
                              50.0 ,59.94, 60.0};
@@ -286,10 +286,10 @@ const double VidRateNum[9]={1.0, 23.976, 24.0, 25.0, 29.97, 30.0,
  *
  * GenMBType
  *
- *	generate macroblock type with given attributes
- *	append result to the specified bitstream
+ *      generate macroblock type with given attributes
+ *      append result to the specified bitstream
  *
- * RETURNS:	nothing
+ * RETURNS:     nothing
  *
  * SIDE EFFECTS:    none
  *
@@ -429,14 +429,15 @@ GenMBType(bbPtr, pict_code_type, mb_quant, motion_forw, motion_back,
 }
 
 
+
 /*===========================================================================*
  *
  * GenMotionCode
  *
- *	generate motion vector output with given value
- *	append result to the specified bitstream
+ *      generate motion vector output with given value
+ *      append result to the specified bitstream
  *
- * RETURNS:	nothing
+ * RETURNS:     nothing
  *
  * SIDE EFFECTS:    none
  *
@@ -459,14 +460,15 @@ GenMotionCode(BitBucket * const bbPtr,
 }
 
 
+
 /*===========================================================================*
  *
  * GenBlockPattern
  *
- *	generate macroblock pattern output
- *	append result to the specified bitstream
+ *      generate macroblock pattern output
+ *      append result to the specified bitstream
  *
- * RETURNS:	nothing
+ * RETURNS:     nothing
  *
  * SIDE EFFECTS:    none
  *
@@ -485,14 +487,15 @@ GenBlockPattern(bbPtr, mb_pattern)
 }
 
 
+
 /*===========================================================================*
  *
  * GenMBAddrIncr
  *
- *	generate macroblock address increment output
- *	append result to the specified bitstream
+ *      generate macroblock address increment output
+ *      append result to the specified bitstream
  *
- * RETURNS:	nothing
+ * RETURNS:     nothing
  *
  * SIDE EFFECTS:    none
  *
@@ -512,14 +515,15 @@ GenMBAddrIncr(bbPtr, addr_incr)
 }
 
 
+
 /*===========================================================================*
  *
  * GenPictHead
  *
- *	generate picture header with given attributes
- *	append result to the specified bitstream
+ *      generate picture header with given attributes
+ *      append result to the specified bitstream
  *
- * RETURNS:	nothing
+ * RETURNS:     nothing
  *
  * SIDE EFFECTS:    none
  *
@@ -557,7 +561,7 @@ GenPictHead(bbPtr, temp_ref, code_type, vbv_delay, full_pel_forw_flag,
     Bitio_Write(bbPtr, code_type, 3);
 
     /* vbv_delay. */
-    vbv_delay = 0xffff;		    /* see page 36 (section 2.4.3.4) */
+    vbv_delay = 0xffff;             /* see page 36 (section 2.4.3.4) */
     Bitio_Write(bbPtr, vbv_delay, 16);
 
     if ((code_type == 2) || (code_type == 3)) {
@@ -624,6 +628,7 @@ GenPictHead(bbPtr, temp_ref, code_type, vbv_delay, full_pel_forw_flag,
 }
 
 
+
 /*=====================*
  * EXPORTED PROCEDURES *
  *=====================*/
@@ -633,9 +638,9 @@ GenPictHead(bbPtr, temp_ref, code_type, vbv_delay, full_pel_forw_flag,
  *
  * SetGOPStartTime
  *
- *	sets the start frame of the GOP; to be used with GenPictureHeader
+ *      sets the start frame of the GOP; to be used with GenPictureHeader
  *
- * RETURNS:	nothing
+ * RETURNS:     nothing
  *
  * SIDE EFFECTS:    none
  *
@@ -649,14 +654,15 @@ SetGOPStartTime(index)
 }
 
 
+
 /*===========================================================================*
  *
  * Mhead_GenPictureHeader
  *
- *	generate picture header with given frame type and picture count
- *	append result to the specified bitstream
+ *      generate picture header with given frame type and picture count
+ *      append result to the specified bitstream
  *
- * RETURNS:	nothing
+ * RETURNS:     nothing
  *
  * SIDE EFFECTS:    none
  *
@@ -668,51 +674,52 @@ Mhead_GenPictureHeader(bbPtr, frameType, pictCount, f_code)
     int pictCount;
     int f_code;
 {
-    int	    temporalRef;
+    int     temporalRef;
 
     if ( pictCount >= gopStartFrame ) {
-	temporalRef = (pictCount-gopStartFrame);
+        temporalRef = (pictCount-gopStartFrame);
     } else {
-	temporalRef = (pictCount-lastGOPStart);
+        temporalRef = (pictCount-lastGOPStart);
     }
     temporalRef = (temporalRef % 1024);
-	
+
     DBG_PRINT(("Picture Header\n"));
     GenPictHead(bbPtr, temporalRef, frameType,
-		0 /* vbv_delay */,
-		pixelFullSearch /* full_pel_forw_flag */,
-		f_code /* forw_f_code */,
-		pixelFullSearch /* full_pel_back_flag */,
-		f_code /* back_f_code */,
-		NULL, 0, NULL, 0, NULL, 0);
+                0 /* vbv_delay */,
+                pixelFullSearch /* full_pel_forw_flag */,
+                f_code /* forw_f_code */,
+                pixelFullSearch /* full_pel_back_flag */,
+                f_code /* back_f_code */,
+                NULL, 0, NULL, 0, NULL, 0);
 }
 
 
+
 /*===========================================================================*
  *
  * Mhead_GenSequenceHeader
  *
- *	generate sequence header with given attributes
- *	append result to the specified bitstream
+ *      generate sequence header with given attributes
+ *      append result to the specified bitstream
  *
- * RETURNS:	nothing
+ * RETURNS:     nothing
  *
  * SIDE EFFECTS:    none
  *
  *===========================================================================*/
 void
-Mhead_GenSequenceHeader(BitBucket *   const bbPtr, 
-                        uint32        const hsize, 
+Mhead_GenSequenceHeader(BitBucket *   const bbPtr,
+                        uint32        const hsize,
                         uint32        const vsize,
-                        int32         const pratio, 
-                        int32         const pict_rate, 
+                        int32         const pratio,
+                        int32         const pict_rate,
                         int32         const bit_rate_arg,
-                        int32         const buf_size_arg, 
-                        int32         const c_param_flag_arg, 
-                        const int32 * const iq_matrix, 
+                        int32         const buf_size_arg,
+                        int32         const c_param_flag_arg,
+                        const int32 * const iq_matrix,
                         const int32 * const niq_matrix,
-                        uint8 *       const ext_data, 
-                        int32         const ext_data_size, 
+                        uint8 *       const ext_data,
+                        int32         const ext_data_size,
                         uint8 *       const user_data,
                         int32         const user_data_size) {
 
@@ -774,7 +781,7 @@ Mhead_GenSequenceHeader(BitBucket *   const bbPtr,
         buf_size = buf_size_arg;
 
     buf_size = (buf_size + (16*1024 - 1)) / (16*1024);
-    if (buf_size>=0x400) 
+    if (buf_size>=0x400)
         buf_size=0x3ff;
     Bitio_Write(bbPtr, buf_size, 10);
 
@@ -849,14 +856,15 @@ Mhead_GenSequenceHeader(BitBucket *   const bbPtr,
 }
 
 
+
 /*===========================================================================*
  *
  * Mhead_GenSequenceEnder
  *
- *	generate sequence ender
- *	append result to the specified bitstream
+ *      generate sequence ender
+ *      append result to the specified bitstream
  *
- * RETURNS:	nothing
+ * RETURNS:     nothing
  *
  * SIDE EFFECTS:    none
  *
@@ -869,22 +877,23 @@ Mhead_GenSequenceEnder(bbPtr)
 }
 
 
+
 /*===========================================================================*
  *
  * Mhead_GenGOPHeader
  *
- *	generate GOP header with specified attributes
- *	append result to the specified bitstream
+ *      generate GOP header with specified attributes
+ *      append result to the specified bitstream
  *
- * RETURNS:	nothing
+ * RETURNS:     nothing
  *
  * SIDE EFFECTS:    none
  *
  *===========================================================================*/
 void
 Mhead_GenGOPHeader(bbPtr, drop_frame_flag, tc_hrs, tc_min, tc_sec, tc_pict,
-		   closed_gop, broken_link, ext_data, ext_data_size,
-		   user_data, user_data_size)
+                   closed_gop, broken_link, ext_data, ext_data_size,
+                   user_data, user_data_size)
     BitBucket *bbPtr;
     int32 drop_frame_flag;
     int32 tc_hrs;
@@ -903,13 +912,13 @@ Mhead_GenGOPHeader(bbPtr, drop_frame_flag, tc_hrs, tc_min, tc_sec, tc_pict,
     /* Write gop start code. */
     Bitio_Write(bbPtr, GOP_START_CODE, 32);
 
-		/* Construct and write timecode. */
+                /* Construct and write timecode. */
 
     /* Drop frame flag. */
     if (drop_frame_flag) {
-	Bitio_Write(bbPtr, 0x01, 1);
+        Bitio_Write(bbPtr, 0x01, 1);
     } else {
-	Bitio_Write(bbPtr, 0x00, 1);
+        Bitio_Write(bbPtr, 0x00, 1);
     }
 
     /* Time code hours. */
@@ -930,16 +939,16 @@ Mhead_GenGOPHeader(bbPtr, drop_frame_flag, tc_hrs, tc_min, tc_sec, tc_pict,
 
     /* Closed gop flag. */
     if (closed_gop) {
-	Bitio_Write(bbPtr, 0x01, 1);
+        Bitio_Write(bbPtr, 0x01, 1);
     } else {
-	Bitio_Write(bbPtr, 0x00, 1);
+        Bitio_Write(bbPtr, 0x00, 1);
     }
 
     /* Broken link flag. */
     if (broken_link) {
-	Bitio_Write(bbPtr, 0x01, 1);
+        Bitio_Write(bbPtr, 0x01, 1);
     } else {
-	Bitio_Write(bbPtr, 0x00, 1);
+        Bitio_Write(bbPtr, 0x00, 1);
     }
 
     /* next start code */
@@ -948,33 +957,34 @@ Mhead_GenGOPHeader(bbPtr, drop_frame_flag, tc_hrs, tc_min, tc_sec, tc_pict,
     /* Write ext data if present. */
 
     if (ext_data != NULL) {
-	Bitio_Write(bbPtr, EXT_START_CODE, 32);
+        Bitio_Write(bbPtr, EXT_START_CODE, 32);
 
-	for (i = 0; i < ext_data_size; i++) {
-	    Bitio_Write(bbPtr, ext_data[i], 8);
-	}
-	Bitio_BytePad(bbPtr);
+        for (i = 0; i < ext_data_size; i++) {
+            Bitio_Write(bbPtr, ext_data[i], 8);
+        }
+        Bitio_BytePad(bbPtr);
     }
     /* Write user data if present. */
     if (user_data != NULL) {
-	Bitio_Write(bbPtr, USER_START_CODE, 32);
+        Bitio_Write(bbPtr, USER_START_CODE, 32);
 
-	for (i = 0; i < user_data_size; i++) {
-	    Bitio_Write(bbPtr, user_data[i], 8);
-	}
-	Bitio_BytePad(bbPtr);
+        for (i = 0; i < user_data_size; i++) {
+            Bitio_Write(bbPtr, user_data[i], 8);
+        }
+        Bitio_BytePad(bbPtr);
     }
 }
 
 
+
 /*===========================================================================*
  *
  * Mhead_GenSliceHeader
  *
- *	generate slice header with specified attributes
- *	append result to the specified bitstream
+ *      generate slice header with specified attributes
+ *      append result to the specified bitstream
  *
- * RETURNS:	nothing
+ * RETURNS:     nothing
  *
  * SIDE EFFECTS:    none
  *
@@ -999,10 +1009,10 @@ Mhead_GenSliceHeader(bbPtr, verticalPos, qscale, extra_info, extra_info_size)
     /* Extra bit slice info. */
 
     if (extra_info != NULL) {
-	for (i = 0; i < extra_info_size; i++) {
-	    Bitio_Write(bbPtr, 0x01, 1);
-	    Bitio_Write(bbPtr, extra_info[i], 8);
-	}
+        for (i = 0; i < extra_info_size; i++) {
+            Bitio_Write(bbPtr, 0x01, 1);
+            Bitio_Write(bbPtr, extra_info[i], 8);
+        }
     }
 
     /* extra_bit_slice */
@@ -1010,14 +1020,15 @@ Mhead_GenSliceHeader(bbPtr, verticalPos, qscale, extra_info, extra_info_size)
 }
 
 
+
 /*===========================================================================*
  *
  * Mhead_GenSliceEnder
  *
- *	generate slice ender
- *	append result to the specified bitstream
+ *      generate slice ender
+ *      append result to the specified bitstream
  *
- * RETURNS:	nothing
+ * RETURNS:     nothing
  *
  * SIDE EFFECTS:    none
  *
@@ -1030,24 +1041,25 @@ Mhead_GenSliceEnder(bbPtr)
 }
 
 
+
 /*===========================================================================*
  *
  * Mhead_GenMBHeader
  *
- *	generate macroblock header with given attributes
- *	append result to the specified bitstream
+ *      generate macroblock header with given attributes
+ *      append result to the specified bitstream
  *
- * RETURNS:	nothing
+ * RETURNS:     nothing
  *
  * SIDE EFFECTS:    none
  *
  *===========================================================================*/
 void
 Mhead_GenMBHeader(bbPtr, pict_code_type, addr_incr, q_scale,
-		  forw_f_code, back_f_code, horiz_forw_r, vert_forw_r,
-		  horiz_back_r, vert_back_r, motion_forw, m_horiz_forw,
-		  m_vert_forw, motion_back, m_horiz_back, m_vert_back,
-		  mb_pattern, mb_intra)
+                  forw_f_code, back_f_code, horiz_forw_r, vert_forw_r,
+                  horiz_back_r, vert_back_r, motion_forw, m_horiz_forw,
+                  m_vert_forw, motion_back, m_horiz_back, m_vert_back,
+                  mb_pattern, mb_intra)
     BitBucket *bbPtr;
     uint32 pict_code_type;
     uint32 addr_incr;
@@ -1077,8 +1089,8 @@ if ( addr_incr != 1 )
 #endif
 
     while (addr_incr > 33) {
-	Bitio_Write(bbPtr, 0x008, 11);
-	addr_incr -= 33;
+        Bitio_Write(bbPtr, 0x008, 11);
+        addr_incr -= 33;
     }
 
     /* Generate addr incr code. */
@@ -1098,66 +1110,67 @@ if ( addr_incr != 1 )
 
     /* MB quant. */
     if (mb_quant) {
-	Bitio_Write(bbPtr, q_scale, 5);
+        Bitio_Write(bbPtr, q_scale, 5);
     }
     /* Forward predictive vector stuff. */
 
     if (motion_forw) {
-	int forw_f, forw_r_size;
-
-	forw_r_size = forw_f_code - 1;
-	forw_f = 1 << forw_r_size;	/* 1 > 0 */
-	if ((m_horiz_forw > 16*forw_f-1) || (m_horiz_forw < -16*forw_f)) {
-	  fprintf(stderr, "Illegal motion? %d %d\n", m_horiz_forw, 16*forw_f);
-	}
-	if ((m_vert_forw > 16*forw_f-1) || (m_vert_forw < -16*forw_f)) {
-	  fprintf(stderr, "Illegal motion? %d %d\n", m_vert_forw, 16*forw_f);
-	}
-	GenMotionCode(bbPtr, m_horiz_forw);
-
-	if ((forw_f != 1) && (m_horiz_forw != 0)) {
-	    Bitio_Write(bbPtr, horiz_forw_r, forw_r_size);
-	}
-	GenMotionCode(bbPtr, m_vert_forw);
-
-	if ((forw_f != 1) && (m_vert_forw != 0)) {
-	    Bitio_Write(bbPtr, vert_forw_r, forw_r_size);
-	}
+        int forw_f, forw_r_size;
+
+        forw_r_size = forw_f_code - 1;
+        forw_f = 1 << forw_r_size;      /* 1 > 0 */
+        if ((m_horiz_forw > 16*forw_f-1) || (m_horiz_forw < -16*forw_f)) {
+          fprintf(stderr, "Illegal motion? %d %d\n", m_horiz_forw, 16*forw_f);
+        }
+        if ((m_vert_forw > 16*forw_f-1) || (m_vert_forw < -16*forw_f)) {
+          fprintf(stderr, "Illegal motion? %d %d\n", m_vert_forw, 16*forw_f);
+        }
+        GenMotionCode(bbPtr, m_horiz_forw);
+
+        if ((forw_f != 1) && (m_horiz_forw != 0)) {
+            Bitio_Write(bbPtr, horiz_forw_r, forw_r_size);
+        }
+        GenMotionCode(bbPtr, m_vert_forw);
+
+        if ((forw_f != 1) && (m_vert_forw != 0)) {
+            Bitio_Write(bbPtr, vert_forw_r, forw_r_size);
+        }
     }
     /* Back predicted vector stuff. */
 
     if (motion_back) {
-	int back_f, back_r_size;
+        int back_f, back_r_size;
 
-	back_r_size = back_f_code - 1;
-	back_f = 1 << back_r_size;	/* 1 > 0 */
+        back_r_size = back_f_code - 1;
+        back_f = 1 << back_r_size;      /* 1 > 0 */
 
-	if ((m_horiz_back > 16*back_f-1) || (m_horiz_back < -16*back_f)) {
-	  fprintf(stderr, "Illegal motion? %d %d\n", m_horiz_back, 16*back_f);
-	}
-	if ((m_vert_back > 16*back_f-1) || (m_vert_back < -16*back_f)) {
-	  fprintf(stderr, "Illegal motion? %d %d\n", m_vert_back, 16*back_f);
-	}
+        if ((m_horiz_back > 16*back_f-1) || (m_horiz_back < -16*back_f)) {
+          fprintf(stderr, "Illegal motion? %d %d\n", m_horiz_back, 16*back_f);
+        }
+        if ((m_vert_back > 16*back_f-1) || (m_vert_back < -16*back_f)) {
+          fprintf(stderr, "Illegal motion? %d %d\n", m_vert_back, 16*back_f);
+        }
 
-	GenMotionCode(bbPtr, m_horiz_back);
+        GenMotionCode(bbPtr, m_horiz_back);
 
-	if ((back_f != 1) && (m_horiz_back != 0)) {
-	    Bitio_Write(bbPtr, horiz_back_r, back_r_size);
-	}
-	GenMotionCode(bbPtr, m_vert_back);
+        if ((back_f != 1) && (m_horiz_back != 0)) {
+            Bitio_Write(bbPtr, horiz_back_r, back_r_size);
+        }
+        GenMotionCode(bbPtr, m_vert_back);
 
-	if ((back_f != 1) && (m_vert_back != 0)) {
-	    Bitio_Write(bbPtr, vert_back_r, back_r_size);
-	}
+        if ((back_f != 1) && (m_vert_back != 0)) {
+            Bitio_Write(bbPtr, vert_back_r, back_r_size);
+        }
     }
     /* MB pattern. */
 
     if (mb_pattern) {
-	GenBlockPattern(bbPtr, mb_pattern);
+        GenBlockPattern(bbPtr, mb_pattern);
     }
 }
 
 
+
 #ifdef UNUSED_PROCEDURES
 
 /* GenMBEnd only used for `D` pictures. Shouldn't really ever be called. */
@@ -1169,4 +1182,6 @@ GenMBEnd(bbPtr)
     Bitio_Write(bbPtr, 0x01, 1);
 }
 
+
+
 #endif /* UNUSED_PROCEDURES */
diff --git a/converter/ppm/ppmtompeg/moutput.c b/converter/ppm/ppmtompeg/moutput.c
index b682efab..bc7fb2b6 100644
--- a/converter/ppm/ppmtompeg/moutput.c
+++ b/converter/ppm/ppmtompeg/moutput.c
@@ -1,13 +1,13 @@
 /*===========================================================================*
- * moutput.c								     *
- *									     *
- *	Procedures concerned with quantization and RLE			     *
- *									     *
- * EXPORTED PROCEDURES:							     *
- *	mp_quant_zig_block						     *
- *	mp_rle_huff_block						     *
- *	mp_rle_huff_pblock						     *
- *									     *
+ * moutput.c                                                                 *
+ *                                                                           *
+ *      Procedures concerned with quantization and RLE                       *
+ *                                                                           *
+ * EXPORTED PROCEDURES:                                                      *
+ *      mp_quant_zig_block                                                   *
+ *      mp_rle_huff_block                                                    *
+ *      mp_rle_huff_pblock                                                   *
+ *                                                                           *
  *===========================================================================*/
 
 /*
@@ -121,52 +121,53 @@ static int qtable[] =
  *=====================*/
 
 
-void	UnQuantZig(FlatBlock in, Block out, int qscale, boolean iblock)
+void    UnQuantZig(FlatBlock in, Block out, int qscale, boolean iblock)
 {
     register int index;
-    int	    start;
-    int	    position;
-    register int	    qentry;
-    int	    level, coeff;
+    int     start;
+    int     position;
+    register int            qentry;
+    int     level, coeff;
     register int16 temp;
 
     if ( iblock )
     {
-	((int16 *)out)[0] = (int16)(in[0]*qtable[0]);
+        ((int16 *)out)[0] = (int16)(in[0]*qtable[0]);
 
-	start = 1;
+        start = 1;
     }
     else
-	start = 0;
+        start = 0;
 
     for ( index = start; index < DCTSIZE_SQ; index++ )
     {
-	position = ZAG[index];
+        position = ZAG[index];
 
-	if (iblock)
-	    qentry = qtable[position] * qscale;
-	else
-	    qentry = 16 * qscale;
+        if (iblock)
+            qentry = qtable[position] * qscale;
+        else
+            qentry = 16 * qscale;
 
-	level = in[index];
+        level = in[index];
         coeff = (level * qentry) >> 3;
         if (level < 0) {
             coeff += (coeff & 1);
-	} else {
+        } else {
             coeff -= (coeff & 1);
-	}
+        }
 
-	((int16 *)out)[position] = coeff;
+        ((int16 *)out)[position] = coeff;
     }
 
 #ifdef BLEAH
     for ( index = 0; index < 64; index++ )
-	fprintf(stdout, "DCT[%d] = %d\n", index, 
-		((int16 *)out)[index]);
+        fprintf(stdout, "DCT[%d] = %d\n", index,
+                ((int16 *)out)[index]);
 #endif
 }
 
 
+
 /*
  * --------------------------------------------------------------
  *
@@ -175,7 +176,7 @@ void	UnQuantZig(FlatBlock in, Block out, int qscale, boolean iblock)
  * Quantizes and zigzags a block -- removing information
  *
  * Results: TRUE iff resulting 'out' is non-zero, FALSE if all
- *	    zero
+ *          zero
  *
  * Side effects: Modifies the out block.
  *
@@ -192,56 +193,56 @@ boolean mp_quant_zig_block(Block in, FlatBlock out, int qscale, int iblock)
 
     DBG_PRINT(("mp_quant_zig_block...\n"));
     if (iblock) {
-	/*
-	 * the DC coefficient is handled specially -- it's not
-	 * sensitive to qscale, but everything else is
-	 */
-	temp = ((int16 *) in)[ZAG[0]];
-	qentry = qtable[ZAG[0]];
-	if (temp < 0) {
-	    temp = -temp;
-	    temp += qentry >> 1;
-	    temp /= qentry;
-	    temp = -temp;
-	} else {
-	    temp += qentry >> 1;
-	    temp /= qentry;
-	}
-	if ( temp != 0 )
-	    nonZero = TRUE;
-	out[0] = temp;
-	start = 1;
+        /*
+         * the DC coefficient is handled specially -- it's not
+         * sensitive to qscale, but everything else is
+         */
+        temp = ((int16 *) in)[ZAG[0]];
+        qentry = qtable[ZAG[0]];
+        if (temp < 0) {
+            temp = -temp;
+            temp += qentry >> 1;
+            temp /= qentry;
+            temp = -temp;
+        } else {
+            temp += qentry >> 1;
+            temp /= qentry;
+        }
+        if ( temp != 0 )
+            nonZero = TRUE;
+        out[0] = temp;
+        start = 1;
     } else
-	start = 0;
+        start = 0;
 
     for (i = start; i < DCTSIZE_SQ; i++) {
-	x = ZAG[i] % 8;
-	y = ZAG[i] / 8;
-	temp = in[y][x];
-	DBG_PRINT(("    in[%d][%d] = %d;  ", y, x, temp));
-
-	if (iblock)
-	    qentry = qtable[ZAG[i]] * qscale;
-	else
-	    qentry = 16 * qscale;
-
-	DBG_PRINT(("quantized with %d = ", qentry));
-
-	if (temp < 0) {
-	    temp = -temp;
-	    temp *= 8;
-	    temp += qentry >> 1;
-	    temp /= qentry;
-	    temp = -temp;
-	} else {
-	    temp *= 8;
-	    temp += qentry >> 1;
-	    temp /= qentry;
-	}
-	if ( temp != 0 )
-	    nonZero = TRUE;
-	out[i] = temp;
-	DBG_PRINT(("%d\n", temp));
+        x = ZAG[i] % 8;
+        y = ZAG[i] / 8;
+        temp = in[y][x];
+        DBG_PRINT(("    in[%d][%d] = %d;  ", y, x, temp));
+
+        if (iblock)
+            qentry = qtable[ZAG[i]] * qscale;
+        else
+            qentry = 16 * qscale;
+
+        DBG_PRINT(("quantized with %d = ", qentry));
+
+        if (temp < 0) {
+            temp = -temp;
+            temp *= 8;
+            temp += qentry >> 1;
+            temp /= qentry;
+            temp = -temp;
+        } else {
+            temp *= 8;
+            temp += qentry >> 1;
+            temp /= qentry;
+        }
+        if ( temp != 0 )
+            nonZero = TRUE;
+        out[i] = temp;
+        DBG_PRINT(("%d\n", temp));
     }
 
     return nonZero;
@@ -263,7 +264,7 @@ boolean mp_quant_zig_block(Block in, FlatBlock out, int qscale, int iblock)
  * --------------------------------------------------------------
  */
 
-void	mp_rle_huff_block(FlatBlock in, BitBucket *out)
+void    mp_rle_huff_block(FlatBlock in, BitBucket *out)
 {
     register int i;
     register int nzeros = 0;
@@ -277,64 +278,65 @@ void	mp_rle_huff_block(FlatBlock in, BitBucket *out)
      * specially, elsewhere.  Not here.
      */
     for (i = 1; i < DCTSIZE_SQ; i++) {
-	cur = in[i];
-	acur = ABS(cur);
-	if (cur) {
-	    if (nzeros < HUFF_MAXRUN && acur < huff_maxlevel[nzeros]) {
-	        /*
-		 * encode using the Huffman tables
-		 */
-
-		DBG_PRINT(("rle_huff %02d: Run %02d, Level %02d\n", i, nzeros, cur));
-		assert(cur);
-
-		code = (huff_table[nzeros])[acur];
-		nbits = (huff_bits[nzeros])[acur];
-
-		assert(nbits);
-
-		if (cur < 0)
-		    code |= 1;	/* the sign bit */
-		Bitio_Write(out, code, nbits);
-	    } else {
-		/*
-		 * encode using the escape code
-		 */
-		DBG_PRINT(("Escape\n"));
-		Bitio_Write(out, 0x1, 6);	/* ESCAPE */
-		DBG_PRINT(("Run Length\n"));
-		Bitio_Write(out, nzeros, 6);	/* Run-Length */
-
-		assert(cur != 0);
-
-		/*
-	         * this shouldn't happen, but the other
-	         * choice is to bomb out and dump core...
-	         */
-		if (cur < -255)
-		    cur = -255;
-		else if (cur > 255)
-		    cur = 255;
-
-		DBG_PRINT(("Level\n"));
-		if (acur < 128) {
-		    Bitio_Write(out, cur, 8);
-		} else {
-		    if (cur < 0) {
-			Bitio_Write(out, 0x8001 + cur + 255, 16);
-		    } else
-			Bitio_Write(out, cur, 16);
-		}
-	    }
-	    nzeros = 0;
-	} else
-	    nzeros++;
+        cur = in[i];
+        acur = ABS(cur);
+        if (cur) {
+            if (nzeros < HUFF_MAXRUN && acur < huff_maxlevel[nzeros]) {
+                /*
+                 * encode using the Huffman tables
+                 */
+
+                DBG_PRINT(("rle_huff %02d: Run %02d, Level %02d\n", i, nzeros, cur));
+                assert(cur);
+
+                code = (huff_table[nzeros])[acur];
+                nbits = (huff_bits[nzeros])[acur];
+
+                assert(nbits);
+
+                if (cur < 0)
+                    code |= 1;  /* the sign bit */
+                Bitio_Write(out, code, nbits);
+            } else {
+                /*
+                 * encode using the escape code
+                 */
+                DBG_PRINT(("Escape\n"));
+                Bitio_Write(out, 0x1, 6);       /* ESCAPE */
+                DBG_PRINT(("Run Length\n"));
+                Bitio_Write(out, nzeros, 6);    /* Run-Length */
+
+                assert(cur != 0);
+
+                /*
+                 * this shouldn't happen, but the other
+                 * choice is to bomb out and dump core...
+                 */
+                if (cur < -255)
+                    cur = -255;
+                else if (cur > 255)
+                    cur = 255;
+
+                DBG_PRINT(("Level\n"));
+                if (acur < 128) {
+                    Bitio_Write(out, cur, 8);
+                } else {
+                    if (cur < 0) {
+                        Bitio_Write(out, 0x8001 + cur + 255, 16);
+                    } else
+                        Bitio_Write(out, cur, 16);
+                }
+            }
+            nzeros = 0;
+        } else
+            nzeros++;
     }
     DBG_PRINT(("End of block\n"));
-    Bitio_Write(out, 0x2, 2);	/* end of block marker */
+    Bitio_Write(out, 0x2, 2);   /* end of block marker */
 }
 
 
+
 /*
  * --------------------------------------------------------------
  *
@@ -349,7 +351,7 @@ void	mp_rle_huff_block(FlatBlock in, BitBucket *out)
  * --------------------------------------------------------------
  */
 
-void	mp_rle_huff_pblock(FlatBlock in, BitBucket *out)
+void    mp_rle_huff_pblock(FlatBlock in, BitBucket *out)
 {
     register int i;
     register int nzeros = 0;
@@ -363,80 +365,83 @@ void	mp_rle_huff_pblock(FlatBlock in, BitBucket *out)
      * yes, Virginia, we start at 0.
      */
     for (i = 0; i < DCTSIZE_SQ; i++) {
-	cur = in[i];
-	acur = ABS(cur);
-	if (cur) {
-	    if (nzeros < HUFF_MAXRUN && acur < huff_maxlevel[nzeros]) {
-	        /*
-		 * encode using the Huffman tables
-		 */
-
-		DBG_PRINT(("rle_huff %02d: Run %02d, Level %02d\n", i, nzeros, cur));
-		assert(cur);
-
-		if ( first_dct && (nzeros == 0) && (acur == 1) )
-		{
-		    /* actually, only needs = 0x2 */
-		    code = (cur == 1) ? 0x2 : 0x3;
-		    nbits = 2;
-		}
-		else
-		{
-		    code = (huff_table[nzeros])[acur];
-		    nbits = (huff_bits[nzeros])[acur];
-		}
-
-		assert(nbits);
-
-		if (cur < 0)
-		    code |= 1;	/* the sign bit */
-		Bitio_Write(out, code, nbits);
-		first_dct = FALSE;
-	    } else {
-		/*
-		 * encode using the escape code
-		 */
-		DBG_PRINT(("Escape\n"));
-		Bitio_Write(out, 0x1, 6);	/* ESCAPE */
-		DBG_PRINT(("Run Length\n"));
-		Bitio_Write(out, nzeros, 6);	/* Run-Length */
-
-		assert(cur != 0);
-
-		/*
-	         * this shouldn't happen, but the other
-	         * choice is to bomb out and dump core...
-	         */
-		if (cur < -255)
-		    cur = -255;
-		else if (cur > 255)
-		    cur = 255;
-
-		DBG_PRINT(("Level\n"));
-		if (acur < 128) {
-		    Bitio_Write(out, cur, 8);
-		} else {
-		    if (cur < 0) {
-			Bitio_Write(out, 0x8001 + cur + 255, 16);
-		    } else
-			Bitio_Write(out, cur, 16);
-		}
-
-		first_dct = FALSE;
-	    }
-	    nzeros = 0;
-	} else
-	    nzeros++;
+        cur = in[i];
+        acur = ABS(cur);
+        if (cur) {
+            if (nzeros < HUFF_MAXRUN && acur < huff_maxlevel[nzeros]) {
+                /*
+                 * encode using the Huffman tables
+                 */
+
+                DBG_PRINT(("rle_huff %02d: Run %02d, Level %02d\n", i, nzeros, cur));
+                assert(cur);
+
+                if ( first_dct && (nzeros == 0) && (acur == 1) )
+                {
+                    /* actually, only needs = 0x2 */
+                    code = (cur == 1) ? 0x2 : 0x3;
+                    nbits = 2;
+                }
+                else
+                {
+                    code = (huff_table[nzeros])[acur];
+                    nbits = (huff_bits[nzeros])[acur];
+                }
+
+                assert(nbits);
+
+                if (cur < 0)
+                    code |= 1;  /* the sign bit */
+                Bitio_Write(out, code, nbits);
+                first_dct = FALSE;
+            } else {
+                /*
+                 * encode using the escape code
+                 */
+                DBG_PRINT(("Escape\n"));
+                Bitio_Write(out, 0x1, 6);       /* ESCAPE */
+                DBG_PRINT(("Run Length\n"));
+                Bitio_Write(out, nzeros, 6);    /* Run-Length */
+
+                assert(cur != 0);
+
+                /*
+                 * this shouldn't happen, but the other
+                 * choice is to bomb out and dump core...
+                 */
+                if (cur < -255)
+                    cur = -255;
+                else if (cur > 255)
+                    cur = 255;
+
+                DBG_PRINT(("Level\n"));
+                if (acur < 128) {
+                    Bitio_Write(out, cur, 8);
+                } else {
+                    if (cur < 0) {
+                        Bitio_Write(out, 0x8001 + cur + 255, 16);
+                    } else
+                        Bitio_Write(out, cur, 16);
+                }
+
+                first_dct = FALSE;
+            }
+            nzeros = 0;
+        } else
+            nzeros++;
     }
 
     /* actually, should REALLY return FALSE and not use this! */
-    if ( first_dct )	/* have to give a first_dct even if all 0's */
+    if ( first_dct )    /* have to give a first_dct even if all 0's */
     {
-	fprintf(stdout, "HUFF called with all-zero coefficients\n");
-	fprintf(stdout, "exiting...\n");
-	exit(1);
+        fprintf(stdout, "HUFF called with all-zero coefficients\n");
+        fprintf(stdout, "exiting...\n");
+        exit(1);
     }
 
     DBG_PRINT(("End of block\n"));
-    Bitio_Write(out, 0x2, 2);	/* end of block marker */
+    Bitio_Write(out, 0x2, 2);   /* end of block marker */
 }
+
+
+
diff --git a/converter/ppm/ppmtompeg/mpeg.c b/converter/ppm/ppmtompeg/mpeg.c
index e67eec1e..ff8c6035 100644
--- a/converter/ppm/ppmtompeg/mpeg.c
+++ b/converter/ppm/ppmtompeg/mpeg.c
@@ -285,7 +285,6 @@ SetBitRateFileName(const char * const fileName) {
 
 
 
-
 static void
 finishFrameOutput(MpegFrame * const frameP,
                   BitBucket * const bbP,
@@ -316,7 +315,6 @@ finishFrameOutput(MpegFrame * const frameP,
 
 
 
-
 static void
 outputIFrame(MpegFrame * const frameP,
              BitBucket * const bbP,
@@ -1241,6 +1239,7 @@ SetStatFileName(const char * const fileName) {
 }
 
 
+
 /*===========================================================================*
  *
  * SetGOPSize
@@ -1260,6 +1259,7 @@ SetGOPSize(size)
 }
 
 
+
 /*===========================================================================*
  *
  * PrintStartStats
@@ -1463,6 +1463,7 @@ SetFrameRate()
 }
 
 
+
 /*=====================*
  * INTERNAL PROCEDURES *
  *=====================*/
diff --git a/converter/ppm/ppmtompeg/mquant.c b/converter/ppm/ppmtompeg/mquant.c
index 1f8ca63a..0251a142 100644
--- a/converter/ppm/ppmtompeg/mquant.c
+++ b/converter/ppm/ppmtompeg/mquant.c
@@ -17,14 +17,14 @@ static int qtable[][8] = {
  *
  * mp_quant_block --
  *
- *	Quantizes a block -- removing information
- *	It's safe for out == in.
+ *      Quantizes a block -- removing information
+ *      It's safe for out == in.
  *
  * Results:
- *	None.
+ *      None.
  *
  * Side effects:
- *	Modifies the out block.
+ *      Modifies the out block.
  *
  *--------------------------------------------------------------
  */
@@ -32,13 +32,16 @@ void mp_quant_block(Block in, Block out) {
     int i;
 
     for(i=0;i<8;i++) {
-	out[i][0] = in[i][0] / qtable[i][0];
-	out[i][1] = in[i][1] / qtable[i][1];
-	out[i][2] = in[i][2] / qtable[i][2];
-	out[i][3] = in[i][3] / qtable[i][3];
-	out[i][4] = in[i][4] / qtable[i][4];
-	out[i][5] = in[i][5] / qtable[i][5];
-	out[i][6] = in[i][6] / qtable[i][6];
-	out[i][7] = in[i][7] / qtable[i][7];
+        out[i][0] = in[i][0] / qtable[i][0];
+        out[i][1] = in[i][1] / qtable[i][1];
+        out[i][2] = in[i][2] / qtable[i][2];
+        out[i][3] = in[i][3] / qtable[i][3];
+        out[i][4] = in[i][4] / qtable[i][4];
+        out[i][5] = in[i][5] / qtable[i][5];
+        out[i][6] = in[i][6] / qtable[i][6];
+        out[i][7] = in[i][7] / qtable[i][7];
     }
 }
+
+
+
diff --git a/converter/ppm/ppmtompeg/nojpeg.c b/converter/ppm/ppmtompeg/nojpeg.c
index 38c05a9e..dc1b222e 100644
--- a/converter/ppm/ppmtompeg/nojpeg.c
+++ b/converter/ppm/ppmtompeg/nojpeg.c
@@ -1,12 +1,12 @@
 /*===========================================================================*
- * nojpeg.c								     *
- *									     *
- *	procedures to deal with JPEG files				     *
- *									     *
- * EXPORTED PROCEDURES:							     *
- *	JMovie2JPEG							     *
- *      ReadJPEG							     *
- *									     *
+ * nojpeg.c                                                                  *
+ *                                                                           *
+ *      procedures to deal with JPEG files                                   *
+ *                                                                           *
+ * EXPORTED PROCEDURES:                                                      *
+ *      JMovie2JPEG                                                          *
+ *      ReadJPEG                                                             *
+ *                                                                           *
  *===========================================================================*/
 
 /*
@@ -52,6 +52,7 @@ JMovie2JPEG(const char * const infilename,
 }
 
 
+
 void
 ReadJPEG(MpegFrame * const mf,
          FILE *      const fp) {
@@ -59,3 +60,6 @@ ReadJPEG(MpegFrame * const mf,
     pm_error("This program has not been built with the "
              "ability to handle JPEG input files");
 }
+
+
+
diff --git a/converter/ppm/ppmtompeg/noparallel.c b/converter/ppm/ppmtompeg/noparallel.c
index 6e6449a4..d21f3e9a 100644
--- a/converter/ppm/ppmtompeg/noparallel.c
+++ b/converter/ppm/ppmtompeg/noparallel.c
@@ -70,7 +70,7 @@ time_t  IOtime = 0;
 
 void
 IoServer(struct inputSource * const inputSourceP,
-         const char *         const parallelHostName, 
+         const char *         const parallelHostName,
          int                  const portNum) {
 
     pm_error("This version of Ppmtompeg cannot run an I/O server because "
@@ -92,6 +92,7 @@ SetParallelPerfect(boolean const val) {
 }
 
 
+
 void
 SetRemoteShell(const char * const shell) {
     /* do nothing -- this may be called during non-parallel execution */
@@ -102,7 +103,7 @@ SetRemoteShell(const char * const shell) {
 void
 NoteFrameDone(int const frameStart,
               int const frameEnd) {
-    fprintf(stdout, 
+    fprintf(stdout,
             "ERROR:  (NoteFrameDone) "
             "This machine can NOT run parallel version\n");
     exit(1);
@@ -151,7 +152,7 @@ WaitForOutputFile(int const number) {
 
 void
 MasterServer(struct inputSource * const inputSourceP,
-             const char *         const paramFileName, 
+             const char *         const paramFileName,
              const char *         const outputFileName) {
 
     pm_error("This version of Ppmtompeg cannot run a master server because "
@@ -161,8 +162,8 @@ MasterServer(struct inputSource * const inputSourceP,
 
 
 void
-CombineServer(int          const numFrames, 
-              const char * const masterHostName, 
+CombineServer(int          const numFrames,
+              const char * const masterHostName,
               int          const masterPortNum,
               const char*  const outputFileName) {
 
@@ -173,9 +174,9 @@ CombineServer(int          const numFrames,
 
 
 void
-DecodeServer(int          const numInputFiles, 
-             const char * const decodeFileName, 
-             const char * const masterHostName, 
+DecodeServer(int          const numInputFiles,
+             const char * const decodeFileName,
+             const char * const masterHostName,
              int          const masterPortNum) {
 
     pm_error("This version of Ppmtompeg cannot run a decode server because "
@@ -185,9 +186,9 @@ DecodeServer(int          const numInputFiles,
 
 
 void
-NotifyMasterDone(const char * const hostName, 
-                 int          const portNum, 
-                 int          const machineNumber, 
+NotifyMasterDone(const char * const hostName,
+                 int          const portNum,
+                 int          const machineNumber,
                  unsigned int const seconds,
                  boolean *    const moreWorkToDoP,
                  int *        const frameStartP,
@@ -228,3 +229,6 @@ GetRemoteDecodedRefFrame(MpegFrame * const frame,
     pm_error("This version of Ppmtompeg cannot run parallel mode because "
              "it does not have socket capability.");
 }
+
+
+
diff --git a/converter/ppm/ppmtompeg/opts.c b/converter/ppm/ppmtompeg/opts.c
index 6f5f9816..9d750c54 100644
--- a/converter/ppm/ppmtompeg/opts.c
+++ b/converter/ppm/ppmtompeg/opts.c
@@ -157,7 +157,6 @@ SetupCollectQuantStats(const char * const charPtr)
 
 
 
-
 /*===========================================================================*
  *
  * SetupKillDimAreas
@@ -223,6 +222,7 @@ SetupSquashSmall(const char * const charPtr)
 }
 
 
+
 /*===========================================================================*
  *
  * SetupLocalDCT
@@ -254,6 +254,7 @@ SetupLocalDCT(const char * const charPtr)
 }
 
 
+
 /*===========================================================================*
  *
  * SetupLaplace
@@ -290,6 +291,8 @@ SetupLaplace()
   }
 }
 
+
+
 static void
 SetupWriteDistortions(const char * const charPtr)
 {
@@ -341,6 +344,8 @@ SetupWriteDistortions(const char * const charPtr)
     }}
 }
 
+
+
 /*=====================*
  * EXPORTED PROCEDURES *
  *=====================*/
@@ -361,6 +366,7 @@ CalcLambdas(void) {
 }
 
 
+
 /*===========================================================================*
  *
  * Mpost_UnQuantZigBlockLaplace
@@ -424,6 +430,8 @@ Mpost_UnQuantZigBlockLaplace(in, out, qscale, iblock)
     }
 }
 
+
+
 int
 mse(Block blk1, Block blk2)
 {
@@ -442,7 +450,6 @@ mse(Block blk1, Block blk2)
 
 
 
-
 /*===========================================================================*
  *
  * Tune_Init
@@ -489,6 +496,8 @@ void Tune_Init()
 
 }
 
+
+
 /*===========================================================================*
  *
  * ParseTuneParam
@@ -545,3 +554,4 @@ void ParseTuneParam(const char * const charPtr)
 }
 
 
+
diff --git a/converter/ppm/ppmtompeg/parallel.c b/converter/ppm/ppmtompeg/parallel.c
index 0fe635ed..fb0f2fe9 100644
--- a/converter/ppm/ppmtompeg/parallel.c
+++ b/converter/ppm/ppmtompeg/parallel.c
@@ -12,6 +12,7 @@
  * HEADER FILES *
  *==============*/
 
+#define _C99_SOURCE  /* Make sure snprintf() is in stdio.h */
 #define _XOPEN_SOURCE 500 /* Make sure stdio.h contains pclose() */
 /* _ALL_SOURCE is needed on AIX to make the C library include the
    socket services (e.g. define struct sockaddr)
@@ -323,6 +324,7 @@ static void
 }
 
 
+
 /*===========================================================================*
  *
  * NotifyDecodeServerReady
@@ -445,6 +447,7 @@ int id;
 }
 
 
+
 /*===========================================================================*
  *
  * SendDecodedFrame
@@ -483,6 +486,7 @@ SendDecodedFrame(MpegFrame * const frameP) {
 }
 
 
+
 /*===========================================================================*
  *
  * GetRemoteDecodedFrame
@@ -523,6 +527,7 @@ GetRemoteDecodedRefFrame(MpegFrame * const frameP,
 }
 
 
+
 /*********
   routines handling forks, execs, PIDs and signals
   save, system-style forks
@@ -558,6 +563,8 @@ static void cleanup_fork( dummy )       /* try to kill all child processes */
   }
 }
 
+
+
 /*===========================================================================*
  *
  * safe_fork
@@ -610,6 +617,7 @@ static int safe_fork(command)       /* fork child process and remember its PID *
 }
 
 
+
 /*=====================*
  * EXPORTED PROCEDURES *
  *=====================*/
@@ -637,6 +645,7 @@ SetIOConvert(boolean const separate) {
 }
 
 
+
 /*===========================================================================*
  *
  * SetParallelPerfect
@@ -656,6 +665,7 @@ SetParallelPerfect(boolean val)
 }
 
 
+
 /*===========================================================================*
  *
  * SetRemoteShell
@@ -674,6 +684,7 @@ SetRemoteShell(const char * const shell) {
 }
 
 
+
 static void
 decodedFrameToDisk(int const otherSock) {
 /*----------------------------------------------------------------------------
@@ -1145,6 +1156,7 @@ GetRemoteFrame(MpegFrame * const frameP,
 }
 
 
+
 struct combineControl {
     unsigned int numFrames;
 };
@@ -1322,6 +1334,7 @@ CombineServer(int          const numFrames,
 }
 
 
+
 /*=====================*
  * MASTER SERVER STUFF *
  *=====================*/
@@ -1341,12 +1354,12 @@ startCombineServer(const char * const encoderName,
     int          otherSock;
     const char * error;
 
-    pm_snprintf(command, sizeof(command),
-                "%s %s -max_machines %d -output_server %s %d %d %s",
-                encoderName,
-                debugMachines ? "-debug_machines" : "",
-                numMachines, masterHostName, masterPortNum,
-                numInputFiles, paramFileName);
+    snprintf(command, sizeof(command),
+             "%s %s -max_machines %d -output_server %s %d %d %s",
+             encoderName,
+             debugMachines ? "-debug_machines" : "",
+             numMachines, masterHostName, masterPortNum,
+             numInputFiles, paramFileName);
 
     machineDebug("MASTER: Starting combine server with shell command '%s'",
                  command);
@@ -1383,12 +1396,12 @@ startDecodeServer(const char * const encoderName,
     int          otherSock;
     const char * error;
 
-    pm_snprintf(command, sizeof(command),
-                "%s %s -max_machines %d -decode_server %s %d %d %s",
-                encoder_name,
-                debugMachines ? "-debug_machines" : "",
-                numMachines, masterHostName, masterPortNum,
-                numInputFiles, paramFileName);
+    snprintf(command, sizeof(command),
+             "%s %s -max_machines %d -decode_server %s %d %d %s",
+             encoder_name,
+             debugMachines ? "-debug_machines" : "",
+             numMachines, masterHostName, masterPortNum,
+             numInputFiles, paramFileName);
 
     machineDebug("MASTER: Starting decode server with shell command '%s'",
                  command);
@@ -1681,22 +1694,22 @@ startChildren(struct scheduler *   const schedulerP,
                 }
                 --childrenLeftCurrentIoServer;
             }
-            pm_snprintf(command, sizeof(command),
-                        "%s %s -l %s %s "
-                        "%s %s -child %s %d %d %d %d %d %d "
-                        "-frames %d %d %s",
-                        rsh,
-                        machineName[childNum], userName[childNum],
-                        beNice ? "nice" : "",
-                        executable[childNum],
-                        debugMachines ? "-debug_machines" : "",
-                        masterHostName, masterPortNum,
-                        remote[childNum] ? ioPortNum[numIoServers-1] : 0,
-                        combinePortNum, decodePortNum, childNum,
-                        remote[childNum] ? 1 : 0,
-                        startFrame, startFrame + nFrames - 1,
-                        remote[childNum] ?
-                          remoteParamFile[childNum] : paramFileName
+            snprintf(command, sizeof(command),
+                     "%s %s -l %s %s "
+                     "%s %s -child %s %d %d %d %d %d %d "
+                     "-frames %d %d %s",
+                     rsh,
+                     machineName[childNum], userName[childNum],
+                     beNice ? "nice" : "",
+                     executable[childNum],
+                     debugMachines ? "-debug_machines" : "",
+                     masterHostName, masterPortNum,
+                     remote[childNum] ? ioPortNum[numIoServers-1] : 0,
+                     combinePortNum, decodePortNum, childNum,
+                     remote[childNum] ? 1 : 0,
+                     startFrame, startFrame + nFrames - 1,
+                     remote[childNum] ?
+                     remoteParamFile[childNum] : paramFileName
                 );
 
             machineDebug("MASTER: Starting child server "
diff --git a/converter/ppm/ppmtompeg/param.c b/converter/ppm/ppmtompeg/param.c
index 9499b4ea..3408c6fc 100644
--- a/converter/ppm/ppmtompeg/param.c
+++ b/converter/ppm/ppmtompeg/param.c
@@ -241,6 +241,7 @@ ReadMachineNames(FILE * const fpointer)
 }
 
 
+
 /*===========================================================================*
  *
  * GetFrameRate
@@ -1044,6 +1045,7 @@ ReadParamFile(const char *         const fileName,
 }
 
 
+
 /*
  * Copyright (c) 1995 The Regents of the University of California.
  * All rights reserved.
diff --git a/converter/ppm/ppmtompeg/pframe.c b/converter/ppm/ppmtompeg/pframe.c
index de91e32c..89aab874 100644
--- a/converter/ppm/ppmtompeg/pframe.c
+++ b/converter/ppm/ppmtompeg/pframe.c
@@ -1,22 +1,22 @@
 /*===========================================================================*
- * pframe.c                                  
- *                                       
- *  Procedures concerned with generation of P-frames             
- *                                       
- * EXPORTED PROCEDURES:                              
- *  GenPFrame                                
- *  ResetPFrameStats                             
- *  ShowPFrameSummary                            
- *  EstimateSecondsPerPFrame                         
- *  ComputeHalfPixelData                             
- *  SetPQScale                               
- *  GetPQScale                               
- *                                                                           
- * NOTE:  when motion vectors are passed as arguments, they are passed as    
- *        twice their value.  In other words, a motion vector of (3,4) will  
- *        be passed as (6,8).  This allows half-pixel motion vectors to be   
- *        passed as integers.  This is true throughout the program.          
- *                                       
+ * pframe.c
+ *
+ *  Procedures concerned with generation of P-frames
+ *
+ * EXPORTED PROCEDURES:
+ *  GenPFrame
+ *  ResetPFrameStats
+ *  ShowPFrameSummary
+ *  EstimateSecondsPerPFrame
+ *  ComputeHalfPixelData
+ *  SetPQScale
+ *  GetPQScale
+ *
+ * NOTE:  when motion vectors are passed as arguments, they are passed as
+ *        twice their value.  In other words, a motion vector of (3,4) will
+ *        be passed as (6,8).  This allows half-pixel motion vectors to be
+ *        passed as integers.  This is true throughout the program.
+ *
  *===========================================================================*/
 
 /*==============*
@@ -75,6 +75,8 @@ halfVector(vector const vector) {
     return half;
 }
 
+
+
 /*===========================================================================*
  *
  *  decide if (0,0) motion is better than the given motion vector
@@ -101,7 +103,7 @@ ZeroMotionBetter(const LumBlock * const currentBlockP,
     int bestDiff;
     int CompareMode;
 
-    /* Junk needed to adapt for TUNEing */ 
+    /* Junk needed to adapt for TUNEing */
     CompareMode = SearchCompareMode;
     SearchCompareMode = DEFAULT_SEARCH;
     bestDiff = LumMotionError(currentBlockP, prev, by, bx, m, 0x7fffffff);
@@ -120,6 +122,7 @@ ZeroMotionBetter(const LumBlock * const currentBlockP,
 }
 
 
+
 /*===========================================================================*
  *
  *                USER-MODIFIABLE
@@ -158,14 +161,14 @@ DoIntraCode(const LumBlock * const currentBlockP,
         for (x = 0; x < 16; ++x) {
             currPixel = currentBlockP->l[y][x];
             prevPixel = motionBlock.l[y][x];
-            
+
             sum += currPixel;
             varc += currPixel*currPixel;
-            
+
             vard += SQR(currPixel - prevPixel);
         }
     }
-    
+
     vard /= 256;     /* divide by 256; assumes mean is close to zero */
     varc = (varc/256) - (sum/256) * (sum/256);
 
@@ -217,11 +220,11 @@ ZeroMotionSufficient(const LumBlock * const currentBlockP,
 
     return (zeroDiff <= 256);
 }
-                 
 
 
-static void 
-computeCurrentBlock(MpegFrame * const current, 
+
+static void
+computeCurrentBlock(MpegFrame * const current,
                     int         const y,
                     int         const x,
                     LumBlock *  const currentBlockP) {
@@ -232,7 +235,7 @@ computeCurrentBlock(MpegFrame * const current,
     for ( iy = 0; iy < 16; iy++ ) {
         int ix;
         for ( ix = 0; ix < 16; ix++ ) {
-            currentBlockP->l[iy][ix] = 
+            currentBlockP->l[iy][ix] =
                 (int16)current->orig_y[fy+iy][fx+ix];
         }
     }
@@ -241,17 +244,17 @@ computeCurrentBlock(MpegFrame * const current,
 
 
 static void
-computeMotionVectors(bool             const specificsOn, 
+computeMotionVectors(bool             const specificsOn,
                      bool             const IntraPBAllowed,
-                     MpegFrame *      const current, 
+                     MpegFrame *      const current,
                      MpegFrame *      const prev,
                      int              const mbAddress,
                      BlockMV **       const infoP,
-                     int              const QScale, 
+                     int              const QScale,
                      const LumBlock * const currentBlockP,
-                     int              const y, 
+                     int              const y,
                      int              const x,
-                     bool *           const useMotionP, 
+                     bool *           const useMotionP,
                      vector *         const motionP) {
 
     bool useCached;
@@ -260,7 +263,7 @@ computeMotionVectors(bool             const specificsOn,
     /* See if we have a cached answer */
     if (specificsOn) {
         SpecLookup(current->id, 2, mbAddress, &info, QScale);
-        if (info != (BlockMV*)NULL) 
+        if (info != (BlockMV*)NULL)
             useCached = TRUE;
         else
             useCached = FALSE;
@@ -293,7 +296,7 @@ computeMotionVectors(bool             const specificsOn,
                 motionP->x = 0;
             } else
                 *motionP = motion;
-            if (IntraPBAllowed) 
+            if (IntraPBAllowed)
                 *useMotionP = !DoIntraCode(currentBlockP, prev, y, x, motion);
             else
                 *useMotionP = TRUE;
@@ -305,12 +308,12 @@ computeMotionVectors(bool             const specificsOn,
 
 
 static void
-calculateForwardDcts(MpegFrame * const current, 
+calculateForwardDcts(MpegFrame * const current,
                      int const y, int const x,
                      Block ** const dct) {
 
     /* calculate forward dct's */
-    if (collect_quant && (collect_quant_detailed & 1)) 
+    if (collect_quant && (collect_quant_detailed & 1))
         fprintf(collect_quant_fp, "l\n");
 
     mp_fwd_dct_block2(current->y_blocks[y][x], dct[y][x]);
@@ -318,7 +321,7 @@ calculateForwardDcts(MpegFrame * const current,
     mp_fwd_dct_block2(current->y_blocks[y+1][x], dct[y+1][x]);
     mp_fwd_dct_block2(current->y_blocks[y+1][x+1], dct[y+1][x+1]);
 
-    if (collect_quant && (collect_quant_detailed & 1)) 
+    if (collect_quant && (collect_quant_detailed & 1))
         fprintf(collect_quant_fp, "c\n");
 
     mp_fwd_dct_block2(current->cb_blocks[y/2][x/2], dctb[y/2][x/2]);
@@ -348,7 +351,7 @@ computeMotionAndDct(int         const lastBlockY,
     int mbAddress;
     int y;
 
-    mbAddress = 0;                        
+    mbAddress = 0;
 
     for (y = 0; y < lastBlockY; y += 2) {
         int x;
@@ -416,7 +419,7 @@ computeMotionAndDct(int         const lastBlockY,
  *===========================================================================*/
 void
 GenPFrame(BitBucket * const bb,
-          MpegFrame * const current, 
+          MpegFrame * const current,
           MpegFrame * const prev) {
 
     extern int **pmvHistogram;
@@ -469,12 +472,12 @@ GenPFrame(BitBucket * const bb,
     if (bitstreamMode == FIXED_RATE) {
         targetRateControl(current);
     }
- 
+
     Mhead_GenPictureHeader(bb, P_FRAME, current->id, fCodeP);
-    /* Check for Qscale change */  
+    /* Check for Qscale change */
     if (specificsOn) {
         /* Set a Qscale for this frame? */
-        newQScale = 
+        newQScale =
             SpecLookup(current->id, 0, 0 /* junk */, &info /*junk*/, QScale);
         if (newQScale != -1) {
             QScale = newQScale;
@@ -515,9 +518,9 @@ GenPFrame(BitBucket * const bb,
 
     computeMotionAndDct(lastBlockY, lastBlockX,
                         specificsOn, IntraPBAllowed, current, prev,
-                        &info, QScale, searchRangeP, dct, 
+                        &info, QScale, searchRangeP, dct,
                         &numPBlocks, &numIBlocks, pmvHistogram);
-    
+
     mbAddress = 0;
     for (y = 0; y < lastBlockY; y += 2) {
         for (x = 0; x < lastBlockX; x += 2) {
@@ -526,7 +529,7 @@ GenPFrame(BitBucket * const bb,
             if ( (slicePos == 0) && (mbAddress != 0) ) {
                 if (specificsOn) {
                     /* Make sure no slice Qscale change */
-                    newQScale = 
+                    newQScale =
                         SpecLookup(current->id, 1, mbAddress/blocksPerSlice,
                                    &info /*junk*/, QScale);
                     if (newQScale != -1) QScale = newQScale;
@@ -541,7 +544,7 @@ GenPFrame(BitBucket * const bb,
 
                 mbAddrInc = 1+(x>>1);
             }
-        
+
             /*  Determine if new Qscale needed for Rate Control purposes  */
             if (bitstreamMode == FIXED_RATE) {
                 rc_blockStart =  bb->cumulativeBits;
@@ -554,10 +557,10 @@ GenPFrame(BitBucket * const bb,
                     QScale = newQScale;
                 }
             }
-        
+
             /* Check for Qscale change */
             if (specificsOn) {
-                newQScale = 
+                newQScale =
                     SpecLookup(current->id, 2, mbAddress, &info, QScale);
                 if (newQScale != -1) {
                     QScale = newQScale;
@@ -607,7 +610,7 @@ GenPFrame(BitBucket * const bb,
                 motion.y = dct_data[y][x].fmotionY;
 
 #ifdef BLEAH
-                ComputeAndPrintPframeMAD(currentBlock, prev, y, x, motion, 
+                ComputeAndPrintPframeMAD(currentBlock, prev, y, x, motion,
                                          mbAddress);
 #endif
 
@@ -625,11 +628,11 @@ GenPFrame(BitBucket * const bb,
 
 #ifdef BLEAH
                 if ( (motion.x != 0) || (motion.y != 0) ) {
-                    fprintf(stdout, "FRAME (y, x)  %d, %d (block %d)\n", 
+                    fprintf(stdout, "FRAME (y, x)  %d, %d (block %d)\n",
                             y, x, mbAddress);
-                    fprintf(stdout, "motion.x = %d, motion.y = %d\n", 
+                    fprintf(stdout, "motion.x = %d, motion.y = %d\n",
                             motion.x, motion.y);
-                    fprintf(stdout, 
+                    fprintf(stdout,
                             "    mxq, mxr = %d, %d    myq, myr = %d, %d\n",
                             motionQuot.x, motionRem.x,
                             motionQuot.y, motionRem.y);
@@ -656,7 +659,7 @@ GenPFrame(BitBucket * const bb,
                 if ( decodeRefFrames) {
                     for ( index = 0; index < 6; index++ ) {
                         if ( pattern & (1 << (5-index))) {
-                            Mpost_UnQuantZigBlock(fba[index], dec[index], 
+                            Mpost_UnQuantZigBlock(fba[index], dec[index],
                                                   QScale, FALSE);
                             mpeg_jrevdct((int16 *)dec[index]);
                         } else {
@@ -671,7 +674,7 @@ GenPFrame(BitBucket * const bb,
                     AddMotionBlock(dec[3], prev->decoded_y, y+1, x+1, motion);
                     AddMotionBlock(dec[4], prev->decoded_cb, y/2, x/2,
                                    halfVector(motion));
-                    AddMotionBlock(dec[5], prev->decoded_cr, y/2, x/2, 
+                    AddMotionBlock(dec[5], prev->decoded_cr, y/2, x/2,
                                    halfVector(motion));
 
                     /* now, unblockify */
@@ -681,7 +684,7 @@ GenPFrame(BitBucket * const bb,
                     BlockToData(current->decoded_y, dec[3], y+1, x+1);
                     BlockToData(current->decoded_cb, dec[4], y/2, x/2);
                     BlockToData(current->decoded_cr, dec[5], y/2, x/2);
-                } 
+                }
 
                 if ((motion.x == 0) && (motion.y == 0)) {
                     if ( pattern == 0 ) {
@@ -698,65 +701,65 @@ GenPFrame(BitBucket * const bb,
                             numSkipped++;
                             numPBlocks--;
                         } else {        /* first/last macroblock */
-                            Mhead_GenMBHeader(bb, 2 /* pict_code_type */, 
+                            Mhead_GenMBHeader(bb, 2 /* pict_code_type */,
                                               mbAddrInc /* addr_incr */,
                                               QScale /* q_scale */,
-                                              fCode /* forw_f_code */, 
+                                              fCode /* forw_f_code */,
                                               1 /* back_f_code */,
-                                              motionRem.x /* horiz_forw_r */, 
+                                              motionRem.x /* horiz_forw_r */,
                                               motionRem.y /* vert_forw_r */,
-                                              0 /* horiz_back_r */, 
+                                              0 /* horiz_back_r */,
                                               0 /* vert_back_r */,
-                                              1 /* motion_forw */, 
+                                              1 /* motion_forw */,
                                               motionQuot.x /* m_horiz_forw */,
-                                              motionQuot.y /* m_vert_forw */, 
+                                              motionQuot.y /* m_vert_forw */,
                                               0 /* motion_back */,
-                                              0 /* m_horiz_back */, 
+                                              0 /* m_horiz_back */,
                                               0 /* m_vert_back */,
-                                              0 /* mb_pattern */, 
+                                              0 /* mb_pattern */,
                                               0 /* mb_intra */);
                             mbAddrInc = 1;
                         }
                     } else {
                         DBG_PRINT(("MB Header(%d,%d)\n", x, y));
-                        Mhead_GenMBHeader(bb, 2 /* pict_code_type */, 
+                        Mhead_GenMBHeader(bb, 2 /* pict_code_type */,
                                           mbAddrInc /* addr_incr */,
                                           QScale /* q_scale */,
-                                          fCode /* forw_f_code */, 
+                                          fCode /* forw_f_code */,
                                           1 /* back_f_code */,
-                                          0 /* horiz_forw_r */, 
+                                          0 /* horiz_forw_r */,
                                           0 /* vert_forw_r */,
-                                          0 /* horiz_back_r */, 
+                                          0 /* horiz_back_r */,
                                           0 /* vert_back_r */,
-                                          0 /* motion_forw */, 
+                                          0 /* motion_forw */,
                                           0 /* m_horiz_forw */,
-                                          0 /* m_vert_forw */, 
+                                          0 /* m_vert_forw */,
                                           0 /* motion_back */,
-                                          0 /* m_horiz_back */, 
+                                          0 /* m_horiz_back */,
                                           0 /* m_vert_back */,
-                                          pattern /* mb_pattern */, 
+                                          pattern /* mb_pattern */,
                                           0 /* mb_intra */);
                         mbAddrInc = 1;
                     }
                 } else {
                     /*      DBG_PRINT(("MB Header(%d,%d)\n", x, y));  */
-          
-                    Mhead_GenMBHeader(bb, 2 /* pict_code_type */, 
+
+                    Mhead_GenMBHeader(bb, 2 /* pict_code_type */,
                                       mbAddrInc /* addr_incr */,
                                       QScale /* q_scale */,
-                                      fCode /* forw_f_code */, 
+                                      fCode /* forw_f_code */,
                                       1 /* back_f_code */,
-                                      motionRem.x /* horiz_forw_r */, 
+                                      motionRem.x /* horiz_forw_r */,
                                       motionRem.y /* vert_forw_r */,
-                                      0 /* horiz_back_r */, 
+                                      0 /* horiz_back_r */,
                                       0 /* vert_back_r */,
-                                      1 /* motion_forw */, 
+                                      1 /* motion_forw */,
                                       motionQuot.x /* m_horiz_forw */,
-                                      motionQuot.y /* m_vert_forw */, 
+                                      motionQuot.y /* m_vert_forw */,
                                       0 /* motion_back */,
-                                      0 /* m_horiz_back */, 
+                                      0 /* m_horiz_back */,
                                       0 /* m_vert_back */,
-                                      pattern /* mb_pattern */, 
+                                      pattern /* mb_pattern */,
                                       0 /* mb_intra */);
                     mbAddrInc = 1;
                 }
@@ -832,7 +835,7 @@ GenPFrame(BitBucket * const bb,
     if ( frameSummary && (! realQuiet) ) {
         fprintf(stdout, "FRAME %d (P):  I BLOCKS:  %d;  "
                 "P BLOCKS:  %d   SKIPPED:  %d  (%ld seconds)\n",
-                current->id, numIBlocks, numPBlocks, numSkipped, 
+                current->id, numIBlocks, numPBlocks, numSkipped,
                 (long)(endTime-startTime)/TIME_RATE);
         if ( printSNR ) {
             fprintf(stdout, "FRAME %d:  SNR:  %.1f\t%.1f\t%.1f\t"
@@ -851,6 +854,7 @@ GenPFrame(BitBucket * const bb,
 }
 
 
+
 /*===========================================================================*
  *
  * ResetPFrameStats
@@ -876,6 +880,7 @@ void
 }
 
 
+
 /*===========================================================================*
  *
  * SetPQScale
@@ -895,6 +900,7 @@ int qP;
 }
 
 
+
 /*===========================================================================*
  *
  * GetPQScale
@@ -913,6 +919,7 @@ int
 }
 
 
+
 float
 PFrameTotalTime(void) {
     return (float)totalTime/(float)TIME_RATE;
@@ -921,8 +928,8 @@ PFrameTotalTime(void) {
 
 
 void
-ShowPFrameSummary(unsigned int const inputFrameBits, 
-                  unsigned int const totalBits, 
+ShowPFrameSummary(unsigned int const inputFrameBits,
+                  unsigned int const totalBits,
                   FILE *       const fpointer) {
 
     if (numFrames > 0) {
@@ -992,6 +999,7 @@ float
 }
 
 
+
 /*===========================================================================*
  *
  * ComputeHalfPixelData
@@ -1048,6 +1056,7 @@ MpegFrame *frame;
 }
 
 
+
 /*
  * Copyright (c) 1995 The Regents of the University of California.
  * All rights reserved.
diff --git a/converter/ppm/ppmtompeg/postdct.c b/converter/ppm/ppmtompeg/postdct.c
index 56a23de9..f3de075a 100644
--- a/converter/ppm/ppmtompeg/postdct.c
+++ b/converter/ppm/ppmtompeg/postdct.c
@@ -1,15 +1,15 @@
 /*===========================================================================*
- * postdct.c								     *
- *									     *
- *	Procedures concerned with MPEG post-DCT processing:		     *
- *	    quantization and RLE Huffman encoding			     *
- *									     *
- * EXPORTED PROCEDURES:							     *
- *	Mpost_QuantZigBlock						     *
- *	Mpost_RLEHuffIBlock						     *
- *	Mpost_RLEHuffPBlock						     *
- *	Mpost_UnQuantZigBlock						     *
- *									     *
+ * postdct.c                                                                 *
+ *                                                                           *
+ *      Procedures concerned with MPEG post-DCT processing:                  *
+ *          quantization and RLE Huffman encoding                            *
+ *                                                                           *
+ * EXPORTED PROCEDURES:                                                      *
+ *      Mpost_QuantZigBlock                                                  *
+ *      Mpost_RLEHuffIBlock                                                  *
+ *      Mpost_RLEHuffPBlock                                                  *
+ *      Mpost_UnQuantZigBlock                                                *
+ *                                                                           *
  *===========================================================================*/
 
 /*
@@ -164,8 +164,8 @@ int32 niqtable[] = {
      16, 16, 16, 16, 16, 16, 16, 16
 };
 
-int32	*customQtable = NULL;
-int32	*customNIQtable = NULL;
+int32   *customQtable = NULL;
+int32   *customNIQtable = NULL;
 
 /*==================*
  * GLOBAL VARIABLES *
@@ -181,10 +181,10 @@ extern boolean realQuiet;
  *
  * Mpost_UnQuantZigBlock
  *
- *	unquantize and zig-zag (decode) a single block
- *	see section 2.4.4.1 of MPEG standard
+ *      unquantize and zig-zag (decode) a single block
+ *      see section 2.4.4.1 of MPEG standard
  *
- * RETURNS:	nothing
+ * RETURNS:     nothing
  *
  * SIDE EFFECTS:    none
  *
@@ -197,77 +197,78 @@ Mpost_UnQuantZigBlock(in, out, qscale, iblock)
     boolean iblock;
 {
     register int index;
-    int	    start;
-    int	    position;
-    register int	    qentry;
-    int	    level, coeff;
-    
+    int     start;
+    int     position;
+    register int            qentry;
+    int     level, coeff;
+
     if ( iblock ) {
-	/* qtable[0] must be 8 */
-	out[0][0] = (int16)(in[0] * 8);
+        /* qtable[0] must be 8 */
+        out[0][0] = (int16)(in[0] * 8);
 
-	/* don't need to do anything fancy here, because we saved orig
-	    value, not encoded dc value */
-	start = 1;
+        /* don't need to do anything fancy here, because we saved orig
+            value, not encoded dc value */
+        start = 1;
     } else {
-	start = 0;
+        start = 0;
     }
 
     for ( index = start;  index < DCTSIZE_SQ;  index++ ) {
-	position = ZAG[index];
-	level = in[index];
-
-	if (level == 0) {
-	  ((int16 *)out)[position] = 0;
-	  continue;
-	}
-
-
-	if ( iblock ) {
-	    qentry = qtable[position] * qscale;
-	    coeff = (level*qentry)/8;
-	    if ( (coeff & 1) == 0 ) {
-		if ( coeff < 0 ) {
-		    coeff++;
-		} else if ( coeff > 0 ) {
-		    coeff--;
-		}
-	    }
-	} else {
-	    qentry = niqtable[position] * qscale;
-	    if ( level == 0 ) {
-		coeff = 0;
-	    } else if ( level < 0 ) {
-		coeff = (((2*level)-1)*qentry) / 16;
-		if ( (coeff & 1) == 0 ) {
-		    coeff++;
-		}
-	    } else {
-		coeff = (((2*level)+1)*qentry) >> 4;
-		if ( (coeff & 1) == 0 ) {
-		    coeff--;
-		}
-	    }
-
-	    if ( coeff > 2047 ) {
-		coeff = 2047;
-	    } else if ( coeff < -2048 ) {
-		coeff = -2048;
-	    }
+        position = ZAG[index];
+        level = in[index];
+
+        if (level == 0) {
+          ((int16 *)out)[position] = 0;
+          continue;
         }
 
-	((int16 *)out)[position] = coeff;
+
+        if ( iblock ) {
+            qentry = qtable[position] * qscale;
+            coeff = (level*qentry)/8;
+            if ( (coeff & 1) == 0 ) {
+                if ( coeff < 0 ) {
+                    coeff++;
+                } else if ( coeff > 0 ) {
+                    coeff--;
+                }
+            }
+        } else {
+            qentry = niqtable[position] * qscale;
+            if ( level == 0 ) {
+                coeff = 0;
+            } else if ( level < 0 ) {
+                coeff = (((2*level)-1)*qentry) / 16;
+                if ( (coeff & 1) == 0 ) {
+                    coeff++;
+                }
+            } else {
+                coeff = (((2*level)+1)*qentry) >> 4;
+                if ( (coeff & 1) == 0 ) {
+                    coeff--;
+                }
+            }
+
+            if ( coeff > 2047 ) {
+                coeff = 2047;
+            } else if ( coeff < -2048 ) {
+                coeff = -2048;
+            }
+        }
+
+        ((int16 *)out)[position] = coeff;
     }
 }
 
 
+
 /*===========================================================================*
  *
  * Mpost_QuantZigBlock
  *
- *	quantize and zigzags a block
+ *      quantize and zigzags a block
  *
- * RETURNS:	MPOST_OVERFLOW if a generated value is outside |255|
+ * RETURNS:     MPOST_OVERFLOW if a generated value is outside |255|
  *              MPOST_ZERO     if all coeffs are zero
  *              MPOST_NON_ZERO otherwisw
  *
@@ -287,7 +288,7 @@ Mpost_QuantZigBlock(in, out, qscale, iblock)
   register int position;
   boolean nonZero = FALSE;
   boolean overflow = FALSE;
-  
+
   DBG_PRINT(("Mpost_QuantZigBlock...\n"));
   if (iblock) {
     /*
@@ -296,7 +297,7 @@ Mpost_QuantZigBlock(in, out, qscale, iblock)
      */
     temp = ((int16 *) in)[ZAG[0]];
     qentry = qtable[ZAG[0]];
-    
+
     if (temp < 0) {
       temp = -temp;
       temp += (qentry >> 1);
@@ -310,60 +311,60 @@ Mpost_QuantZigBlock(in, out, qscale, iblock)
       nonZero = TRUE;
     }
     out[0] = temp;
-    
+
     for (i = 1; i < DCTSIZE_SQ; i++) {
       position = ZAG[i];
       temp = ((int16 *) in)[position];
       qentry = qtable[position] * qscale;
-      
+
       /* see 1993 MPEG doc, section D.6.3.4 */
       if (temp < 0) {
-	temp = -temp;
-	temp = (temp << 3);	/* temp > 0 */
-	temp += (qentry >> 1);
-	temp /= qentry;
-	temp = -temp;
+        temp = -temp;
+        temp = (temp << 3);     /* temp > 0 */
+        temp += (qentry >> 1);
+        temp /= qentry;
+        temp = -temp;
       } else {
-	temp = (temp << 3);	/* temp > 0 */
-	temp += (qentry >> 1);
-	temp /= qentry;
+        temp = (temp << 3);     /* temp > 0 */
+        temp += (qentry >> 1);
+        temp /= qentry;
       }
-      
+
       if ( temp != 0 ) {
-	nonZero = TRUE;
-	out[i] = temp;
-	if (temp < -255) {
-	  temp = -255;
-	  overflow = TRUE;
-	} else if (temp > 255) {
-	  temp = 255;
-	  overflow = TRUE;
-	}
+        nonZero = TRUE;
+        out[i] = temp;
+        if (temp < -255) {
+          temp = -255;
+          overflow = TRUE;
+        } else if (temp > 255) {
+          temp = 255;
+          overflow = TRUE;
+        }
       } else out[i]=0;
     }
   } else {
     for (i = 0; i < DCTSIZE_SQ; i++) {
       position = ZAG[i];
       temp = ((int16 *) in)[position];
-      
+
       /* multiply by non-intra qtable */
       qentry = qscale * niqtable[position];
-      
+
       /* see 1993 MPEG doc, D.6.4.5 */
       temp *= 8;
-      temp /= qentry;	    /* truncation toward 0 -- correct */
-      
+      temp /= qentry;       /* truncation toward 0 -- correct */
+
       if ( temp != 0 ) {
-	nonZero = TRUE;
-	out[i] = temp;
-	if (temp < -255) {
-	  temp = -255;
-	  overflow = TRUE;
-	} else if (temp > 255) {
-	  temp = 255;
-	  overflow = TRUE;
-	}
-	
+        nonZero = TRUE;
+        out[i] = temp;
+        if (temp < -255) {
+          temp = -255;
+          overflow = TRUE;
+        } else if (temp > 255) {
+          temp = 255;
+          overflow = TRUE;
+        }
+
       } else out[i]=0;
     }
   }
@@ -379,9 +380,9 @@ Mpost_QuantZigBlock(in, out, qscale, iblock)
  *
  * Mpost_RLEHuffIBlock
  *
- *	generate the huffman bits from an I-block
+ *      generate the huffman bits from an I-block
  *
- * RETURNS:	nothing
+ * RETURNS:     nothing
  *
  * SIDE EFFECTS:    none
  *
@@ -403,70 +404,71 @@ Mpost_RLEHuffIBlock(in, out)
      * specially, elsewhere.  Not here.
      */
     for (i = 1; i < DCTSIZE_SQ; i++) {
-	cur = in[i];
-	acur = ABS(cur);
-	if (cur) {
-	    if ( (nzeros < HUFF_MAXRUN) && (acur < huff_maxlevel[nzeros])) {
-	        /*
-		 * encode using the Huffman tables
-		 */
-
-		DBG_PRINT(("rle_huff %02d.%02d: Run %02d, Level %4d\n", i,  ZAG[i], nzeros, cur));
-		code = (huff_table[nzeros])[acur];
-		nbits = (huff_bits[nzeros])[acur];
-
-		if (cur < 0) {
-		    code |= 1;	/* the sign bit */
-		}
-		Bitio_Write(out, code, nbits);
-	    } else {
-		/*
-		 * encode using the escape code
-		 */
-		DBG_PRINT(("Escape\n"));
-		Bitio_Write(out, 0x1, 6);	/* ESCAPE */
-		DBG_PRINT(("Run Length\n"));
-		Bitio_Write(out, nzeros, 6);	/* Run-Length */
-
-		/*
-	         * this shouldn't happen, but the other
-	         * choice is to bomb out and dump core...
-		 * Hmmm, seems to happen with small Qtable entries (1) -srs
-	         */
-		if (cur < -255) {
-		    cur = -255;
-		} else if (cur > 255) {
-		    cur = 255;
-		}
-
-		DBG_PRINT(("Level\n"));
-		if (acur < 128) {
-		    Bitio_Write(out, cur, 8);
-		} else {
-		    if (cur < 0) {
-			Bitio_Write(out, 0x8001 + cur + 255, 16);
-		    } else {
-			Bitio_Write(out, cur, 16);
-		    }
-		}
-	    }
-	    nzeros = 0;
-	} else {
-	    nzeros++;
-	}
+        cur = in[i];
+        acur = ABS(cur);
+        if (cur) {
+            if ( (nzeros < HUFF_MAXRUN) && (acur < huff_maxlevel[nzeros])) {
+                /*
+                 * encode using the Huffman tables
+                 */
+
+                DBG_PRINT(("rle_huff %02d.%02d: Run %02d, Level %4d\n", i,  ZAG[i], nzeros, cur));
+                code = (huff_table[nzeros])[acur];
+                nbits = (huff_bits[nzeros])[acur];
+
+                if (cur < 0) {
+                    code |= 1;  /* the sign bit */
+                }
+                Bitio_Write(out, code, nbits);
+            } else {
+                /*
+                 * encode using the escape code
+                 */
+                DBG_PRINT(("Escape\n"));
+                Bitio_Write(out, 0x1, 6);       /* ESCAPE */
+                DBG_PRINT(("Run Length\n"));
+                Bitio_Write(out, nzeros, 6);    /* Run-Length */
+
+                /*
+                 * this shouldn't happen, but the other
+                 * choice is to bomb out and dump core...
+                 * Hmmm, seems to happen with small Qtable entries (1) -srs
+                 */
+                if (cur < -255) {
+                    cur = -255;
+                } else if (cur > 255) {
+                    cur = 255;
+                }
+
+                DBG_PRINT(("Level\n"));
+                if (acur < 128) {
+                    Bitio_Write(out, cur, 8);
+                } else {
+                    if (cur < 0) {
+                        Bitio_Write(out, 0x8001 + cur + 255, 16);
+                    } else {
+                        Bitio_Write(out, cur, 16);
+                    }
+                }
+            }
+            nzeros = 0;
+        } else {
+            nzeros++;
+        }
     }
     DBG_PRINT(("End of block\n"));
-    Bitio_Write(out, 0x2, 2);	/* end of block marker */
+    Bitio_Write(out, 0x2, 2);   /* end of block marker */
 }
 
 
+
 /*===========================================================================*
  *
  * Mpost_RLEHuffPBlock
  *
- *	generate the huffman bits from an P-block
+ *      generate the huffman bits from an P-block
  *
- * RETURNS:	nothing
+ * RETURNS:     nothing
  *
  * SIDE EFFECTS:    none
  *
@@ -488,90 +490,91 @@ Mpost_RLEHuffPBlock(in, out)
      * yes, Virginia, we start at 0.
      */
     for (i = 0; i < DCTSIZE_SQ; i++) {
-	cur = in[i];
-	acur = ABS(cur);
-	if (cur) {
-	    if ((nzeros < HUFF_MAXRUN) && (acur < huff_maxlevel[nzeros])) {
-	        /*
-		 * encode using the Huffman tables
-		 */
-
-		DBG_PRINT(("rle_huff %02d.%02d: Run %02d, Level %4d\n", i, ZAG[i], nzeros, cur));
-		if ( first_dct && (nzeros == 0) && (acur == 1) ) {
-		    /* actually, only needs = 0x2 */
-		    code = (cur == 1) ? 0x2 : 0x3;
-		    nbits = 2;
-		} else {
-		    code = (huff_table[nzeros])[acur];
-		    nbits = (huff_bits[nzeros])[acur];
-		  }
-
-		assert(nbits);
-
-		if (cur < 0) {
-		    code |= 1;	/* the sign bit */
-		}
-		Bitio_Write(out, code, nbits);
-		first_dct = FALSE;
-	    } else {
-		/*
-		 * encode using the escape code
-		 */
-		DBG_PRINT(("Escape\n"));
-		Bitio_Write(out, 0x1, 6);	/* ESCAPE */
-		DBG_PRINT(("Run Length\n"));
-		Bitio_Write(out, nzeros, 6);	/* Run-Length */
-
-		/*
-	         * this shouldn't happen, but the other
-	         * choice is to bomb out and dump core...
-		 * Hmmm, seems to happen with small Qtable entries (1) -srs
-	         */
-		if (cur < -255) {
-		  cur = -255;
-		} else if (cur > 255) {
-		  cur = 255;
-		}
-
-		DBG_PRINT(("Level\n"));
-		if (acur < 128) {
-		    Bitio_Write(out, cur, 8);
-		} else {
-		    if (cur < 0) {
-			Bitio_Write(out, 0x8001 + cur + 255, 16);
-		    } else {
-			Bitio_Write(out, cur, 16);
-		    }
-		}
-
-		first_dct = FALSE;
-	    }
-	    nzeros = 0;
-	} else {
-	    nzeros++;
-	}
+        cur = in[i];
+        acur = ABS(cur);
+        if (cur) {
+            if ((nzeros < HUFF_MAXRUN) && (acur < huff_maxlevel[nzeros])) {
+                /*
+                 * encode using the Huffman tables
+                 */
+
+                DBG_PRINT(("rle_huff %02d.%02d: Run %02d, Level %4d\n", i, ZAG[i], nzeros, cur));
+                if ( first_dct && (nzeros == 0) && (acur == 1) ) {
+                    /* actually, only needs = 0x2 */
+                    code = (cur == 1) ? 0x2 : 0x3;
+                    nbits = 2;
+                } else {
+                    code = (huff_table[nzeros])[acur];
+                    nbits = (huff_bits[nzeros])[acur];
+                  }
+
+                assert(nbits);
+
+                if (cur < 0) {
+                    code |= 1;  /* the sign bit */
+                }
+                Bitio_Write(out, code, nbits);
+                first_dct = FALSE;
+            } else {
+                /*
+                 * encode using the escape code
+                 */
+                DBG_PRINT(("Escape\n"));
+                Bitio_Write(out, 0x1, 6);       /* ESCAPE */
+                DBG_PRINT(("Run Length\n"));
+                Bitio_Write(out, nzeros, 6);    /* Run-Length */
+
+                /*
+                 * this shouldn't happen, but the other
+                 * choice is to bomb out and dump core...
+                 * Hmmm, seems to happen with small Qtable entries (1) -srs
+                 */
+                if (cur < -255) {
+                  cur = -255;
+                } else if (cur > 255) {
+                  cur = 255;
+                }
+
+                DBG_PRINT(("Level\n"));
+                if (acur < 128) {
+                    Bitio_Write(out, cur, 8);
+                } else {
+                    if (cur < 0) {
+                        Bitio_Write(out, 0x8001 + cur + 255, 16);
+                    } else {
+                        Bitio_Write(out, cur, 16);
+                    }
+                }
+
+                first_dct = FALSE;
+            }
+            nzeros = 0;
+        } else {
+            nzeros++;
+        }
     }
 
     /* actually, should REALLY return FALSE and not use this! */
 
-    if ( first_dct ) {	/* have to give a first_dct even if all 0's */
-	fprintf(stderr, "HUFF called with all-zero coefficients\n");
-	fprintf(stderr, "exiting...\n");
-	exit(1);
+    if ( first_dct ) {  /* have to give a first_dct even if all 0's */
+        fprintf(stderr, "HUFF called with all-zero coefficients\n");
+        fprintf(stderr, "exiting...\n");
+        exit(1);
     }
 
     DBG_PRINT(("End of block\n"));
-    Bitio_Write(out, 0x2, 2);	/* end of block marker */
+    Bitio_Write(out, 0x2, 2);   /* end of block marker */
 }
 
 
+
 /*===========================================================================*
  *
  * CalcRLEHuffLength
  *
- *	count the huffman bits for an P-block
+ *      count the huffman bits for an P-block
  *
- * RETURNS:	number of bits
+ * RETURNS:     number of bits
  *
  * SIDE EFFECTS:    none
  *
@@ -587,40 +590,43 @@ CalcRLEHuffLength(in)
   register int nbits;
   register int countbits=0;
   boolean first_dct = TRUE;
-  
+
   for (i = 0; i < DCTSIZE_SQ; i++) {
     cur = in[i];
     acur = ABS(cur);
     if (cur) {
       if ((nzeros < HUFF_MAXRUN) && (acur < huff_maxlevel[nzeros])) {
-	/*
-	 * encode using the Huffman tables
-	 */
-
-	if ( first_dct && (nzeros == 0) && (acur == 1) ) {
-	  nbits = 2;
-	} else {
-	  nbits = (huff_bits[nzeros])[acur];
-	}
-	countbits += nbits;
-	first_dct = FALSE;
+        /*
+         * encode using the Huffman tables
+         */
+
+        if ( first_dct && (nzeros == 0) && (acur == 1) ) {
+          nbits = 2;
+        } else {
+          nbits = (huff_bits[nzeros])[acur];
+        }
+        countbits += nbits;
+        first_dct = FALSE;
       } else {
-	countbits += 12;	/* ESCAPE + runlength */
+        countbits += 12;        /* ESCAPE + runlength */
 
-	if (acur < 128) {
-	  countbits += 8;
-	} else {
-	  countbits += 16;
-	}
+        if (acur < 128) {
+          countbits += 8;
+        } else {
+          countbits += 16;
+        }
 
-	first_dct = FALSE;
+        first_dct = FALSE;
       }
       nzeros = 0;
     } else {
       nzeros++;
     }
   }
-  
+
   countbits += 2; /* end of block marker */
   return countbits;
 }
+
+
+
diff --git a/converter/ppm/ppmtompeg/ppmtompeg.c b/converter/ppm/ppmtompeg/ppmtompeg.c
index 837b1b9d..78e33c54 100644
--- a/converter/ppm/ppmtompeg/ppmtompeg.c
+++ b/converter/ppm/ppmtompeg/ppmtompeg.c
@@ -127,7 +127,7 @@ parseArgs(int     const argc,
     cmdlineP->outputFrames = 0;
     cmdlineP->maxMachines = MAXINT;
     cmdlineP->specificFrames = FALSE;
-    
+
     /* parse the arguments */
     idx = 1;
     while (idx < argc-1) {
@@ -143,10 +143,10 @@ parseArgs(int     const argc,
             } else
                 pm_error("Invalid -stat option");
         } else if (streq(argv[idx], "-gop")) {
-            if (cmdlineP->function != ENCODE_FRAMES || 
+            if (cmdlineP->function != ENCODE_FRAMES ||
                 cmdlineP->specificFrames)
                 pm_error("Invalid -gop option");
-            
+
             if (idx+1 < argc-1) {
                 whichGOP = atoi(argv[idx+1]);
                 idx += 2;
@@ -170,12 +170,12 @@ parseArgs(int     const argc,
                 cmdlineP->specificFrames = TRUE;
                 cmdlineP->frameStart = frameStart;
                 cmdlineP->frameEnd   = frameEnd;
-                
+
                 idx += 3;
             } else
                 pm_error("-frames needs to be followed by two values");
         } else if (streq(argv[idx], "-combine_gops")) {
-            if (cmdlineP->function != ENCODE_FRAMES || whichGOP != -1 || 
+            if (cmdlineP->function != ENCODE_FRAMES || whichGOP != -1 ||
                 cmdlineP->specificFrames) {
                 pm_error("Invalid -combine_gops option");
             }
@@ -345,7 +345,7 @@ announceJob(enum frameContext const context,
             combineDest = strdup("for delivery to combine server");
         else
             combineDest = strdup("");
-    
+
         pm_message("%s:  ENCODING FRAMES %u-%u to %s %s",
                    hostname, frameStart, frameEnd, outputDest, combineDest);
 
@@ -359,7 +359,7 @@ announceJob(enum frameContext const context,
 static void
 encodeSomeFrames(struct inputSource * const inputSourceP,
                  boolean              const childProcess,
-                 enum frameContext    const context, 
+                 enum frameContext    const context,
                  unsigned int         const frameStart,
                  unsigned int         const frameEnd,
                  int32                const qtable[],
@@ -370,7 +370,7 @@ encodeSomeFrames(struct inputSource * const inputSourceP,
                  bool                 const wantVbvOverflowWarning,
                  boolean              const printStats,
                  unsigned int *       const encodeTimeP) {
-    
+
     time_t framesTimeStart, framesTimeEnd;
     unsigned int inputFrameBits;
     unsigned int totalBits;
@@ -383,7 +383,7 @@ encodeSomeFrames(struct inputSource * const inputSourceP,
                         frameStart, frameEnd, inputSourceP);
 
     GenMPEGStream(inputSourceP, context, frameStart, frameEnd,
-                  qtable, niqtable, childProcess, ofp, outputFileName, 
+                  qtable, niqtable, childProcess, ofp, outputFileName,
                   wantVbvUnderflowWarning, wantVbvOverflowWarning,
                   &inputFrameBits, &totalBits);
 
@@ -396,13 +396,12 @@ encodeSomeFrames(struct inputSource * const inputSourceP,
                    hostname, frameStart, frameEnd, *encodeTimeP);
 
     if (printStats)
-        PrintEndStats(framesTimeStart, framesTimeEnd, 
+        PrintEndStats(framesTimeStart, framesTimeEnd,
                       inputFrameBits, totalBits);
 }
 
 
 
-
 static void
 encodeFrames(struct inputSource * const inputSourceP,
              boolean              const childProcess,
@@ -422,14 +421,14 @@ encodeFrames(struct inputSource * const inputSourceP,
   Encode the stream.  If 'specificFrames' is true, then encode frames
   'whichFrameStart' through 'whichFrameEnd' individually.  Otherwise,
   encode the entire input stream as a complete MPEG stream.
-  
+
   'childProcess' means to do it as a child process that is under the
   supervision of a master process and is possibly doing only part of
   a larger batch.
-  
+
   (If we had proper modularity, we wouldn't care, but parallel operation
   was glued on to this program after it was complete).
-  
+
   One thing we don't do when running as a child process is print
   statistics; our master will do that for the whole job.
 ----------------------------------------------------------------------------*/
@@ -442,7 +441,7 @@ encodeFrames(struct inputSource * const inputSourceP,
 
     if (whichGOP != -1) {
         /* He wants just one particular GOP from the middle of the movie. */
-        ComputeGOPFrames(whichGOP, &frameStart, &frameEnd, 
+        ComputeGOPFrames(whichGOP, &frameStart, &frameEnd,
                          inputSourceP->numInputFiles);
         context = CONTEXT_GOP;
     } else if (specificFrames) {
@@ -465,36 +464,36 @@ encodeFrames(struct inputSource * const inputSourceP,
         frameEnd   = inputSourceP->numInputFiles - 1;
         context = CONTEXT_WHOLESTREAM;
     }
-    
+
     printStats = !childProcess;
-    
+
     encodeSomeFrames(inputSourceP, childProcess, context, frameStart, frameEnd,
                      customQtable, customNIQtable,
-                     ofp, outputFileName, 
+                     ofp, outputFileName,
                      wantVbvUnderflowWarning, wantVbvOverflowWarning,
                      printStats,
                      &lastEncodeTime);
 
     if (childProcess) {
         boolean moreWorkToDo;
-        
+
         /* A child is not capable of generating GOP or stream headers */
         assert(context == CONTEXT_JUSTFRAMES);
-        
+
         moreWorkToDo = TRUE;  /* initial assumption */
         while (moreWorkToDo) {
             int nextFrameStart, nextFrameEnd;
 
-            NotifyMasterDone(masterHostname, masterPortNumber, machineNumber, 
+            NotifyMasterDone(masterHostname, masterPortNumber, machineNumber,
                              lastEncodeTime, &moreWorkToDo,
                              &nextFrameStart, &nextFrameEnd);
             if (moreWorkToDo)
-                encodeSomeFrames(inputSourceP, childProcess, 
-                                 CONTEXT_JUSTFRAMES, 
+                encodeSomeFrames(inputSourceP, childProcess,
+                                 CONTEXT_JUSTFRAMES,
                                  nextFrameStart, nextFrameEnd,
                                  customQtable, customNIQtable,
-                                 NULL, outputFileName, 
-                                 wantVbvUnderflowWarning, 
+                                 NULL, outputFileName,
+                                 wantVbvUnderflowWarning,
                                  wantVbvOverflowWarning,
                                  FALSE,
                                  &lastEncodeTime);
@@ -507,7 +506,6 @@ encodeFrames(struct inputSource * const inputSourceP,
 
 
 
-
 static void
 runMaster(struct inputSource * const inputSourceP,
           const char *         const paramFileName,
@@ -527,13 +525,13 @@ static void
 getUserFrameFile(void *       const handle,
                  unsigned int const frameNumber,
                  FILE **      const ifPP) {
-    
+
     struct inputSource * const inputSourceP = (struct inputSource *) handle;
 
     if (inputSourceP->stdinUsed)
         pm_error("You cannot combine frames from Standard Input.");
             /* Because Caller detects end of frames by EOF */
-    
+
     if (frameNumber >= inputSourceP->numInputFiles)
         *ifPP = NULL;
     else {
@@ -541,14 +539,14 @@ getUserFrameFile(void *       const handle,
         const char * inputFileName;
 
         GetNthInputFileName(inputSourceP, frameNumber, &inputFileName);
-        
+
         pm_asprintf(&fileName, "%s/%s", currentFramePath, inputFileName);
-        
+
         *ifPP = fopen(fileName, "rb");
         if (*ifPP == NULL)
             pm_error("Unable to open file '%s'.  Errno = %d (%s)",
                      fileName, errno, strerror(errno));
-        
+
         pm_strfree(inputFileName);
         pm_strfree(fileName);
     }
@@ -585,11 +583,11 @@ framePoolSize(bool const sequentialInput) {
         for ( idx = 0, bcount = 0; idx < strlen(framePattern); idx++) {
 
             /* counts the maximum number of B frames between two reference
-             * frames. 
+             * frames.
              */
-            
+
             switch( framePattern[idx] ) {
-            case 'b': 
+            case 'b':
                 bcount++;
                 break;
             case 'i':
@@ -599,12 +597,12 @@ framePoolSize(bool const sequentialInput) {
                 bcount = 0;
                 break;
             }
-            
+
             /* add 2 to hold the forward and past reference frames in addition
-             * to the maximum number of B's 
+             * to the maximum number of B's
              */
         }
-        
+
         numOfFrames += 2;
 
     } else {
@@ -656,22 +654,22 @@ main(int argc, char **argv) {
     Tune_Init();
     Frame_Init(framePoolSize(params.inputSourceP->stdinUsed));
 
-    if (specificsOn) 
+    if (specificsOn)
         Specifics_Init();
 
-    ComputeFrameTable(params.inputSourceP->stdinUsed ? 
+    ComputeFrameTable(params.inputSourceP->stdinUsed ?
                       0 : params.inputSourceP->numInputFiles);
 
     if (ioServer) {
-        IoServer(params.inputSourceP, cmdline.masterHostname, 
+        IoServer(params.inputSourceP, cmdline.masterHostname,
                  cmdline.masterPortNumber);
         return 0;
     } else if (outputServer) {
-        CombineServer(cmdline.outputFrames, 
+        CombineServer(cmdline.outputFrames,
                       cmdline.masterHostname, cmdline.masterPortNumber,
                       outputFileName);
     } else if (decodeServer) {
-        DecodeServer(cmdline.outputFrames, outputFileName, 
+        DecodeServer(cmdline.outputFrames, outputFileName,
                      cmdline.masterHostname, cmdline.masterPortNumber);
     } else {
         if (!cmdline.specificFrames &&
@@ -681,18 +679,18 @@ main(int argc, char **argv) {
                 pm_error("Could not open output file!");
         } else
             ofP = NULL;
-        
+
         if (cmdline.function == ENCODE_FRAMES) {
             if (numMachines == 0 || cmdline.specificFrames) {
                 encodeFrames(params.inputSourceP,
-                             cmdline.childProcess, 
+                             cmdline.childProcess,
                              cmdline.masterHostname, cmdline.masterPortNumber,
                              whichGOP, cmdline.specificFrames,
                              cmdline.frameStart, cmdline.frameEnd,
                              customQtable, customNIQtable,
                              ofP, outputFileName,
                              params.warnUnderflow, params.warnOverflow);
-                
+
             } else
                 runMaster(params.inputSourceP,
                           cmdline.paramFileName, outputFileName);
@@ -701,10 +699,13 @@ main(int argc, char **argv) {
         else if (cmdline.function == COMBINE_FRAMES)
             FramesToMPEG(ofP, params.inputSourceP,
                          &getUserFrameFile, &nullDisposeFile);
-    } 
+    }
     Frame_Exit();
-        
+
     pm_strfree(hostname);
 
     return 0;
 }
+
+
+
diff --git a/converter/ppm/ppmtompeg/psearch.c b/converter/ppm/ppmtompeg/psearch.c
index e350137e..c82ad4ad 100644
--- a/converter/ppm/ppmtompeg/psearch.c
+++ b/converter/ppm/ppmtompeg/psearch.c
@@ -1,8 +1,8 @@
 /*===========================================================================*
- * psearch.c                                     
- *                                       
- *  Procedures concerned with the P-frame motion search          
- *                                       
+ * psearch.c
+ *
+ *  Procedures concerned with the P-frame motion search
+ *
  *===========================================================================*/
 
 /*==============*
@@ -79,10 +79,10 @@ int psearchAlg;
  *
  *===========================================================================*/
 void
-PMotionSearch(const LumBlock * const currentBlockP, 
-              MpegFrame *      const prev, 
+PMotionSearch(const LumBlock * const currentBlockP,
+              MpegFrame *      const prev,
               int              const by,
-              int              const bx, 
+              int              const bx,
               vector *         const motionP) {
 
     /* CALL SEARCH PROCEDURE */
@@ -92,14 +92,14 @@ PMotionSearch(const LumBlock * const currentBlockP,
         PSubSampleSearch(currentBlockP, prev, by, bx, motionP, searchRangeP);
         break;
     case PSEARCH_EXHAUSTIVE:
-        PLocalSearch(currentBlockP, prev, by, bx, 
+        PLocalSearch(currentBlockP, prev, by, bx,
                      motionP, INT_MAX, searchRangeP);
         break;
     case PSEARCH_LOGARITHMIC:
         PLogarithmicSearch(currentBlockP, prev, by, bx, motionP, searchRangeP);
         break;
     case PSEARCH_TWOLEVEL:
-        PTwoLevelSearch(currentBlockP, prev, by, bx, 
+        PTwoLevelSearch(currentBlockP, prev, by, bx,
                         motionP, INT_MAX, searchRangeP);
         break;
     default:
@@ -122,7 +122,7 @@ PMotionSearch(const LumBlock * const currentBlockP,
  *===========================================================================*/
 void
 SetPixelSearch(const char * const searchType) {
-    if ( (strcmp(searchType, "FULL") == 0 ) || 
+    if ( (strcmp(searchType, "FULL") == 0 ) ||
          ( strcmp(searchType, "WHOLE") == 0 )) {
         pixelFullSearch = TRUE;
     } else if ( strcmp(searchType, "HALF") == 0 ) {
@@ -135,6 +135,7 @@ SetPixelSearch(const char * const searchType) {
 }
 
 
+
 /*===========================================================================*
  *
  * SetPSearchAlg
@@ -164,6 +165,7 @@ SetPSearchAlg(const char * const alg)
 }
 
 
+
 /*===========================================================================*
  *
  * PSearchName
@@ -198,6 +200,7 @@ PSearchName(void)
 }
 
 
+
 /*===========================================================================*
  *
  * SetSearchRange
@@ -216,22 +219,23 @@ SetSearchRange(int const pixelsP, int const pixelsB) {
         int const max_search = max(searchRangeP, searchRangeB);
 
         int index;
-    
+
         pmvHistogram = (int **) malloc((2*searchRangeP+3)*sizeof(int *));
         bbmvHistogram = (int **) malloc((2*searchRangeB+3)*sizeof(int *));
         bfmvHistogram = (int **) malloc((2*searchRangeB+3)*sizeof(int *));
         for ( index = 0; index < 2*max_search+3; index++ ) {
-            pmvHistogram[index] = 
+            pmvHistogram[index] =
                 (int *) calloc(2*searchRangeP+3, sizeof(int));
-            bbmvHistogram[index] = 
+            bbmvHistogram[index] =
                 (int *) calloc(2*searchRangeB+3, sizeof(int));
-            bfmvHistogram[index] = 
+            bfmvHistogram[index] =
                 (int *) calloc(2*searchRangeB+3, sizeof(int));
         }
     }
 }
 
 
+
 /*===========================================================================*
  *
  *              USER-MODIFIABLE
@@ -252,6 +256,7 @@ MotionSearchPreComputation(MpegFrame * const frameP) {
 }
 
 
+
 /*===========================================================================*
  *
  * PSubSampleSearch
@@ -269,12 +274,12 @@ MotionSearchPreComputation(MpegFrame * const frameP) {
  *===========================================================================*/
 int
 PSubSampleSearch(const LumBlock * const currentBlockP,
-                 MpegFrame *      const prev, 
+                 MpegFrame *      const prev,
                  int              const by,
                  int              const bx,
                  vector *         const motionP,
                  int              const searchRange) {
-    
+
     int my, mx;
     int bestBestDiff;
     int stepSize;
@@ -311,7 +316,7 @@ PSubSampleSearch(const LumBlock * const currentBlockP,
                     m.y = my; m.x = mx;
                     diff = LumMotionErrorA(currentBlockP, prev, by, bx, m,
                                            bestDiff[0]);
-                    
+
                     if (diff < bestDiff[0]) {
                         bestMY[0] = my;
                         bestMX[0] = mx;
@@ -330,9 +335,9 @@ PSubSampleSearch(const LumBlock * const currentBlockP,
                     int diff;
                     vector m;
                     m.y = my; m.x = mx;
-                    diff = LumMotionErrorB(currentBlockP, prev, by, bx, m, 
+                    diff = LumMotionErrorB(currentBlockP, prev, by, bx, m,
                                            bestDiff[1]);
-                    
+
                     if (diff < bestDiff[1]) {
                         bestMY[1] = my;
                         bestMX[1] = mx;
@@ -353,7 +358,7 @@ PSubSampleSearch(const LumBlock * const currentBlockP,
                     m.y = my; m.x = mx;
                     diff = LumMotionErrorC(currentBlockP, prev, by, bx, m,
                                            bestDiff[2]);
-                    
+
                     if (diff < bestDiff[2]) {
                         bestMY[2] = my;
                         bestMX[2] = mx;
@@ -374,7 +379,7 @@ PSubSampleSearch(const LumBlock * const currentBlockP,
                     m.y = my; m.x = mx;
                     diff = LumMotionErrorD(currentBlockP, prev, by, bx, m,
                                            bestDiff[3]);
-                    
+
                     if (diff < bestDiff[3]) {
                         bestMY[3] = my;
                         bestMX[3] = mx;
@@ -388,7 +393,7 @@ PSubSampleSearch(const LumBlock * const currentBlockP,
     /* first check old motion */
     if ((motionP->y >= leftMY) && (motionP->y < rightMY) &&
         (motionP->x >= leftMX) && (motionP->x < rightMX)) {
-        bestBestDiff = LumMotionError(currentBlockP, prev, by, bx, 
+        bestBestDiff = LumMotionError(currentBlockP, prev, by, bx,
                                       *motionP, INT_MAX);
     } else
         bestBestDiff = INT_MAX;
@@ -417,15 +422,15 @@ findBestSpaced(int              const minMY,
                int              const maxMY,
                int              const maxMX,
                int              const spacing,
-               const LumBlock * const currentBlockP, 
+               const LumBlock * const currentBlockP,
                MpegFrame *      const prev,
                int              const by,
                int              const bx,
-               int *            const bestDiffP, 
+               int *            const bestDiffP,
                vector *         const centerP) {
 /*----------------------------------------------------------------------------
-   Examine every 'spacing'th half-pixel within the rectangle 
-   ('minBoundX', 'minBoundY', 'maxBoundX', 'maxBoundY'), 
+   Examine every 'spacing'th half-pixel within the rectangle
+   ('minBoundX', 'minBoundY', 'maxBoundX', 'maxBoundY'),
 
    If one of the half-pixels examined has a lower "LumMotionError" value
    than *bestDiffP, update *bestDiffP to that value and update
@@ -446,9 +451,9 @@ findBestSpaced(int              const minMY,
             vector m;
 
             m.y = my; m.x = mx;
-            
+
             diff = LumMotionError(currentBlockP, prev, by, bx, m, *bestDiffP);
-            
+
             if (diff < *bestDiffP) {
                 *centerP   = m;
                 *bestDiffP = diff;
@@ -474,9 +479,9 @@ findBestSpaced(int              const minMY,
  *===========================================================================*/
 int
 PLogarithmicSearch(const LumBlock * const currentBlockP,
-                   MpegFrame *      const prev, 
+                   MpegFrame *      const prev,
                    int              const by,
-                   int              const bx, 
+                   int              const bx,
                    vector *         const motionP,
                    int              const searchRange) {
 
@@ -493,7 +498,7 @@ PLogarithmicSearch(const LumBlock * const currentBlockP,
         /* The difference between the current block and the block offset
            'motion' from it.
         */
-    
+
     COMPUTE_MOTION_BOUNDARY(by, bx, stepSize, minMY, minMX, maxMY, maxMX);
     minMX = max(minMX, - searchRange);
     minMY = max(minMY, - searchRange);
@@ -510,20 +515,20 @@ PLogarithmicSearch(const LumBlock * const currentBlockP,
 
     for (spacing = searchRange; spacing >= stepSize;) {
         if (stepSize == 2) {  /* make sure spacing is even */
-            if (spacing == 2) 
+            if (spacing == 2)
                 spacing = 0;
             else {
                 spacing = (spacing+1)/2;
-                if (spacing % 2 != 0) 
+                if (spacing % 2 != 0)
                     --spacing;
             }
         } else {
             if (spacing == 1) {
                 spacing = 0;
-            } else 
+            } else
                 spacing = (spacing + 1) / 2;
         }
-        if (spacing >= stepSize) 
+        if (spacing >= stepSize)
             findBestSpaced(minMY, minMX, maxMY, maxMX,
                            spacing, currentBlockP, prev, by, bx,
                            &bestDiff, &motion);
@@ -534,14 +539,14 @@ PLogarithmicSearch(const LumBlock * const currentBlockP,
         /* check old motion -- see if it's better */
         if ((motionP->y >= minMY) && (motionP->y < maxMY) &&
             (motionP->x >= minMX) && (motionP->x < maxMX)) {
-            diff = LumMotionError(currentBlockP, prev, by, bx, 
+            diff = LumMotionError(currentBlockP, prev, by, bx,
                                   *motionP, bestDiff);
-        } else 
+        } else
             diff = INT_MAX;
-        
+
         if (bestDiff < diff)
             *motionP = motion;
-        else 
+        else
             bestDiff = diff;
     }
 
@@ -563,7 +568,7 @@ PLogarithmicSearch(const LumBlock * const currentBlockP,
  *===========================================================================*/
 int
 PLocalSearch(const LumBlock * const currentBlockP,
-             MpegFrame *      const prev, 
+             MpegFrame *      const prev,
              int              const by,
              int              const bx,
              vector *         const motionP,
@@ -584,7 +589,7 @@ PLocalSearch(const LumBlock * const currentBlockP,
 
     /* try old motion vector first */
     if (VALID_MOTION(*motionP)) {
-        bestDiff = LumMotionError(currentBlockP, prev, by, bx, 
+        bestDiff = LumMotionError(currentBlockP, prev, by, bx,
                                   *motionP, bestSoFar);
 
         if (bestSoFar < bestDiff)
@@ -594,7 +599,7 @@ PLocalSearch(const LumBlock * const currentBlockP,
         bestDiff = bestSoFar;
     }
 
-    /* try a spiral pattern */    
+    /* try a spiral pattern */
     for (distance = stepSize; distance <= searchRange; distance += stepSize) {
         tempRightMY = MIN(distance, rightMY);
         tempRightMX = MIN(distance, rightMX);
@@ -607,11 +612,11 @@ PLocalSearch(const LumBlock * const currentBlockP,
                     if (mx >= leftMX) {
                         int diff;
                         vector m;
-                        
+
                         m.y = my; m.x = mx;
-                        diff = LumMotionError(currentBlockP, prev, by, bx, m, 
+                        diff = LumMotionError(currentBlockP, prev, by, bx, m,
                                               bestDiff);
-                        
+
                         if (diff < bestDiff) {
                             *motionP = m;
                             bestDiff = diff;
@@ -635,7 +640,7 @@ PLocalSearch(const LumBlock * const currentBlockP,
                         m.y = my; m.x = mx;
                         diff = LumMotionError(currentBlockP, prev, by, bx, m,
                                               bestDiff);
-                        
+
                         if (diff < bestDiff) {
                             *motionP = m;
                             bestDiff = diff;
@@ -649,6 +654,7 @@ PLocalSearch(const LumBlock * const currentBlockP,
 }
 
 
+
 /*===========================================================================*
  *
  * PTwoLevelSearch
@@ -664,9 +670,9 @@ PLocalSearch(const LumBlock * const currentBlockP,
  *===========================================================================*/
 int
 PTwoLevelSearch(const LumBlock * const currentBlockP,
-                MpegFrame *      const prev, 
+                MpegFrame *      const prev,
                 int              const by,
-                int              const bx, 
+                int              const bx,
                 vector *         const motionP,
                 int              const bestSoFar,
                 int              const searchRange) {
@@ -702,7 +708,7 @@ PTwoLevelSearch(const LumBlock * const currentBlockP,
 
     /* try old motion vector first */
     if (VALID_MOTION(*motionP)) {
-        bestDiff = LumMotionError(currentBlockP, prev, by, bx, 
+        bestDiff = LumMotionError(currentBlockP, prev, by, bx,
                                   *motionP, bestSoFar);
 
         if ( bestSoFar < bestDiff ) {
@@ -716,7 +722,7 @@ PTwoLevelSearch(const LumBlock * const currentBlockP,
     ++rightMY;
     ++rightMX;
 
-    /* try a spiral pattern */    
+    /* try a spiral pattern */
     for ( distance = 2; distance <= searchRange; distance += 2 ) {
         tempRightMY = MIN(distance, rightMY);
         tempRightMX = MIN(distance, rightMX);
@@ -729,9 +735,9 @@ PTwoLevelSearch(const LumBlock * const currentBlockP,
                     if (mx >= leftMX) {
                         vector m;
                         m.y = my; m.x = mx;
-                        diff = LumMotionError(currentBlockP, prev, by, bx, m, 
+                        diff = LumMotionError(currentBlockP, prev, by, bx, m,
                                               bestDiff);
-                        
+
                         if (diff < bestDiff) {
                             *motionP = m;
                             bestDiff = diff;
@@ -750,9 +756,9 @@ PTwoLevelSearch(const LumBlock * const currentBlockP,
                         int diff;
                         vector m;
                         m.y = my; m.x = mx;
-                        diff = LumMotionError(currentBlockP, prev, by, bx, m, 
+                        diff = LumMotionError(currentBlockP, prev, by, bx, m,
                                               bestDiff);
-                        
+
                         if ( diff < bestDiff ) {
                             *motionP = m;
                             bestDiff = diff;
@@ -837,6 +843,7 @@ ShowPMVHistogram(fpointer)
 }
 
 
+
 void
 ShowBBMVHistogram(fpointer)
     FILE *fpointer;
@@ -884,6 +891,7 @@ ShowBBMVHistogram(fpointer)
 }
 
 
+
 void
 ShowBFMVHistogram(fpointer)
     FILE *fpointer;
@@ -931,6 +939,7 @@ ShowBFMVHistogram(fpointer)
 }
 
 
+
 /*
  * Copyright (c) 1995 The Regents of the University of California.
  * All rights reserved.
@@ -952,7 +961,7 @@ ShowBFMVHistogram(fpointer)
  * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
  */
 
-/*  
+/*
  *  $Header: /u/smoot/md/mpeg_encode/RCS/psearch.c,v 1.9 1995/01/19 23:09:12 eyhung Exp $
  *  $Log: psearch.c,v $
  * Revision 1.9  1995/01/19  23:09:12  eyhung
diff --git a/converter/ppm/ppmtompeg/qtest.c b/converter/ppm/ppmtompeg/qtest.c
index b3d26593..15e4e197 100644
--- a/converter/ppm/ppmtompeg/qtest.c
+++ b/converter/ppm/ppmtompeg/qtest.c
@@ -19,7 +19,7 @@
  * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
  */
 
-/*  
+/*
  *  $Header: /n/charlie-brown/project/mm/mpeg/mpeg_dist/mpeg_encode/RCS/qtest.c,v 1.5 1995/01/19 23:09:15 eyhung Exp $
  *  $Log: qtest.c,v $
  * Revision 1.5  1995/01/19  23:09:15  eyhung
@@ -50,14 +50,17 @@ main()
     bb = new_bitbucket();
 
     for (i = 0; i < 8; i++)
-	for (j = 0; j < 8; j++)
-	    a[i][j] = rand() % 100;
+        for (j = 0; j < 8; j++)
+            a[i][j] = rand() % 100;
     mp_quant_zig_block(a, b, 1, 1);
     for (i = 0; i < 64; i++)
-	printf("%6d ", b[i]);
+        printf("%6d ", b[i]);
     printf("\n");
 
-    mp_rle_huff_block(b, bb);	/* intuititve names, huh? */
+    mp_rle_huff_block(b, bb);   /* intuititve names, huh? */
 
     printf("Huffman output is %d bits\n", bb->totalbits);
 }
+
+
+
diff --git a/converter/ppm/ppmtompeg/rate.c b/converter/ppm/ppmtompeg/rate.c
index 3fa41102..4237427e 100644
--- a/converter/ppm/ppmtompeg/rate.c
+++ b/converter/ppm/ppmtompeg/rate.c
@@ -1,9 +1,9 @@
 /*============================================================================*
- * rate.c								      *
- *									      *
- *	Procedures concerned with rate control                                *
- *									      *
- * EXPORTED PROCEDURES:							      *
+ * rate.c                                                                     *
+ *                                                                            *
+ *      Procedures concerned with rate control                                *
+ *                                                                            *
+ * EXPORTED PROCEDURES:                                                       *
  *      initRatecontrol()                                                     *
  *      targetRateControl()                                                   *
  *      updateRateControl()                                                   *
@@ -11,7 +11,7 @@
  *      needQScaleChange()                                                    *
  *      incNumBlocks()                                                        *
  *      incQuant()                                                            *
- *	incMacroBlockBits()                                                   *
+ *      incMacroBlockBits()                                                   *
  *      setPictureRate()                                                      *
  *      setBitRate()                                                          *
  *      getBitRate()                                                          *
@@ -19,7 +19,7 @@
  *      getBufferSize()                                                       *
  *                                                                            *
  * NOTES:                                                                     *
- *	Naming conventions follow those of MPEG-2 draft algorithm (chap. 10)  *
+ *      Naming conventions follow those of MPEG-2 draft algorithm (chap. 10)  *
  *============================================================================*/
 
 
@@ -73,7 +73,7 @@
  * GLOBAL VARIABLES *
  *==================*/
 
-#define MAX_BIT_RATE 104857600		/* 18 digit number in units of 400 */
+#define MAX_BIT_RATE 104857600          /* 18 digit number in units of 400 */
 #define MAX_BUFFER_SIZE 16760832        /* 10 digit number in units of 16k */
 #define DEFAULT_BUFFER_SIZE 327680      /* maximum for "constrained" bitstream */
 #define DEFAULT_VBV_FULLNESS 3          /* wait till 1/3 full */
@@ -82,9 +82,9 @@
 #define MAX_VBV_DELAY 32768             /* 16 digits */
 
 
-/*	  Variables from Parameter File */
+/*        Variables from Parameter File */
 
-static int	RateControlMode = VARIABLE_RATE;
+static int      RateControlMode = VARIABLE_RATE;
 static int32 buffer_size = DEFAULT_BUFFER_SIZE;
 static int32 bit_rate = -1;
 
@@ -94,9 +94,9 @@ static bool wantVbvOverflowWarning;
 /*   Variables for the VBV buffer defined in MPEG specs */
 static unsigned int VBV_remainingDelay;
     /* delay in units of 1/90000 seconds */
-static int32 VBV_buffer = 0;	  /* fullness of the theoretical VBV buffer */
+static int32 VBV_buffer = 0;      /* fullness of the theoretical VBV buffer */
 static int32 bufferFillRate = 0;    /* constant rate at which buffer filled */
-static int32 frameDelayIncrement = 0;	/* number of "delay" units/Frame */
+static int32 frameDelayIncrement = 0;   /* number of "delay" units/Frame */
 
 /*  Global complexity measure variables */
 static int Xi, Xp, Xb;  /*  Global complexity measure  */
@@ -108,7 +108,7 @@ static float Qi, Qp, Qb; /* avg quantizaton for last picture of type  */
 /*  Target bit allocations for each type of picture*/
 int Ti, Tp, Tb;
 
-int current_Tx;	/* allocation for current frame */
+int current_Tx; /* allocation for current frame */
 
 /*  Count of number of pictures of each type remaining */
 int GOP_X;
@@ -131,7 +131,7 @@ int rc_totalFrameBits;
 int rc_totalOverheadBits = 0;
 
 
-/*	Want to print out Macroblock info every Nth MB */
+/*      Want to print out Macroblock info every Nth MB */
 int RC_MB_SAMPLE_RATE = 0;
 
 static float Ki = .7;
@@ -150,23 +150,23 @@ static int d0_b;
 static int lastFrameVirtBuf;   /* fullness after last frame of this type */
 static int currentVirtBuf;     /* fullness during current encoding*/
 
-static int MB_cnt = -1;	       /* Number of MB's in picture */
+static int MB_cnt = -1;        /* Number of MB's in picture */
 
 static int rc_Q;               /* reference quantization parameter */
 
 static int reactionParameter;  /*  Reaction parameter */
 
-/*	Adaptive Quantization variables */
+/*      Adaptive Quantization variables */
 static int act_j;              /*  spatial activity measure */
 static float N_act;            /*  Normalized spacial activity */
-static int avg_act;	   /*  average activity value in last picture encoded */
-static int total_act_j;	       /*  Sum of activity values in current frame */
+static int avg_act;        /*  average activity value in last picture encoded */
+static int total_act_j;        /*  Sum of activity values in current frame */
 
-static int var_sblk;	       /* sub-block activity */
-static int P_mean;	       /* Mean value of pixels in 8x8 sub-block */
+static int var_sblk;           /* sub-block activity */
+static int P_mean;             /* Mean value of pixels in 8x8 sub-block */
 
-static int mquant;	       /* Raw Quantization value */
-static int Qscale;	       /* Clipped, truncated quantization value */
+static int mquant;             /* Raw Quantization value */
+static int Qscale;             /* Clipped, truncated quantization value */
 
 
 
@@ -177,7 +177,7 @@ static FILE *RC_FILE;
 
 static char rc_buffer[101];
 
-/*	EXTERNAL Variables  */
+/*      EXTERNAL Variables  */
 extern char *framePattern;
 extern int framePatternLen;
 
@@ -230,9 +230,9 @@ analyzePattern(const char *  const framePattern,
  *
  * initRateControl
  *
- *	initialize the allocation parameters.
+ *      initialize the allocation parameters.
  *
- * RETURNS:	nothing
+ * RETURNS:     nothing
  *
  * SIDE EFFECTS:   many global variables
  *
@@ -292,11 +292,11 @@ initRateControl(bool const wantUnderflowWarning,
     d0_p = (Kp * d0_i);
     d0_b = (Kb * d0_i);
 
-    lastFrameVirtBuf = d0_i;	/*  start with I Frame */
+    lastFrameVirtBuf = d0_i;    /*  start with I Frame */
     rc_Q = lastFrameVirtBuf  * 31 / reactionParameter;
 
     /*   init spatial activity measures */
-    avg_act = 400;		/* Suggested initial value */
+    avg_act = 400;              /* Suggested initial value */
     N_act = 1;
 
     mquant = rc_Q * N_act;
@@ -316,14 +316,16 @@ initRateControl(bool const wantUnderflowWarning,
     return result;
 }
 
+
+
 /*===========================================================================*
  *
  * initGOPRateControl
  *
- *		(re)-initialize the RC for the a new Group of Pictures.
- *	New bit allocation, but carry over complexity measures.
+ *              (re)-initialize the RC for the a new Group of Pictures.
+ *      New bit allocation, but carry over complexity measures.
  *
- * RETURNS:	nothing
+ * RETURNS:     nothing
  *
  * SIDE EFFECTS:   many global variables
  *
@@ -464,7 +466,6 @@ targetRateControl(MpegFrame * const frame) {
 
 
 
-
 static void
 updateVBVBuffer(int const frameBits) {
 /*----------------------------------------------------------------------------
@@ -580,14 +581,15 @@ updateRateControl(int const type) {
 }
 
 
+
 /*===========================================================================*
  *
  * MB_RateOut
  *
  *      Prints out sampling of MB rate control data.  Every "nth" block
- *	stats are printed, with "n" controlled by global RC_MB_SAMPLE_RATE
- *	(NB. "skipped" blocks do not go through this function and thus do not
- *		show up in the sample )
+ *      stats are printed, with "n" controlled by global RC_MB_SAMPLE_RATE
+ *      (NB. "skipped" blocks do not go through this function and thus do not
+ *              show up in the sample )
  *
  * RETURNS:     nothing
  *
@@ -612,8 +614,8 @@ int type;
   pctUsed = (totalBits *100/current_Tx);
 
   sprintf(rc_buffer, "%3d  %5d %2d %3d %6d  %3d %6d   %2.2f   %6d %4d    %3d   %3d\n",
-	  (rc_numBlocks - 1), bitsThisMB, Qscale, mquant, currentVirtBuf,
-	  rc_Q, act_j, N_act, totalBits, bitsPerMB, pctUsed, pctDone);
+          (rc_numBlocks - 1), bitsThisMB, Qscale, mquant, currentVirtBuf,
+          rc_Q, act_j, N_act, totalBits, bitsPerMB, pctUsed, pctDone);
 #ifdef RC_STATS_FILE
   fprintf(RC_FILE, "%s", rc_buffer);
   fflush(RC_FILE);
@@ -647,11 +649,12 @@ void incNumBlocks(num)
 }
 
 
+
 /*===========================================================================*
  *
  * incMacroBlockBits()
  *
- *	Increments the number of Macro Block bits and the total of Frame
+ *      Increments the number of Macro Block bits and the total of Frame
  *  bits by the number passed.
  *
  * RETURNS:   nothing
@@ -670,9 +673,10 @@ void incMacroBlockBits(num)
 }
 
 
+
 /*===========================================================================*
  *
- *   	needQScaleChange(current Q scale, 4 luminance blocks)
+ *      needQScaleChange(current Q scale, 4 luminance blocks)
  *
  *
  * RETURNS:     new Qscale
@@ -689,7 +693,7 @@ int needQScaleChange(oldQScale, blk0, blk1, blk2, blk3)
 {
 
   /*   One more MacroBlock seen */
-  rc_numBlocks++;		/* this notes each block num in MB */
+  rc_numBlocks++;               /* this notes each block num in MB */
 
   checkBufferFullness(oldQScale);
 
@@ -707,12 +711,13 @@ int needQScaleChange(oldQScale, blk0, blk1, blk2, blk3)
 }
 
 
+
 /*===========================================================================*
  *
  * determineMBCount()
  *
  *      Determines number of Macro Blocks in frame from the frame sizes
- *	passed.
+ *      passed.
  *
  * RETURNS:     nothing
  *
@@ -761,12 +766,13 @@ void checkBufferFullness (oldQScale)
 }
 
 
+
 /*===========================================================================*
  *
  * void checkSpatialActivity()
  *
  *      Calculates the spatial activity for the four luminance blocks of the
- *	macroblock.  Along with the normalized reference quantization parameter
+ *      macroblock.  Along with the normalized reference quantization parameter
  *  (rc_Q) , it determines the quantization factor for the next macroblock.
  *
  * RETURNS:     nothing
@@ -796,18 +802,18 @@ void checkSpatialActivity(blk0, blk1, blk2, blk3)
   blkArray[3] = (int16 *) blk3;
 
 
-  for (i =0; i < 4; i++) {	/* Compute the activity in each block */
+  for (i =0; i < 4; i++) {      /* Compute the activity in each block */
     curBlock = blkArray[i];
     blk_ptr = curBlock;
     P_mean = 0;
     /*  Find the mean pixel value */
     for (j=0; j < DCTSIZE_SQ; j ++) {
       P_mean += *(blk_ptr++);
-      /*			P_mean += curBlock[j];
-				if (curBlock[j] != *(blk_ptr++)) {
-				printf("ARRAY ERROR: block %d\n", j);
-				}
-				*/
+      /*                        P_mean += curBlock[j];
+                                if (curBlock[j] != *(blk_ptr++)) {
+                                printf("ARRAY ERROR: block %d\n", j);
+                                }
+                                */
     }
     P_mean /= DCTSIZE_SQ;
 
@@ -818,7 +824,7 @@ void checkSpatialActivity(blk0, blk1, blk2, blk3)
     for (j=0; j < DCTSIZE_SQ; j++) {
 #ifdef notdef
       if (curBlock[j] != *(blk_ptr++)) {
-	printf("ARRAY ERROR: block %d\n", j);
+        printf("ARRAY ERROR: block %d\n", j);
       }
       temp = curBlock[j] - P_mean;
 #endif
@@ -845,7 +851,6 @@ void checkSpatialActivity(blk0, blk1, blk2, blk3)
 
 
 
-
 /*============================================================================*
  *
  * getRateMode ()
@@ -864,19 +869,20 @@ int getRateMode()
 }
 
 
+
 /*===========================================================================*
  *
  * setBitRate ()
  *
  *      Checks the string parsed from the parameter file.  Verifies
  *  number and sets global values. MPEG standard specifies that bit rate
- *	be rounded up to nearest 400 bits/sec.
+ *      be rounded up to nearest 400 bits/sec.
  *
  * RETURNS:     nothing
  *
  * SIDE EFFECTS:   global variables
  *
- * NOTES:	Should this be in the 400-bit units used in sequence header?
+ * NOTES:       Should this be in the 400-bit units used in sequence header?
  *
  *===========================================================================*/
 void setBitRate (const char * const charPtr)
@@ -888,7 +894,7 @@ void setBitRate (const char * const charPtr)
     RateControlMode = FIXED_RATE;
   } else {
     printf("Parameter File Error:  invalid BIT_RATE: \"%s\", defaults to Variable ratemode\n",
-	   charPtr);
+           charPtr);
     RateControlMode = VARIABLE_RATE;
     bit_rate = -1;
   }
@@ -921,7 +927,6 @@ int getBitRate ()
 
 
 
-
 /*===========================================================================*
  *
  * setBufferSize ()
@@ -933,7 +938,7 @@ int getBitRate ()
  *
  * SIDE EFFECTS:   buffer_size global variable.
  *
- * NOTES:	The global is in bits, NOT the 16kb units used in sequence header
+ * NOTES:       The global is in bits, NOT the 16kb units used in sequence header
  *
  *===========================================================================*/
 void setBufferSize (const char * const charPtr)
@@ -948,12 +953,13 @@ void setBufferSize (const char * const charPtr)
   } else {
     buffer_size = DEFAULT_BUFFER_SIZE;
     printf("Parameter File Error:  invalid BUFFER_SIZE: \"%s\", defaults to : %d\n",
-	   charPtr, buffer_size);
+           charPtr, buffer_size);
   }
   DBG_PRINT(("Buffer size is: %d\n", buffer_size));
 }
 
 
+
 /*===========================================================================*
  *
  * getBufferSize ()
diff --git a/converter/ppm/ppmtompeg/readframe.c b/converter/ppm/ppmtompeg/readframe.c
index 2a359b2f..85f432d8 100644
--- a/converter/ppm/ppmtompeg/readframe.c
+++ b/converter/ppm/ppmtompeg/readframe.c
@@ -1,13 +1,13 @@
 /*===========================================================================*
- * readframe.c                    
- *                                
- *  procedures to read in frames  
- *                                
- * EXPORTED PROCEDURES:           
- *  ReadFrame                     
- *  SetFileType                   
- *  SetFileFormat                 
- *                                
+ * readframe.c
+ *
+ *  procedures to read in frames
+ *
+ * EXPORTED PROCEDURES:
+ *  ReadFrame
+ *  SetFileType
+ *  SetFileFormat
+ *
  *===========================================================================*/
 
 /* COPYRIGHT INFORMATION IS AT THE END OF THIS FILE */
@@ -62,7 +62,7 @@ struct YuvLine {
 #ifdef __OS2__
   #define popen _popen
 #endif
-   
+
 
 /*==================*
  * Global VARIABLES *
@@ -100,7 +100,7 @@ static void DoKillDim (MpegFrame *mf, int w, int h);
 
 
 
-void    
+void
 SetResize(bool const set) {
     resizeFrame = set;
 }
@@ -134,7 +134,7 @@ ReadPNM(MpegFrame * const mpegFrameP,
 static void
 openFile(struct inputSource * const inputSourceP,
          unsigned int         const frameNumber,
-         const char *         const conversion, 
+         const char *         const conversion,
          FILE **              const ifPP) {
 
     if (inputSourceP->stdinUsed) {
@@ -145,24 +145,24 @@ openFile(struct inputSource * const inputSourceP,
                 "INPUT_CONVERTER * in the parameter file or supply the "
                 "frames in files by specifying a directory with "
                 "INPUT_DIRECTORY in the parameter file.");
-        
+
         *ifPP = stdin;
     } else {
         const char * fileName;
         const char * fullFileName;
-        
+
         GetNthInputFileName(inputSourceP, frameNumber, &fileName);
-        
+
         pm_asprintf(&fullFileName, "%s/%s", currentPath, fileName);
-        
+
         CurrFile = fullFileName;
-        
+
         if (fileType == ANY_FILE_TYPE) {
             char command[1024];
             const char * convertPtr;
             char * commandPtr;
             const char * charPtr;
-            
+
             /* replace every occurrence of '*' with fullFileName */
             convertPtr = conversion;
             commandPtr = command;
@@ -172,7 +172,7 @@ openFile(struct inputSource * const inputSourceP,
                     ++commandPtr;
                     ++convertPtr;
                 }
-                
+
                 if (*convertPtr == '*') {
                     /* copy fullFileName */
                     charPtr = fullFileName;
@@ -185,7 +185,7 @@ openFile(struct inputSource * const inputSourceP,
                 }
             }
             *commandPtr = '\0';
-            
+
             *ifPP = popen(command, "r");
             if (*ifPP == NULL) {
                 pm_message(
@@ -201,7 +201,7 @@ openFile(struct inputSource * const inputSourceP,
             *ifPP = fopen(fullFileName, "rb");
             if (*ifPP == NULL)
                 pm_error("Couldn't open input file '%s'", fullFileName);
-            
+
             if (baseFormat == JMOVIE_FILE_TYPE)
                 unlink(fullFileName);
         }
@@ -238,7 +238,7 @@ fileIsAtEnd(FILE * const ifP) {
 
     c = getc(ifP);
     if (c == EOF) {
-        if (feof(ifP)) 
+        if (feof(ifP))
             eof = TRUE;
         else
             pm_error("File error on getc() to position to image");
@@ -248,7 +248,7 @@ fileIsAtEnd(FILE * const ifP) {
         eof = FALSE;
 
         rc = ungetc(c, ifP);
-        if (rc == EOF) 
+        if (rc == EOF)
             pm_error("File error doing ungetc() to position to image.");
     }
     return eof;
@@ -262,14 +262,11 @@ ReadFrameFile(MpegFrame *  const frameP,
               const char * const conversion,
               bool *       const eofP) {
 /*----------------------------------------------------------------------------
-   Read a frame from the file 'ifP'.
+   Read a frame from the file 'ifP', doing adjustments as indicated.
 
    Return *eofP == TRUE iff we encounter EOF before we can get the
    frame.
 -----------------------------------------------------------------------------*/
-    MpegFrame   tempFrame;
-    MpegFrame * framePtr;
-
     /* To make this code fit Netpbm properly, we should remove handling
        of all types except PNM and use pm_nextimage() to handle sensing
        of end of stream.
@@ -278,53 +275,59 @@ ReadFrameFile(MpegFrame *  const frameP,
     if (fileIsAtEnd(ifP))
         *eofP = TRUE;
     else {
+        MpegFrame   preResizeFrame;
+            /* The frame object that holds the frame before resizing */
+        MpegFrame * rawFrameP;
+            /* The frame object with which we read in the raw frame */
+
         *eofP = FALSE;
 
         if (resizeFrame) {
-            tempFrame.inUse = FALSE;
-            tempFrame.orig_y = NULL;
-            tempFrame.y_blocks = NULL;
-            tempFrame.decoded_y = NULL;
-            tempFrame.halfX = NULL;
-            framePtr = &tempFrame;
+            preResizeFrame.inUse = FALSE;
+            preResizeFrame.orig_y = NULL;
+            preResizeFrame.y_blocks = NULL;
+            preResizeFrame.decoded_y = NULL;
+            preResizeFrame.halfX = NULL;
+            rawFrameP = &preResizeFrame;
         } else
-            framePtr = frameP;
+            rawFrameP = frameP;
 
         switch(baseFormat) {
         case YUV_FILE_TYPE:
 
             /* Encoder YUV */
             if ((strncmp (yuvConversion, "EYUV", 4) == 0) ||
-                (strncmp (yuvConversion, "UCB", 3) == 0)) 
+                (strncmp (yuvConversion, "UCB", 3) == 0))
 
-                ReadEYUV(framePtr, ifP, realWidth, realHeight);
+                ReadEYUV(rawFrameP, ifP, realWidth, realHeight);
 
             else
                 /* Abekas-type (interlaced) YUV */
-                ReadAYUV(framePtr, ifP, realWidth, realHeight);
+                ReadAYUV(rawFrameP, ifP, realWidth, realHeight);
 
             break;
         case Y_FILE_TYPE:
-            ReadY(framePtr, ifP, realWidth, realHeight);
+            ReadY(rawFrameP, ifP, realWidth, realHeight);
             break;
         case PNM_FILE_TYPE:
-            ReadPNM(framePtr, ifP);
+            ReadPNM(rawFrameP, ifP);
             break;
         case SUB4_FILE_TYPE:
-            ReadSub4(framePtr, ifP, yuvWidth, yuvHeight);
+            ReadSub4(rawFrameP, ifP, yuvWidth, yuvHeight);
             break;
         case JPEG_FILE_TYPE:
         case JMOVIE_FILE_TYPE:
-            ReadJPEG(framePtr, ifP);
+            ReadJPEG(rawFrameP, ifP);
             break;
         default:
             break;
         }
 
-        if (resizeFrame)
-            Frame_Resize(frameP, &tempFrame, Fsize_x, Fsize_y, 
+        if (resizeFrame) {
+            assert(rawFrameP == &preResizeFrame);
+            Frame_Resize(frameP, &preResizeFrame, Fsize_x, Fsize_y,
                          outputWidth, outputHeight);
-    
+        }
         if (GammaCorrection)
             DoGamma(frameP, Fsize_x, Fsize_y);
 
@@ -338,7 +341,7 @@ ReadFrameFile(MpegFrame *  const frameP,
 
 
 void
-ReadFrame(MpegFrame *          const frameP, 
+ReadFrame(MpegFrame *          const frameP,
           struct inputSource * const inputSourceP,
           unsigned int         const frameNumber,
           const char *         const conversion,
@@ -383,6 +386,7 @@ SetFileType(const char * const conversion)
 }
 
 
+
 /*===========================================================================*
  *
  * SetFileFormat
@@ -555,6 +559,8 @@ ReadEYUV(mf, fpointer, width, height)
     /* ignore leftover stuff on the bottom */
 }
 
+
+
 /*===========================================================================*
  *
  * ReadAYUV
@@ -613,6 +619,8 @@ ReadAYUV(mf, fpointer, width, height)
 
 }
 
+
+
 /*===========================================================================*
  *
  * SeparateLine
@@ -693,12 +701,13 @@ SeparateLine(fpointer, lineptr, width)
         fprintf(stderr, "       or any even-length string consisting of the letters U, V, and Y.\n");
             exit(1);
         }
-    
+
     }
 
 }
 
 
+
 /*===========================================================================*
  *
  * ReadY
@@ -738,7 +747,7 @@ ReadY(mf, fpointer, width, height)
     for (y = Fsize_y; y < height; y++) {
     safe_fread(junk, 1, width, fpointer);
     }
-    
+
     for (y = 0 ; y < (Fsize_y >> 1); y++) {
       memset(mf->orig_cb[y], 128, (Fsize_x>>1));
       memset(mf->orig_cr[y], 128, (Fsize_x>>1));
@@ -746,6 +755,7 @@ ReadY(mf, fpointer, width, height)
 }
 
 
+
 /*===========================================================================*
  *
  * ReadSub4
@@ -805,6 +815,7 @@ ReadSub4(mf, fpointer, width, height)
 }
 
 
+
 /*=====================*
  * INTERNAL PROCEDURES *
  *=====================*/
@@ -830,7 +841,7 @@ int w,h;
   int i,j;
 
   if (!init_done) {
-    for(i=0; i<256; i++) 
+    for(i=0; i<256; i++)
       GammaVal[i]=(unsigned char) (pow(((double) i)/255.0,GammaValue)*255.0+0.5);
     init_done=TRUE;
   }
@@ -843,7 +854,6 @@ int w,h;
 
 
 
-
 /*===========================================================================*
  *
  * DoKillDim
@@ -871,7 +881,7 @@ int w,h;
                         ^ kill_dim_break
                              ^kill_dim_end
               kill_dim_slope gives the slope (y = kill_dim_slope * x +0)
-              from 0 to kill_dim_break                      
+              from 0 to kill_dim_break
  *
  *===========================================================================*/
 
@@ -909,6 +919,7 @@ int w,h;
 }
 
 
+
 /*
  * Copyright (c) 1995 The Regents of the University of California.
  * All rights reserved.
@@ -930,7 +941,7 @@ int w,h;
  * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
  */
 
-/*  
+/*
  *  $Header: /n/picasso/project/mpeg/mpeg_dist/mpeg_encode/RCS/readframe.c,v 1.27 1995/08/14 22:31:40 smoot Exp $
  *  $Log: readframe.c,v $
  *  Revision 1.27  1995/08/14 22:31:40  smoot
diff --git a/converter/ppm/ppmtompeg/rgbtoycc.c b/converter/ppm/ppmtompeg/rgbtoycc.c
index 2dd1899a..189003d7 100644
--- a/converter/ppm/ppmtompeg/rgbtoycc.c
+++ b/converter/ppm/ppmtompeg/rgbtoycc.c
@@ -53,23 +53,23 @@ compute_mult_tables(const pixval maxval) {
 
     /* For speed, we do the arithmetic with eight tables that reduce a
        bunch of multiplications and divisions to a simple table lookup.
-       
+
        Because a large maxval could require a significant amount of
        table space, we allocate the space dynamically.
 
-       If we had to compute the tables for every frame, it wouldn't be 
+       If we had to compute the tables for every frame, it wouldn't be
        fast at all, but since all the frames normally have the same
        maxval, we only need to compute them once.  But just in case,
        we check each frame to see if it has a different maxval and
        recompute the tables if so.
     */
-    
+
     if (table_maxval != maxval) {
         /* We need to compute or re-compute the multiplication tables */
         if (table_maxval != 0) {
             free(mult299); free(mult587); free(mult114); free(mult16874);
-            free(mult33126); free(mult5); free(mult41869); free(mult08131);  
-        } 
+            free(mult33126); free(mult5); free(mult41869); free(mult08131);
+        }
         table_maxval = maxval;
 
         mult299   = malloc((table_maxval+1)*sizeof(float));
@@ -83,18 +83,18 @@ compute_mult_tables(const pixval maxval) {
 
         if (mult299 == NULL || mult587 == NULL || mult114 == NULL ||
             mult16874 == NULL || mult33126 == NULL || mult5 == NULL ||
-            mult41869 == NULL || mult08131 == NULL) 
+            mult41869 == NULL || mult08131 == NULL)
             pm_error("Unable to allocate storage for arithmetic tables.  "
                      "We need %d bytes, which is the maxval of the input "
                      "image, plus 1, "
-                     "times the storage size of a floating point value.", 
+                     "times the storage size of a floating point value.",
                      (unsigned)(8 * (table_maxval+1)*sizeof(float)));
 
         {
             int index;
 
             for (index = 0; index <= table_maxval; index++ ) {
-                mult299[index]   = index*0.29900  * 255 / table_maxval; 
+                mult299[index]   = index*0.29900  * 255 / table_maxval;
                 mult587[index]   = index*0.58700  * 255 / table_maxval;
                 mult114[index]   = index*0.11400  * 255 / table_maxval;
                 mult16874[index] = -0.16874*index * 255 / table_maxval;
@@ -108,6 +108,7 @@ compute_mult_tables(const pixval maxval) {
 }
 
 
+
 /*=====================*
  * EXPORTED PROCEDURES *
  *=====================*/
@@ -195,10 +196,13 @@ PNMtoYUV(MpegFrame *  const frameP,
                      mult41869[PPM_GETG(src1[1])] +
                      mult08131[PPM_GETB(src1[1])]) / 4) + 128;
 
-            DBG_PRINT(("%3d,%3d: (%3d,%3d,%3d) --> (%3d,%3d,%3d)\n", 
-                       x, y, 
-                       PPM_GETR(*src0), PPM_GETG(*src0), PPM_GETB(*src0), 
+            DBG_PRINT(("%3d,%3d: (%3d,%3d,%3d) --> (%3d,%3d,%3d)\n",
+                       x, y,
+                       PPM_GETR(*src0), PPM_GETG(*src0), PPM_GETB(*src0),
                        *dy0, *dcb, *dcr));
         }
     }
 }
+
+
+
diff --git a/converter/ppm/ppmtompeg/specifics.c b/converter/ppm/ppmtompeg/specifics.c
index aa3d7b18..acf98116 100644
--- a/converter/ppm/ppmtompeg/specifics.c
+++ b/converter/ppm/ppmtompeg/specifics.c
@@ -1,13 +1,13 @@
 /*===========================================================================*
- * specifics.c								     *
- *									     *
- *	basic procedures to deal with the specifics file                     *
- *									     *
- * EXPORTED PROCEDURES:							     *
- *	Specifics_Init							     *
+ * specifics.c                                                               *
+ *                                                                           *
+ *      basic procedures to deal with the specifics file                     *
+ *                                                                           *
+ * EXPORTED PROCEDURES:                                                      *
+ *      Specifics_Init                                                       *
  *      Spec_Lookup                                                          *
  *      SpecTypeLookup                                                       *
- *									     *
+ *                                                                           *
  *===========================================================================*/
 
 /*
@@ -41,6 +41,7 @@
 
 #include "netpbm/mallocvar.h"
 #include "netpbm/nstring.h"
+#include "netpbm/pm_system.h"
 
 #include "all.h"
 #include "mtypes.h"
@@ -68,7 +69,7 @@ void Parse_Specifics_File_v2 (FILE *fp);
 FrameSpecList *MakeFslEntry (void);
 void AddSlc (FrameSpecList *c,int snum, int qs);
 Block_Specifics *AddBs (FrameSpecList *c,int bnum,
-				    boolean rel, int qs);
+                                    boolean rel, int qs);
 FrameSpecList *MakeFslEntry (void);
 #define my_upper(c) (((c>='a') && (c<='z')) ? (c-'a'+'A') : c)
 #define CvtType(x) ReallyCvt(my_upper(x))
@@ -152,38 +153,37 @@ static char version = -1;
 void
 Specifics_Init() {
 
-    FILE *specificsFP;
+    /* 'specificsFile' is a global variable whose value is the name of the
+       specifics file, given by the parameter file.
+    */
+
+    FILE *       specificsFP;
+    const char * preprocessedFileNm;
+
+    pm_message("Specifics file: %s", specificsFile);
+
+    pm_asprintf(&preprocessedFileNm, "%s.cpp", specificsFile);
+
+    pm_system_lp("rm", NULL, NULL, NULL, NULL, "-f", preprocessedFileNm);
 
     {
         const char * command;
-        pm_asprintf(&command, "rm -f %s.cpp", specificsFile);
-        system(command);
-        pm_strfree(command);
-    }
-    {
-        const char * command;
-        pm_asprintf(&command, "cpp -P %s %s %s.cpp",
-                    specificsDefines, specificsFile, specificsFile);
-        system(command);
+        pm_asprintf(&command, "cpp -P %s '%s' -o '%s'",
+                    specificsDefines, specificsFile, preprocessedFileNm);
+        pm_system(NULL, NULL, NULL, NULL, command);
         pm_strfree(command);
     }
-    strcat(specificsFile, ".cpp");
-    if ((specificsFP = fopen(specificsFile, "r")) == NULL) {
-        fprintf(stderr, "Error with specifics file, cannot open %s\n",
-                specificsFile);
-        exit(1);
-    }
-    printf("Specifics file: %s\n", specificsFile);
+
+    specificsFP = pm_openr(preprocessedFileNm);
+
+    pm_system_lp("rm", NULL, NULL, NULL, NULL, "-f", preprocessedFileNm);
 
     Parse_Specifics_File(specificsFP);
-    {
-        const char * command;
-        pm_asprintf(&command, "rm -f %s.cpp", specificsFile);
-        system(command);
-        pm_strfree(command);
-    }
-}
 
+    pm_close(specificsFP);
+
+    pm_strfree(preprocessedFileNm);
+}
 
 
 
@@ -221,24 +221,24 @@ FILE *fp;
     case 'V':
       lp += 7;
       if (1 != sscanf(lp, "%d", &vers)) {
-	fprintf(stderr," Improper version line in specs file: %s\n", line);
+        fprintf(stderr," Improper version line in specs file: %s\n", line);
       } else {
-	switch (vers) {
-	case 1:
-	  version = vers;
-	  Parse_Specifics_File_v1(fp);
-	  break;
-	case 2:
-	  version = vers;
-	  Parse_Specifics_File_v2(fp);
-	  break;
-	default:
-	  fprintf(stderr, "Improper version line in specs file: %s\n", line);
-	  fprintf(stderr, "\tSpecifics file will be IGNORED.\n");
-	  specificsOn = FALSE;
-	  return;
-	  break;
-	}}
+        switch (vers) {
+        case 1:
+          version = vers;
+          Parse_Specifics_File_v1(fp);
+          break;
+        case 2:
+          version = vers;
+          Parse_Specifics_File_v2(fp);
+          break;
+        default:
+          fprintf(stderr, "Improper version line in specs file: %s\n", line);
+          fprintf(stderr, "\tSpecifics file will be IGNORED.\n");
+          specificsOn = FALSE;
+          return;
+          break;
+        }}
       break;
     default:
       fprintf(stderr, "Specifics file: What? *%s*\n", line);
@@ -247,6 +247,8 @@ FILE *fp;
 
 }
 
+
+
 /* Version 1 */
 void Parse_Specifics_File_v1(fp)
 FILE *fp;
@@ -271,9 +273,9 @@ FILE *fp;
       lp += 6;
       sscanf(lp, "%d %c %d", &fnum, &typ, &qs);
       if (current->framenum != -1) {
-	new=MakeFslEntry();
-	current->next = new;
-	current = new;
+        new=MakeFslEntry();
+        current->next = new;
+        current = new;
       }
       current->framenum = fnum;
       current->frametype = CvtType(typ);
@@ -442,7 +444,6 @@ Parse_Specifics_File_v2(FILE * const fP) {
 
 
 
-
 /*=================================================================
  *
  *     MakeFslEntry
@@ -467,8 +468,6 @@ FrameSpecList *MakeFslEntry()
 
 
 
-
-
 /*================================================================
  *
  *   AddSlc
@@ -503,8 +502,6 @@ int snum,qs;
 
 
 
-
-
 /*================================================================
  *
  *   AddBs
@@ -544,9 +541,6 @@ int bnum,qs;
 
 
 
-
-
-
 /*================================================================
  *
  *  SpecLookup
@@ -581,8 +575,8 @@ int start_qs;
     found_it = FALSE;
     while (tmp != (FrameSpecList *) NULL) {
       if (tmp->framenum == fn) {
-	found_it = TRUE;
-	break;
+        found_it = TRUE;
+        break;
       } else tmp = tmp->next;
     }
     if (!found_it) return -1;
@@ -591,20 +585,20 @@ int start_qs;
     if (last->framenum != fn) { /* cache miss! */
       /* first check if it is next */
       if ((last->next != (FrameSpecList *) NULL) &&
-	  (last->next->framenum == fn)) {
-	last = last->next;
+          (last->next->framenum == fn)) {
+        last = last->next;
       } else {
-	/* if not next, check from the start.
-	   (this allows people to put frames out of order,even
-	   though the spec doesn't allow it.) */
-	tmp = fsl;
-	found_it = FALSE;
-	while (tmp != (FrameSpecList *) NULL) {
-	  if (tmp->framenum==fn) {found_it = TRUE; break;}
-	  tmp = tmp->next;
-	}
-	if (!found_it) return -1;
-	last = tmp;
+        /* if not next, check from the start.
+           (this allows people to put frames out of order,even
+           though the spec doesn't allow it.) */
+        tmp = fsl;
+        found_it = FALSE;
+        while (tmp != (FrameSpecList *) NULL) {
+          if (tmp->framenum==fn) {found_it = TRUE; break;}
+          tmp = tmp->next;
+        }
+        if (!found_it) return -1;
+        last = tmp;
       }
     }
   }
@@ -634,10 +628,10 @@ int start_qs;
     for (sptr = last->slc; sptr != (Slice_Specifics *) NULL; sptr = sptr->next) {
       if (sptr->num == num) {
 #ifdef BLEAH
-	printf("QSchange Slice %d.%d to %d\n", fn, num, sptr->qscale);
+        printf("QSchange Slice %d.%d to %d\n", fn, num, sptr->qscale);
 #endif
-	if (sptr->qscale == 0) return -1;
-	return sptr->qscale;
+        if (sptr->qscale == 0) return -1;
+        return sptr->qscale;
       }
     }
     break;
@@ -649,30 +643,30 @@ int start_qs;
     }
     for (bptr=last->bs; bptr != (Block_Specifics *) NULL; bptr=bptr->next) {
       if (bptr->num == num) {
-	int new_one;
+        int new_one;
 #ifdef BLEAH
-	printf("QSchange Block %d.%d to %d\n", fn, num, bptr->qscale);
+        printf("QSchange Block %d.%d to %d\n", fn, num, bptr->qscale);
 #endif
-	*info = bptr->mv;
-	if (bptr->relative) {
-	  if (bptr->qscale == 0) {
-	    /* Do nothing! */
-	    new_one = start_qs;
-	  } else {
-	    new_one = start_qs + bptr->qscale + leftovers;
-	    if (new_one < 1) {
-	      leftovers = new_one - 1;
-	      new_one = 1;
-	    } else if (new_one > 31) {
-	      leftovers = new_one - 31;
-	      new_one = 31;
-	    } else leftovers = 0;
-	  }}
-	else {
-	  new_one = bptr->qscale;
-	  leftovers = 0;
-	}
-	return new_one;
+        *info = bptr->mv;
+        if (bptr->relative) {
+          if (bptr->qscale == 0) {
+            /* Do nothing! */
+            new_one = start_qs;
+          } else {
+            new_one = start_qs + bptr->qscale + leftovers;
+            if (new_one < 1) {
+              leftovers = new_one - 1;
+              new_one = 1;
+            } else if (new_one > 31) {
+              leftovers = new_one - 31;
+              new_one = 31;
+            } else leftovers = 0;
+          }}
+        else {
+          new_one = bptr->qscale;
+          leftovers = 0;
+        }
+        return new_one;
       }
     }
     break;
@@ -685,6 +679,7 @@ int start_qs;
 }
 
 
+
 /*================================================================
  *
  *  SpecTypeLookup
@@ -718,3 +713,6 @@ int fn;
 #endif
   return tmp->frametype;
 }
+
+
+
diff --git a/converter/ppm/ppmtompeg/subsample.c b/converter/ppm/ppmtompeg/subsample.c
index 69401a1d..e411feb4 100644
--- a/converter/ppm/ppmtompeg/subsample.c
+++ b/converter/ppm/ppmtompeg/subsample.c
@@ -67,14 +67,14 @@ computePrevFyFx(MpegFrame * const prevFrame,
         if (yHalf) {
             if (m.y < 0)
                 --*fyP;
-        
+
             *prevP = prevFrame->halfBoth;
         } else
             *prevP = prevFrame->halfX;
     } else if (yHalf) {
         if (m.y < 0)
             --*fyP;
-        
+
         *prevP = prevFrame->halfY;
     } else
         *prevP = prevFrame->ref_y;
@@ -185,7 +185,7 @@ LumMotionErrorB(const LumBlock * const currentBlockP,
     computePrevFyFx(prevFrame, by, bx, m, &prev, &fy, &fx);
 
     diff = 0;  /* initial value */
-    
+
     for (rowNumber = 0; rowNumber < 16; rowNumber +=2) {
         uint8 *       const macross    = &(prev[fy + rowNumber][fx]);
         const int32 * const currentRow = currentBlockP->l[rowNumber];
@@ -199,6 +199,7 @@ LumMotionErrorB(const LumBlock * const currentBlockP,
 }
 
 
+
 /*===========================================================================*
  *
  * LumMotionErrorC
@@ -226,7 +227,7 @@ LumMotionErrorC(const LumBlock * const currentBlockP,
     computePrevFyFx(prevFrame, by, bx, m, &prev, &fy, &fx);
 
     diff = 0;  /* initial value */
-    
+
     for (rowNumber = 1; rowNumber < 16; rowNumber +=2) {
         uint8 *       const macross    = &(prev[fy + rowNumber][fx]);
         const int32 * const currentRow = currentBlockP->l[rowNumber];
@@ -240,6 +241,7 @@ LumMotionErrorC(const LumBlock * const currentBlockP,
 }
 
 
+
 /*===========================================================================*
  *
  * LumMotionErrorD
@@ -279,3 +281,6 @@ LumMotionErrorD(const LumBlock * const currentBlockP,
     }
     return diff;
 }
+
+
+
diff --git a/converter/ppm/ppmtoneo.c b/converter/ppm/ppmtoneo.c
index 5703c12a..d573e9e6 100644
--- a/converter/ppm/ppmtoneo.c
+++ b/converter/ppm/ppmtoneo.c
@@ -121,3 +121,6 @@ main(int argc, char *argv[] ) {
 
     exit( 0 );
 }
+
+
+
diff --git a/converter/ppm/ppmtopcx.c b/converter/ppm/ppmtopcx.c
index 5b7e1003..68ad4db0 100644
--- a/converter/ppm/ppmtopcx.c
+++ b/converter/ppm/ppmtopcx.c
@@ -17,6 +17,7 @@
 ** http://bespin.org/~qz/pc-gpe/pcx.txt
 ** http://web.archive.org/web/20100206055706/http://www.qzx.com/pc-gpe/pcx.txt
 */
+#include <stdbool.h>
 #include <assert.h>
 
 #include "pm_c_util.h"
@@ -83,8 +84,6 @@ parseCommandLine(int argc, const char ** argv,
    was passed to us as the argv array.  We also trash *argv.
 -----------------------------------------------------------------------------*/
     optEntry * option_def;
-        /* Instructions to pm_optParseOptions3 on how to parse our options.
-         */
     optStruct3 opt;
 
     unsigned int option_def_index;
@@ -112,10 +111,10 @@ parseCommandLine(int argc, const char ** argv,
     OPTENT3(0, "ypos",  OPT_INT, &cmdlineP->ypos, &yposSpec,   0);
 
     opt.opt_table = option_def;
-    opt.short_allowed = FALSE;  /* We have no short (old-fashioned) options */
-    opt.allowNegNum = FALSE;  /* We have no parms that are negative numbers */
+    opt.short_allowed = false;  /* We have no short (old-fashioned) options */
+    opt.allowNegNum = false;  /* We have no parms that are negative numbers */
 
-    pm_optParseOptions3( &argc, (char **)argv, opt, sizeof(opt), 0 );
+    pm_optParseOptions4(&argc, argv, opt, sizeof(opt), 0 );
         /* Uses and sets argc, argv, and some of *cmdline_p and others. */
 
     if (!xposSpec)
diff --git a/converter/ppm/ppmtopi1.c b/converter/ppm/ppmtopi1.c
index 64f836c7..896ec7f7 100644
--- a/converter/ppm/ppmtopi1.c
+++ b/converter/ppm/ppmtopi1.c
@@ -118,3 +118,6 @@ main( argc, argv )
 
     exit( 0 );
     }
+
+
+
diff --git a/converter/ppm/ppmtopict.c b/converter/ppm/ppmtopict.c
index 36464b6c..c7f1d61d 100644
--- a/converter/ppm/ppmtopict.c
+++ b/converter/ppm/ppmtopict.c
@@ -12,8 +12,10 @@
 */
 
 #include <assert.h>
+
 #include "pm_c_util.h"
 #include "pm.h"
+#include "mallocvar.h"
 #include "ppm.h"
 
 #define HEADER_SIZE     512
@@ -130,14 +132,15 @@
 #define PICT_headerOp       0x0C00
 
 #define MAXCOLORS 256
-static colorhash_table cht;
 
 
 
 static void
 putFill(FILE *       const ifP,
         unsigned int const n) {
-
+/*----------------------------------------------------------------------------
+   Write 'n' bytes of zeroes to *ifP.
+-----------------------------------------------------------------------------*/
     unsigned int i;
 
     for (i = 0; i < n; ++i)
@@ -194,19 +197,21 @@ putRect(FILE * const ifP,
 #define     counttochar(c)  ((c)-1)
 
 static void
-putRow(FILE *         const ofP,
-       unsigned int   const row,
-       unsigned int   const cols,
-       pixel *        const rowpixels,
-       char *         const outBuf,
-       unsigned int * const outCountP) {
+putRow(FILE *          const ofP,
+       unsigned int    const row,
+       unsigned int    const cols,
+       pixel *         const rowpixels,
+       colorhash_table const cht,
+       unsigned char * const outBuf,
+       unsigned int *  const outCountP) {
 /*----------------------------------------------------------------------------
    Write the row rowpixels[], which is 'cols' pixels wide and is row 'row' of
    the image, to file *ofP in PICT format.
 
    Return as *outCountP the number of bytes we write to *ofP.
 
-   Use buffer 'outBuf'.
+   Use buffer 'outBuf', which is at least 1.5*cols + 1 bytes -- the worst
+   case compacted size of the row.
 -----------------------------------------------------------------------------*/
     unsigned int i;
     unsigned int count;
@@ -214,13 +219,13 @@ putRow(FILE *         const ofP,
     unsigned int rep;
     unsigned int outCount;
     pixel lastpix;
-    char * p;
+    unsigned int outCursor;
 
-    run = 0;
-    count = 0;
-    lastpix = rowpixels[cols-1];
+    run = 0;  /* initial value */
+    count = 0;  /* initial value */
+    lastpix = rowpixels[cols-1];  /* initial value */
 
-    for (i = 0, p = &outBuf[0]; i < cols; ++i) {
+    for (i = 0, outCursor = 0; i < cols; ++i) {
 
         pixel const pix = rowpixels[cols - 1 - i];
 
@@ -228,23 +233,23 @@ putRow(FILE *         const ofP,
             ++run;
         else if (run < RUN_THRESH) {
             while (run > 0) {
-                *p++ = ppm_lookupcolor(cht, &lastpix);
+                outBuf[outCursor++] = ppm_lookupcolor(cht, &lastpix);
                 --run;
                 ++count;
                 if (count == MAX_COUNT) {
-                    *p++ = counttochar(MAX_COUNT);
+                    outBuf[outCursor++] = counttochar(MAX_COUNT);
                     count -= MAX_COUNT;
                 }
             }
             run = 1;
         } else {
             if (count > 0)
-                *p++ = counttochar(count);
+                outBuf[outCursor++] = counttochar(count);
             count = 0;
             while (run > 0) {
                 rep = MIN(run, MAX_RUN);
-                *p++ = ppm_lookupcolor(cht, &lastpix);
-                *p++ = runtochar(rep);
+                outBuf[outCursor++] = ppm_lookupcolor(cht, &lastpix);
+                outBuf[outCursor++] = runtochar(rep);
                 assert(run >= rep);
                 run -= rep;
             }
@@ -254,46 +259,43 @@ putRow(FILE *         const ofP,
     }
     if (run < RUN_THRESH) {
         while (run > 0) {
-            *p++ = ppm_lookupcolor(cht, &lastpix);
+            outBuf[outCursor++] = ppm_lookupcolor(cht, &lastpix);
             --run;
             ++count;
             if (count == MAX_COUNT) {
-                *p++ = counttochar(MAX_COUNT);
+                outBuf[outCursor++] = counttochar(MAX_COUNT);
                 count -= MAX_COUNT;
             }
         }
     } else {
         if (count > 0)
-            *p++ = counttochar(count);
+            outBuf[outCursor++] = counttochar(count);
         count = 0;
         while (run > 0) {
             rep = MIN(run, MAX_RUN);
-            *p++ = ppm_lookupcolor(cht, &lastpix);
-            *p++ = runtochar(rep);
+            outBuf[outCursor++] = ppm_lookupcolor(cht, &lastpix);
+            outBuf[outCursor++] = runtochar(rep);
             assert(run >= rep);
             run -= rep;
         }
         run = 1;
     }
     if (count > 0)
-        *p++ = counttochar(count);
+        outBuf[outCursor++] = counttochar(count);
 
-    {
-        unsigned int const packcols = p - outBuf;
-            /* How many we wrote */
-        if (cols-1 > 200) {
-            putShort(ofP, packcols);
-            outCount = packcols + 2;
-        } else {
-            putc(packcols, ofP);
-            outCount = packcols + 1;
-        }
-    }
-    /* now write out the packed row */
-    while (p != outBuf) {
-        --p;
-        putc(*p, ofP);
+    /* Write out the packed row */
+
+    if (cols-1 > 200) {
+        putShort(ofP, outCursor);
+        outCount = outCursor + 2;
+    } else {
+        putc(outCursor, ofP);
+        outCount = outCursor + 1;
     }
+
+    for (i = 0; i < outCursor; ++i)
+        putc(outBuf[outCursor-i-1], ofP);
+
     *outCountP = outCount;
 }
 
@@ -303,12 +305,13 @@ putRow(FILE *         const ofP,
 
 /* real dumb putRow with no compression */
 static void
-putRow(FILE *         const ifP,
-       unsigned int   const row,
-       unsigned int   const cols,
-       pixel *        const rowpixels,
-       char *         const outBuf,
-       unsigned int * const outCountP) {
+putRow(FILE *          const ifP,
+       unsigned int    const row,
+       unsigned int    const cols,
+       pixel *         const rowpixels,
+       char *          const outBuf,
+       colorhash_table const cht,
+       unsigned int *  const outCountP) {
 
     unsigned int const bc = cols + (cols + MAX_COUNT - 1) / MAX_COUNT;
 
@@ -345,20 +348,82 @@ putRow(FILE *         const ifP,
 
 
 
+static void
+writeColorMap(FILE *           const ofP,
+              colorhist_vector const chv,
+              unsigned int     const colorCt,
+              long             const lmaxval) {
+
+    unsigned int i;
+
+    for (i = 0; i < colorCt; ++i) {
+        long rval, gval, bval;
+
+        putShort(ofP, i);
+        rval = PPM_GETR(chv[i].color);
+        gval = PPM_GETG(chv[i].color);
+        bval = PPM_GETB(chv[i].color);
+        if (lmaxval != 65535L) {
+            rval = rval * 65535L / lmaxval;
+            gval = gval * 65535L / lmaxval;
+            bval = bval * 65535L / lmaxval;
+        }
+        putShort(ofP, (short)rval);
+        putShort(ofP, (short)gval);
+        putShort(ofP, (short)bval);
+    }
+}
+
+
+
+static void
+writeRaster(FILE *          const ofP,
+            pixel **        const pixels,
+            unsigned int    const rows,
+            unsigned int    const cols,
+            colorhash_table const cht) {
+
+    unsigned char * outBuf;  /* malloc'ed */
+    unsigned int oc;
+    unsigned int row;
+
+    if (cols > UINT_MAX - cols/MAX_COUNT - 1) {
+        /* We can't compute the size of buffer 'putRow' needs for worst-case
+           compaction.
+        */
+        pm_error("Image is too wide (%u columns) for computation", cols);
+    }
+
+    MALLOCARRAY(outBuf, cols + cols/MAX_COUNT + 1);
+    if (!outBuf)
+        pm_error("Unable to allocate %u-byte row buffer",
+                 cols + cols/MAX_COUNT + 1);
+
+    for (row = 0, oc = 0; row < rows; ++row) {
+        unsigned int rowSize;
+        putRow(ofP, row, cols, pixels[row], cht, outBuf, &rowSize);
+        oc += rowSize;
+    }
+    /* Pad to an even number of pixdata bytes */
+    if (oc & 0x1)
+        putc(0, ofP);
+
+    free(outBuf);
+}
+
+
+
 int
 main(int argc, const char ** argv) {
 
     FILE * ifP;
-    int nColors;
-    unsigned int oc;
-    unsigned int i;
+    int colorCt;
     int rows, cols;
-    unsigned int row;
     pixel ** pixels;
-    char * outBuf;
     pixval maxval;
-    long lmaxval, rval, gval, bval;
     colorhist_vector chv;
+    colorhash_table cht;
+    long lmaxval;
 
     pm_proginit(&argc, argv);
 
@@ -367,8 +432,8 @@ main(int argc, const char ** argv) {
     else
         ifP = stdin;
     if (argc-1 > 1)
-        pm_error("Too many arguments.  The only argument is the "
-                 "input file name");
+        pm_error("Too many arguments (%u).  The only argument is the "
+                 "input file name", argc-1);
 
     pixels = ppm_readppm(ifP, &cols, &rows, &maxval);
     if (cols < 8)
@@ -378,19 +443,19 @@ main(int argc, const char ** argv) {
 
     /* Figure out the colormap. */
     pm_message("computing colormap..." );
-    chv = ppm_computecolorhist(pixels, cols, rows, MAXCOLORS, &nColors);
+    chv = ppm_computecolorhist(pixels, cols, rows, MAXCOLORS, &colorCt);
     if (chv == NULL)
         pm_error("too many colors - try doing a 'pnmquant %u'", MAXCOLORS);
-    pm_message("%u colors found", nColors);
+    pm_message("%u colors found", colorCt);
 
     /* Make a hash table for fast color lookup. */
-    cht = ppm_colorhisttocolorhash(chv, nColors);
+    cht = ppm_colorhisttocolorhash(chv, colorCt);
 
     /* write the header */
     putFill(stdout, HEADER_SIZE);
 
     /* write picSize and picFrame */
-    putShort(stdout, 0);
+    putShort(stdout, 0);  /* We overwrite this later when we know the size */
     putRect(stdout, 0, 0, rows, cols);
 
     /* write version op and version */
@@ -427,43 +492,24 @@ main(int argc, const char ** argv) {
     putLong(stdout, 0L);    /* pmReserved */
     putLong(stdout, 0L);    /* ctSeed */
     putShort(stdout, 0);    /* ctFlags */
-    putShort(stdout, nColors-1); /* ctSize */
+    putShort(stdout, colorCt-1); /* ctSize */
 
-    /* Write out the colormap. */
-    for (i = 0; i < nColors; ++i) {
-        putShort(stdout, i);
-        rval = PPM_GETR(chv[i].color);
-        gval = PPM_GETG(chv[i].color);
-        bval = PPM_GETB(chv[i].color);
-        if (lmaxval != 65535L) {
-            rval = rval * 65535L / lmaxval;
-            gval = gval * 65535L / lmaxval;
-            bval = bval * 65535L / lmaxval;
-        }
-        putShort(stdout, (short)rval);
-        putShort(stdout, (short)gval);
-        putShort(stdout, (short)bval);
-    }
+    writeColorMap(stdout, chv, colorCt, lmaxval);
 
     putRect(stdout, 0, 0, rows, cols);  /* srcRect */
     putRect(stdout, 0, 0, rows, cols);  /* dstRect */
     putShort(stdout, 0);            /* mode */
 
-    /* Finally, write out the data. */
-    outBuf = malloc((unsigned)(cols+cols/MAX_COUNT+1));
-    for (row = 0, oc = 0; row < rows; ++row) {
-        unsigned int rowSize;
-        putRow(stdout, row, cols, pixels[row], outBuf, &rowSize);
-        oc += rowSize;
-    }
-    /* if we wrote an odd number of pixdata bytes, pad */
-    if (oc & 0x1)
-        putc(0, stdout);
+    writeRaster(stdout, pixels, rows, cols, cht);
+
     putShort(stdout, PICT_EndOfPicture);
 
-    lmaxval = ftell(stdout) - HEADER_SIZE;
-    if (fseek(stdout, (long)HEADER_SIZE, 0) >= 0)
-        putShort(stdout, (short)(lmaxval & 0xffff));
+    {
+        /* patch size of pict in */
+        long const picSz = ftell(stdout) - HEADER_SIZE;
+        if (fseek(stdout, (long)HEADER_SIZE, 0) >= 0)
+            putShort(stdout, (short)(picSz & 0xffff));
+    }
 
     return 0;
 }
diff --git a/converter/ppm/ppmtopj.c b/converter/ppm/ppmtopj.c
index d116773f..8fe6c05d 100644
--- a/converter/ppm/ppmtopj.c
+++ b/converter/ppm/ppmtopj.c
@@ -1,4 +1,4 @@
-/* ppmtopj.c - convert a portable pixmap to an HP PainJetXL image
+/* ppmtopj.c - convert a PPM to an HP PainJetXL image
 **
 ** Copyright (C) 1990 by Christos Zoulas (christos@ee.cornell.edu)
 **
@@ -12,245 +12,263 @@
 
 #include <string.h>
 
+#include "mallocvar.h"
 #include "nstring.h"
 #include "ppm.h"
 
-static int compress_row ARGS((unsigned char *op, unsigned char *oe, unsigned char *cp));
 /*
  * XXX: Only 8.5 x 11 paper
  */
-#define WIDTH	  8.5
-#define HEIGHT	  11.0
-#define DPI	  180
-#define XPIX	  ((int) ((DPI * WIDTH + 7) / 8) << 3)
-#define YPIX	  ((int) ((DPI * HEIGHT + 7) / 8) << 3)
-
-#define C_RESET 			"\033E"
-#define C_RENDER 			"\033*t%dJ"
-# define C_RENDER_NONE			0
-# define C_RENDER_SNAP			1
-# define C_RENDER_BW			2
-# define C_RENDER_DITHER		3
-# define C_RENDER_DIFFUSE		4
-# define C_RENDER_MONODITHER		5
-# define C_RENDER_MONODIFFUSE		6
-# define C_RENDER_MONO_CL_DITHER	5
-# define C_RENDER_MONO_CL_DIFFUSE	6
-#define C_BACK_SCALE			"\033*t%dK"
-# define C_BACK_SCALE_LIGHT		0
-# define C_BACK_SCALE_DARK		1
-#define C_GAMMA				"\033*t%dI"
-#define C_IMAGE_WIDTH			"\033*r%dS"
-#define C_IMAGE_HEIGHT			"\033*r%dT"
-#define C_DATA_PLANES			"\033*r%dU"
-#define C_TRANS_MODE			"\033*b%dM"
-# define C_TRANS_MODE_STD		0
-# define C_TRANS_MODE_RLE		1
-# define C_TRANS_MODE_TIFF		2
-#define C_SEND_PLANE			"\033*b%dV"
-#define C_LAST_PLANE			"\033*b%dW"
-#define C_BEGIN_RASTER			"\033*r%dA"
-# define C_BEGIN_RASTER_MARGIN		0
-# define C_BEGIN_RASTER_ACTIVE		1
-# define C_BEGIN_RASTER_NOSCALE		0
-# define C_BEGIN_RASTER_SCALE		2
-#define C_END_RASTER			"\033*r%dC"
-# define C_END_RASTER_UNUSED		0
-#define C_RESOLUTION			"\033*t%dR"
-# define C_RESOLUTION_90DPI		90
-# define C_RESOLUTION_180DPI		180
-#define C_MOVE_X			"\033*p+%dX"
-#define C_MOVE_Y			"\033*p+%dY"
-
-static const char * const rmode[] = { 
-    "none", "snap", "bw", "dither", "diffuse", 
-    "monodither", "monodiffuse", "clusterdither", 
-    "monoclusterdither", NULL 
+#define WIDTH     8.5
+#define HEIGHT    11.0
+#define DPI   180
+#define XPIX      ((int) ((DPI * WIDTH + 7) / 8) << 3)
+#define YPIX      ((int) ((DPI * HEIGHT + 7) / 8) << 3)
+
+#define C_RESET             "\033E"
+#define C_RENDER            "\033*t%dJ"
+# define C_RENDER_NONE          0
+# define C_RENDER_SNAP          1
+# define C_RENDER_BW            2
+# define C_RENDER_DITHER        3
+# define C_RENDER_DIFFUSE       4
+# define C_RENDER_MONODITHER        5
+# define C_RENDER_MONODIFFUSE       6
+# define C_RENDER_MONO_CL_DITHER    5
+# define C_RENDER_MONO_CL_DIFFUSE   6
+#define C_BACK_SCALE            "\033*t%dK"
+# define C_BACK_SCALE_LIGHT     0
+# define C_BACK_SCALE_DARK      1
+#define C_GAMMA             "\033*t%dI"
+#define C_IMAGE_WIDTH           "\033*r%dS"
+#define C_IMAGE_HEIGHT          "\033*r%dT"
+#define C_DATA_PLANES           "\033*r%dU"
+#define C_TRANS_MODE            "\033*b%dM"
+# define C_TRANS_MODE_STD       0
+# define C_TRANS_MODE_RLE       1
+# define C_TRANS_MODE_TIFF      2
+#define C_SEND_PLANE            "\033*b%dV"
+#define C_LAST_PLANE            "\033*b%dW"
+#define C_BEGIN_RASTER          "\033*r%dA"
+# define C_BEGIN_RASTER_MARGIN      0
+# define C_BEGIN_RASTER_ACTIVE      1
+# define C_BEGIN_RASTER_NOSCALE     0
+# define C_BEGIN_RASTER_SCALE       2
+#define C_END_RASTER            "\033*r%dC"
+# define C_END_RASTER_UNUSED        0
+#define C_RESOLUTION            "\033*t%dR"
+# define C_RESOLUTION_90DPI     90
+# define C_RESOLUTION_180DPI        180
+#define C_MOVE_X            "\033*p+%dX"
+#define C_MOVE_Y            "\033*p+%dY"
+
+static const char * const rmode[] = {
+    "none",
+    "snap",
+    "bw",
+    "dither",
+    "diffuse",
+    "monodither",
+    "monodiffuse",
+    "clusterdither",
+    "monoclusterdither",
+    NULL
 };
 
-/*
- * Run-length encoding for the PaintJet. We have pairs of <instances>
- * <value>, where instances goes from 0 (meaning one instance) to 255
- * If we are unlucky we can double the size of the image.
- */
-static int
-compress_row(op, oe, cp)
-unsigned char *op, *oe, *cp;
-{
-    unsigned char *ce = cp;
-    while ( op < oe ) {	
-	unsigned char px = *op++;
-	unsigned char *pr = op;
-	while ( op < oe && *op == px && op - pr < 255) op++;
-	*ce++ = op - pr;
-	*ce++ = px;
+
+
+static void
+compressRow(const unsigned char * const opArg,
+            const unsigned char * const oe,
+            unsigned char *       const cp,
+            int *                 const szP) {
+/*----------------------------------------------------------------------------
+  Run-length encoding for the PaintJet. We have pairs of <instances> <value>,
+  where instances goes from 0 (meaning one instance) to 255 If we are unlucky
+  we can double the size of the image.
+-----------------------------------------------------------------------------*/
+    unsigned char * ce;
+    const unsigned char * op;
+
+    for (op = opArg, ce = cp; op < oe; ) {
+        unsigned char         const px = *op++;
+        const unsigned char * const pr = op;
+
+        while (op < oe && *op == px && op - pr < 255)
+            ++op;
+
+        *ce++ = op - pr;
+        *ce++ = px;
     }
-    return ce - cp;
+    *szP = ce - cp;
 }
 
-int main(argc, argv)
-int argc;
-char *argv[];
-{
-	pixel **pixels;
-	FILE *ifp;
-	int argn, rows, cols, r, c, k, p;
-	pixval maxval;
-	unsigned char *obuf, *op, *cbuf;
-	int render_mode = C_RENDER_NONE;
-	int back_scale = C_BACK_SCALE_DARK;
-	int gamma = 0;
-	int mode = C_TRANS_MODE_STD;
-	int center = 0;
-	int xoff = 0, yoff = 0;
-	/*
-	 * XXX: Someday we could make this command line options.
-	 */
-	int posscale = C_BEGIN_RASTER_MARGIN | C_BEGIN_RASTER_NOSCALE;
-	int resolution = C_RESOLUTION_180DPI;
-
-	const char * const usage = "[-center] [-xpos <pos>] [-ypos <pos>] [-gamma <val>] [-back <dark|lite>] [-rle] [-render <none|snap|bw|dither|diffuse|monodither|monodiffuse|clusterdither|monoclusterdither>] [ppmfile]";
-
-
-	ppm_init( &argc, argv );
-
-	argn = 1;
-	while ( argn < argc && argv[argn][0] == '-' && argv[argn][1] != '\0' )
-	    {
-	    if ( pm_keymatch(argv[argn],"-render",2) && argn + 1 < argc )
-		{
-		++argn;
-		for (r = 0; rmode[r] != NULL; r++)
-		     if (streq(rmode[r], argv[argn]))
-			 break;
-		if (rmode[r] != NULL)
-		    render_mode = r;
-		else
-		    pm_usage(usage);
-		}
-	    else if ( pm_keymatch(argv[argn],"-back",2) && argn + 1 < argc )
-		{
-		++argn;
-		if (streq(argv[argn], "dark"))
-		    back_scale = C_BACK_SCALE_DARK;
-		else if (streq(argv[argn], "lite"))
-		    back_scale = C_BACK_SCALE_LIGHT;
-		else
-		    pm_usage(usage);
-		}
-	    else if ( pm_keymatch(argv[argn],"-gamma",2) && argn + 1 < argc )
-		{
-		++argn;
-		if ( sscanf( argv[argn], "%d",&gamma ) != 1 )
-		    pm_usage( usage );
-		}
-	    else if ( pm_keymatch(argv[argn],"-xpos",2) && argn + 1 < argc )
-		{
-		++argn;
-		if ( sscanf( argv[argn], "%d",&xoff ) != 1 )
-		    pm_usage( usage );
-		}
-	    else if ( pm_keymatch(argv[argn],"-ypos",2) && argn + 1 < argc )
-		{
-		++argn;
-		if ( sscanf( argv[argn], "%d",&yoff ) != 1 )
-		    pm_usage( usage );
-		}
-	    else if (pm_keymatch(argv[argn],"-rle",2))
-		mode = C_TRANS_MODE_RLE;
-	    else if (pm_keymatch(argv[argn],"-center",2))
-		center = 1;
-	    else
-		pm_usage( usage );
-	    ++argn;
-	    }
-
-	if ( argn < argc )
-	    {
-	    ifp = pm_openr( argv[argn] );
-	    ++argn;
-	    }
-	else
-	    ifp = stdin;
-
-	if ( argn != argc )
-	    pm_usage( usage );
-
-	pixels = ppm_readppm( ifp, &cols, &rows, &maxval );
-
-	pm_close( ifp );
-	obuf = (unsigned char *) pm_allocrow(cols, sizeof(unsigned char));
-	cbuf = (unsigned char *) pm_allocrow(cols * 2, sizeof(unsigned char));
-
-        if (cols > XPIX || rows > YPIX)
-	    pm_message("image too large for page");
-        if (center) {
-	    if (xoff || yoff)
-		pm_error("cannot specify both center and position");
-	    xoff = (XPIX - cols) / 2;
-	    yoff = (YPIX - rows) / 2;
-	}
-
-	(void) printf(C_RESET);
-	/*
-	 * Set the resolution before begin raster otherwise it
-	 * does not work.
-	 */
-	(void) printf(C_RESOLUTION, resolution);
-	(void) printf(C_BEGIN_RASTER, posscale);
-	if (xoff)
-	    (void) printf(C_MOVE_X, xoff);
-	if (yoff)
-	    (void) printf(C_MOVE_Y, yoff);
-	(void) printf(C_TRANS_MODE, mode);
-	(void) printf(C_RENDER, render_mode);
-	(void) printf(C_BACK_SCALE, back_scale);
-	(void) printf(C_GAMMA,	 gamma);
-	(void) printf(C_IMAGE_WIDTH, cols);
-	(void) printf(C_IMAGE_HEIGHT, rows);
-	(void) printf(C_DATA_PLANES, 3);
-
-        for (r = 0; r < rows; r++)
-	    /* for each primary */
-	    for (p = 0; p < 3; p++) {
-		switch (p) {
-		case 0:
-		    for (c = 0, op = &obuf[-1]; c < cols; c++) {
-			if ((k = (c & 7)) == 0)
-			    *++op = 0;
-			if (PPM_GETR(pixels[r][c]) > maxval / 2)
-			    *op |= 1 << (7 - k);
-		    }
-		    break;
-		case 1:
-		    for (c = 0, op = &obuf[-1]; c < cols; c++) {
-			if ((k = (c & 7)) == 0)
-			    *++op = 0;
-			if (PPM_GETG(pixels[r][c]) > maxval / 2)
-			    *op |= 1 << (7 - k);
-		    }
-		    break;
-		case 2:
-		    for (c = 0, op = &obuf[-1]; c < cols; c++) {
-			if ((k = (c & 7)) == 0)
-			    *++op = 0;
-			if (PPM_GETB(pixels[r][c]) > maxval / 2)
-			    *op |= 1 << (7 - k);
-		    }
-		    break;
-		}
-		++op;
-		if (mode == C_TRANS_MODE_RLE) {
-		    k = compress_row(obuf, op, cbuf);
-		    op = cbuf;
-		}
-		else {
-		    k = op - obuf;
-		    op = obuf;
-		}
-		(void) printf(p == 2 ? C_LAST_PLANE : C_SEND_PLANE, k);
-		(void) fwrite(op, 1, k, stdout);
-	    }
-	(void) printf(C_END_RASTER, C_END_RASTER_UNUSED);
-	exit(0);
+
+
+int
+main(int argc, const char ** argv) {
+
+    pixel ** pixels;
+    FILE * ifP;
+    int argn, rows, cols, k;
+    unsigned int row;
+    pixval maxval;
+    unsigned char *obuf, *op, *cbuf;
+    int render_mode = C_RENDER_NONE;
+    int back_scale = C_BACK_SCALE_DARK;
+    int gamma = 0;
+    int mode = C_TRANS_MODE_STD;
+    int center = 0;
+    int xoff = 0, yoff = 0;
+    /*
+     * XXX: Someday we could make this command line options.
+     */
+    int const posscale = C_BEGIN_RASTER_MARGIN | C_BEGIN_RASTER_NOSCALE;
+    int const resolution = C_RESOLUTION_180DPI;
+
+    const char * const usage = "[-center] [-xpos <pos>] [-ypos <pos>] [-gamma <val>] [-back <dark|lite>] [-rle] [-render <none|snap|bw|dither|diffuse|monodither|monodiffuse|clusterdither|monoclusterdither>] [ppmfile]";
+
+
+    pm_proginit( &argc, argv );
+
+    argn = 1;
+    while ( argn < argc && argv[argn][0] == '-' && argv[argn][1] != '\0' )
+        {
+        if ( pm_keymatch(argv[argn],"-render",2) && argn + 1 < argc )
+        {
+        unsigned int r;
+        ++argn;
+        for (r = 0; rmode[r] != NULL; r++)
+             if (streq(rmode[r], argv[argn]))
+             break;
+        if (rmode[r] != NULL)
+            render_mode = r;
+        else
+            pm_usage(usage);
+        }
+        else if ( pm_keymatch(argv[argn],"-back",2) && argn + 1 < argc )
+        {
+        ++argn;
+        if (streq(argv[argn], "dark"))
+            back_scale = C_BACK_SCALE_DARK;
+        else if (streq(argv[argn], "lite"))
+            back_scale = C_BACK_SCALE_LIGHT;
+        else
+            pm_usage(usage);
+        }
+        else if ( pm_keymatch(argv[argn],"-gamma",2) && argn + 1 < argc )
+        {
+        ++argn;
+        if ( sscanf( argv[argn], "%d",&gamma ) != 1 )
+            pm_usage( usage );
+        }
+        else if ( pm_keymatch(argv[argn],"-xpos",2) && argn + 1 < argc )
+        {
+        ++argn;
+        if ( sscanf( argv[argn], "%d",&xoff ) != 1 )
+            pm_usage( usage );
+        }
+        else if ( pm_keymatch(argv[argn],"-ypos",2) && argn + 1 < argc )
+        {
+        ++argn;
+        if ( sscanf( argv[argn], "%d",&yoff ) != 1 )
+            pm_usage( usage );
+        }
+        else if (pm_keymatch(argv[argn],"-rle",2))
+        mode = C_TRANS_MODE_RLE;
+        else if (pm_keymatch(argv[argn],"-center",2))
+        center = 1;
+        else
+        pm_usage( usage );
+        ++argn;
+        }
+
+    if ( argn < argc )
+        {
+        ifP = pm_openr( argv[argn] );
+        ++argn;
+        }
+    else
+        ifP = stdin;
+
+    if ( argn != argc )
+        pm_usage( usage );
+
+    pixels = ppm_readppm(ifP, &cols, &rows, &maxval);
+
+    pm_close(ifP);
+
+    MALLOCARRAY_NOFAIL(obuf, cols);
+
+    if (cols > UINT_MAX / 2)
+        pm_error("Image too wide (%u columns) for computation", cols);
+
+    MALLOCARRAY_NOFAIL(cbuf, cols * 2);
+
+    if (cols > XPIX || rows > YPIX)
+        pm_message("image too large for page");
+
+    if (center) {
+        if (xoff || yoff)
+        pm_error("cannot specify both center and position");
+        xoff = (XPIX - cols) / 2;
+        yoff = (YPIX - rows) / 2;
+    }
+
+    printf(C_RESET);
+    /*
+     * Set the resolution before begin raster otherwise it
+     * does not work.
+     */
+    printf(C_RESOLUTION, resolution);
+    printf(C_BEGIN_RASTER, posscale);
+    if (xoff)
+        printf(C_MOVE_X, xoff);
+    if (yoff)
+        printf(C_MOVE_Y, yoff);
+    printf(C_TRANS_MODE, mode);
+    printf(C_RENDER, render_mode);
+    printf(C_BACK_SCALE, back_scale);
+    printf(C_GAMMA,   gamma);
+    printf(C_IMAGE_WIDTH, cols);
+    printf(C_IMAGE_HEIGHT, rows);
+    printf(C_DATA_PLANES, 3);
+
+    for (row = 0; row < rows; ++row) {
+        /* for each primary */
+        unsigned int plane;
+        for (plane = 0; plane < 3; ++plane) {
+            unsigned int col;
+
+            for (col = 0, op = &obuf[-1]; col < cols; ++col) {
+                pixel  const p = pixels[row][col];
+                pixval const comp =
+                    plane == 0 ? PPM_GETR(p) :
+                    plane == 1 ? PPM_GETG(p) :
+                    plane == 2 ? PPM_GETB(p) :
+                    0; /* can't happen */
+
+                if ((k = (col & 0x7)) == 0)
+                    *++op = 0;
+                if (comp > maxval / 2)
+                        *op |= 1 << (7 - k);
+            }
+            ++op;
+            if (mode == C_TRANS_MODE_RLE) {
+                compressRow(obuf, op, cbuf, &k);
+                op = cbuf;
+            } else {
+                k = op - obuf;
+                op = obuf;
+            }
+            printf(plane == 2 ? C_LAST_PLANE : C_SEND_PLANE, k);
+            fwrite(op, 1, k, stdout);
+        }
+    }
+    printf(C_END_RASTER, C_END_RASTER_UNUSED);
+
+    exit(0);
 }
+
+
+
diff --git a/converter/ppm/ppmtopjxl.c b/converter/ppm/ppmtopjxl.c
index 90bcef0f..daaf7d59 100644
--- a/converter/ppm/ppmtopjxl.c
+++ b/converter/ppm/ppmtopjxl.c
@@ -1,7 +1,7 @@
 /* ppmtopcl.c - convert PPM into PCL language for HP PaintJet and
  *              PaintJet XL color printers
  * AJCD 12/3/91
- * 
+ *
  * usage:
  *       ppmtopcl [-nopack] [-gamma <n>] [-presentation] [-dark]
  *          [-diffuse] [-cluster] [-dither]
@@ -18,6 +18,7 @@
 #include <string.h>
 
 #include "pm_c_util.h"
+#include "mallocvar.h"
 #include "nstring.h"
 #include "ppm.h"
 #include "runlength.h"
@@ -47,7 +48,7 @@ static int yshift = 0;
 static int quality = 0;
 static double xscale = 0.0;
 static double yscale = 0.0;
-static double gamma_val = 0.0;
+static double gammaVal = 0.0;
 
 /* argument types */
 #define DIM 0
@@ -58,7 +59,7 @@ static const struct options {
     int type;
     void *value;
 } options[] = {
-   {"-gamma",        REAL, &gamma_val },
+   {"-gamma",        REAL, &gammaVal },
    {"-presentation", BOOL, &quality },
    {"-width",        DIM,  &xsize },
    {"-xsize",        DIM,  &xsize },
@@ -86,12 +87,12 @@ putword(unsigned short const w) {
 
 
 static unsigned int
-bitsperpixel(unsigned int v) {
+bitwidth(unsigned int v) {
 
     unsigned int bpp;
 
     /* calculate # bits for value */
-    
+
     for (bpp = 0; v > 0; ) {
         ++bpp;
         v >>= 1;
@@ -101,83 +102,350 @@ bitsperpixel(unsigned int v) {
 
 
 
-static char *inrow = NULL;
-static char *outrow = NULL;
-/* "signed" was commented out below, but it caused warnings on an SGI 
+/* The following belong to the bit putter.  They really should be in a
+   struct passed to the methods of the bit putter instead.
+*/
+
+static char *inrow;
+static char *outrow;
+/* "signed" was commented out below, but it caused warnings on an SGI
    compiler, which defaulted to unsigned character.  2001.03.30 BJH */
-static signed char *runcnt = NULL;
+static signed char * runcnt;
+static int out = 0;
+static int cnt = 0;
+static int num = 0;
+static bool pack = false;
+
+static void
+initbits(unsigned int const bytesPerRow) {
+
+    MALLOCARRAY(inrow,  bytesPerRow);
+    MALLOCARRAY(outrow, bytesPerRow * 2);
+    MALLOCARRAY(runcnt, bytesPerRow);
+
+    if (!inrow || !outrow || !runcnt)
+        pm_error("can't allocate space for row");
+}
+
+
+
+static void
+termbits() {
+
+    free(runcnt);
+    free(outrow);
+    free(inrow);
+}
 
-static void 
-putbits(int const bArg,
-        int const nArg) {
+
+
+static void
+putbits(unsigned int const bArg,
+        unsigned int const nArg) {
 /*----------------------------------------------------------------------------
-  Put 'n' bits in 'b' out, packing into bytes; n=0 flushes bits.
+  Add 'bArg' to byte-packing output buffer as 'n' bits.
 
-  n should never be > 8 
+  n should never be > 8
 -----------------------------------------------------------------------------*/
-    static int out = 0;
-    static int cnt = 0;
-    static int num = 0;
-    static bool pack = false;
-
     int b;
     int n;
+    int xo;
+    int xc;
 
     b = bArg;
     n = nArg;
 
-    if (n) {
-        int xo = 0;
-        int xc = 0;
+    assert(n <= 8);
+
+    if (cnt + n > 8) {  /* overflowing current byte? */
+        xc = cnt + n - 8;
+        xo = (b & ~(-1 << xc)) << (8-xc);
+        n -= xc;
+        b >>= xc;
+    } else {
+        xo = 0;
+        xc = 0;
+    }
+
+    cnt += n;
 
-        assert(n <= 8);
+    out |= (b & ~(-1 << n)) << (8-cnt);
 
-        if (cnt + n > 8) {  /* overflowing current byte? */
-            xc = cnt + n - 8;
-            xo = (b & ~(-1 << xc)) << (8-xc);
-            n -= xc;
-            b >>= xc;
-        }
-        cnt += n;
-        out |= (b & ~(-1 << n)) << (8-cnt);
-        if (cnt >= 8) {
-            inrow[num++] = out;
-            out = xo;
-            cnt = xc;
+    if (cnt >= 8) {
+        inrow[num++] = out;
+        out = xo;
+        cnt = xc;
+    }
+}
+
+
+
+static void
+flushbits() {
+/*----------------------------------------------------------------------------
+   flush a row of buffered bits.
+-----------------------------------------------------------------------------*/
+    if (cnt) {
+        inrow[num++] = out;
+        out = cnt = 0;
+    }
+    for (; num > 0 && inrow[num-1] == 0; --num);
+    /* remove trailing zeros */
+    printf("\033*b");
+    if (num && !nopack) {            /* TIFF 4.0 packbits encoding */
+        size_t outSize;
+        pm_rlenc_compressbyte(
+            (unsigned char *)inrow, (unsigned char *)outrow,
+            PM_RLE_PACKBITS, num, &outSize);
+        if (outSize < num) {
+            num = outSize;
+            if (!pack) {
+                printf("2m");
+                pack = true;
+            }
+        } else {
+            if (pack) {
+                printf("0m");
+                pack = false;
+            }
         }
-    } else { /* flush row */
-        if (cnt) {
-            inrow[num++] = out;
-            out = cnt = 0;
+    }
+    printf("%dW", num);
+    {
+        unsigned int i;
+        for (i = 0; i < num; ++i)
+            putchar(pack ? outrow[i] : inrow[i]);
+    }
+    num = 0; /* new row */
+}
+
+
+
+static void
+computeColormap(pixel **           const pixels,
+                unsigned int       const cols,
+                unsigned int       const rows,
+                unsigned int       const maxColors,
+                colorhist_vector * const chvP,
+                colorhash_table *  const chtP,
+                unsigned int *     const colorCtP) {
+
+    colorhist_vector chv;
+    colorhash_table cht;
+    int colorCt;
+
+    pm_message("Computing colormap...");
+
+    chv = ppm_computecolorhist(pixels, cols, rows, MAXCOLORS, &colorCt);
+    if (!chv)
+        pm_error("too many colors; reduce to %u or fewer with 'pnmquant'",
+                 MAXCOLORS);
+
+    pm_message("... Done.  %u colors found.", colorCt);
+
+    /* And make a hash table for fast lookup. */
+    cht = ppm_colorhisttocolorhash(chv, colorCt);
+
+    *chvP     = chv;
+    *chtP     = cht;
+    *colorCtP = colorCt;
+}
+
+
+
+static unsigned int
+nextPowerOf2(unsigned int const arg) {
+/*----------------------------------------------------------------------------
+   Works only on 0-7
+-----------------------------------------------------------------------------*/
+        switch (arg) { /* round up to 1,2,4,8 */
+        case 0:                         return 0; break;
+        case 1:                         return 1; break;
+        case 2:                         return 2; break;
+        case 3: case 4:                 return 4; break;
+        case 5: case 6: case 7: case 8: return 8; break;
+        default:
+            assert(false);
         }
-        for (; num > 0 && inrow[num-1] == 0; --num);
-            /* remove trailing zeros */
-        printf("\033*b"); 
-        if (num && !nopack) {            /* TIFF 4.0 packbits encoding */
-            size_t outSize;
-            pm_rlenc_compressbyte(
-                (unsigned char *)inrow, (unsigned char *)outrow,
-                PM_RLE_PACKBITS, num, &outSize); 
-            if (outSize < num) {
-                num = outSize;
-                if (!pack) {
-                    printf("2m");
-                    pack = true;
-                }
-            } else {
-                if (pack) {
-                    printf("0m");
-                    pack = false;
-                }
+}
+
+
+
+static void
+computeColorDownloadingMode(unsigned int   const colorCt,
+                            unsigned int   const cols,
+                            pixval         const maxval,
+                            unsigned int * const bytesPerRowP,
+                            bool *         const colorMappedP,
+                            unsigned int * const bitsPerPixelRedP,
+                            unsigned int * const bitsPerPixelGrnP,
+                            unsigned int * const bitsPerPixelBluP,
+                            unsigned int * const bitsPerIndexP) {
+/*----------------------------------------------------------------------------
+-----------------------------------------------------------------------------*/
+    unsigned int const indexBitCt = bitwidth(colorCt);
+
+    assert(colorCt > 0);
+    assert(indexBitCt > 0);
+
+    if (indexBitCt > 8) {
+        /* Can't use indexed mode */
+        /* We will instead write 1-3 full bytes per pixel, with those
+           bytes divided into red bits, green bits, and blue bits.  We
+           pad the red bits as needed to fill out whole bytes.  We
+           stick to 1, 2, 4, or 8 bits per pixel only because this program's
+           bit writer can't handle more than 8, which would happen with those
+           padded red fields if we allowed e.g. 7 bits for green and blue
+           (ergo 10 bits for red).
+        */
+        unsigned int const bitsPerSample = nextPowerOf2(bitwidth(maxval));
+        unsigned int const bitsPerPixel  = ROUNDUP(3 * bitsPerSample, 8);
+        unsigned int const bytesPerPixel = bitsPerPixel / 8;
+
+        *colorMappedP     = false;
+        *bitsPerPixelGrnP = bitsPerSample;
+        *bitsPerPixelBluP = bitsPerSample;
+        *bitsPerPixelRedP =
+            bitsPerPixel - *bitsPerPixelGrnP - *bitsPerPixelBluP;
+        *bytesPerRowP = bytesPerPixel * cols;
+    } else {
+        unsigned int const bitsPerPixel = nextPowerOf2(indexBitCt);
+
+        unsigned int pixelsPerByte;
+
+        *colorMappedP = true;
+
+        *bitsPerIndexP = bitsPerPixel;
+        pixelsPerByte = 8 / bitsPerPixel;
+        *bytesPerRowP = (cols + pixelsPerByte - 1) / pixelsPerByte;
+    }
+    if (*colorMappedP)
+        pm_message("Writing %u bit color indices", *bitsPerIndexP);
+    else
+        pm_message("Writing direct color, %u red bits, %u green, %u blue",
+                   *bitsPerPixelRedP, *bitsPerPixelGrnP, *bitsPerPixelBluP);
+}
+
+
+
+static void
+writePclHeader(unsigned int const cols,
+               unsigned int const rows,
+               pixval       const maxval,
+               int          const xshift,
+               int          const yshift,
+               unsigned int const quality,
+               unsigned int const xsize,
+               unsigned int const ysize,
+               double       const gammaVal,
+               unsigned int const dark,
+               unsigned int const render,
+               bool         const colorMapped,
+               unsigned int const bitsPerPixelRed,
+               unsigned int const bitsPerPixelGrn,
+               unsigned int const bitsPerPixelBlu,
+               unsigned int const bitsPerIndex) {
+
+#if 0
+    printf("\033&l26A");                         /* paper size */
+#endif
+    printf("\033*r%us%uT", cols, rows);          /* source width, height */
+    if (xshift != 0 || yshift != 0)
+        printf("\033&a%+dh%+dV", xshift, yshift); /* xshift, yshift */
+    if (quality)
+        printf("\033*o%uQ", quality);             /* print quality */
+    printf("\033*t");
+    if (xsize == 0 && ysize == 0)
+        printf("180r");                   /* resolution */
+    else {                               /* destination width, height */
+        if (xsize != 0)
+            printf("%uh", xsize);
+        if (ysize != 0)
+            printf("%uv", ysize);
+    }
+    if (gammaVal != 0)
+        printf("%.3fi", gammaVal);                    /* gamma correction */
+    if (dark)
+        printf("%uk", dark);              /* scaling algorithms */
+    printf("%uJ", render);               /* rendering algorithm */
+    printf("\033*v18W");                           /* configure image data */
+    putchar(0); /* relative colors */
+    putchar(colorMapped ? 1 : 3); /* index/direct pixel mode */
+    putchar(bitsPerIndex); /* ignored in direct pixel mode */
+    putchar(colorMapped ? 0 : bitsPerPixelRed);
+    putchar(colorMapped ? 0 : bitsPerPixelGrn);
+    putchar(colorMapped ? 0 : bitsPerPixelBlu);
+    putword(maxval); /* max red reference */
+    putword(maxval); /* max green reference */
+    putword(maxval); /* max blue reference */
+    putword(0); /* min red reference */
+    putword(0); /* min green reference */
+    putword(0); /* min blue reference */
+}
+
+
+
+static void
+writePalette(colorhist_vector const chv,
+             unsigned int     const colorCt) {
+
+    unsigned int i;
+
+    for (i = 0; i < colorCt; ++i) {
+        unsigned int const r = PPM_GETR( chv[i].color);
+        unsigned int const g = PPM_GETG( chv[i].color);
+        unsigned int const b = PPM_GETB( chv[i].color);
+
+        if (i == 0)
+            printf("\033*v");
+        if (r)
+            printf("%ua", r);
+        if (g)
+            printf("%ub", g);
+        if (b)
+            printf("%uc", b);
+        if (i == colorCt - 1)
+            printf("%uI", i);    /* assign color index */
+        else
+            printf("%ui", i);    /* assign color index */
+    }
+}
+
+
+
+static void
+writeRaster(pixel **        const pixels,
+            unsigned int    const rows,
+            unsigned int    const cols,
+            colorhash_table const cht,
+            bool            const colorMapped,
+            unsigned int    const bitsPerIndex,
+            unsigned int    const bitsPerPixelRed,
+            unsigned int    const bitsPerPixelGrn,
+            unsigned int    const bitsPerPixelBlu) {
+
+    unsigned int row;
+
+    for (row = 0; row < rows; ++row) {
+        pixel * const pixrow = pixels[row];
+
+        if (colorMapped) {
+            unsigned int col;
+
+            for (col = 0; col < cols; ++col)
+                putbits(ppm_lookupcolor(cht, &pixrow[col]), bitsPerIndex);
+            flushbits();
+        } else {
+            unsigned int col;
+
+            for (col = 0; col < cols; ++col) {
+                putbits(PPM_GETR(pixrow[col]), bitsPerPixelRed);
+                putbits(PPM_GETG(pixrow[col]), bitsPerPixelGrn);
+                putbits(PPM_GETB(pixrow[col]), bitsPerPixelBlu);
+                /* don't need to flush */
             }
+            flushbits();
         }
-        printf("%dW", num);
-        {
-            unsigned int i;
-            for (i = 0; i < num; ++i)
-                putchar(pack ? outrow[i] : inrow[i]);
-        }
-        num = 0; /* new row */
     }
 }
 
@@ -188,16 +456,17 @@ main(int argc, const char * argv[]) {
 
     FILE * ifP;
     pixel ** pixels;
-    unsigned int row;
-    unsigned int bpp;
     int rows, cols;
     pixval maxval;
-    int bpr, bpg, bpb;
+    bool colorMapped;
+    unsigned int bytesPerRow;
+    unsigned int bitsPerPixelRed, bitsPerPixelGrn, bitsPerPixelBlu;
+    unsigned int bitsPerIndex;
     int render;
-    int colors, pclindex;
+    unsigned int colorCt;
     colorhist_vector chv;
     colorhash_table cht;
-   
+
     pm_proginit(&argc, argv);
 
     while (argc > 1 && argv[1][0] == '-') {
@@ -267,42 +536,14 @@ main(int argc, const char * argv[]) {
     if (maxval > PCL_MAXVAL)
         pm_error("color range too large; reduce with ppmcscale");
 
-    /* Figure out the colormap. */
-    pm_message("Computing colormap...");
-    chv = ppm_computecolorhist(pixels, cols, rows, MAXCOLORS, &colors);
-    if (!chv)
-        pm_error("too many colors; reduce with pnmquant");
-    pm_message("... Done.  %u colors found.", colors);
+    computeColormap(pixels, cols, rows, MAXCOLORS, &chv, &cht, &colorCt);
 
-    /* And make a hash table for fast lookup. */
-    cht = ppm_colorhisttocolorhash(chv, colors);
-
-    /* work out color downloading mode */
-    pclindex = bitsperpixel(colors);
-    if (pclindex > 8) /* can't use indexed mode */
-        pclindex = 0;
-    else {
-        switch (pclindex) { /* round up to 1,2,4,8 */
-        case 0: /* direct mode (no palette) */
-            bpp = bitsperpixel(maxval); /* bits per pixel */
-            bpg = bpp; bpb = bpp;
-            bpp = (bpp*3+7)>>3;     /* bytes per pixel now */
-            bpr = (bpp<<3)-bpg-bpb; 
-            bpp *= cols;            /* bytes per row now */
-            break;
-        case 5:         pclindex++;
-        case 6:         pclindex++;
-        case 3: case 7: pclindex++;
-        default:
-            bpp = 8/pclindex;
-            bpp = (cols+bpp-1)/bpp;      /* bytes per row */
-        }
-    }
-    inrow = (char *)malloc((unsigned)bpp);
-    outrow = (char *)malloc((unsigned)bpp*2);
-    runcnt = (signed char *)malloc((unsigned)bpp);
-    if (inrow == NULL || outrow == NULL || runcnt == NULL)
-        pm_error("can't allocate space for row");
+    computeColorDownloadingMode(
+        colorCt, cols, maxval,
+        &bytesPerRow, &colorMapped,
+        &bitsPerPixelRed, &bitsPerPixelGrn, &bitsPerPixelBlu, &bitsPerIndex);
+
+    initbits(bytesPerRow);
 
     /* set up image details */
     if (xscale != 0.0)
@@ -310,92 +551,31 @@ main(int argc, const char * argv[]) {
     if (yscale != 0.0)
         ysize = rows * yscale * 4;
 
-    /* write PCL header */
-#if 0
-    printf("\033&l26A");                         /* paper size */
-#endif
-    printf("\033*r%ds%dT", cols, rows);          /* source width, height */
-    if (xshift != 0 || yshift != 0)
-        printf("\033&a%+dh%+dV", xshift, yshift); /* xshift, yshift */
-    if (quality)
-        printf("\033*o%dQ", quality);             /* print quality */
-    printf("\033*t");
-    if (xsize == 0 && ysize == 0)
-        printf("180r");                   /* resolution */
-    else {                               /* destination width, height */
-        if (xsize != 0)
-            printf("%dh", xsize);
-        if (ysize != 0)
-            printf("%dv", ysize);
-    }
-    if (gamma_val != 0)
-        printf("%.3fi", gamma_val);                    /* gamma correction */
-    if (dark)
-        printf("%dk", dark);              /* scaling algorithms */
-    printf("%dJ", render);               /* rendering algorithm */
-    printf("\033*v18W");                           /* configure image data */
-    putchar(0); /* relative colors */
-    putchar(pclindex ? 1 : 3); /* index/direct pixel mode */
-    putchar(pclindex); /* ignored in direct pixel mode */
-    if (pclindex) {
-        putchar(0);
-        putchar(0);
-        putchar(0);
-    } else {
-        putchar(bpr); /* bits per red */
-        putchar(bpg); /* bits per green */
-        putchar(bpb); /* bits per blue */
-    }
-    putword(maxval); /* max red reference */
-    putword(maxval); /* max green reference */
-    putword(maxval); /* max blue reference */
-    putword(0); /* min red reference */
-    putword(0); /* min green reference */
-    putword(0); /* min blue reference */
-    if (pclindex) {                        /* set palette */
-        unsigned int i;
-        for (i = 0; i < colors; ++i) {
-            int const r = PPM_GETR( chv[i].color);
-            int const g = PPM_GETG( chv[i].color);
-            int const b = PPM_GETB( chv[i].color);
-            if (i == 0)
-                printf("\033*v");
-            if (r)
-                printf("%da", r);
-            if (g)
-                printf("%db", g);
-            if (b)
-                printf("%dc", b);
-            if (i == colors-1)
-                printf("%dI", i);    /* assign color index */
-            else
-                printf("%di", i);    /* assign color index */
-        }
-    }
-    ppm_freecolorhist(chv);
+    writePclHeader(cols, rows, maxval, xshift, yshift, quality, xsize, ysize,
+                   gammaVal, dark, render,
+                   colorMapped,
+                   bitsPerPixelRed, bitsPerPixelGrn, bitsPerPixelBlu,
+                   bitsPerIndex);
+
+    if (colorMapped)
+        writePalette(chv, colorCt);
 
     /* start raster graphics at CAP */
     printf("\033*r%dA", (xsize != 0 || ysize != 0) ? 3 : 1);
 
-    for (row = 0; row < rows; row++) {
-        pixel * const pixrow = pixels[row];
-        if (pclindex) { /* indexed color mode */
-            unsigned int col;
-            for (col = 0; col < cols; ++col)
-                putbits(ppm_lookupcolor(cht, &pixrow[col]), pclindex);
-            putbits(0, 0); /* flush row */
-        } else { /* direct color mode */
-            unsigned int col;
-            for (col = 0; col < cols; ++col) {
-                putbits(PPM_GETR(pixrow[col]), bpr);
-                putbits(PPM_GETG(pixrow[col]), bpg);
-                putbits(PPM_GETB(pixrow[col]), bpb);
-                /* don't need to flush */
-            }
-            putbits(0, 0); /* flush row */
-        }
-    }
+    writeRaster(pixels, rows, cols, cht, colorMapped,
+                bitsPerIndex,
+                bitsPerPixelRed, bitsPerPixelGrn, bitsPerPixelBlu);
+
     printf("\033*rC"); /* end raster graphics */
 
+    ppm_freecolorhash(cht);
+    ppm_freecolorhist(chv);
+
+    termbits();
+
     return 0;
 }
+
+
+
diff --git a/converter/ppm/ppmtoppm.c b/converter/ppm/ppmtoppm.c
index 500c9856..3a48eacc 100644
--- a/converter/ppm/ppmtoppm.c
+++ b/converter/ppm/ppmtoppm.c
@@ -20,7 +20,7 @@ main(int argc, char *argv[]) {
     pixval maxval;
     int row;
     pixel* pixelrow;
-    
+
     ppm_init(&argc, argv);
 
     if (argc-1 != 0)
@@ -42,3 +42,6 @@ main(int argc, char *argv[]) {
 
     exit(0);
 }
+
+
+
diff --git a/converter/ppm/ppmtopuzz.c b/converter/ppm/ppmtopuzz.c
index 1277cc20..08b852b0 100644
--- a/converter/ppm/ppmtopuzz.c
+++ b/converter/ppm/ppmtopuzz.c
@@ -33,12 +33,12 @@ main( argc, argv )
     ppm_init( &argc, argv );
 
     if ( argc > 2 )
-	pm_usage( "[ppmfile]" );
+        pm_usage( "[ppmfile]" );
 
     if ( argc == 2 )
-	ifp = pm_openr( argv[1] );
+        ifp = pm_openr( argv[1] );
     else
-	ifp = stdin;
+        ifp = stdin;
 
     pixels = ppm_readppm( ifp, &cols, &rows, &maxval );
     pm_close( ifp );
@@ -46,11 +46,11 @@ main( argc, argv )
     pm_message( "computing colormap..." );
     chv = ppm_computecolorhist( pixels, cols, rows, MAXCOLORS, &colors );
     if ( chv == (colorhist_vector) 0 )
-	{
-	pm_message(
-	    "too many colors - try doing a 'pnmquant %d'", MAXCOLORS );
-	exit( 1 );
-	}
+        {
+        pm_message(
+            "too many colors - try doing a 'pnmquant %d'", MAXCOLORS );
+        exit( 1 );
+        }
     pm_message( "%d colors found", colors );
 
     /* Write puzzle header. */
@@ -58,19 +58,19 @@ main( argc, argv )
     (void) pm_writebiglong( stdout, rows );
     (void) putchar( (unsigned char) colors );
     if ( maxval > MAXVAL )
-	pm_message(
-	    "maxval is not %d - automatically rescaling colors", MAXVAL );
+        pm_message(
+            "maxval is not %d - automatically rescaling colors", MAXVAL );
     for ( i = 0; i < colors; ++i )
-	{
-	pixel p;
+        {
+        pixel p;
 
-	p = chv[i].color;
-	if ( maxval != MAXVAL )
-	    PPM_DEPTH( p, p, maxval, MAXVAL );
-	(void) putchar( (unsigned char) PPM_GETR( p ) );
-	(void) putchar( (unsigned char) PPM_GETG( p ) );
-	(void) putchar( (unsigned char) PPM_GETB( p ) );
-	}
+        p = chv[i].color;
+        if ( maxval != MAXVAL )
+            PPM_DEPTH( p, p, maxval, MAXVAL );
+        (void) putchar( (unsigned char) PPM_GETR( p ) );
+        (void) putchar( (unsigned char) PPM_GETG( p ) );
+        (void) putchar( (unsigned char) PPM_GETB( p ) );
+        }
 
     /* Convert color vector to color hash table, for fast lookup. */
     cht = ppm_colorhisttocolorhash( chv, colors );
@@ -78,19 +78,22 @@ main( argc, argv )
 
     /* And write out the data. */
     for ( row = 0; row < rows; ++row )
-	{
-	for ( col = 0, pP = pixels[row]; col < cols; ++col, ++pP )
-	    {
-	    register int color;
-
-	    color = ppm_lookupcolor( cht, pP );
-	    if ( color == -1 )
-		pm_error(
-		    "color not found?!?  row=%d col=%d  r=%d g=%d b=%d",
-		    row, col, PPM_GETR(*pP), PPM_GETG(*pP), PPM_GETB(*pP) );
-	    (void) putchar( (unsigned char) color );
-	    }
-	}
+        {
+        for ( col = 0, pP = pixels[row]; col < cols; ++col, ++pP )
+            {
+            register int color;
+
+            color = ppm_lookupcolor( cht, pP );
+            if ( color == -1 )
+                pm_error(
+                    "color not found?!?  row=%d col=%d  r=%d g=%d b=%d",
+                    row, col, PPM_GETR(*pP), PPM_GETG(*pP), PPM_GETB(*pP) );
+            (void) putchar( (unsigned char) color );
+            }
+        }
 
     exit( 0 );
     }
+
+
+
diff --git a/converter/ppm/ppmtosixel.c b/converter/ppm/ppmtosixel.c
index 5f361e45..24454214 100644
--- a/converter/ppm/ppmtosixel.c
+++ b/converter/ppm/ppmtosixel.c
@@ -1,4 +1,4 @@
-/* ppmtosix.c - read a portable pixmap and produce a color sixel file
+/* ppmtosix.c - read a PPM and produce a color sixel file
 **
 ** Copyright (C) 1991 by Rick Vinci.
 **
@@ -8,208 +8,308 @@
 ** copyright notice and this permission notice appear in supporting
 ** documentation.  This software is provided "as is" without express or
 ** implied warranty.
+**
+** "-7bit" option added August 2023 by Scott Pakin <scott+pbm@pakin.org>.
 */
 
+#include "pm_c_util.h"
+#include "mallocvar.h"
+#include "shhopt.h"
 #include "ppm.h"
 
-static void WriteHeader ARGS((void));
-static void WriteColorMap 
-  ARGS((colorhist_vector chv, int colors, pixval maxval));
-static void WriteRawImage ARGS((colorhash_table cht, int rows, int cols));
-static void WritePackedImage ARGS((colorhash_table cht, int rows, int cols));
-static void WriteEnd ARGS((void));
-#define MAXVAL 100
-#define MAXCOLORS 256
+static unsigned int const SIXEL_MAXVAL = 100;
+static unsigned int const MAXCOLORCT = 256;
 
-#define DCS '\220'   /* Device Control String */
-#define ST  '\234'   /* String Terminator */
-#define CSI '\233'   /* Control String Introducer */
-#define ESC '\033'   /* Escape character */
+static const char * const sixel = "@ACGO_";
 
-static pixel** pixels;   /* stored ppm pixmap input */
-static colorhash_table cht;
-int margin;
+/* Named escape sequences */
+typedef struct {
+  const char * DCS;   /* Device Control String */
+  const char * ST;    /* String Terminator */
+  const char * CSI;   /* Control String Introducer */
+  const char * ESC;   /* Escape character */
+} EscapeSequenceSet;
 
 
 
-int
-main( argc, argv )
-    int argc;
-    char* argv[];
-{
-    FILE* ifp;
-    int argn, rows, cols, colors;
-    int raw;
-    pixval maxval;
-    colorhist_vector chv;
-    const char* const usage = "[-raw] [-margin] [ppmfile]";
-
-
-    ppm_init( &argc, argv );
-
-    argn = 1;
-    raw = 0;
-    margin = 0;
-
-    /* Parse args. */
-    while ( argn < argc && argv[argn][0] == '-' && argv[argn][1] != '\0' )
-	{
-	if ( pm_keymatch( argv[argn], "-raw", 2 ) )
-	    raw = 1;
-	else if ( pm_keymatch( argv[argn], "-margin", 2 ) )
-	    margin = 1;
-	else
-	    pm_usage( usage );
-	++argn;
-	}
-
-    if ( argn < argc )
-	{
-	ifp = pm_openr( argv[argn] );
-	++argn;
-	}
-    else
-	ifp = stdin;
-
-    if ( argn != argc )
-	pm_usage( usage );
-
-    /* Read in the whole ppmfile. */
-    pixels = ppm_readppm( ifp, &cols, &rows, &maxval );
-    pm_close( ifp );
-
-    /* Print a warning if we could lose accuracy when rescaling colors. */
-    if ( maxval > MAXVAL )
-	pm_message(
-	    "maxval is not %d - automatically rescaling colors", MAXVAL );
-
-    /* Figure out the colormap. */
-    pm_message( "computing colormap..." );
-    chv = ppm_computecolorhist( pixels, cols, rows, MAXCOLORS, &colors );
-    if ( chv == (colorhist_vector) 0 )
-	pm_error( "too many colors - try doing a 'pnmquant %d'", MAXCOLORS );
-    pm_message( "%d colors found", colors );
-
-    /* Make a hash table for fast color lookup. */
-    cht = ppm_colorhisttocolorhash( chv, colors );
-
-    WriteHeader();
-    WriteColorMap( chv, colors, maxval );
-    if ( raw == 1 )
-	WriteRawImage( cht, rows, cols );
-    else
-	WritePackedImage( cht, rows, cols );
-    WriteEnd();
+enum Charwidth {CHARWIDTH_8BIT, CHARWIDTH_7BIT};
 
-    /* If the program failed, it previously aborted with nonzero completion
-       code, via various function calls.
+struct CmdlineInfo {
+    /* All the information the user supplied in the command line, in a form
+       easy for the program to use.
     */
-    return 0;
+    const char *   inputFileName;
+    unsigned int   raw;
+    unsigned int   margin;
+    enum Charwidth charWidth;
+};
+
+
+
+static EscapeSequenceSet
+escapeSequenceSet(enum Charwidth const charWidth) {
+
+    EscapeSequenceSet eseqs;
+
+    switch (charWidth) {
+    case CHARWIDTH_8BIT: {
+        eseqs.DCS = "\220";
+        eseqs.ST  = "\234";
+        eseqs.CSI = "\233";
+        eseqs.ESC = "\033";
+    } break;
+    case CHARWIDTH_7BIT: {
+        eseqs.DCS = "\033P";
+        eseqs.ST  = "\033\\";
+        eseqs.CSI = "\033[";
+        eseqs.ESC = "\033";
+    } break;
+    }
+    return eseqs;
 }
 
 
 
 static void
-WriteHeader()
-    {
-    if ( margin == 1 )
-	printf( "%c%d;%ds", CSI, 14, 72 );
-    printf( "%c", DCS );  /* start with Device Control String */
-    printf( "0;0;8q" );   /* Horizontal Grid Size at 1/90" and graphics On */
-    printf( "\"1;1\n" );  /* set aspect ratio 1:1 */
-    }
+parseCommandLine(int argc, const char ** argv,
+                 struct CmdlineInfo * const cmdlineP) {
+/*----------------------------------------------------------------------------
+   Parse the program arguments (given by argc and argv) into a form
+   the program can deal with more easily -- a cmdline_info structure.
+   If the syntax is invalid, issue a message and exit the program via
+   pm_error().
+
+   Note that the file spec array we return is stored in the storage that
+   was passed to us as the argv array.
+-----------------------------------------------------------------------------*/
+    optEntry * option_def;  /* malloc'ed */
+    optStruct3 opt;  /* set by OPTENT3 */
+    unsigned int option_def_index;
+
+    unsigned int opt7Bit;
+
+    MALLOCARRAY_NOFAIL(option_def, 100);
+
+    option_def_index = 0;   /* incremented by OPTENT3 */
+    OPTENT3(0,   "raw",      OPT_FLAG,
+            NULL,                       &cmdlineP->raw, 0);
+    OPTENT3(0,   "margin",   OPT_FLAG,
+            NULL,                       &cmdlineP->margin, 0);
+    OPTENT3(0,   "7bit",     OPT_FLAG,
+            NULL,                       &opt7Bit, 0);
+
+    opt.opt_table = option_def;
+    opt.short_allowed = false; /* We have no short (old-fashioned) options */
+    opt.allowNegNum = false;   /* We have no parms that are negative numbers */
+
+    pm_optParseOptions4(&argc, argv, opt, sizeof(opt), 0);
+        /* Uses and sets argc, argv, and some of *cmdlineP and others. */
+
+    cmdlineP->charWidth = opt7Bit ? CHARWIDTH_7BIT : CHARWIDTH_8BIT;
+
+    if (argc-1 == 0)
+        cmdlineP->inputFileName = "-";
+    else if (argc-1 != 1)
+        pm_error("Program takes zero or one argument (filename).  You "
+                 "specified %d", argc-1);
+    else
+        cmdlineP->inputFileName = argv[1];
+
+    free(option_def);
+}
 
 
 
 static void
-WriteColorMap( colorhist_vector chv, int colors, pixval maxval )
-    {
-    register int colornum;
-    pixel p;
-
-    for ( colornum = 0; colornum < colors ; ++colornum )
-	{
-	p = chv[colornum].color;
-	if ( maxval != MAXVAL )
-	    PPM_DEPTH( p, p, maxval, MAXVAL );
-	printf( "#%d;2;%d;%d;%d", colornum,
-	    (int) PPM_GETR( p ), (int) PPM_GETG( p ), (int) PPM_GETB( p ) );
-	}
-    printf( "\n" );
+writePackedImage(pixel **        const pixels,
+                 unsigned int    const rows,
+                 unsigned int    const cols,
+                 colorhash_table const cht) {
+
+    unsigned int row;
+
+    for (row = 0; row < rows; ++row) {
+
+        unsigned int const b = row % 6;
+
+        unsigned int repeatCt;
+        unsigned int col;
+
+        repeatCt = 1;
+
+        for (col = 0; col < cols; ++col) {
+            const pixel * const thisRow = pixels[row];
+
+            unsigned int const thisColorIdx =
+                ppm_lookupcolor(cht, &thisRow[col]);
+
+            if (col == cols - 1)   /* last pixel in row */
+                if (repeatCt == 1)
+                    printf("#%d%c", thisColorIdx, sixel[b]);
+                else
+                    printf("#%d!%d%c", thisColorIdx, repeatCt, sixel[b]);
+            else {  /* not last pixel in row */
+                unsigned int const nextColorIdx =
+                    ppm_lookupcolor(cht, &thisRow[col+1]);
+                if (thisColorIdx == nextColorIdx)
+                    ++repeatCt;
+                else {
+                    if (repeatCt == 1)
+                        printf("#%d%c", thisColorIdx, sixel[b]);
+                    else {
+                        printf("#%d!%d%c", thisColorIdx, repeatCt, sixel[b]);
+                        repeatCt = 1;
+                    }
+                }
+            }
+        }
+        printf( "$\n" );   /* Carriage Return */
+
+        if (b == 5)
+            printf("-\n");   /* Line Feed (one sixel height) */
     }
+}
 
 
 
 static void
-WriteRawImage( cht, rows, cols )
-    colorhash_table cht;
-    int rows, cols;
-    {
-    int rownum, colnum, b;
-    const char* sixel = "@ACGO_";
-    register pixel* pP;
-
-    for ( rownum = 0; rownum < rows; ++rownum )
-	{
-	b = rownum % 6;
-	for ( colnum = 0, pP = pixels[rownum]; colnum < cols; ++colnum, ++pP )
-	    printf( "#%d%c", ppm_lookupcolor(cht, pP), sixel[b] );
-	printf( "$\n" );   /* Carriage Return */
-	if ( b == 5 )
-	    printf( "-\n" );   /* Line Feed (one sixel height) */
-	}
+writeHeader(bool              const wantMargin,
+            EscapeSequenceSet const eseqs) {
+
+    if (wantMargin)
+        printf("%s%d;%ds", eseqs.CSI, 14, 72);
+
+    printf("%s", eseqs.DCS);  /* start with Device Control String */
+
+    printf("0;0;8q");   /* Horizontal Grid Size at 1/90" and graphics On */
+
+    printf("\"1;1\n");  /* set aspect ratio 1:1 */
+}
+
+
+
+static void
+writeColorMap(colorhist_vector const chv,
+              unsigned int     const colorCt,
+              pixval           const maxval) {
+
+    unsigned int colorIdx;
+
+    for (colorIdx = 0; colorIdx < colorCt ; ++colorIdx) {
+        pixel const p = chv[colorIdx].color;
+
+        pixel scaledColor;
+
+        if (maxval == SIXEL_MAXVAL)
+            scaledColor = p;
+        else
+            PPM_DEPTH(scaledColor, p, maxval, SIXEL_MAXVAL);
+
+        printf("#%d;2;%d;%d;%d", colorIdx,
+               PPM_GETR(scaledColor),
+               PPM_GETG(scaledColor),
+               PPM_GETB(scaledColor));
     }
+    printf("\n");
+}
 
 
 
 static void
-WritePackedImage( cht, rows, cols )
-    colorhash_table cht;
-    int rows, cols;
-    {
-    int rownum, colnum, b, repeat, thiscolor, nextcolor;
-    const char* sixel = "@ACGO_";
-    register pixel* pP;
-
-    for ( rownum = 0; rownum < rows; ++rownum )
-	{
-	b = rownum % 6;
-	repeat = 1;
-	for ( colnum = 0, pP = pixels[rownum]; colnum < cols; ++colnum, ++pP )
-	    {
-	    thiscolor = ppm_lookupcolor(cht, pP);
-	    if ( colnum == cols -1 )   /* last pixel in row */
-		if ( repeat == 1 )
-		    printf( "#%d%c", thiscolor, sixel[b] );
-		else
-		    printf( "#%d!%d%c", thiscolor, repeat, sixel[b] );
-	    else   /* not last pixel in row */
-		{
-		nextcolor =  ppm_lookupcolor(cht, pP+1);
-		if ( thiscolor == nextcolor )
-		    ++repeat;
-		else
-		    if ( repeat == 1 )
-			printf( "#%d%c", thiscolor, sixel[b] );
-		    else
-		    {
-		    printf( "#%d!%d%c", thiscolor, repeat, sixel[b] );
-		    repeat = 1;
-		    }
-		}
-	    }   /* end column loop */
-	printf( "$\n" );   /* Carriage Return */
-	if ( b == 5 )
-	    printf( "-\n" );   /* Line Feed (one sixel height) */
-	}
+writeRawImage(pixel **        const pixels,
+              unsigned int    const rows,
+              unsigned int    const cols,
+              colorhash_table const cht) {
+
+    unsigned int row;
+
+    for (row = 0; row < rows; ++row) {
+        pixel * const thisRow = pixels[row];
+        unsigned int const b = row % 6;
+
+        unsigned int col;
+
+        for (col = 0; col < cols; ++col)
+            printf("#%d%c", ppm_lookupcolor(cht, &thisRow[col]), sixel[b]);
+
+        printf("$\n");   /* Carriage Return */
+
+        if (b == 5)
+            printf("-\n");   /* Line Feed (one sixel height) */
     }
+}
 
 
 
 static void
-WriteEnd()
-    {
-    if ( margin == 1 )
-	printf ( "%c%d;%ds", CSI, 1, 80 );
-    printf( "%c\n", ST );
+writeEnd(bool              const wantMargin,
+         EscapeSequenceSet const eseqs) {
+
+    if (wantMargin)
+        printf ("%s%d;%ds", eseqs.CSI, 1, 80);
+
+    printf("%s\n", eseqs.ST);
+}
+
+
+
+int
+main(int argc, const char ** argv) {
+
+    struct CmdlineInfo cmdline;
+    FILE * ifP;
+    int rows, cols;
+    pixval maxval;
+    int colorCt;
+    pixel ** pixels;
+    colorhist_vector chv;
+        /* List of colors in the image, indexed by colormap index */
+    colorhash_table cht;
+        /* Hash table for fast colormap index lookup */
+    EscapeSequenceSet eseqs;
+        /* The escape sequences we use in our output for various functions */
+
+    pm_proginit(&argc, argv);
+
+    parseCommandLine(argc, argv, &cmdline);
+
+    ifP = pm_openr(cmdline.inputFileName);
+
+    pixels = ppm_readppm(ifP, &cols, &rows, &maxval);
+
+    if (maxval > SIXEL_MAXVAL) {
+        pm_message(
+            "maxval of input is not the sixel maxval (%u) - "
+            "rescaling to fewer colors", SIXEL_MAXVAL);
     }
+
+    pm_message("computing colormap...");
+    chv = ppm_computecolorhist(pixels, cols, rows, MAXCOLORCT, &colorCt);
+    if (!chv)
+        pm_error("too many colors - try 'pnmquant %u'", MAXCOLORCT);
+
+    pm_message("%d colors found", colorCt);
+
+    cht = ppm_colorhisttocolorhash(chv, colorCt);
+
+    eseqs = escapeSequenceSet(cmdline.charWidth);
+
+    writeHeader(!!cmdline.margin, eseqs);
+
+    writeColorMap(chv, colorCt, maxval);
+
+    if (cmdline.raw)
+        writeRawImage(pixels, rows, cols, cht);
+    else
+        writePackedImage(pixels, rows, cols, cht);
+
+    writeEnd(!!cmdline.margin, eseqs);
+
+    /* If the program failed, it previously aborted with nonzero completion
+       code, via various function calls.
+    */
+    return 0;
+}
+
+
+
diff --git a/converter/ppm/ppmtospu.c b/converter/ppm/ppmtospu.c
index a6acbaa0..4ba70f02 100644
--- a/converter/ppm/ppmtospu.c
+++ b/converter/ppm/ppmtospu.c
@@ -5,6 +5,7 @@
  *  Copyright (C) 1990, Steve Belczyk
  */
 
+#include <stdbool.h>
 #include <assert.h>
 #include <stdio.h>
 
@@ -48,18 +49,18 @@ parseCommandLine(int argc, const char ** argv,
     MALLOCARRAY_NOFAIL(option_def, 100);
 
     option_def_index = 0;   /* incremented by OPTENT3 */
-    OPTENT3(0,   "d0",       OPT_FLAG,   
+    OPTENT3(0,   "d0",       OPT_FLAG,
             NULL,                       &d0Spec, 0);
-    OPTENT3(0,   "d2",       OPT_FLAG,   
+    OPTENT3(0,   "d2",       OPT_FLAG,
             NULL,                       &d2Spec, 0);
-    OPTENT3(0,   "d4",       OPT_FLAG,   
+    OPTENT3(0,   "d4",       OPT_FLAG,
             NULL,                       &d4Spec, 0);
 
     opt.opt_table = option_def;
-    opt.short_allowed = FALSE;  /* We have no short (old-fashioned) options */
-    opt.allowNegNum = FALSE;  /* We have no parms that are negative numbers */
+    opt.short_allowed = false;  /* We have no short (old-fashioned) options */
+    opt.allowNegNum = false;  /* We have no parms that are negative numbers */
 
-    pm_optParseOptions3(&argc, (char **)argv, opt, sizeof(opt), 0);
+    pm_optParseOptions4(&argc, argv, opt, sizeof(opt), 0);
         /* Uses and sets argc, argv, and some of *cmdlineP and others. */
 
 
@@ -72,7 +73,7 @@ parseCommandLine(int argc, const char ** argv,
     else
         cmdlineP->dithflag = 2;
 
-    if (argc-1 < 1) 
+    if (argc-1 < 1)
         cmdlineP->inputFileName = "-";
     else {
         cmdlineP->inputFileName = argv[1];
@@ -129,7 +130,7 @@ findIndex(unsigned int const col,
    Spectrum palette index.
 -----------------------------------------------------------------------------*/
     int r, x1;
-    
+
     x1 = 10 * index;  /* initial value */
     if (index & 0x1)
         x1 -= 5;
@@ -143,7 +144,7 @@ findIndex(unsigned int const col,
 
     if (col >= (x1+160))
         r += 32;
-    
+
     return r;
 }
 
@@ -183,7 +184,7 @@ dither(unsigned int       const row,
         { 0, 2 },
         { 3, 1 }
     };
-    
+
     unsigned int c[3];  /* An element for each plane */
     unsigned int col;
 
@@ -262,7 +263,7 @@ sort(struct PixelType * const pixelType,
             ++i;
         while (pixelType[j-1].popularity > pivot)
             --j;
-        
+
         if (i < j) {
             /* An element not less popular than pivot is to the left of a
                pixel not more popular than pivot, so swap them.  Note that we
@@ -274,7 +275,7 @@ sort(struct PixelType * const pixelType,
             --j;
         }
     }
-    
+
     if (j - left > 1)
         sort(pixelType, left, j);
     if (right - i > 1)
@@ -445,7 +446,7 @@ convertRow(unsigned int       const row,
     /* Mark palette entries as all free */
     for (i = 0; i < 48; ++i)
         palP->pal[row][i] = -1;
-    
+
     /* Mark reserved palette entries */
     palP->pal[row][0]  = palP->pal[row][15] = palP->pal[row][16] = 0;
     palP->pal[row][31] = palP->pal[row][32] = palP->pal[row][47] = 0;
@@ -494,7 +495,7 @@ writeScreen(const short * const screen) {
     /* Write the bitmap */
 
     unsigned int i;
-    
+
     for (i = 0; i < 16000; ++i) {
         char const c0 = 0xff & (screen[i] >> 8);
         char const c1 = 0xff & screen[i];
diff --git a/converter/ppm/ppmtoterm.c b/converter/ppm/ppmtoterm.c
index d388f77d..b1d94fa2 100644
--- a/converter/ppm/ppmtoterm.c
+++ b/converter/ppm/ppmtoterm.c
@@ -19,6 +19,7 @@
 **
 */
 
+#include <stdbool.h>
 #include <assert.h>
 #include <string.h>
 
@@ -43,7 +44,6 @@ parseCommandLine(int argc, const char ** argv,
                  struct cmdlineInfo * const cmdlineP) {
 
     optEntry * option_def;
-        /* Instructions to OptParseOptions3 on how to parse our options */
     optStruct3 opt;
 
     unsigned int option_def_index;
@@ -54,10 +54,10 @@ parseCommandLine(int argc, const char ** argv,
     OPTENT3(0, "verbose", OPT_FLAG, NULL, &cmdlineP->verbose, 0);
 
     opt.opt_table = option_def;
-    opt.short_allowed = FALSE;  /* We have no short (old-fashioned) options */
-    opt.allowNegNum = FALSE;  /* We have no parms that are negative numbers */
+    opt.short_allowed = false;  /* We have no short (old-fashioned) options */
+    opt.allowNegNum = false;  /* We have no parms that are negative numbers */
 
-    pm_optParseOptions3(&argc, (char **)argv, opt, sizeof(opt), 0);
+    pm_optParseOptions4(&argc, argv, opt, sizeof(opt), 0);
         /* Uses and sets argc, argv, and some of *cmdlineP and others. */
 
     if (argc-1 < 1)
@@ -86,7 +86,7 @@ parseCommandLine(int argc, const char ** argv,
 
 
 static void
-generatePalette(unsigned char        rgb[NUM_COLORS][3], 
+generatePalette(unsigned char        rgb[NUM_COLORS][3],
                 char                 ansiCode[NUM_COLORS][MAX_ANSI_STR_LEN],
                 unsigned int * const paletteSizeP) {
 /*----------------------------------------------------------------------------
@@ -150,7 +150,7 @@ generatePalette(unsigned char        rgb[NUM_COLORS][3],
 static void
 lookupInPalette(pixel          const pixel,
                 pixval         const maxval,
-                unsigned char        rgb[NUM_COLORS][3], 
+                unsigned char        rgb[NUM_COLORS][3],
                 unsigned int   const palLen,
                 unsigned int * const paletteIdxP) {
 /*----------------------------------------------------------------------------
@@ -166,7 +166,7 @@ lookupInPalette(pixel          const pixel,
     unsigned int paletteIdxSoFar;
     unsigned int dist;
     unsigned int i;
-            
+
     /* The following loop calculates the index that corresponds to the
        minimum color distance between the given RGB values and the
        values available in the palette.
@@ -200,18 +200,18 @@ main(int argc, const char ** argv) {
     unsigned char   rgb[NUM_COLORS][3];
     char            ansiCode[NUM_COLORS][MAX_ANSI_STR_LEN];
 
-    pm_proginit(&argc, argv);    
+    pm_proginit(&argc, argv);
 
     parseCommandLine(argc, argv, &cmdline);
 
     ifP = pm_openr(cmdline.inputFileName);
-    
+
     pixels = ppm_readppm(ifP, &cols, &rows, &maxval);
 
     pm_close(ifP);
-        
+
     generatePalette(rgb, ansiCode, &palLen);
-    
+
     for (row = 0; row < rows; ++row) {
         unsigned int col;
         for (col = 0; col < cols; ++col) {
@@ -227,6 +227,9 @@ main(int argc, const char ** argv) {
     printf(ESC "\x30m");
 
     ppm_freearray(pixels, rows);
-    
+
     return 0;
 }
+
+
+
diff --git a/converter/ppm/ppmtowinicon.c b/converter/ppm/ppmtowinicon.c
index c673798f..2d8ddaf7 100644
--- a/converter/ppm/ppmtowinicon.c
+++ b/converter/ppm/ppmtowinicon.c
@@ -1,4 +1,4 @@
-/* ppmtowinicon.c - read portable pixmap file(s) and write a MS Windows .ico
+/* ppmtowinicon.c - read PPM images and write a MS Windows .ico
 **
 ** Copyright (C) 2000 by Lee Benfield - lee@benf.org
 **
@@ -10,6 +10,8 @@
 ** implied warranty.
 */
 
+#include <stdbool.h>
+#include <assert.h>
 #include <math.h>
 #include <string.h>
 
@@ -25,31 +27,30 @@
 
 #define MAXCOLORS 256
 
-struct cmdlineInfo {
+struct CmdlineInfo {
     /* All the information the user supplied in the command line,
        in a form easy for the program to use.
     */
-    unsigned int iconCount;
-    const char **inputFilespec;  /* '-' if stdin; malloc'ed array */
-    const char **andpgmFilespec;    /* NULL if unspecified; malloc'ed array */
-    const char *output;     /* '-' if unspecified */
-    unsigned int truetransparent;
-    unsigned int verbose;
+    unsigned int  iconCount;
+    const char ** inputFileNm;  /* '-' if stdin; malloc'ed array */
+    const char ** andpgmFileNm;    /* NULL if unspecified; malloc'ed array */
+    const char *  output;     /* '-' if unspecified */
+    unsigned int  truetransparent;
+    unsigned int  verbose;
 };
 
 
 static bool verbose;
 
-static int      file_offset = 0; /* not actually used, but useful for debug. */
-static FILE *   ofp;
+static int      fileOffset = 0; /* not actually used, but useful for debug. */
 
 static void
-parseCommandLine(int                 argc, 
-                 char **             argv,
-                 struct cmdlineInfo *cmdlineP ) {
+parseCommandLine(int                  argc,
+                 const char **        argv,
+                 struct CmdlineInfo * cmdlineP) {
 /*----------------------------------------------------------------------------
    Parse program command line described in Unix standard form by argc
-   and argv.  Return the information in the options as *cmdlineP.  
+   and argv.  Return the information in the options as *cmdlineP.
 
    If command line is internally inconsistent (invalid options, etc.),
    issue error message to stderr and abort program.
@@ -57,9 +58,7 @@ parseCommandLine(int                 argc,
    Note that the strings we return are stored in the storage that
    was passed to us as the argv array.  We also trash *argv.
 -----------------------------------------------------------------------------*/
-    optEntry *option_def;
-        /* Instructions to pm_optParseOptions3 on how to parse our options.
-         */
+    optEntry * option_def;
     optStruct3 opt;
 
     unsigned int option_def_index;
@@ -79,34 +78,33 @@ parseCommandLine(int                 argc,
             &cmdlineP->verbose,            0);
 
     opt.opt_table = option_def;
-    opt.short_allowed = FALSE;  /* We have no short (old-fashioned) options */
-    opt.allowNegNum = FALSE;  /* We have no parms that are negative numbers */
+    opt.short_allowed = false;  /* We have no short (old-fashioned) options */
+    opt.allowNegNum = false;  /* We have no parms that are negative numbers */
 
-    pm_optParseOptions3( &argc, argv, opt, sizeof(opt), 0);
+    pm_optParseOptions4(&argc, argv, opt, sizeof(opt), 0);
         /* Uses and sets argc, argv, and some of *cmdlineP and others. */
 
     if (!outputSpec)
         cmdlineP->output = "-";
 
-
     if (!andpgms) {
         if (argc-1 == 0) {
             cmdlineP->iconCount = 1;
-            MALLOCARRAY_NOFAIL(cmdlineP->inputFilespec, cmdlineP->iconCount);
-            cmdlineP->inputFilespec[0] = "-";
+            MALLOCARRAY_NOFAIL(cmdlineP->inputFileNm, cmdlineP->iconCount);
+            cmdlineP->inputFileNm[0] = "-";
         } else {
             unsigned int iconIndex;
 
             cmdlineP->iconCount = argc-1;
-            MALLOCARRAY_NOFAIL(cmdlineP->inputFilespec, cmdlineP->iconCount);
+            MALLOCARRAY_NOFAIL(cmdlineP->inputFileNm, cmdlineP->iconCount);
             for (iconIndex = 0; iconIndex < cmdlineP->iconCount; ++iconIndex)
-                cmdlineP->inputFilespec[iconIndex] = argv[iconIndex+1];
+                cmdlineP->inputFileNm[iconIndex] = argv[iconIndex+1];
         }
         {
             unsigned int iconIndex;
-            MALLOCARRAY_NOFAIL(cmdlineP->andpgmFilespec, cmdlineP->iconCount);
+            MALLOCARRAY_NOFAIL(cmdlineP->andpgmFileNm, cmdlineP->iconCount);
             for (iconIndex = 0; iconIndex < cmdlineP->iconCount; ++iconIndex)
-                cmdlineP->andpgmFilespec[iconIndex] = NULL;
+                cmdlineP->andpgmFileNm[iconIndex] = NULL;
         }
     } else {
         if (argc-1 < 2)
@@ -119,11 +117,11 @@ parseCommandLine(int                 argc,
         else {
             unsigned int iconIndex;
             cmdlineP->iconCount = (argc-1)/2;
-            MALLOCARRAY_NOFAIL(cmdlineP->inputFilespec, cmdlineP->iconCount);
-            MALLOCARRAY_NOFAIL(cmdlineP->andpgmFilespec, cmdlineP->iconCount);
+            MALLOCARRAY_NOFAIL(cmdlineP->inputFileNm, cmdlineP->iconCount);
+            MALLOCARRAY_NOFAIL(cmdlineP->andpgmFileNm, cmdlineP->iconCount);
             for (iconIndex = 0; iconIndex < cmdlineP->iconCount; ++iconIndex) {
-                cmdlineP->inputFilespec[iconIndex] = argv[1 + iconIndex*2];
-                cmdlineP->andpgmFilespec[iconIndex] = argv[2 + iconIndex*2];
+                cmdlineP->inputFileNm[iconIndex] = argv[1 + iconIndex*2];
+                cmdlineP->andpgmFileNm[iconIndex] = argv[2 + iconIndex*2];
             }
         }
     }
@@ -132,429 +130,430 @@ parseCommandLine(int                 argc,
 
 
 
-static void 
-PutByte(int const v) {
-   
-   if (putc(v, ofp) == EOF)
-       pm_error("Unable to write byte to output file.");
+static void
+freeCmdline(struct CmdlineInfo const cmdline) {
+
+    free(cmdline.inputFileNm);
+    free(cmdline.andpgmFileNm);
 }
-   
 
 
-static void 
-PutShort(short const v) {
-   
-   if (pm_writelittleshort(ofp, v) == -1)
-       pm_error("Unable to write short integer to output file");
-}
-   
 
+static void
+writeU1(FILE * const ofP,
+        u1     const v) {
 
-static void 
-PutLong(long const v) {
-   
-   if (pm_writelittlelong(ofp, v) == -1)
-       pm_error("Unable to write long integer to output file");
+    ++fileOffset;
+    pm_writechar(ofP, v);
 }
 
 
-   
-/*
- * These have no purpose but to wrapper the Byte, Short & Long 
- * functions.
- */
-static void 
-writeU1 (u1 const v) {
-   file_offset++;
-   PutByte(v);
-}
 
-static  void 
-writeU2 (u2 const v) {
-   file_offset +=2;
-   PutShort(v);
-}
+static  void
+writeU2(FILE * const ofP,
+        u2     const v) {
 
-static void 
-writeU4 (u4 const v) {
-   file_offset += 4;
-   PutLong(v);
+    fileOffset +=2;
+    pm_writelittleshort(ofP, v);
 }
 
-static MS_Ico 
-createIconFile (void) {
-   MS_Ico MSIconData;
-   
-   MALLOCVAR_NOFAIL(MSIconData);
-
-   MSIconData->reserved     = 0;
-   MSIconData->type         = 1;
-   MSIconData->count        = 0;
-   MSIconData->entries      = NULL;
-   return MSIconData;
+
+
+static void
+writeU4(FILE * const ofP,
+        u4     const v) {
+
+    fileOffset += 4;
+    pm_writelittlelong(ofP, v);
 }
 
 
-/* create andBitmap from pgm */
 
-static ICON_bmp 
-createAndBitmap (gray ** const ba, int const cols, int const rows,
-                 gray const maxval) {
-   /*
-    * How wide should the u1 string for each row be?
-    * each byte is 8 pixels, but must be a multiple of 4 bytes.
-    */
-   unsigned int const xBytes = ROUNDUP(cols, 32)/8;
-   ICON_bmp icBitmap;
-   int y,x;
-   u1 ** rowData;
-
-   MALLOCVAR_NOFAIL(icBitmap);
-
-   MALLOCARRAY_NOFAIL(rowData, rows);
-   icBitmap->xBytes = xBytes;
-   icBitmap->data   = rowData;
-   icBitmap->size   = xBytes * rows;
-   for (y=0;y<rows;y++) {
-      u1 * row;
-      int byteOn = 0;
-      int bitOn = 128;
-
-      MALLOCARRAY_NOFAIL(row, xBytes);
-
-      memset (row, 0, xBytes);
-      rowData[rows-y-1] = row;
-      /* 
-       * Check there's a bit array, otherwise we're just faking this...
-       */
-      if (ba) {
-     for (x=0;x<cols;x++) {
-            /* Black (bit clear) is transparent in PGM alpha maps,
-             * in ICO bit *set* is transparent.
-             */
-            if (ba[y][x] <= maxval/2) row[byteOn] |= bitOn;
-
-        if (bitOn == 1) {
-           byteOn++;
-           bitOn = 128;
-        } else {
-           bitOn >>= 1;
-        }
-     }
-      }
-   }
-   return icBitmap;
+static MS_Ico *
+newIconFile(void) {
+
+   MS_Ico * MSIconDataP;
+
+   MALLOCVAR_NOFAIL(MSIconDataP);
+
+   MSIconDataP->reserved     = 0;
+   MSIconDataP->type         = 1;
+   MSIconDataP->count        = 0;
+   MSIconDataP->entries      = NULL;
+
+   return MSIconDataP;
 }
 
 
-/*
- * Depending on if the image is stored as 1bpp, 4bpp or 8bpp, the 
- * encoding mechanism is different.
- * 
- * I didn't re-use the code from ppmtobmp since I need to keep the
- * bitmaps in memory till I've loaded all ppms.
- * 
- * 8bpp => 1 byte/palette index.
- * 4bpp => High Nibble, Low Nibble
- * 1bpp => 1 palette value per bit, high bit 1st.
- */
-static ICON_bmp 
-create1Bitmap (pixel ** const pa, int const cols, int const rows, 
-               colorhash_table const cht) {
-   /*
-    * How wide should the u1 string for each row be?
-    * each byte is 8 pixels, but must be a multiple of 4 bytes.
-    */
-   ICON_bmp icBitmap;
-   int xBytes,y,x;
-   int wt = cols;
-   u1 ** rowData;
-
-   MALLOCVAR_NOFAIL(icBitmap);
-   
-   wt >>= 3;
-   if (wt & 3) {
-      wt = (wt & ~3) + 4;
-   }
-   xBytes = wt;
-   MALLOCARRAY_NOFAIL(rowData, rows);
-   icBitmap->xBytes = xBytes;
-   icBitmap->data   = rowData;
-   icBitmap->size   = xBytes * rows;
-   for (y=0;y<rows;y++) {
-      u1 * row;
-      int byteOn = 0;
-      int bitOn = 128;
-      int value;
-      
-      MALLOCARRAY_NOFAIL(row, xBytes);
-      memset (row, 0, xBytes);
-      rowData[rows-y-1] = row;
-      /* 
-       * Check there's a pixel array, otherwise we're just faking this...
+
+static ICON_bmp *
+newAndBitmap(gray **      const ba,
+             unsigned int const cols,
+             unsigned int const rows,
+             gray         const maxval) {
+/*----------------------------------------------------------------------------
+  create andBitmap from PGM
+-----------------------------------------------------------------------------*/
+    unsigned int const xByteCt = ROUNDUP(cols, 32)/8;
+       /* How wide the u1 string for each row should be -- Each byte is 8
+          pixels, but must be a multiple of 4 bytes.
        */
-      if (pa) {
-     for (x=0;x<cols;x++) {
-        /*
-         * So we've got a colorhash_table with two colors in it.
-         * Which is black?!
-         * 
-         * Unless the hashing function changes, 0's black.
-         */
-        value = ppm_lookupcolor(cht, &pa[y][x]);
-        if (!value) {
-           /* leave black. */
-        } else {
-           row[byteOn] |= bitOn;
-        }
-        if (bitOn == 1) {
-           byteOn++;
-           bitOn = 128;
+    ICON_bmp * icBitmapP;
+    unsigned int row;
+    u1 ** rowData;
+
+    MALLOCVAR_NOFAIL(icBitmapP);
+
+    MALLOCARRAY_NOFAIL(rowData, rows);
+    icBitmapP->xBytes = xByteCt;
+    icBitmapP->data   = rowData;
+    icBitmapP->size   = xByteCt * rows;
+    for (row = 0; row < rows; ++row) {
+        u1 * thisRow;  /* malloc'ed */
+        unsigned int byteOn;
+        unsigned int bitOn;
+
+        MALLOCARRAY_NOFAIL(thisRow, xByteCt);
+
+        byteOn =   0;  /* initial value */
+        bitOn  = 128;  /* initial value */
+
+        memset (thisRow, 0, xByteCt);
+        rowData[rows - row - 1] = thisRow;
+
+        if (ba) {
+            unsigned int col;
+
+            for (col = 0; col < cols; ++col) {
+                /* Black (bit clear) is transparent in PGM alpha maps,
+                   in ICO bit *set* is transparent.
+                */
+                if (ba[row][col] <= maxval/2) thisRow[byteOn] |= bitOn;
+
+                if (bitOn == 1) {
+                    ++byteOn;
+                    bitOn = 128;
+                } else {
+                    bitOn >>= 1;
+                }
+            }
         } else {
-           bitOn >>= 1;
+            /* No array -- we're just faking this */
         }
-     }
-      }
-   }
-   return icBitmap;
+    }
+    return icBitmapP;
 }
 
 
-static ICON_bmp 
-create4Bitmap (pixel ** const pa, int const cols, int const rows,
-               colorhash_table const cht) {
-   /*
-    * How wide should the u1 string for each row be?
-    * each byte is 8 pixels, but must be a multiple of 4 bytes.
-    */
-   ICON_bmp icBitmap;
-   int xBytes,y,x;
-   int wt = cols;
-   u1 ** rowData;
-
-   MALLOCVAR_NOFAIL(icBitmap);
-
-   wt >>= 1;
-   if (wt & 3) {
-      wt = (wt & ~3) + 4;
-   }
-   xBytes = wt;
-   MALLOCARRAY_NOFAIL(rowData, rows);
-   icBitmap->xBytes = xBytes;
-   icBitmap->data   = rowData;
-   icBitmap->size   = xBytes * rows;
-
-   for (y=0;y<rows;y++) {
-      u1 * row;
-      int byteOn = 0;
-      int nibble = 1;   /* high nibble = 1, low nibble = 0; */
-      int value;
-
-      MALLOCARRAY_NOFAIL(row, xBytes);
-
-      memset (row, 0, xBytes);
-      rowData[rows-y-1] = row;
-      /* 
-       * Check there's a pixel array, otherwise we're just faking this...
-       */
-      if (pa) {
-     for (x=0;x<cols;x++) {
-        value = ppm_lookupcolor(cht, &pa[y][x]);
-        /*
-         * Shift it, if we're putting it in the high nibble.
-         */
-        if (nibble) {
-           value <<= 4;
-        }
-        row[byteOn] |= value;
-        if (nibble) {
-           nibble = 0;
+
+/* Depending on if the image is stored as 1bpp, 4bpp or 8bpp, the
+   encoding mechanism is different.
+
+   I didn't re-use the code from ppmtobmp since I need to keep the
+   bitmaps in memory until I've loaded all ppms.
+
+   8bpp => 1 byte/palette index.
+   4bpp => High Nibble, Low Nibble
+   1bpp => 1 palette value per bit, high bit 1st.
+*/
+
+
+
+static void
+fillInRaster1(u1 **           const rowData,
+              unsigned int    const xByteCt,
+              pixel **        const pa,
+              unsigned int    const cols,
+              unsigned int    const rows,
+              colorhash_table const cht) {
+
+    unsigned int row;
+
+    for (row = 0; row <rows; ++row) {
+        u1 * thisRow;  /* malloc'ed */
+        unsigned int byteSeq;
+        unsigned int bitOnMask;
+
+        MALLOCARRAY_NOFAIL(thisRow, xByteCt);
+        memset(thisRow, 0, xByteCt);  /* initial value */
+        rowData[rows - row - 1] = thisRow;
+        byteSeq   = 0;    /* initial value */
+        bitOnMask = 0x80; /* initial value */
+
+        if (pa) {
+            unsigned int col;
+
+            for (col = 0; col < cols; ++col) {
+                /* So we've got a colorhash_table with two colors in it.  Which
+                   is black?!
+
+                   Unless the hashing function changes, 0's black.
+                */
+                int const value = ppm_lookupcolor(cht, &pa[row][col]);
+
+                assert(byteSeq < xByteCt);
+
+                if (!value) {
+                    /* leave black. */
+                } else {
+                    thisRow[byteSeq] |= bitOnMask;
+                }
+                if (bitOnMask == 0x1) {
+                    ++byteSeq;
+                    bitOnMask = 0x80;
+                } else {
+                    bitOnMask >>= 1;
+                }
+            }
         } else {
-           nibble = 1;
-           byteOn++;
+            /* No pixel array -- we're just faking this */
         }
-     }
-      }
-   }
-   return icBitmap;
+    }
 }
 
 
 
-static ICON_bmp 
-create8Bitmap (pixel ** const pa, int const cols, int const rows,
-               colorhash_table const cht) {
-   /*
-    * How wide should the u1 string for each row be?
-    * each byte is 8 pixels, but must be a multiple of 4 bytes.
-    */
-   ICON_bmp icBitmap;
-   int xBytes,y,x;
-   int wt = cols;
-   u1 ** rowData;
-
-   MALLOCVAR_NOFAIL(icBitmap);
-
-   if (wt & 3) {
-      wt = (wt & ~3) + 4;
-   }
-   xBytes = wt;
-   MALLOCARRAY_NOFAIL(rowData, rows);
-   icBitmap->xBytes = xBytes;
-   icBitmap->data   = rowData;
-   icBitmap->size   = xBytes * rows;
-
-   for (y=0;y<rows;y++) {
-      u1 * row;
-
-      MALLOCARRAY_NOFAIL(row, xBytes);
-      memset (row, 0, xBytes);
-      rowData[rows-y-1] = row;
-      /* 
-       * Check there's a pixel array, otherwise we're just faking this...
-       */
-      if (pa) {
-     for (x=0;x<cols;x++) {
-        row[x] = ppm_lookupcolor(cht, &pa[y][x]);
-     }
-      }
-   }
-   return icBitmap;
+static void
+fillInRaster4(u1 **           const rowData,
+              unsigned int    const xByteCt,
+              pixel **        const pa,
+              unsigned int    const cols,
+              unsigned int    const rows,
+              colorhash_table const cht) {
+
+    unsigned int row;
+
+    for (row = 0; row < rows; ++row) {
+        u1 * thisRow;
+        unsigned int byteSeq;
+        unsigned int nibbleSig;   /* high nibble = 1, low nibble = 0; */
+
+        MALLOCARRAY_NOFAIL(thisRow, xByteCt);
+
+        memset(thisRow, 0, xByteCt);
+        rowData[rows - row - 1] = thisRow;
+        byteSeq   = 0;  /* initial value */
+        nibbleSig = 1;  /* initial value */
+
+        if (pa) {
+            unsigned int col;
+
+            for (col = 0; col < cols; ++col) {
+                int value;
+
+                assert(byteSeq < xByteCt);
+
+                value = ppm_lookupcolor(cht, &pa[row][col]);  /* init value */
+                /* Shift it, if we're putting it in the high nibble. */
+                if (nibbleSig == 1)
+                    value <<= 4;
+                thisRow[byteSeq] |= value;
+                if (nibbleSig == 1)
+                    nibbleSig = 0;
+                else {
+                    nibbleSig = 1;
+                    ++byteSeq;
+                }
+            }
+        } else {
+            /* No pixel array -- we're just faking this */
+        }
+    }
 }
 
 
 
-static IC_InfoHeader 
-createInfoHeader(IC_Entry const entry, ICON_bmp const xbmp,
-                 ICON_bmp const abmp) {
-   IC_InfoHeader ih;
-   
-   MALLOCVAR_NOFAIL(ih);
-
-   ih->size          = 40;
-   ih->width         = entry->width;
-   ih->height        = entry->height * 2;  
-   ih->planes        = 1;  
-   ih->bitcount      = entry->bitcount;
-   ih->compression   = 0;
-   ih->imagesize     = entry->width * entry->height * 8 / entry->bitcount;
-   ih->x_pixels_per_m= 0;
-   ih->y_pixels_per_m= 0;
-   ih->colors_used   = 1 << entry->bitcount;
-   ih->colors_important = 0;
-   return ih;
-}
+static void
+fillInRaster8(u1 **           const rowData,
+              unsigned int    const xByteCt,
+              pixel **        const pa,
+              unsigned int    const cols,
+              unsigned int    const rows,
+              colorhash_table const cht) {
 
+    unsigned int row;
+
+    for (row = 0; row < rows; ++row) {
+        u1 * thisRow;  /* malloc'ed */
 
+        assert(cols <= xByteCt);
 
-static IC_Palette 
-createCleanPalette(void) {
-   IC_Palette palette;
-   int x;
-   
-   MALLOCVAR_NOFAIL(palette);
+        MALLOCARRAY_NOFAIL(thisRow, xByteCt);
+        memset(thisRow, 0, xByteCt);
+        rowData[rows - row - 1] = thisRow;
+        if (pa) {
+            unsigned int col;
 
-   MALLOCARRAY_NOFAIL(palette->colors, MAXCOLORS);
-   for (x=0;x<MAXCOLORS;x++ ){
-      palette->colors[x] = NULL;
-   }
-   return palette;
+            for (col = 0; col < cols; ++col)
+                thisRow[col] = ppm_lookupcolor(cht, &pa[row][col]);
+        } else {
+            /* No pixel array -- we're just faking this */
+        }
+    }
 }
 
 
 
-static void 
-addColorToPalette(IC_Palette const palette, int const i,
-                  int const r, int const g, int const b) {
+static ICON_bmp *
+newBitmap(unsigned int    const bpp,
+          pixel **        const pa,
+          unsigned int    const cols,
+          unsigned int    const rows,
+          colorhash_table const cht) {
 
-    MALLOCVAR_NOFAIL(palette->colors[i]);
+    unsigned int const xByteCt = ROUNDUP(cols * bpp, 32)/8;
+       /* How wide the u1 string for each row should be.  Pixels are packed
+          into bytes, padded to a multiple of 4 bytes.
+       */
+    ICON_bmp * icBitmapP;  /* malloc'ed */
+    u1 ** rowData;  /* malloc'ed */
 
-    palette->colors[i]->red      = r;
-    palette->colors[i]->green    = g;
-    palette->colors[i]->blue     = b;
-    palette->colors[i]->reserved = 0;
-}
+    assert(cols < 256); assert(rows < 256);  /* required for no overflow */
 
+    MALLOCVAR_NOFAIL(icBitmapP);
 
+    MALLOCARRAY_NOFAIL(rowData, rows);
 
-static ICON_bmp 
-createBitmap (int const bpp, pixel ** const pa, 
-              int const cols, int const rows, 
-              colorhash_table const cht) {
-    
-    ICON_bmp retval;
-    const int assumed_bpp = (pa == NULL) ? 1 : bpp;
+    icBitmapP->xBytes = xByteCt;
+    icBitmapP->data   = rowData;
+    icBitmapP->size   = xByteCt * rows;
+
+    unsigned int const assumedBpp = (pa == NULL) ? 1 : bpp;
 
-    switch (assumed_bpp) {
+    switch (assumedBpp) {
     case 1:
-        retval = create1Bitmap (pa,cols,rows,cht);
+        fillInRaster1(rowData, xByteCt, pa, cols, rows, cht);
         break;
     case 4:
-        retval = create4Bitmap (pa,cols,rows,cht);
+        fillInRaster4(rowData, xByteCt, pa, cols, rows, cht);
         break;
     case 8:
     default:
-        retval = create8Bitmap (pa,cols,rows,cht);
+        fillInRaster8(rowData, xByteCt, pa, cols, rows, cht);
         break;
     }
-    return retval;
+    return icBitmapP;
+}
+
+
+
+static IC_InfoHeader *
+newInfoHeader(IC_Entry const entry) {
+
+   IC_InfoHeader * ihP;
+
+   MALLOCVAR_NOFAIL(ihP);
+
+   ihP->size             = 40;
+   ihP->width            = entry.width;
+   ihP->height           = entry.height * 2;
+   ihP->planes           = 1;
+   ihP->bitcount         = entry.bitcount;
+   ihP->compression      = 0;
+   ihP->imagesize        = entry.width * entry.height * 8 / entry.bitcount;
+   ihP->x_pixels_per_m   = 0;
+   ihP->y_pixels_per_m   = 0;
+   ihP->colors_used      = 1 << entry.bitcount;
+   ihP->colors_important = 0;
+
+   return ihP;
+}
+
+
+
+static IC_Palette *
+newCleanPalette(void) {
+
+    IC_Palette * paletteP;  /* malloc'ed */
+
+    unsigned int i;
+
+    MALLOCVAR_NOFAIL(paletteP);
+
+    MALLOCARRAY_NOFAIL(paletteP->colors, MAXCOLORS);
+
+    for (i=0; i <MAXCOLORS; ++i) {
+        paletteP->colors[i] = NULL;
+    }
+    return paletteP;
+}
+
+
+
+static void
+addColorToPalette(IC_Palette * const paletteP,
+                  unsigned int const i,
+                  unsigned int const r,
+                  unsigned int const g,
+                  unsigned int const b) {
+
+    MALLOCVAR_NOFAIL(paletteP->colors[i]);
+
+    paletteP->colors[i]->red      = r;
+    paletteP->colors[i]->green    = g;
+    paletteP->colors[i]->blue     = b;
+    paletteP->colors[i]->reserved = 0;
 }
 
 
 
 static void
 makePalette(pixel **          const xorPPMarray,
-            int               const xorCols,
-            int               const xorRows,
+            unsigned int      const xorCols,
+            unsigned int      const xorRows,
             pixval            const xorMaxval,
-            IC_Palette *      const paletteP,
+            IC_Palette **     const palettePP,
             colorhash_table * const xorChtP,
-            int *             const colorsP,
+            unsigned int *    const colorsP,
             const char **     const errorP) {
-   /*
-    * Figure out the colormap and turn it into the appropriate GIF
-    * colormap - this code's pretty much straight from ppmtobpm
-    */
+/*----------------------------------------------------------------------------
+   Figure out the colormap and turn it into the appropriate GIF colormap -
+   this code's pretty much straight from 'ppmtobpm'.
+-----------------------------------------------------------------------------*/
+    IC_Palette * const paletteP = newCleanPalette();
+
     colorhist_vector xorChv;
     unsigned int i;
-    int colors;
-    IC_Palette palette = createCleanPalette();
+    int colorCt;
+
+    if (verbose)
+        pm_message("computing colormap...");
 
-    if (verbose) pm_message("computing colormap...");
-    xorChv = ppm_computecolorhist(xorPPMarray, xorCols, xorRows, MAXCOLORS, 
-                                  &colors);
-    if (xorChv == NULL)
+    xorChv = ppm_computecolorhist(xorPPMarray, xorCols, xorRows, MAXCOLORS,
+                                  &colorCt);
+    if (!xorChv)
         pm_asprintf(errorP,
-                    "image has too many colors - try doing a 'pnmquant %d'",
+                    "image has too many colors - try doing a 'pnmquant %u'",
                     MAXCOLORS);
     else {
         *errorP = NULL;
 
-        if (verbose) pm_message("%d colors found", colors);
-        
+        if (verbose)
+            pm_message("%u colors found", colorCt);
+
         if (verbose && (xorMaxval > 255))
             pm_message("maxval is not 255 - automatically rescaling colors");
-        for (i = 0; i < colors; ++i) {
+        for (i = 0; i < colorCt; ++i) {
             if (xorMaxval == 255) {
-                addColorToPalette(palette,i,
+                addColorToPalette(paletteP, i,
                                   PPM_GETR(xorChv[i].color),
                                   PPM_GETG(xorChv[i].color),
                                   PPM_GETB(xorChv[i].color));
             } else {
-                addColorToPalette(palette,i,
+                addColorToPalette(paletteP, i,
                                   PPM_GETR(xorChv[i].color) * 255 / xorMaxval,
                                   PPM_GETG(xorChv[i].color) * 255 / xorMaxval,
                                   PPM_GETB(xorChv[i].color) * 255 / xorMaxval);
             }
         }
-        
+
         /* And make a hash table for fast lookup. */
-        *xorChtP = ppm_colorhisttocolorhash(xorChv, colors);
-        
+        *xorChtP = ppm_colorhisttocolorhash(xorChv, colorCt);
+
         ppm_freecolorhist(xorChv);
-        
-        *paletteP = palette;
-        *colorsP = colors;
+
+        *palettePP = paletteP;
+        *colorsP   = colorCt;
     }
 }
 
@@ -562,15 +561,15 @@ makePalette(pixel **          const xorPPMarray,
 
 static void
 getOrFakeAndMap(const char *      const andPgmFname,
-                int               const xorCols,
-                int               const xorRows,
+                unsigned int      const xorCols,
+                unsigned int      const xorRows,
                 gray ***          const andPGMarrayP,
                 pixval *          const andMaxvalP,
                 colorhash_table * const andChtP,
                 const char **     const errorP) {
 
     int andRows, andCols;
-    
+
     if (!andPgmFname) {
         /* He's not supplying a bitmap for 'and'.  Fake the bitmap. */
         *andPGMarrayP = NULL;
@@ -578,15 +577,15 @@ getOrFakeAndMap(const char *      const andPgmFname,
         *andChtP      = NULL;
         *errorP       = NULL;
     } else {
-        FILE * andfile;
-        andfile = pm_openr(andPgmFname);
-        *andPGMarrayP = pgm_readpgm(andfile, &andCols, &andRows, andMaxvalP);
-        pm_close(andfile);
+        FILE * andFileP;
+        andFileP = pm_openr(andPgmFname);
+        *andPGMarrayP = pgm_readpgm(andFileP, &andCols, &andRows, andMaxvalP);
+        pm_close(andFileP);
 
         if ((andCols != xorCols) || (andRows != xorRows)) {
             pm_asprintf(errorP,
                         "And mask and image have different dimensions "
-                        "(%d x %d vs %d x %d).  Aborting.",
+                        "(%u x %u vs %u x %u).  Aborting.",
                         andCols, xorCols, andRows, xorRows);
         } else
             *errorP = NULL;
@@ -596,18 +595,20 @@ getOrFakeAndMap(const char *      const andPgmFname,
 
 
 static void
-blackenTransparentAreas(pixel ** const xorPPMarray,
-                        int      const cols,
-                        int      const rows,
-                        gray **  const andPGMarray,
-                        pixval   const andMaxval) {
+blackenTransparentAreas(pixel **     const xorPPMarray,
+                        unsigned int const cols,
+                        unsigned int const rows,
+                        gray **      const andPGMarray,
+                        pixval       const andMaxval) {
 
     unsigned int row;
 
-    if (verbose) pm_message("Setting transparent pixels to black");
+    if (verbose)
+        pm_message("Setting transparent pixels to black");
 
     for (row = 0; row < rows; ++row) {
         unsigned int col;
+
         for (col = 0; col < cols; ++col) {
             if (andPGMarray[row][col] < andMaxval)
                 /* It's not opaque here; make it black */
@@ -618,70 +619,69 @@ blackenTransparentAreas(pixel ** const xorPPMarray,
 
 
 
-static void 
-addEntryToIcon(MS_Ico       const MSIconData, 
+static void
+addEntryToIcon(MS_Ico *     const MSIconDataP,
                const char * const xorPpmFname,
                const char * const andPgmFname,
                bool         const trueTransparent) {
 
-    IC_Entry entry;
+    IC_Entry * entryP;
     FILE * xorfile;
     pixel ** xorPPMarray;
     gray ** andPGMarray;
-    ICON_bmp xorBitmap;
-    ICON_bmp andBitmap;
+    ICON_bmp * xorBitmapP;
+    ICON_bmp * andBitmapP;
     int rows, cols;
-    int bpp, colors;
-    int entry_cols;
-    IC_Palette palette;
-    colorhash_table  xorCht;
-    colorhash_table  andCht; 
+    unsigned int bpp;
+    unsigned int colorCt;
+    unsigned int entryCols;
+    IC_Palette * paletteP;
+    colorhash_table xorCht;
+    colorhash_table andCht;
     const char * error;
-   
+
     pixval xorMaxval;
     gray andMaxval;
 
-    MALLOCVAR_NOFAIL(entry);
+    MALLOCVAR_NOFAIL(entryP);
 
-   /*
-    * Read the xor PPM.
-    */
+    /* Read the xor PPM. */
     xorfile = pm_openr(xorPpmFname);
     xorPPMarray = ppm_readppm(xorfile, &cols, &rows, &xorMaxval);
     pm_close(xorfile);
-    /*
-    * Since the entry uses 1 byte to hold the width and height of the icon, the
-    * image can't be more than 256 x 256.
+
+    /* Since the entry uses 1 byte to hold the width and height of the icon,
+       the image can't be more than 256 x 256.
     */
     if (rows > 255 || cols > 255) {
         pm_error("Max size for a icon is 255 x 255 (1 byte fields).  "
-                 "%s is %d x %d", xorPpmFname, cols, rows);
+                 "%s is %u x %u", xorPpmFname, cols, rows);
     }
-   
-    if (verbose) pm_message("read PPM: %dw x %dh, maxval = %d", 
-                            cols, rows, xorMaxval);
 
-    makePalette(xorPPMarray, cols, rows, xorMaxval, 
-                &palette, &xorCht, &colors, &error);
+    if (verbose)
+        pm_message("read PPM: %uw x %uh, maxval = %u", cols, rows, xorMaxval);
+
+    makePalette(xorPPMarray, cols, rows, xorMaxval,
+                &paletteP, &xorCht, &colorCt, &error);
 
     if (error)
         pm_error("Unable to make palette for '%s'.  %s", xorPpmFname, error);
-   /*
-    * All the icons I found seemed to pad the palette to the max entries
-    * for that bitdepth.
-    * 
-    * The spec indicates this isn't necessary, but I'll follow this behaviour
-    * just in case.
+
+    /* All the icons I found seemed to pad the palette to the max entries for
+       that bitdepth.
+
+       The spec indicates this isn't necessary, but I'll follow this behaviour
+       just in case.
     */
-    if (colors < 3) {
+    if (colorCt < 3) {
         bpp = 1;
-        entry_cols = 2;
-    } else if (colors < 17) {
+        entryCols = 2;
+    } else if (colorCt < 17) {
         bpp = 4;
-        entry_cols = 16;
+        entryCols = 16;
     } else {
         bpp = 8;
-        entry_cols = 256;
+        entryCols = 256;
     }
 
     getOrFakeAndMap(andPgmFname, cols, rows,
@@ -690,164 +690,182 @@ addEntryToIcon(MS_Ico       const MSIconData,
         pm_error("Error in and map for '%s'.  %s", xorPpmFname, error);
 
     if (andPGMarray && trueTransparent)
-        blackenTransparentAreas(xorPPMarray, cols, rows, 
+        blackenTransparentAreas(xorPPMarray, cols, rows,
                                 andPGMarray, andMaxval);
 
-    xorBitmap = createBitmap(bpp, xorPPMarray, cols, rows, xorCht);
-    andBitmap = createAndBitmap(andPGMarray, cols, rows, andMaxval);
-    /*
-     * Fill in the entry data fields.
-    */
-    entry->width         = cols;
-    entry->height        = rows;
-    entry->color_count   = entry_cols;
-    entry->reserved      = 0;
-    entry->planes        = 1;
-    /* 
-    * all the icons I looked at ignored this value...
-    */
-    entry->bitcount      = bpp;
-    entry->ih            = createInfoHeader(entry, xorBitmap, andBitmap);
-    entry->colors        = palette->colors;
-    entry->size_in_bytes = 
-        xorBitmap->size + andBitmap->size + 40 + (4 * entry->color_count);
-    if (verbose) 
-        pm_message("entry->size_in_bytes = %d + %d + %d = %d",
-                   xorBitmap->size ,andBitmap->size, 
-                   40, entry->size_in_bytes );
-    /*
-    * We don't know the offset ATM, set to 0 for now.
-    * Have to calculate this at the end.
-    */
-    entry->file_offset   = 0;
-    entry->xorBitmapOut  = xorBitmap->data;
-    entry->andBitmapOut  = andBitmap->data;
-    entry->xBytesXor     = xorBitmap->xBytes;
-    entry->xBytesAnd     = andBitmap->xBytes;  
-    /*
-    * Add the entry to the entries array.
+    xorBitmapP = newBitmap(bpp, xorPPMarray, cols, rows, xorCht);
+    andBitmapP = newAndBitmap(andPGMarray, cols, rows, andMaxval);
+
+    /* Fill in the entry data fields. */
+    entryP->width         = cols;
+    entryP->height        = rows;
+    entryP->color_count   = entryCols;
+    entryP->reserved      = 0;
+    entryP->planes        = 1;
+    entryP->bitcount      = bpp;
+    /* all the icons I looked at ignored this value */
+    entryP->ih            = newInfoHeader(*entryP);
+    entryP->colors        = paletteP->colors;
+    entryP->size_in_bytes =
+        xorBitmapP->size + andBitmapP->size + 40 + (4 * entryCols);
+    if (verbose)
+        pm_message("entry->size_in_bytes = %u + %u + %u = %u",
+                   xorBitmapP->size, andBitmapP->size,
+                   40, entryP->size_in_bytes );
+
+    /* We don't know the offset ATM, set to 0 for now.  Have to calculate this
+       at the end.
     */
-    ++MSIconData->count;
+    entryP->file_offset  = 0;
+    entryP->xorBitmapOut = xorBitmapP->data;
+    entryP->andBitmapOut = andBitmapP->data;
+    entryP->xBytesXor    = xorBitmapP->xBytes;
+    entryP->xBytesAnd    = andBitmapP->xBytes;
+
+    /* Add the entry to the entries array. */
+    ++MSIconDataP->count;
+
     /* Perhaps I should allocate ahead, and take fewer trips to the well. */
-    REALLOCARRAY(MSIconData->entries, MSIconData->count);
-    MSIconData->entries[MSIconData->count-1] = entry;
+    REALLOCARRAY(MSIconDataP->entries, MSIconDataP->count);
+    MSIconDataP->entries[MSIconDataP->count - 1] = entryP;
 }
 
 
 
-static void 
-writeIC_Entry (IC_Entry const entry) {
-   writeU1(entry->width);
-   writeU1(entry->height);
-   writeU1(entry->color_count); /* chops 256->0 on its own.. */
-   writeU1(entry->reserved);
-   writeU2(entry->planes);
-   writeU2(entry->bitcount);
-   writeU4(entry->size_in_bytes);
-   writeU4(entry->file_offset);
+static void
+writeIC_Entry(FILE *     const ofP,
+              IC_Entry * const entryP) {
+
+   writeU1(ofP, entryP->width);
+   writeU1(ofP, entryP->height);
+   writeU1(ofP, entryP->color_count); /* chops 256->0 on its own.. */
+   writeU1(ofP, entryP->reserved);
+   writeU2(ofP, entryP->planes);
+   writeU2(ofP, entryP->bitcount);
+   writeU4(ofP, entryP->size_in_bytes);
+   writeU4(ofP, entryP->file_offset);
 }
 
 
 
-static void 
-writeIC_InfoHeader (IC_InfoHeader const ih) {
-   writeU4(ih->size);
-   writeU4(ih->width);
-   writeU4(ih->height);
-   writeU2(ih->planes);
-   writeU2(ih->bitcount);
-   writeU4(ih->compression);
-   writeU4(ih->imagesize);
-   writeU4(ih->x_pixels_per_m);
-   writeU4(ih->y_pixels_per_m);
-   writeU4(ih->colors_used);
-   writeU4(ih->colors_important);
+static void
+writeIC_InfoHeader(FILE *          const ofP,
+                   IC_InfoHeader * const ihP) {
+
+   writeU4(ofP, ihP->size);
+   writeU4(ofP, ihP->width);
+   writeU4(ofP, ihP->height);
+   writeU2(ofP, ihP->planes);
+   writeU2(ofP, ihP->bitcount);
+   writeU4(ofP, ihP->compression);
+   writeU4(ofP, ihP->imagesize);
+   writeU4(ofP, ihP->x_pixels_per_m);
+   writeU4(ofP, ihP->y_pixels_per_m);
+   writeU4(ofP, ihP->colors_used);
+   writeU4(ofP, ihP->colors_important);
 }
 
 
 
-static void 
-writeIC_Color (IC_Color const col) {
-   /* Since the ppm might not have as many colors in it as we'd like,
-    * (2, 16, 256), stick 0 in the gaps.
-    * 
-    * This means that we lose palette information, but that can't be
-    * helped.  
+static void
+writeIC_Color(FILE *     const ofP,
+              IC_Color * const colorP) {
+
+    /* Since the ppm might not have as many colors in it as we'd like,
+       (2, 16, 256), stick 0 in the gaps.
+
+       This means that we lose palette information, but that can't be helped.
     */
-   if (col == NULL) {
-      writeU1(0);
-      writeU1(0);
-      writeU1(0);
-      writeU1(0);
-   } else {
-      writeU1(col->blue);
-      writeU1(col->green);
-      writeU1(col->red);
-      writeU1(col->reserved);
-   }
+    if (!colorP) {
+        writeU1(ofP, 0);
+        writeU1(ofP, 0);
+        writeU1(ofP, 0);
+        writeU1(ofP, 0);
+    } else {
+        writeU1(ofP, colorP->blue);
+        writeU1(ofP, colorP->green);
+        writeU1(ofP, colorP->red);
+        writeU1(ofP, colorP->reserved);
+    }
 }
 
 
 
 static void
-writeBitmap(u1 ** const bitmap, int const xBytes, int const height) {
-   int y;
-   for (y = 0;y<height;y++) {
-      fwrite (bitmap[y],1,xBytes,ofp);
-      file_offset += xBytes;
-   }
+writeBitmap(FILE *       const ofP,
+            u1 **        const bitmap,
+            unsigned int const xByteCt,
+            unsigned int const height) {
+
+    unsigned int row;
+
+    for (row = 0; row < height; ++row) {
+        fwrite(bitmap[row], 1, xByteCt, ofP);
+        fileOffset += xByteCt;
+    }
 }
 
 
 
-static void 
-writeMS_Ico(MS_Ico       const MSIconData, 
+static void
+writeMS_Ico(MS_Ico *     const MSIconDataP,
             const char * const outFname) {
-    int x,y;
-   
-    ofp = pm_openw(outFname);
-
-    writeU2(MSIconData->reserved);
-    writeU2(MSIconData->type);
-    writeU2(MSIconData->count);
-    for (x=0;x<MSIconData->count;x++) writeIC_Entry(MSIconData->entries[x]);
-    for (x=0;x<MSIconData->count;x++) {
-        writeIC_InfoHeader(MSIconData->entries[x]->ih);
-        for (y=0;y<(MSIconData->entries[x]->color_count);y++) {
-            writeIC_Color(MSIconData->entries[x]->colors[y]);
+
+    FILE * const ofP = pm_openw(outFname);
+
+    unsigned int i;
+
+    writeU2(ofP, MSIconDataP->reserved);
+    writeU2(ofP, MSIconDataP->type);
+    writeU2(ofP, MSIconDataP->count);
+
+    for (i = 0; i < MSIconDataP->count; ++i)
+        writeIC_Entry(ofP, MSIconDataP->entries[i]);
+
+    for (i = 0; i < MSIconDataP->count; ++i) {
+        IC_Entry * const entryP = MSIconDataP->entries[i];
+
+        unsigned int j;
+
+        writeIC_InfoHeader(ofP, MSIconDataP->entries[i]->ih);
+
+        for (j = 0; j < (MSIconDataP->entries[i]->color_count); ++j) {
+            writeIC_Color(ofP, MSIconDataP->entries[i]->colors[j]);
         }
-        if (verbose) pm_message("writing xor bitmap");
-        writeBitmap(MSIconData->entries[x]->xorBitmapOut,
-                    MSIconData->entries[x]->xBytesXor,
-                    MSIconData->entries[x]->height);
-        if (verbose) pm_message("writing and bitmap");
-        writeBitmap(MSIconData->entries[x]->andBitmapOut,
-                    MSIconData->entries[x]->xBytesAnd,
-                    MSIconData->entries[x]->height);
+        if (verbose)
+            pm_message("writing xor bitmap");
+
+        writeBitmap(ofP,
+                    entryP->xorBitmapOut, entryP->xBytesXor, entryP->height);
+        if (verbose)
+            pm_message("writing and bitmap");
+
+        writeBitmap(ofP,
+                    entryP->andBitmapOut, entryP->xBytesAnd, entryP->height);
     }
-    fclose(ofp);
+    fclose(ofP);
 }
 
 
 
-int 
-main(int argc, char ** argv) {
+int
+main(int argc, const char ** argv) {
 
-    struct cmdlineInfo cmdline;
+    MS_Ico * const MSIconDataP = newIconFile();
 
-    MS_Ico const MSIconDataP = createIconFile();
+    struct CmdlineInfo cmdline;
     unsigned int iconIndex;
     unsigned int offset;
-   
-    ppm_init (&argc, argv);
+
+    pm_proginit(&argc, argv);
 
     parseCommandLine(argc, argv, &cmdline);
 
     verbose = cmdline.verbose;
 
     for (iconIndex = 0; iconIndex < cmdline.iconCount; ++iconIndex) {
-        addEntryToIcon(MSIconDataP, cmdline.inputFilespec[iconIndex],
-                       cmdline.andpgmFilespec[iconIndex], 
+        addEntryToIcon(MSIconDataP, cmdline.inputFileNm[iconIndex],
+                       cmdline.andpgmFileNm[iconIndex],
                        cmdline.truetransparent);
     }
     /*
@@ -856,22 +874,24 @@ main(int argc, char ** argv) {
      */
     offset = (MSIconDataP->count * 16) + 6;
     for (iconIndex = 0; iconIndex < MSIconDataP->count; ++iconIndex) {
-        IC_Entry entry = MSIconDataP->entries[iconIndex];
-        entry->file_offset = offset;
-        /* 
+        IC_Entry * const entryP = MSIconDataP->entries[iconIndex];
+
+        entryP->file_offset = offset;
+        /*
          * Increase the offset by the size of this offset & data.
          * this includes the size of the color data.
          */
-        offset += entry->size_in_bytes;
+        offset += entryP->size_in_bytes;
     }
     /*
      * And now, we have to actually SAVE the .ico!
      */
     writeMS_Ico(MSIconDataP, cmdline.output);
 
-    free(cmdline.inputFilespec);
-    free(cmdline.andpgmFilespec);
+    freeCmdline(cmdline);
 
     return 0;
 }
 
+
+
diff --git a/converter/ppm/ppmtoxpm.c b/converter/ppm/ppmtoxpm.c
index 0e316928..9cbab8f3 100644
--- a/converter/ppm/ppmtoxpm.c
+++ b/converter/ppm/ppmtoxpm.c
@@ -1,4 +1,4 @@
-/* ppmtoxpm.c - read a portable pixmap and produce a (version 3) X11 pixmap
+/* ppmtoxpm.c - read a PPM image and produce a (version 3) X11 pixmap
 **
 ** Copyright (C) 1990 by Mark W. Snitily
 **
@@ -24,7 +24,7 @@
 ** Rainer Sinkwitz sinkwitz@ifi.unizh.ch - 21 Nov 91:
 **  - Bug fix, should should malloc space for rgbn[j].name+1 in line 441
 **    caused segmentation faults
-**    
+**
 **  - lowercase conversion of RGB names def'ed out,
 **    considered harmful.
 **
@@ -37,6 +37,7 @@
 #define _BSD_SOURCE   /* Make sure strdup() is in string.h */
 #define _XOPEN_SOURCE 500  /* Make sure strdup() is in string.h */
 
+#include <stdbool.h>
 #include <stdio.h>
 #include <ctype.h>
 #include <string.h>
@@ -47,7 +48,7 @@
 #include "nstring.h"
 #include "mallocvar.h"
 
-/* Max number of entries we will put in the XPM color map 
+/* Max number of entries we will put in the XPM color map
    Don't forget the one entry for transparency.
 
    We don't use this anymore.  Ppmtoxpm now has no arbitrary limit on
@@ -75,14 +76,14 @@ static const char * const printable =
 ASDFGHJKLPIUYTREWQ!~^/()_`'][{}|";
 
 
-struct cmdlineInfo {
+struct CmdlineInfo {
     /* All the information the user supplied in the command line,
        in a form easy for the program to use.
     */
-    const char *inputFilename;
-    const char *name;
-    const char *rgb;
-    const char *alpha_filename;
+    const char * inputFilename;
+    const char * name;
+    const char * rgb;
+    const char * alphaFilename;
     unsigned int hexonly;
     unsigned int verbose;
 };
@@ -90,15 +91,13 @@ struct cmdlineInfo {
 
 
 static void
-parseCommandLine(int argc, char ** argv,
-                 struct cmdlineInfo * const cmdlineP) {
+parseCommandLine(int argc, const char ** argv,
+                 struct CmdlineInfo * const cmdlineP) {
 /*----------------------------------------------------------------------------
    Note that the file spec array we return is stored in the storage that
    was passed to us as the argv array.
 -----------------------------------------------------------------------------*/
-    optEntry *option_def;
-        /* Instructions to OptParseOptions3 on how to parse our options.
-         */
+    optEntry * option_def;
     optStruct3 opt;
 
     unsigned int option_def_index;
@@ -108,11 +107,11 @@ parseCommandLine(int argc, char ** argv,
     MALLOCARRAY(option_def, 100);
 
     option_def_index = 0;   /* incremented by OPTENTRY */
-    OPTENT3(0,   "alphamask",   OPT_STRING, &cmdlineP->alpha_filename, 
+    OPTENT3(0,   "alphamask",   OPT_STRING, &cmdlineP->alphaFilename,
             NULL, 0);
-    OPTENT3(0,   "name",        OPT_STRING, &nameOpt,                   
+    OPTENT3(0,   "name",        OPT_STRING, &nameOpt,
             &nameSpec, 0);
-    OPTENT3(0,   "rgb",         OPT_STRING, &cmdlineP->rgb,            
+    OPTENT3(0,   "rgb",         OPT_STRING, &cmdlineP->rgb,
             NULL, 0);
     OPTENT3(0,   "hexonly",     OPT_FLAG, NULL,
             &cmdlineP->hexonly, 0);
@@ -120,17 +119,17 @@ parseCommandLine(int argc, char ** argv,
             &cmdlineP->verbose, 0);
 
     /* Set the defaults */
-    cmdlineP->alpha_filename = NULL;  /* no transparency */
+    cmdlineP->alphaFilename = NULL;  /* no transparency */
     cmdlineP->rgb = NULL;      /* no rgb file specified */
 
     opt.opt_table = option_def;
-    opt.short_allowed = FALSE;  /* We have no short (old-fashioned) options */
-    opt.allowNegNum = FALSE;  /* We may have parms that are negative numbers */
+    opt.short_allowed = false;  /* We have no short (old-fashioned) options */
+    opt.allowNegNum = false;  /* We may have parms that are negative numbers */
 
-    pm_optParseOptions3(&argc, argv, opt, sizeof(opt), 0);
+    pm_optParseOptions4(&argc, argv, opt, sizeof(opt), 0);
         /* Uses and sets argc, argv, and some of *cmdlineP and others. */
 
-    if (argc-1 == 0) 
+    if (argc-1 == 0)
         cmdlineP->inputFilename = "-";
     else if (argc-1 != 1)
         pm_error("Program takes zero or one argument (filename).  You "
@@ -156,28 +155,24 @@ parseCommandLine(int argc, char ** argv,
 }
 
 
-typedef struct {            /* rgb values and ascii names (from
-                             * rgb text file) */
-    int r, g, b;            /* rgb values, range of 0 -> 65535 */
-    char *name;             /* color mnemonic of rgb value */
-} rgb_names;
 
-typedef struct {            
+typedef struct {
     /* Information for an XPM color map entry */
-    char *cixel;    
+    char *cixel;
        /* XPM color number, as might appear in the XPM raster */
-    const char *rgbname;  
+    const char *rgbname;
        /* color name, e.g. "blue" or "#01FF23" */
-} cixel_map;
+} CixelMap;
 
 
 
 static char *
-genNumstr(unsigned int const input, int const digits) {
+numstr(unsigned int const input,
+       unsigned int const digitCt) {
 /*---------------------------------------------------------------------------
    Given a number and a base (MAXPRINTABLE), this routine prints the
    number into a malloc'ed string and returns it.  The length of the
-   string is specified by "digits".  It is not printed in decimal or
+   string is specified by 'digitCt'.  It is not printed in decimal or
    any other number system you're used to.  Rather, each digit is from
    the set printable[], which contains MAXPRINTABLE characters; the
    character printable[n] has value n.
@@ -185,35 +180,35 @@ genNumstr(unsigned int const input, int const digits) {
    The string is printable[0] filled with high order zeroes.
 
    Example:
-     Assume: 
+     Assume:
        printable[0] == 'q'
        printable[1] == '%'
-       MAXPRINTABLE == 2 
-       digits == 5
-       input == 3 
+       MAXPRINTABLE == 2
+       digitCt == 5
+       input == 3
      Result is the malloc'ed string "qqq%%"
 ---------------------------------------------------------------------------*/
-    char *str, *p;
-    int d;
+    char * str;  /* malloc'ed */
+    char * p;
     unsigned int i;
 
     /* Allocate memory for printed number.  Abort if error. */
-    if (!(str = (char *) malloc(digits + 1)))
-        pm_error("out of memory");
+    MALLOCARRAY_NOFAIL(str, digitCt + 1);
 
-    i = input;
+    i = input; /* initial value */
     /* Generate characters starting with least significant digit. */
-    p = str + digits;
+    p = str + digitCt;  /* initial value */
     *p-- = '\0';            /* nul terminate string */
     while (p >= str) {
-        d = i % MAXPRINTABLE;
+        unsigned int const d = i % MAXPRINTABLE;
+
         i /= MAXPRINTABLE;
         *p-- = printable[d];
     }
 
     if (i != 0)
-        pm_error("Overflow converting %d to %d digits in base %d",
-                 input, digits, MAXPRINTABLE);
+        pm_error("Overflow converting %u to %u digits in base %u",
+                 input, digitCt, MAXPRINTABLE);
 
     return str;
 }
@@ -225,10 +220,9 @@ xpmMaxvalFromMaxval(pixval const maxval) {
 
     unsigned int retval;
 
-    /*
-     * Determine how many hex digits we'll be normalizing to if the rgb
-     * value doesn't match a color mnemonic. 
-     */
+    /* Determine how many hex digits we'll be normalizing to if the rgb
+       value doesn't match a color mnemonic.
+    */
     if (maxval <= 0x000F)
         retval = 0x000F;
     else if (maxval <= 0x00FF)
@@ -242,22 +236,21 @@ xpmMaxvalFromMaxval(pixval const maxval) {
 
     return retval;
 }
-    
+
 
 
 static unsigned int
-charsPerPixelForSize(unsigned int const cmapSize) { 
+charsPerPixelForSize(unsigned int const cmapSize) {
 /*----------------------------------------------------------------------------
-   Return the number of characters it will take to represent a pixel in
-   an XPM that has a colormap of size 'cmapSize'.  Each pixel in an XPM
-   represents an index into the colormap with a base-92 scheme where each
-   character is one of 92 printable characters.  Ergo, if the colormap
-   has at most 92 characters, each pixel will be represented by a single
-   character.  If it has more than 92, but at most 92*92, it will take 2, 
-   etc.
-
-   If cmapSize is zero, there's no such thing as an XPM pixel, so we
-   return an undefined value.
+   The number of characters it will take to represent a pixel in an XPM that
+   has a colormap of size 'cmapSize'.  Each pixel in an XPM represents an
+   index into the colormap with a base-92 scheme where each character is one
+   of 92 printable characters.  Ergo, if the colormap has at most 92
+   characters, each pixel will be represented by a single character.  If it
+   has more than 92, but at most 92*92, it will take 2, etc.
+
+   If cmapSize is zero, there's no such thing as an XPM pixel, so we return an
+   undefined value.
 -----------------------------------------------------------------------------*/
     unsigned int charsPerPixel;
 
@@ -268,23 +261,22 @@ charsPerPixelForSize(unsigned int const cmapSize) {
             j /= MAXPRINTABLE;
     }
     return charsPerPixel;
-} 
+}
 
 
 
 static void
-genCmap(colorhist_vector const chv, 
-        int              const ncolors, 
-        pixval           const maxval, 
-        colorhash_table  const colornameHash,
-        const char *     const colornames[],
+genCmap(colorhist_vector const chv,
+        unsigned int     const ncolors,
+        pixval           const maxval,
+        ppm_ColorDict *  const colorDictP,
         bool             const includeTransparent,
-        cixel_map **     const cmapP, 
+        CixelMap **      const cmapP,
         unsigned int *   const transIndexP,
         unsigned int *   const cmapSizeP,
         unsigned int *   const charsPerPixelP) {
 /*----------------------------------------------------------------------------
-   Generate the XPM color map in cixel_map format (which is just a step
+   Generate the XPM color map in CixelMap format (which is just a step
    away from the actual text that needs to be written the XPM file).  The
    color map is defined by 'chv', which contains 'ncolors' colors which
    have maxval 'maxval'.
@@ -295,14 +287,10 @@ genCmap(colorhist_vector const chv,
    This map includes an entry for transparency, whether the raster uses
    it or not.  We return its index as *transIndexP.
 
-   In the map, identify colors by the names given by 'colornameHash' and
-   colornames[].  'colornameHash' maps a color in 'pixel' form to an
-   index into colornames[]; colornames[] contains the text to identify the
-   color in the XPM format.  The colors in 'colornameHash' have maxval 255.
-   If a color is not in 'colornameHash', use hexadecimal notation in the
-   output colormap.
+   In the map, identify colors by the names given by *colorDictP.  If a color
+   is not in *colorDictP, use hexadecimal notation in the output colormap.
 
-   But if 'colornameHash' is null, don't use color names at all.  Just use
+   But if *colorDictP is null, don't use color names at all.  Just use
    hexadecimal notation.
 
    Return as *charsPerPixel the number of characters, or digits, that
@@ -310,15 +298,14 @@ genCmap(colorhist_vector const chv,
 -----------------------------------------------------------------------------*/
     unsigned int const cmapSize = ncolors + (includeTransparent ? 1 : 0);
 
-    cixel_map * cmap;  /* malloc'ed */
+    CixelMap * cmap;  /* malloc'ed */
     unsigned int cmapIndex;
     unsigned int charsPerPixel;
     unsigned int xpmMaxval;
-    
+
     MALLOCARRAY(cmap, cmapSize);
     if (cmapP == NULL)
-        pm_error("Out of memory allocating %u bytes for a color map.",
-                 (unsigned)sizeof(cixel_map) * (ncolors+1));
+        pm_error("Can't get memory for a %u-entry color map", cmapSize);
 
     xpmMaxval = xpmMaxvalFromMaxval(maxval);
 
@@ -326,7 +313,7 @@ genCmap(colorhist_vector const chv,
 
     /*
      * Generate the character-pixel string and the rgb name for each
-     * colormap entry. 
+     * colormap entry.
      */
     for (cmapIndex = 0; cmapIndex < ncolors; ++cmapIndex) {
         pixel const color = chv[cmapIndex].color;
@@ -338,19 +325,19 @@ genCmap(colorhist_vector const chv,
          * The character-pixel string is simply a printed number in base
          * MAXPRINTABLE where the digits of the number range from
          * printable[0] .. printable[MAXPRINTABLE-1] and the printed length
-         * of the number is 'charsPerPixel'. 
+         * of the number is 'charsPerPixel'.
          */
-        cmap[cmapIndex].cixel = genNumstr(cmapIndex, charsPerPixel);
-        
+        cmap[cmapIndex].cixel = numstr(cmapIndex, charsPerPixel);
+
         PPM_DEPTH(color255, color, maxval, 255);
 
-        if (colornameHash == NULL)
+        if (!colorDictP)
             colorname = NULL;
         else {
             int colornameIndex;
-            colornameIndex = ppm_lookupcolor(colornameHash, &color255);
+            colornameIndex = ppm_lookupcolor(colorDictP->cht, &color255);
             if (colornameIndex >= 0)
-                colorname = strdup(colornames[colornameIndex]);
+                colorname = strdup(colorDictP->name[colornameIndex]);
             else
                 colorname = NULL;
         }
@@ -367,7 +354,7 @@ genCmap(colorhist_vector const chv,
             pm_asprintf(&hexString, xpmMaxval == 0x000F ? "#%X%X%X" :
                         xpmMaxval == 0x00FF ? "#%02X%02X%02X" :
                         xpmMaxval == 0x0FFF ? "#%03X%03X%03X" :
-                        "#%04X%04X%04X", 
+                        "#%04X%04X%04X",
                         PPM_GETR(scaledColor),
                         PPM_GETG(scaledColor),
                         PPM_GETB(scaledColor)
@@ -383,7 +370,7 @@ genCmap(colorhist_vector const chv,
         /* Add the special transparency entry to the colormap */
         unsigned int const transIndex = ncolors;
         cmap[transIndex].rgbname = strdup("None");
-        cmap[transIndex].cixel = genNumstr(transIndex, charsPerPixel);
+        cmap[transIndex].cixel = numstr(transIndex, charsPerPixel);
         *transIndexP = transIndex;
     }
     *cmapP          = cmap;
@@ -394,107 +381,111 @@ genCmap(colorhist_vector const chv,
 
 
 static void
-destroyCmap(cixel_map *  const cmap, 
+destroyCmap(CixelMap *   const cmap,
             unsigned int const cmapSize) {
 
-    int i;
+    unsigned int i;
+
     /* Free the real color entries */
-    for (i = 0; i < cmapSize; i++) {
+    for (i = 0; i < cmapSize; ++i) {
         pm_strfree(cmap[i].rgbname);
         free(cmap[i].cixel);
     }
+
     free(cmap);
 }
 
 
 
 static void
-writeXpmFile(FILE *          const outfile, 
-             pixel **        const pixels, 
-             gray **         const alpha, 
-             pixval          const alphamaxval,
-             char            const name[], 
-             int             const cols, 
-             int             const rows, 
-             unsigned int    const cmapSize,
-             unsigned int    const charsPerPixel, 
-             cixel_map       const cmap[],
-             colorhash_table const cht,
-             unsigned int    const transIndex) {
+writeXpmFile(FILE *           const ofP,
+             pixel **         const pixels,
+             gray **          const alpha,
+             pixval           const alphamaxval,
+             char             const name[],
+             unsigned int     const cols,
+             unsigned int     const rows,
+             unsigned int     const cmapSize,
+             unsigned int     const charsPerPixel,
+             const CixelMap * const cmap,
+             colorhash_table  const cht,
+             unsigned int     const transIndex) {
 /*----------------------------------------------------------------------------
-   Write the whole XPM file to the open stream 'outfile'.
+   Write the whole XPM file to the open stream 'ofP'.
 
-   'cmap' is the colormap to be placed in the XPM.  'cmapSize' is the
-   number of entries in it.  'cht' is a hash table that gives you an 
-   index into 'cmap' given a color.  'transIndex' is the index into cmap
-   of the transparent color, and is valid only if 'alpha' is non-null
-   (otherwise, cmap might not contain a transparent color).
+   'cmap' is the colormap to be placed in the XPM.  'cmapSize' is the number
+   of entries in it.  'cht' is a hash table that gives you an index into
+   'cmap' given a color.  'transIndex' is the index into cmap of the
+   transparent color, and is valid only if 'alpha' is non-null (otherwise,
+   cmap might not contain a transparent color).
 -----------------------------------------------------------------------------*/
     /* First the header */
     printf("/* XPM */\n");
-    fprintf(outfile, "static char *%s[] = {\n", name);
-    fprintf(outfile, "/* width height ncolors chars_per_pixel */\n");
-    fprintf(outfile, "\"%d %d %d %d\",\n", cols, rows, 
-            cmapSize, charsPerPixel);
+    fprintf(ofP, "static char *%s[] = {\n", name);
+    fprintf(ofP, "/* width height ncolors chars_per_pixel */\n");
+    fprintf(ofP, "\"%u %u %u %u\",\n", cols, rows, cmapSize, charsPerPixel);
 
     {
-        int i;
+        unsigned int i;
         /* Write out the colormap (part of header) */
-        fprintf(outfile, "/* colors */\n");
-        for (i = 0; i < cmapSize; i++) { 
-            fprintf(outfile, "\"%s c %s\",\n", cmap[i].cixel, cmap[i].rgbname);
+        fprintf(ofP, "/* colors */\n");
+        for (i = 0; i < cmapSize; i++) {
+            fprintf(ofP, "\"%s c %s\",\n", cmap[i].cixel, cmap[i].rgbname);
         }
     }
     {
-        int row;
+        unsigned int row;
 
         /* And now the raster */
-        fprintf(outfile, "/* pixels */\n");
-        for (row = 0; row < rows; row++) {
-            int col;
-            fprintf(outfile, "\"");
-            for (col = 0; col < cols; col++) {
+        fprintf(ofP, "/* pixels */\n");
+        for (row = 0; row < rows; ++row) {
+            unsigned int col;
+            fprintf(ofP, "\"");
+            for (col = 0; col < cols; ++col) {
                 if (alpha && alpha[row][col] <= alphamaxval/2)
                     /* It's a transparent pixel */
-                    fprintf(outfile, "%s", cmap[transIndex].cixel);
-                else 
-                    fprintf(outfile, "%s", 
-                            cmap[ppm_lookupcolor(cht, 
+                    fprintf(ofP, "%s", cmap[transIndex].cixel);
+                else
+                    fprintf(ofP, "%s",
+                            cmap[ppm_lookupcolor(cht,
                                                  &pixels[row][col])].cixel);
             }
-            fprintf(outfile, "\"%s\n", (row == (rows - 1) ? "" : ","));
+            fprintf(ofP, "\"%s\n", (row == (rows - 1) ? "" : ","));
         }
     }
     /* And close up */
-    fprintf(outfile, "};\n");
+    fprintf(ofP, "};\n");
 }
 
 
 
 static void
-readAlpha(const char filespec[], gray *** const alphaP,
-          int const cols, int const rows, pixval * const alphamaxvalP) {
+readAlpha(const char * const fileNm,
+          gray ***     const alphaP,
+          unsigned int const cols,
+          unsigned int const rows,
+          pixval *     const alphamaxvalP) {
 
-    FILE * alpha_file;
+    FILE * alphaFileP;
     int alphacols, alpharows;
-        
-    alpha_file = pm_openr(filespec);
-    *alphaP = pgm_readpgm(alpha_file, &alphacols, &alpharows, alphamaxvalP);
-    pm_close(alpha_file);
-    
+
+    alphaFileP = pm_openr(fileNm);
+    *alphaP = pgm_readpgm(alphaFileP, &alphacols, &alpharows, alphamaxvalP);
+    pm_close(alphaFileP);
+
     if (cols != alphacols || rows != alpharows)
         pm_error("Alpha mask is not the same dimensions as the "
-                 "image.  Image is %d by %d, while mask is %d x %d.",
+                 "image.  Image is %u by %u, while mask is %d x %d.",
                  cols, rows, alphacols, alpharows);
 }
-    
+
 
 
 static void
 computecolorhash(pixel **          const pixels,
                  gray **           const alpha,
-                 int               const cols,
-                 int               const rows,
+                 unsigned int      const cols,
+                 unsigned int      const rows,
                  gray              const alphaMaxval,
                  colorhash_table * const chtP,
                  unsigned int *    const ncolorsP,
@@ -507,49 +498,55 @@ computecolorhash(pixel **          const pixels,
    The value associated with the color in the hash we build is meaningless.
 
    Return the colorhash_table as *chtP, and the number of colors in it
-   as *ncolorsP.  Return *transparentSomewhereP == TRUE iff the image has
+   as *ncolorsP.  Return *transparentSomewhereP == true iff the image has
    at least one pixel that is mostly transparent.
 -----------------------------------------------------------------------------*/
     colorhash_table cht;
-    int row;
-    
-    cht = ppm_alloccolorhash( );
-    *ncolorsP = 0;   /* initial value */
-    *transparentSomewhereP = FALSE;  /* initial assumption */
+    unsigned int row;
+    bool foundTransparent;
+    unsigned int ncolors;
+
+    cht = ppm_alloccolorhash();
 
     /* Go through the entire image, building a hash table of colors. */
-    for (row = 0; row < rows; ++row) {
-        int col;
+    for (row = 0, ncolors = 0, foundTransparent = false; row < rows; ++row) {
+        unsigned int col;
 
         for (col = 0; col < cols; ++col) {
             if (!alpha || alpha[row][col] > alphaMaxval/2) {
                 /* It's mostly opaque, so add this color to the hash
-                   if it's not already there.  
+                   if it's not already there.
                 */
                 pixel const color = pixels[row][col];
                 int const lookupRc = ppm_lookupcolor(cht, &color);
- 
+
                 if (lookupRc < 0) {
                     /* It's not in the hash yet, so add it */
+                    if (ncolors > UINT_MAX - 10)
+                        pm_error("Number of colors (> %u) "
+                                 "is uncomputably large",
+                                 ncolors);
                     ppm_addtocolorhash(cht, &color, 0);
-                    ++(*ncolorsP);
+                    ++ncolors;
                 }
             } else
-                *transparentSomewhereP = TRUE;
+                *transparentSomewhereP = true;
         }
     }
-    *chtP = cht;
+    *chtP                  = cht;
+    *ncolorsP              = ncolors;
+    *transparentSomewhereP = foundTransparent;
 }
 
 
 
 static void
-computeColormap(pixel **           const pixels, 
+computeColormap(pixel **           const pixels,
                 gray **            const alpha,
-                int                const cols, 
-                int                const rows,
+                unsigned int       const cols,
+                unsigned int       const rows,
                 gray               const alphaMaxval,
-                colorhist_vector * const chvP, 
+                colorhist_vector * const chvP,
                 colorhash_table *  const chtP,
                 unsigned int *     const ncolorsP,
                 bool *             const transparentSomewhereP) {
@@ -558,23 +555,21 @@ computeColormap(pixel **           const pixels,
    in Netpbm data structures (a colorhist_vector for index-to-color lookups
    and a colorhash_table for color-to-index lookups).
 
-   Exclude pixels that alpha mask 'alpha' (which has maxval
-   'alphaMaxval') says are mostly transparent.  alpha == NULL means all
-   pixels are opaque.
+   Exclude pixels that alpha mask 'alpha' (which has maxval 'alphaMaxval')
+   says are mostly transparent.  alpha == NULL means all pixels are opaque.
 
-   We return as *chvP an array of the colors present in 'pixels',
-   excluding those that are mostly transparent.  We return as
-   *ncolorsP the number of such colors.  We return
-   *transparentSomewhereP == TRUE iff the image has at least one
-   pixel that is mostly transparent.
+   We return as *chvP an array of the colors present in 'pixels', excluding
+   those that are mostly transparent.  We return as *ncolorsP the number of
+   such colors.  We return *transparentSomewhereP == true iff the image has at
+   least one pixel that is mostly transparent.
 -----------------------------------------------------------------------------*/
     colorhash_table histCht;
 
     pm_message("(Computing colormap...");
-    computecolorhash(pixels, alpha, cols, rows, alphaMaxval, 
+    computecolorhash(pixels, alpha, cols, rows, alphaMaxval,
                      &histCht, ncolorsP, transparentSomewhereP);
     pm_message("...Done.  %d colors found.)", *ncolorsP);
-    
+
     *chvP = ppm_colorhashtocolorhist(histCht, *ncolorsP);
     ppm_freecolorhash(histCht);
     /* Despite the name, the following generates an index on *chvP,
@@ -587,9 +582,9 @@ computeColormap(pixel **           const pixels,
 
 
 int
-main(int argc, char *argv[]) {
+main(int argc, const char * *argv) {
 
-    FILE *ifp;
+    FILE * ifP;
     int rows, cols;
     unsigned int ncolors;
     bool transparentSomewhere;
@@ -597,38 +592,33 @@ main(int argc, char *argv[]) {
     colorhash_table cht;
     colorhist_vector chv;
 
-    colorhash_table colornameHash;
-        /* Hash table to map colors to their names */
-    const char ** colornames;
-        /* Table of color names; 'colornameHash' yields an index into this
-           array.
-        */
+    ppm_ColorDict * colorDictP;  /* The color name dictionary we use */
 
-    pixel **pixels;
-    gray **alpha;
+    pixel ** pixels;
+    gray ** alpha;
 
     /* Used for rgb value -> character-pixel string mapping */
-    cixel_map *cmap;  /* malloc'ed */
+    CixelMap * cmap;  /* malloc'ed */
         /* The XPM colormap */
     unsigned int cmapSize;
         /* Number of entries in 'cmap' */
     unsigned int transIndex;
         /* Index into 'cmap' of the transparent color, if there is one */
 
-    unsigned int charsPerPixel;  
+    unsigned int charsPerPixel;
 
-    struct cmdlineInfo cmdline;
+    struct CmdlineInfo cmdline;
 
-    ppm_init(&argc, argv);
+    pm_proginit(&argc, argv);
 
     parseCommandLine(argc, argv, &cmdline);
 
-    ifp = pm_openr(cmdline.inputFilename);
-    pixels = ppm_readppm(ifp, &cols, &rows, &maxval);
-    pm_close(ifp);
+    ifP = pm_openr(cmdline.inputFilename);
+    pixels = ppm_readppm(ifP, &cols, &rows, &maxval);
+    pm_close(ifP);
 
-    if (cmdline.alpha_filename) 
-        readAlpha(cmdline.alpha_filename, &alpha, cols, rows, &alphaMaxval);
+    if (cmdline.alphaFilename)
+        readAlpha(cmdline.alphaFilename, &alpha, cols, rows, &alphaMaxval);
     else
         alpha = NULL;
 
@@ -636,29 +626,29 @@ main(int argc, char *argv[]) {
                     &chv, &cht, &ncolors, &transparentSomewhere);
 
     if (cmdline.hexonly)
-        colornameHash = NULL;
+        colorDictP = NULL;
     else if (cmdline.rgb)
-        ppm_readcolornamefile(cmdline.rgb, TRUE, &colornameHash, &colornames);
+        colorDictP = ppm_colorDict_new(cmdline.rgb, true);
     else
-        ppm_readcolornamefile(NULL, FALSE, &colornameHash, &colornames);
+        colorDictP = ppm_colorDict_new(NULL, false);
 
     /* Now generate the character-pixel colormap table. */
-    genCmap(chv, ncolors, maxval, 
-            colornameHash, colornames, transparentSomewhere, 
+    genCmap(chv, ncolors, maxval, colorDictP, transparentSomewhere,
             &cmap, &transIndex, &cmapSize, &charsPerPixel);
 
     writeXpmFile(stdout, pixels, alpha, alphaMaxval,
                  cmdline.name, cols, rows, cmapSize,
                  charsPerPixel, cmap, cht, transIndex);
-    
-    if (colornameHash) {
-        ppm_freecolorhash(colornameHash);
-        ppm_freecolornames(colornames);
-    }
+
+    if (colorDictP)
+        ppm_colorDict_destroy(colorDictP);
     destroyCmap(cmap, cmapSize);
     ppm_freearray(pixels, rows);
-    if (alpha) pgm_freearray(alpha, rows);
+    if (alpha)
+        pgm_freearray(alpha, rows);
 
     return 0;
 }
 
+
+
diff --git a/converter/ppm/ppmtoyuv.c b/converter/ppm/ppmtoyuv.c
index 75f79c1e..3b6f873d 100644
--- a/converter/ppm/ppmtoyuv.c
+++ b/converter/ppm/ppmtoyuv.c
@@ -2,7 +2,7 @@
 **
 ** by Marc Boucher
 ** Internet: marc@PostImage.COM
-** 
+**
 ** Based on Example Conversion Program, A60/A64 Digital Video Interface
 ** Manual, page 69.
 **
@@ -42,7 +42,7 @@ convertRow(const pixel *   const pixelrow,
             pixval const r = PPM_GETR(pixelrow[col]);
             pixval const g = PPM_GETG(pixelrow[col]);
             pixval const b = PPM_GETB(pixelrow[col]);
-            
+
             y1 = 16829 * r + 33039 * g +  6416 * b + (*y2CarryP & 0xffff);
             u1 = -4853 * r -  9530 * g + 14383 * b;
             v1 = 14386 * r - 12046 * g -  2340 * b;
@@ -110,7 +110,7 @@ main(int argc, const char **argv) {
         ppm_readppmrow(ifP, pixelrow, cols, maxval, format);
 
         convertRow(pixelrow, cols, yuvBuf, &u, &v, &u0, &v0, &y2Carry);
-        
+
         fwrite(yuvBuf, cols*2, 1, stdout);
     }
 
@@ -118,3 +118,6 @@ main(int argc, const char **argv) {
 
     return 0;
 }
+
+
+
diff --git a/converter/ppm/ppmtoyuvsplit.c b/converter/ppm/ppmtoyuvsplit.c
index eb89ad29..a8723e32 100644
--- a/converter/ppm/ppmtoyuvsplit.c
+++ b/converter/ppm/ppmtoyuvsplit.c
@@ -209,3 +209,6 @@ main(int argc, const char ** argv) {
     fclose(vf);
     return 0;
 }
+
+
+
diff --git a/converter/ppm/qrttoppm.c b/converter/ppm/qrttoppm.c
index 935463e7..48a395e9 100644
--- a/converter/ppm/qrttoppm.c
+++ b/converter/ppm/qrttoppm.c
@@ -1,4 +1,4 @@
-/* qrttoppm.c - read a QRT ray-tracer output file and produce a portable pixmap
+/* qrttoppm.c - read a QRT ray-tracer output file and produce a PPM
 **
 ** Copyright (C) 1989 by Jef Poskanzer.
 **
@@ -10,60 +10,76 @@
 ** implied warranty.
 */
 
+#include "mallocvar.h"
 #include "ppm.h"
 
+
+
 int
-main( argc, argv )
-    int argc;
-    char* argv[];
-    {
-    FILE* ifp;
-    register pixel* pixelrow;
-    int rows, cols, row, col;
-    pixval maxval;
-    unsigned char* buf;
+main(int argc, const char ** argv) {
 
+    FILE * ifP;
+    pixel * pixelrow;
+    unsigned int rows, cols;
+    unsigned int row;
+    pixval maxval;
+    unsigned char * buf;
 
-    ppm_init( &argc, argv );
+    pm_proginit(&argc, argv);
 
-    if ( argc > 2 )
-	pm_usage( "[qrtfile]" );
+    if (argc-1 > 1)
+        pm_error("Too many arguments (%u).  The only possible argument "
+                 "is the input file name", argc-1);
 
-    if ( argc == 2 )
-	ifp = pm_openr( argv[1] );
+    if (argc-1 >= 1)
+        ifP = pm_openr(argv[1]);
     else
-	ifp = stdin;
+        ifP = stdin;
 
     /* Read in the QRT file.  First the header. */
-    cols = getc( ifp );
-    cols += getc( ifp ) << 8;
-    rows = getc( ifp );
-    rows += getc( ifp ) << 8;
+    cols = (unsigned char)getc(ifP);
+    cols += (unsigned char)getc(ifP) << 8;
+    rows = (unsigned char)getc(ifP);
+    rows += (unsigned char)getc(ifP) << 8;
+
+    if (cols <= 0 || rows <= 0)
+        pm_error("Invalid size: %u %u", cols, rows);
 
-    if ( cols <= 0 || rows <= 0 )
-	pm_error( "invalid size: %d %d", cols, rows );
     maxval = 255;
 
-    ppm_writeppminit( stdout, cols, rows, maxval, 0 );
-    pixelrow = ppm_allocrow( cols );
-    buf = (unsigned char *) malloc( 3 * cols );
-    if ( buf == (unsigned char *) 0 )
-	pm_error( "out of memory" );
-
-    for ( row = 0; row < rows; row++ )
-	{
-        (void) getc( ifp );	/* discard */
-        (void) getc( ifp );	/* linenum */
-	if ( fread( buf, 3 * cols, 1, ifp ) != 1 )
-	    pm_error( "EOF / read error" );
-	for ( col = 0; col < cols; col++ )
-	    PPM_ASSIGN(
-		pixelrow[col], buf[col], buf[cols + col], buf[2 * cols + col] );
-	ppm_writeppmrow( stdout, pixelrow, cols, maxval, 0 );
-	}
-
-    pm_close( ifp );
-    pm_close( stdout );
-
-    exit( 0 );
+    ppm_writeppminit(stdout, cols, rows, maxval, 0);
+
+    pixelrow = ppm_allocrow(cols);
+
+    MALLOCARRAY(buf, 3 * cols);
+
+    if (!buf)
+        pm_error("Failed to allocate buffer for %u columns", cols);
+
+    for (row = 0; row < rows; ++row) {
+        unsigned int col;
+
+        getc(ifP); /* discard */
+        getc(ifP); /* linenum */
+
+        if (fread(buf, 3 * cols, 1, ifP) != 1)
+            pm_error("EOF / read error");
+
+        for (col = 0; col < cols; ++col) {
+            PPM_ASSIGN(pixelrow[col],
+                       buf[col], buf[cols + col], buf[2 * cols + col]);
+        }
+        ppm_writeppmrow(stdout, pixelrow, cols, maxval, 0);
     }
+
+    free(buf);
+    ppm_freerow(pixelrow);
+
+    pm_close(ifP);
+    pm_close(stdout);
+
+    exit(0);
+}
+
+
+
diff --git a/converter/ppm/rawtoppm.c b/converter/ppm/rawtoppm.c
index 44e856da..7ba579ef 100644
--- a/converter/ppm/rawtoppm.c
+++ b/converter/ppm/rawtoppm.c
@@ -201,7 +201,7 @@ main(int argc, const char * argv[]) {
 
     if ( argn + 2 > argc )
         pm_usage( usage );
-    
+
     cols = pm_parse_width(argv[argn++]);
     rows = pm_parse_height(argv[argn++]);
 
@@ -250,3 +250,6 @@ main(int argc, const char * argv[]) {
 
     exit( 0 );
     }
+
+
+
diff --git a/converter/ppm/rgb3toppm.c b/converter/ppm/rgb3toppm.c
index a666553c..00d76916 100644
--- a/converter/ppm/rgb3toppm.c
+++ b/converter/ppm/rgb3toppm.c
@@ -37,7 +37,7 @@ main( argc, argv )
     ppm_init( &argc, argv );
 
     if ( argc != 4 )
-	pm_usage( "<red pgmfile> <green pgmfile> <blue pgmfile> " );
+        pm_usage( "<red pgmfile> <green pgmfile> <blue pgmfile> " );
 
     rfd = pm_openr( argv[1] );
     gfd = pm_openr( argv[2] );
@@ -46,10 +46,10 @@ main( argc, argv )
     pgm_readpgminit( rfd, &cols, &rows, &rmaxval, &rformat );
     pgm_readpgminit( gfd, &tcols, &trows, &gmaxval, &gformat );
     if ( tcols != cols || trows != rows )
-	pm_error( "all three graymaps must be the same size" );
+        pm_error( "all three graymaps must be the same size" );
     pgm_readpgminit( bfd, &tcols, &trows, &bmaxval, &bformat );
     if ( tcols != cols || trows != rows )
-	pm_error( "all three graymaps must be the same size" );
+        pm_error( "all three graymaps must be the same size" );
 
     pmaxval = rmaxval;
     if ( gmaxval > pmaxval ) pmaxval = gmaxval;
@@ -62,22 +62,22 @@ main( argc, argv )
     pixelrow = ppm_allocrow( cols );
 
     for ( row = 0; row < rows; row++ )
-	{
-	pgm_readpgmrow( rfd, rrow, cols, rmaxval, rformat );
-	pgm_readpgmrow( gfd, grow, cols, gmaxval, gformat );
-	pgm_readpgmrow( bfd, brow, cols, bmaxval, bformat );
-
-	for ( col = 0, rP = rrow, gP = grow, bP = brow, pP = pixelrow;
-	      col < cols;
-	      ++col, ++rP, ++gP, ++bP, ++pP )
-	    {
-	    if ( rmaxval != pmaxval ) *rP = (int) *rP * pmaxval / rmaxval;
-	    if ( gmaxval != pmaxval ) *gP = (int) *gP * pmaxval / gmaxval;
-	    if ( bmaxval != pmaxval ) *bP = (int) *bP * pmaxval / bmaxval;
-	    PPM_ASSIGN( *pP, *rP, *gP, *bP );
-	    }
-	ppm_writeppmrow( stdout, pixelrow, cols, pmaxval, 0 );
-	}
+        {
+        pgm_readpgmrow( rfd, rrow, cols, rmaxval, rformat );
+        pgm_readpgmrow( gfd, grow, cols, gmaxval, gformat );
+        pgm_readpgmrow( bfd, brow, cols, bmaxval, bformat );
+
+        for ( col = 0, rP = rrow, gP = grow, bP = brow, pP = pixelrow;
+              col < cols;
+              ++col, ++rP, ++gP, ++bP, ++pP )
+            {
+            if ( rmaxval != pmaxval ) *rP = (int) *rP * pmaxval / rmaxval;
+            if ( gmaxval != pmaxval ) *gP = (int) *gP * pmaxval / gmaxval;
+            if ( bmaxval != pmaxval ) *bP = (int) *bP * pmaxval / bmaxval;
+            PPM_ASSIGN( *pP, *rP, *gP, *bP );
+            }
+        ppm_writeppmrow( stdout, pixelrow, cols, pmaxval, 0 );
+        }
 
     pm_close( rfd );
     pm_close( gfd );
@@ -86,3 +86,6 @@ main( argc, argv )
 
     exit( 0 );
     }
+
+
+
diff --git a/converter/ppm/sldtoppm.c b/converter/ppm/sldtoppm.c
index 2fef0233..35d8c33a 100644
--- a/converter/ppm/sldtoppm.c
+++ b/converter/ppm/sldtoppm.c
@@ -23,6 +23,8 @@
 
 */
 
+#include <limits.h>
+#include <assert.h>
 #include <string.h>
 #include <math.h>
 
@@ -30,35 +32,38 @@
 #include "ppm.h"
 #include "ppmdraw.h"
 #include "nstring.h"
-#include <assert.h>
 
 #include "autocad.h"                  /* AutoCAD standard color assignments */
 
 
 /*  Define a variable type accepting numbers -127 <= n <= 127.  But note
-    that we still expect it to act UNSIGNED. */
+    that we still expect it to act UNSIGNED.
+*/
 
 #define smallint unsigned char        /* Small integers */
 
 #define EOS     '\0'
 
-/* Screen point */
-
 struct spoint {
+/*----------------------------------------------------------------------------
+   A screen point
+-----------------------------------------------------------------------------*/
     int x, y;
 };
 
-/* Screen polygon */
-
 struct spolygon {
-    int npoints,              /* Number of points in polygon */
-          fill;           /* Fill type */
-    struct spoint pt[11];         /* Actual points */
+/*----------------------------------------------------------------------------
+   A screen polygon
+-----------------------------------------------------------------------------*/
+    int npoints;           /* Number of points in polygon */
+    int fill;              /* Fill type */
+    struct spoint pt[11];  /* The points */
 };
 
-/* Screen vector */
-
 struct svector {
+/*----------------------------------------------------------------------------
+   A screen vector
+-----------------------------------------------------------------------------*/
     struct spoint f;          /* From point */
     struct spoint t;          /* To point */
 };
@@ -73,12 +78,8 @@ static int ixdots, iydots;        /* Screen size in dots */
 static FILE * slfile;             /* Slide file descriptor */
 static bool blither;              /* Dump slide file information ? */
 static bool info;                 /* Print header information */
-static pixel **pixels;            /* Pixel map */
+static pixel ** pixels;           /* Pixel map */
 static int pixcols, pixrows;      /* Pixel map size */
-static double uscale = -1;        /* Uniform scale factor */
-static int sxsize = -1, sysize = -1;  /* Scale to X, Y size ? */
-
-/*  Local variables  */
 
 struct slhead {
     char slh[17];             /* Primate-readable header */
@@ -90,7 +91,6 @@ struct slhead {
     char spad;                /* Pad to even byte length */
 };
 
-static bool adjust;           /* Adjust to correct aspect ratio ? */
 static struct slhead slfrof;  /* Slide file header */
 static long xfac, yfac;       /* Aspect ratio scale factors */
 
@@ -99,21 +99,22 @@ static bool sdrawkcab;
 
 
 
-/*  EXTEND  --  Turn a smallint into an int with sign extension, whether
-    or not that happens automatically.
-*/
-
 static int
 extend(unsigned char const ch) {
+/*----------------------------------------------------------------------------
+   Turn a smallint into an int with sign extension, whether
+   or not that happens automatically.
+-----------------------------------------------------------------------------*/
     return ((int) ((ch & 0x80) ? (ch | ~0xFF) : ch));
 }
 
 
 
-/*  SLI  --  Input word from slide file  */
-
 static int
 sli(void) {
+/*----------------------------------------------------------------------------
+   Read and return a word from the slide file.
+-----------------------------------------------------------------------------*/
     short wd;
 
     if (fread(&wd, sizeof wd, 1, slfile) != 1) {
@@ -128,10 +129,11 @@ sli(void) {
 
 
 
-/*  SLIB  --  Input byte from slide file  */
-
 static int
 slib(void) {
+/*----------------------------------------------------------------------------
+   Read and return a byte from the slide file.
+-----------------------------------------------------------------------------*/
     unsigned char ch;
 
     if (fread(&ch, sizeof(ch), 1, slfile) != 1) {
@@ -142,12 +144,12 @@ slib(void) {
 
 
 
-/*  VSCALE -- scale screen coordinates for mismatched display.  */
-
 static void
 vscale(int * const px,
        int * const py) {
-
+/*----------------------------------------------------------------------------
+    Scale screen coordinates for mismatched display.
+-----------------------------------------------------------------------------*/
     *px = (((unsigned) *px) * xfac) >> 16;
     *py = (((unsigned) *py) * yfac) >> 16;
 }
@@ -244,16 +246,17 @@ scanDirectory(FILE *       const slFileP,
     *foundP = found;
 }
 
-/*  SLIDEFIND  --  Find  a  slide  in  a  library  or,  if  DIRONLY is
-           nonzero, print a directory listing of the  library.
-           If  UCASEN  is nonzero, the requested slide name is
-           converted to upper case. */
+
 
 static void
 slidefind(const char * const slideName,
           bool         const dirOnly,
           bool         const ucasen) {
-
+/*----------------------------------------------------------------------------
+   Find a slide in a library or, if DIRONLY is nonzero, print a directory
+   listing of the library.  If UCASEN is nonzero, the requested slide name is
+   converted to upper case.
+-----------------------------------------------------------------------------*/
     char uname[32];  /* upper case translation of 'slideName' */
     char header[32]; /* (supposed) header read from file */
     bool found;
@@ -279,14 +282,14 @@ slidefind(const char * const slideName,
 
 
 
-/*  DRAW  --  Draw a vector in the given AutoCAD color.  */
-
 static slvecfn draw;
 
 static void
 draw(struct svector * vec,
      int              color) {
-
+/*----------------------------------------------------------------------------
+   Draw a vector in the given AutoCAD color.
+-----------------------------------------------------------------------------*/
     pixel rgbcolor;
 
     if (blither) {
@@ -307,14 +310,14 @@ draw(struct svector * vec,
 
 
 
-/*  FLOOD  --  Draw a filled polygon.  */
-
 static slfloodfn flood;
 
 static void
 flood(struct spolygon * const poly,
       int               const color) {
-
+/*----------------------------------------------------------------------------
+  Draw a filled polygon.
+-----------------------------------------------------------------------------*/
     unsigned int i;
     struct fillobj * handle;
     pixel rgbcolor;
@@ -350,16 +353,116 @@ flood(struct spolygon * const poly,
 
 
 
-/*  SLIDER  --  Read slide file.  This is called with the name of the
-        file to be read and function pointers to the routines
-        which process vectors and polygon fill requests
-        respectively.
-*/
-
 static void
-slider(slvecfn   slvec,
-       slfloodfn slflood) {
+computeSize(struct slhead const slfrof,
+            bool          const wantAdjust,
+            double        const uscale,
+            int           const sxsize,
+            int           const sysize,
+            int *         const ixdotsP,
+            int *         const iydotsP,
+            double *      const dsarP) {
+/*----------------------------------------------------------------------------
+-----------------------------------------------------------------------------*/
+    double const originalDsar = ((double) slfrof.sxdots) / slfrof.sydots;
+
+    double ixdots, iydots;
+        /* Algorithmic variables -- value changes as algorithm progresses */
+    bool adjusted;
+
+    /*
+      If the display aspect ratio indicates that the pixels on the sending
+      screen were not square, adjust the size of the generated bitmap to
+      correct the aspect ratio to square the pixels.
+
+      We always correct the aspect ratio by adjusting the width of the image.
+      This guarantees that output from the SHADE command, which is essentially
+      scan-line data written in vector form, will not be corrupted.
+    */
+
+    if (fabs(slfrof.sdsar - originalDsar) > 0.0001) {
+        if (wantAdjust) {
+            ixdots   = slfrof.sxdots * (slfrof.sdsar / originalDsar);
+            iydots   = slfrof.sydots;
+            *dsarP   = ixdots / iydots;
+            adjusted = true;
+        } else {
+            pm_message("Warning - pixels on source screen were non-square.  "
+                       "Specifying -adjust will correct image width "
+                       "to compensate.");
+            ixdots   = slfrof.sxdots;
+            iydots   = slfrof.sydots;
+            *dsarP   = slfrof.sdsar;
+            adjusted = false;
+        }
+    } else {
+        /* Source pixels were square. */
+        ixdots   = slfrof.sxdots;
+        iydots   = slfrof.sydots;
+        *dsarP   = slfrof.sdsar;
+        adjusted = false;
+    }
+
+    if (uscale > 0) {
+        /* There is a uniform scale factor specified.  Apply it. */
+        ixdots *= uscale;
+        iydots *= uscale;
+    }
+
+    /* If the image is to be stretched  to  a  given  width,  set  the
+       output  image  sizes accordingly.  If only a height or width is
+       given, scale the other direction proportionally to preserve the
+       aspect ratio.
+    */
 
+    if (sxsize > 0) {
+        if (sysize > 0)
+            iydots = sysize - 1;
+        else {
+            double const stretchFactor = (sxsize - 1) / ixdots;
+            iydots = iydots * stretchFactor;
+        }
+        ixdots = sxsize - 1;
+    } else if (sysize > 0) {
+        if (sxsize > 0)
+            ixdots = sxsize - 1;
+        else {
+            double const stretchFactor = (sysize - 1) / iydots;
+            ixdots = ixdots * stretchFactor;
+        }
+        iydots = sysize - 1;
+    }
+
+    if (ixdots > INT_MAX-10)
+        pm_error("width is uncomputable large (%f dots)", ixdots);
+    else
+        *ixdotsP = ROUND(ixdots);
+    if (iydots > INT_MAX-10)
+        pm_error("height is uncomputable large (%f dots)", iydots);
+    else
+        *iydotsP = ROUND(iydots);
+
+    if (adjusted) {
+        pm_message(
+            "Resized from %dx%d to %dx%d to correct pixel aspect ratio.",
+            slfrof.sxdots + 1, slfrof.sydots + 1, *ixdotsP + 1, *iydotsP + 1);
+    }
+}
+
+
+
+static void
+slider(slvecfn         slvec,
+       slfloodfn       slflood,
+       bool      const wantAdjust,
+       double    const uscale,
+       int       const sxsize,
+       int       const sysize) {
+/*----------------------------------------------------------------------------
+   Read slide file.  This is called with the name of the file to be read and
+   function pointers to the routines which process vectors and polygon fill
+   requests respectively.
+-----------------------------------------------------------------------------*/
     int i, rescale;
     unsigned char ubfr[4];        /* Utility character buffer */
     int lx, ly;               /* Last x and y point */
@@ -372,7 +475,7 @@ slider(slvecfn   slvec,
     short rtest;              /* Value to test byte reversal */
     short btest = 0x1234;         /* Value to test byte-reversal */
     static struct slhead slhi =       /* Master slide header sample */
-    {"AutoCAD Slide\r\n\32", 86,2, 0,0, 0.0, 0};
+        {"AutoCAD Slide\r\n\32", 86,2, 0,0, 0.0, 0};
     int curcolor = 7;             /* Current vector color */
     pixel rgbcolor;           /* Pixel used to clear pixmap */
 
@@ -434,79 +537,14 @@ slider(slvecfn   slvec,
                    sdrawkcab ? "being reversed" : "the same");
     }
 
-    /* If the display aspect ratio indicates that the  pixels  on  the
-       sending  screen  were  not  square,  adjust  the  size  of  the
-       generated bitmap to correct the  aspect  ratio  to  square  the
-       pixels.
-
-       We  always  correct  the aspect ratio by adjusting the width of
-       the image.  This guarantees that output from the SHADE command,
-       which  is  essentially  scan-line  data written in vector form,
-       will not be corrupted.
-    */
-
-    dsar = ((double) slfrof.sxdots) / slfrof.sydots;
-    if (fabs(slfrof.sdsar - dsar) > 0.0001) {
-        if (adjust) {
-            ixdots = slfrof.sxdots * (slfrof.sdsar / dsar) + 0.5;
-            iydots = slfrof.sydots;
-            dsar = ((double) ixdots) / iydots;
-        } else {
-            pm_message("Warning - pixels on source screen were non-square.  "
-                       "Specifying -adjust will correct image width "
-                       "to compensate.");
-            ixdots = slfrof.sxdots;
-            iydots = slfrof.sydots;
-            dsar = slfrof.sdsar;
-        }
-    } else {
-        /* Source pixels were square. */
-        ixdots = slfrof.sxdots;
-        iydots = slfrof.sydots;
-        dsar = slfrof.sdsar;
-        adjust = false;           /* Mark no adjustment needed */
-    }
-
-    /* If there's a uniform scale factor specified, apply it. */
-
-    if (uscale > 0) {
-        ixdots = (ixdots * uscale) + 0.5;
-        iydots = (iydots * uscale) + 0.5;
-    }
-
-    /* If the image is to be stretched  to  a  given  width,  set  the
-       output  image  sizes accordingly.  If only a height or width is
-       given, scale the other direction proportionally to preserve the
-       aspect ratio.
-    */
-
-    if (sxsize > 0) {
-        if (sysize > 0) {
-            iydots = sysize - 1;
-        } else {
-            iydots = ((((long) iydots) * (sxsize - 1)) +
-                      (iydots / 2)) / ixdots;
-        }
-        ixdots = sxsize - 1;
-    } else if (sysize > 0) {
-        if (sxsize > 0) {
-            ixdots = sxsize - 1;
-        } else {
-            ixdots = ((((long) ixdots) * (sysize - 1)) +
-                      (ixdots / 2)) / iydots;
-        }
-        iydots = sysize - 1;
-    }
-
-    if (adjust) {
-        pm_message(
-            "Resized from %dx%d to %dx%d to correct pixel aspect ratio.",
-            slfrof.sxdots + 1, slfrof.sydots + 1, ixdots + 1, iydots + 1);
-    }
+    computeSize(slfrof, wantAdjust, uscale, sxsize, sysize,
+                &ixdots, &iydots, &dsar);
 
     /* Allocate image buffer and clear it to black. */
 
-    pixels = ppm_allocarray(pixcols = ixdots + 1, pixrows = iydots + 1);
+    pixcols = ixdots + 1;
+    pixrows = iydots + 1;
+    pixels = ppm_allocarray(pixcols, pixrows);
     PPM_ASSIGN(rgbcolor, 0, 0, 0);
     ppmd_filledrectangle(pixels, pixcols, pixrows, pixmaxval, 0, 0,
                          pixcols, pixrows, PPMD_NULLDRAWPROC,
@@ -619,8 +657,6 @@ slider(slvecfn   slvec,
 
 
 
-/*  Main program. */
-
 int
 main(int          argc,
      const char * argv[]) {
@@ -634,7 +670,10 @@ main(int          argc,
     bool widspec;
     bool scalespec;
     bool ucasen;
-    const char * slobber;       /* Slide library item */
+    bool adjust;           /* Adjust to correct aspect ratio ? */
+    double uscale;         /* Uniform scale factor */
+    int sxsize, sysize;    /* Scale to X, Y size ? */
+    const char * slobber;  /* Slide library item */
 
     pm_proginit(&argc, argv);
     argn = 1;
@@ -648,6 +687,9 @@ main(int          argc,
     blither = false;
     info = false;
     adjust = false;
+    uscale = -1.0;
+    sxsize = -1;
+    sysize = -1;
 
     while (argn < argc && argv[argn][0] == '-' && argv[argn][1] != '\0') {
         if (pm_keymatch(argv[argn], "-verbose", 2)) {
@@ -725,7 +767,7 @@ main(int          argc,
         slidefind(slobber, dironly, ucasen);
 
     if (!dironly) {
-        slider(draw, flood);
+        slider(draw, flood, adjust, uscale, sxsize, sysize);
         ppm_writeppm(stdout, pixels, pixcols, pixrows, pixmaxval, 0);
     }
     pm_close(slfile);
@@ -733,3 +775,6 @@ main(int          argc,
 
     return 0;
 }
+
+
+
diff --git a/converter/ppm/spctoppm.c b/converter/ppm/spctoppm.c
index d2a48187..a20fcfd4 100644
--- a/converter/ppm/spctoppm.c
+++ b/converter/ppm/spctoppm.c
@@ -41,19 +41,19 @@ main( argc, argv )
 
     /* Check args. */
     if ( argc > 2 )
-	pm_usage( "[spcfile]" );
+        pm_usage( "[spcfile]" );
 
     if ( argc == 2 )
-	ifp = pm_openr( argv[1] );
+        ifp = pm_openr( argv[1] );
     else
-	ifp = stdin;
+        ifp = stdin;
 
     /* Check SPC file header. */
     c1 = getc( ifp );
     c2 = getc( ifp );
 
     if ( ( c1 != 'S' ) || ( c2 != 'P' ) )
-	pm_error( "not a Spectrum picture" );
+        pm_error( "not a Spectrum picture" );
 
     /* Skip reserved bytes. */
     getc( ifp );
@@ -78,35 +78,35 @@ main( argc, argv )
     pixelrow = ppm_allocrow( COLS );
 
     for ( row = 0; row < ROWS; ++row )
-	{
-	for ( col = 0, pP = pixelrow; col < COLS; ++col, ++pP )
-	    {
-	    int c, ind, b, plane, x1;
-
-	    /* Compute pixel value. */
-	    ind = ( 80 * row ) + ( ( col >> 4 ) << 2 );
-	    b = 0x8000 >> (col & 0xf);
-	    c = 0;
-	    for ( plane = 0; plane < 4; ++plane )
-		if ( b & sscreen[ind+plane] )
-		    c |= (1 << plane);
-
-	    /* Compute palette index. */
-	    x1 = 10 * c;
-	    if ( c & 1 )
-		x1 -= 5;
-	    else
-		++x1;
-	    if ( ( col >= x1 ) && ( col < ( x1 + 160 ) ) )
-		c += 16;
-	    if ( col >= ( x1 + 160 ) )
-		c += 32;
-
-	    /* Store the proper color. */
-	    *pP = pal[row][c];
-	    }
-	ppm_writeppmrow( stdout, pixelrow, COLS, (pixval) MAXVAL, 0 );
-	}
+        {
+        for ( col = 0, pP = pixelrow; col < COLS; ++col, ++pP )
+            {
+            int c, ind, b, plane, x1;
+
+            /* Compute pixel value. */
+            ind = ( 80 * row ) + ( ( col >> 4 ) << 2 );
+            b = 0x8000 >> (col & 0xf);
+            c = 0;
+            for ( plane = 0; plane < 4; ++plane )
+                if ( b & sscreen[ind+plane] )
+                    c |= (1 << plane);
+
+            /* Compute palette index. */
+            x1 = 10 * c;
+            if ( c & 1 )
+                x1 -= 5;
+            else
+                ++x1;
+            if ( ( col >= x1 ) && ( col < ( x1 + 160 ) ) )
+                c += 16;
+            if ( col >= ( x1 + 160 ) )
+                c += 32;
+
+            /* Store the proper color. */
+            *pP = pal[row][c];
+            }
+        ppm_writeppmrow( stdout, pixelrow, COLS, (pixval) MAXVAL, 0 );
+        }
 
     pm_close( stdout );
 
@@ -123,7 +123,7 @@ DoBitmap( ifp )
 
     /* Zero out first scan line. */
     for ( i = 0; i < 160; ++i )
-	screen[i] = 0;
+        screen[i] = 0;
 
     /* 'count' counts number of input bytes. */
     count = 0;
@@ -132,37 +132,37 @@ DoBitmap( ifp )
     data = 0;
 
     while ( count < bitmap_length )
-	{
-	/* Get next record header. */
-	h = getc( ifp );
-	++count;
-
-	if ( ( h >= 0 ) && ( count < bitmap_length ) )
-	    {
-	    for ( i = 0; i <= h; ++i )
-		{
-		c = getc( ifp );
-		++count;
-		DoChar( data, c );
-		++data;
-		}
-	    }
-	else if ( ( h < 0 ) && ( count < bitmap_length ) )
-	    {
-	    c = getc( ifp );
-	    ++count;
-
-	    for ( i = 0; i < ( 2 - h ); ++i )
-		{
-		DoChar( data, c );
-		++data;
-		}
-	    }
+        {
+        /* Get next record header. */
+        h = getc( ifp );
+        ++count;
+
+        if ( ( h >= 0 ) && ( count < bitmap_length ) )
+            {
+            for ( i = 0; i <= h; ++i )
+                {
+                c = getc( ifp );
+                ++count;
+                DoChar( data, c );
+                ++data;
+                }
+            }
+        else if ( ( h < 0 ) && ( count < bitmap_length ) )
+            {
+            c = getc( ifp );
+            ++count;
+
+            for ( i = 0; i < ( 2 - h ); ++i )
+                {
+                DoChar( data, c );
+                ++data;
+                }
+            }
     }
 
     /* Convert the char version of the screen to short. */
     for ( i = 0; i < ROWS*COLS/4; ++i )
-	sscreen[i] = ( screen[i<<1] << 8 ) + ( 0xff & screen[(i<<1)+1] );
+        sscreen[i] = ( screen[i<<1] << 8 ) + ( 0xff & screen[(i<<1)+1] );
     }
 
 static void
@@ -184,22 +184,25 @@ DoColormap( ifp )
 
     /* Clear first three palettes. */
     for ( j = 0; j < 48; ++j )
-	PPM_ASSIGN( pal[0][j], 0, 0, 0 );
+        PPM_ASSIGN( pal[0][j], 0, 0, 0 );
 
     /* Read the palettes. */
     for ( i = 1; i < ROWS; ++i )
-	for ( j = 0; j < 3; ++j )
-	    {
-	    (void) pm_readbigshort( ifp, &mask );
-	    for ( b = 0; b < 15; ++b )
-		if ( mask & ( 1 << b ) )
-		    {
-		    short k;
-		    (void) pm_readbigshort( ifp, &k );
-		    PPM_ASSIGN( pal[i][(j*16)+b],
-			( k & 0x700 ) >> 8,
-			( k & 0x070 ) >> 4,
-			( k & 0x007 ) );
-		    }
-	    }
+        for ( j = 0; j < 3; ++j )
+            {
+            (void) pm_readbigshort( ifp, &mask );
+            for ( b = 0; b < 15; ++b )
+                if ( mask & ( 1 << b ) )
+                    {
+                    short k;
+                    (void) pm_readbigshort( ifp, &k );
+                    PPM_ASSIGN( pal[i][(j*16)+b],
+                        ( k & 0x700 ) >> 8,
+                        ( k & 0x070 ) >> 4,
+                        ( k & 0x007 ) );
+                    }
+            }
     }
+
+
+
diff --git a/converter/ppm/tgatoppm.c b/converter/ppm/tgatoppm.c
index 662f741b..82225516 100644
--- a/converter/ppm/tgatoppm.c
+++ b/converter/ppm/tgatoppm.c
@@ -94,7 +94,6 @@ parseCommandLine(int argc, char ** argv,
 
 
 
-
 static unsigned char
 getbyte(FILE * const ifP) {
 
diff --git a/converter/ppm/vidtoppm.c b/converter/ppm/vidtoppm.c
index f3c20404..b0abe731 100644
--- a/converter/ppm/vidtoppm.c
+++ b/converter/ppm/vidtoppm.c
@@ -1,15 +1,15 @@
 /* Bryan got this from mm.ftp-cs.berkeley.edu from the package
-   mpeg-encode-1.5b-src under the name vidtoppm.c on March 30, 2000.  
-   The file was dated January 19, 1995.  
+   mpeg-encode-1.5b-src under the name vidtoppm.c on March 30, 2000.
+   The file was dated January 19, 1995.
 
    This program does not use the netpbm libraries, but generates its
    output via the program rawtoppm.  If any work is ever done on it
    (or, more to the point, any interest ever expressed in it), it
    should be converted just to call ppmwrite(), etc. directly.
 
-   There was no attached documentation, but the program appears to 
+   There was no attached documentation, but the program appears to
    convert from Parallax XVideo JPEG format to a sequence of PPM files.  It
-   does this conversion by putting each frame in a window and then 
+   does this conversion by putting each frame in a window and then
    reading it out of the window, using libXvid.
 
    Because it requires special libraries and there is no known
@@ -57,6 +57,8 @@ char *p;
     exit (1);
 }
 
+
+
 static char buffer[300000];
 
 Visual *
@@ -67,11 +69,11 @@ FindFullColorVisual (dpy, depth)
   XVisualInfo vinfo;
   XVisualInfo *vinfo_ret;
   int numitems, maxdepth;
-  
+
   vinfo.class = TrueColor;
-  
+
   vinfo_ret = XGetVisualInfo(dpy, VisualClassMask, &vinfo, &numitems);
-  
+
   if (numitems == 0) return NULL;
 
   maxdepth = 0;
@@ -85,15 +87,17 @@ FindFullColorVisual (dpy, depth)
 
   if (maxdepth < 24) return NULL;
 
-  if (XMatchVisualInfo(dpy, DefaultScreen(dpy), maxdepth, 
-		       TrueColor, &vinfo)) {
+  if (XMatchVisualInfo(dpy, DefaultScreen(dpy), maxdepth,
+                       TrueColor, &vinfo)) {
     *depth = maxdepth;
     return vinfo.visual;
   }
-  
+
   return NULL;
 }
 
+
+
 Window
 CreateFullColorWindow (dpy, x, y, w, h)
     Display *dpy;
@@ -107,21 +111,23 @@ CreateFullColorWindow (dpy, x, y, w, h)
     int screen;
 
     screen = XDefaultScreen(dpy);
-    class = InputOutput;	/* Could be InputOnly */
+    class = InputOutput;        /* Could be InputOnly */
     visual = FindFullColorVisual (dpy, &depth);
     if (visual == NULL) {
-	return 0;
+        return 0;
     }
     mask = CWBackPixel | CWColormap | CWBorderPixel;
     xswa.colormap = XCreateColormap(dpy, XRootWindow(dpy, screen),
-		    visual, AllocNone);
+                    visual, AllocNone);
     xswa.background_pixel = BlackPixel(dpy, DefaultScreen(dpy));
     xswa.border_pixel = WhitePixel(dpy, DefaultScreen(dpy));
 
     return XCreateWindow(dpy, RootWindow(dpy, screen), x, y, w, h,
-	1, depth, class, visual, mask, &xswa);
+        1, depth, class, visual, mask, &xswa);
 }
 
+
+
 main (argc, argv)
 int argc;
 char **argv;
@@ -169,16 +175,16 @@ char **argv;
   obase = argv[6];
 
   quality = 100;
-  
+
   if (argc > 7)
     quality = atoi (argv[7]);
-  
+
   dpy = XOpenDisplay (NULL);
   screen = DefaultScreen(dpy);
   root = DefaultRootWindow(dpy);
 /*  gc = DefaultGC(dpy, screen); */
 /*  win = XCreateSimpleWindow (dpy, root, 0, 0, width, height,
-			     0, NULL, NULL);
+                             0, NULL, NULL);
 */
   win = CreateFullColorWindow(dpy, 0, 0, width+4, height+4);
   gc = XCreateGC(dpy, win, 0, NULL);
@@ -195,7 +201,7 @@ char **argv;
   XPlxPutTable(dpy, win, gc, qTable, size, 0);
   XPlxPutTable(dpy, win, gc, qTable, size, 1);
   XPlxVideoTag (dpy, win, gc, PLX_VIDEO);
-  
+
   inFile = fopen(filename, "rb");
   if (inFile == NULL) {
     perror (filename);
@@ -215,7 +221,7 @@ char **argv;
       exit();
     }
   }
-    
+
   for (i=start; i<=end; i++) {
     fprintf(stdout, "GRABBING FRAME %d\n", i);
 
@@ -228,15 +234,15 @@ char **argv;
       perror("End of file.");
       exit();
     }
-    
+
     XPlxPutCImage (dpy, win, gc, &image, 0, 0, image.width,
-		   image.height, 0, 0, width+2, height+2, 1);
+                   image.height, 0, 0, width+2, height+2, 1);
 
     XFlush(dpy);
 
     ximage = XGetImage(dpy, win, 0, 0, width, height, 0x00ffffff,
-		       ZPixmap);
-    
+                       ZPixmap);
+
     if (i == 0) {
       fprintf(stderr, "Depth %d\n", ximage->depth);
       fprintf(stderr, "Height: %d Width: %d\n", height, width );
@@ -252,10 +258,10 @@ char **argv;
 
     for (r=0; r<height; r++) {
       for (j=0; j<width; j++) {
-	fputc(*(tdata+3), outFile);
-	fputc(*(tdata+2), outFile);
-	fputc(*(tdata+1), outFile);
-	tdata += 4;
+        fputc(*(tdata+3), outFile);
+        fputc(*(tdata+2), outFile);
+        fputc(*(tdata+1), outFile);
+        tdata += 4;
       }
     }
 
@@ -264,7 +270,10 @@ char **argv;
     free(tdata);
 
     sprintf(command, "rawtoppm %d %d < /tmp/foobar > %s",
-	    width, height, ofname);
+            width, height, ofname);
     system(command);
   }
 }
+
+
+
diff --git a/converter/ppm/winico.h b/converter/ppm/winico.h
index c6133ef0..de05ca4d 100644
--- a/converter/ppm/winico.h
+++ b/converter/ppm/winico.h
@@ -11,19 +11,19 @@ typedef unsigned char      u1;
 typedef unsigned short int u2;
 typedef unsigned int       u4;
 
-typedef struct MS_Ico_ *          MS_Ico;
-typedef struct IC_Entry_ *        IC_Entry;
-typedef struct IC_InfoHeader_ *   IC_InfoHeader;
-typedef struct IC_Color_ *        IC_Color;
+typedef struct MS_Ico_           MS_Ico;
+typedef struct IC_Entry_         IC_Entry;
+typedef struct IC_InfoHeader_    IC_InfoHeader;
+typedef struct IC_Color_         IC_Color;
 /* Not part of the spec, but useful in constructing the icon. */
-typedef struct IC_Palette_ *      IC_Palette;
-typedef struct ICON_bmp_ *        ICON_bmp;
+typedef struct IC_Palette_       IC_Palette;
+typedef struct ICON_bmp_         ICON_bmp;
 
 struct MS_Ico_ {
    u2 reserved;
    u2 type;
    u2 count;
-   IC_Entry * entries;
+   IC_Entry ** entries;
 };
 
 
@@ -40,8 +40,8 @@ struct IC_Entry_ {
    u2 bitcount;    /* 0, 1, 4, or 8 */
    u4 size_in_bytes;
    u4 file_offset;
-   IC_InfoHeader ih;
-   IC_Color * colors;
+   IC_InfoHeader * ih;
+   IC_Color ** colors;
    /*
     * Below here, I have useful fields which aren't in the spec, but
     * save having to keep stoopid amounts of global data.
@@ -77,7 +77,7 @@ struct IC_Color_ {
 
 struct IC_Palette_ {
    u4 col_amount;
-   IC_Color * colors;
+   IC_Color ** colors;
 };
 
 struct ICON_bmp_ {
diff --git a/converter/ppm/winicontoppm.c b/converter/ppm/winicontoppm.c
index ede0a2b9..f7847df5 100644
--- a/converter/ppm/winicontoppm.c
+++ b/converter/ppm/winicontoppm.c
@@ -18,6 +18,7 @@
 #define _BSD_SOURCE 1      /* Make sure strdup() is in string.h */
 #define _XOPEN_SOURCE 500  /* Make sure strdup() is in string.h */
 
+#include <stdbool.h>
 #include <math.h>
 #include <string.h>
 #include <assert.h>
@@ -66,8 +67,6 @@ parseCommandLine (int argc, const char ** argv,
    was passed to us as the argv array.  We also trash *argv.
 -----------------------------------------------------------------------------*/
     optEntry * option_def;
-        /* Instructions to pm_optParseOptions3 on how to parse our options.
-         */
     optStruct3 opt;
 
     unsigned int option_def_index;
@@ -87,10 +86,10 @@ parseCommandLine (int argc, const char ** argv,
             &cmdlineP->verbose,        0 );
 
     opt.opt_table = option_def;
-    opt.short_allowed = FALSE;  /* We have no short (old-fashioned) options */
-    opt.allowNegNum = FALSE;  /* We have no parms that are negative numbers */
+    opt.short_allowed = false;  /* We have no short (old-fashioned) options */
+    opt.allowNegNum = false;  /* We have no parms that are negative numbers */
 
-    pm_optParseOptions3(&argc, (char **)argv, opt, sizeof(opt), 0);
+    pm_optParseOptions4(&argc, argv, opt, sizeof(opt), 0);
         /* Uses and sets argc, argv, and some of *cmdlineP and others. */
 
     if (argc-1 < 1)
@@ -115,7 +114,6 @@ parseCommandLine (int argc, const char ** argv,
 
 
 
-
 static int
 GetByte(FILE * const ifP) {
 
@@ -216,17 +214,17 @@ readU4 (FILE * const ifP) {
 
 
 
-static IC_Entry
+static IC_Entry *
 readICEntry(FILE * const ifP) {
 
-    IC_Entry entryP;
+    IC_Entry * entryP;  /* malloc'ed */
     u1 widthFld;   /* 0 means 256 */
     u1 heightFld;  /* 0 means 256 */
     u1 colorCtFld; /* 0 means 256 */
 
     MALLOCVAR(entryP);
 
-    if (entryP == NULL)
+    if (!entryP)
         pm_error("Unable to allocate memory for IC entry");
 
     widthFld              = readU1(ifP);
@@ -255,15 +253,15 @@ readICEntry(FILE * const ifP) {
 
 
 
-static IC_InfoHeader
-readInfoHeader (FILE *   const ifP,
-                IC_Entry const entryP) {
+static IC_InfoHeader *
+readInfoHeader(FILE *           const ifP,
+               const IC_Entry * const entryP) {
 
-    IC_InfoHeader ihP;
+    IC_InfoHeader * ihP;  /* malloc'ed */
 
     MALLOCVAR(ihP);
 
-    if (ihP == NULL)
+    if (!ihP)
         pm_error("Unable to allocate memory for info header");
 
     ihP->size             = readU4(ifP);  /* never referenced */
@@ -315,14 +313,14 @@ readInfoHeader (FILE *   const ifP,
 
 
 
-static IC_Color
+static IC_Color *
 readICColor(FILE * const ifP)  {
 
-    IC_Color colorP;
+    IC_Color * colorP;  /* malloc'ed */
 
     MALLOCVAR(colorP);
 
-    if (colorP == NULL)
+    if (!colorP)
         pm_error("Unable to allocate memory for color");
 
     /* I don't know why this isn't the same as the spec, it just isn't.
@@ -514,40 +512,40 @@ readXBitmap (FILE *       const ifP,
 
 
 
-static MS_Ico
+static MS_Ico *
 readIconFile(FILE * const ifP,
              bool   const verbose) {
 
     unsigned int i;
 
-    MS_Ico MSIconData;
+    MS_Ico * MSIconDataP;  /* malloc'ed */
 
-    MALLOCVAR(MSIconData);
+    MALLOCVAR(MSIconDataP);
 
-    MSIconData->reserved = readU2(ifP);  /* should be 0 */
-    MSIconData->type     = readU2(ifP);  /* should be 1 (ICO) or 2 (CUR) */
-    MSIconData->count    = readU2(ifP);  /* # icons in file */
+    MSIconDataP->reserved = readU2(ifP);  /* should be 0 */
+    MSIconDataP->type     = readU2(ifP);  /* should be 1 (ICO) or 2 (CUR) */
+    MSIconDataP->count    = readU2(ifP);  /* # icons in file */
 
-    if (MSIconData->reserved != 0)
+    if (MSIconDataP->reserved != 0)
        pm_message("Signature 'reserved' field is %u (should be 0)",
-                  MSIconData->reserved);
+                  MSIconDataP->reserved);
 
-    if (MSIconData->type != 1 && MSIconData->type != 2)
+    if (MSIconDataP->type != 1 && MSIconDataP->type != 2)
         pm_error("Type %u file.  Can handle only type 1 or 2.",
-                 MSIconData->type);
+                 MSIconDataP->type);
 
-    if (MSIconData->count == 0)
+    if (MSIconDataP->count == 0)
         pm_error("Invalid image count: 0");
     else if (verbose)
-        pm_message("File contains %u images", MSIconData->count);
+        pm_message("File contains %u images", MSIconDataP->count);
 
-    MALLOCARRAY(MSIconData->entries, MSIconData->count);
-    if (MSIconData->entries == NULL)
+    MALLOCARRAY(MSIconDataP->entries, MSIconDataP->count);
+    if (MSIconDataP->entries == NULL)
         pm_error("out of memory");
 
     /* Read in each of the entries */
-    for (i = 0; i < MSIconData->count; ++i)
-        MSIconData->entries[i] = readICEntry(ifP);
+    for (i = 0; i < MSIconDataP->count; ++i)
+        MSIconDataP->entries[i] = readICEntry(ifP);
 
     /* Read in the infoheader, color map (if any) and the actual bit/pix maps
        for the icons.
@@ -555,12 +553,12 @@ readIconFile(FILE * const ifP,
     if (verbose)
         pm_message("#\tColors\tBPP\tWidth\tHeight\n");
 
-    for (i = 0; i < MSIconData->count; ++i) {
-        IC_Entry const entryP = MSIconData->entries[i];
+    for (i = 0; i < MSIconDataP->count; ++i) {
+        IC_Entry * const entryP = MSIconDataP->entries[i];
 
         unsigned int bpp;  /* bits per pixel */
 
-        entryP->ih = readInfoHeader(ifP, MSIconData->entries[i]);
+        entryP->ih = readInfoHeader(ifP, MSIconDataP->entries[i]);
 
         bpp  = entryP->bitcount ? entryP->bitcount : entryP->ih->bitcount;
 
@@ -633,7 +631,7 @@ readIconFile(FILE * const ifP,
         }
 
     }
-    return MSIconData;
+    return MSIconDataP;
 }
 
 
@@ -655,15 +653,15 @@ trimmedOutputName(const char inputName[]) {
 
 
 static int
-getBestQualityIcon(MS_Ico MSIconData)
-{
+getBestQualityIcon(MS_Ico * const MSIconDataP) {
+
     unsigned int i;
     unsigned int best;
     unsigned int bestSize;
     unsigned int bestBpp;
 
-    for (i = 0, bestSize = 0, bestBpp = 0; i < MSIconData->count; ++i) {
-        IC_Entry const entryP = MSIconData->entries[i];
+    for (i = 0, bestSize = 0, bestBpp = 0; i < MSIconDataP->count; ++i) {
+        IC_Entry * const entryP = MSIconDataP->entries[i];
         unsigned int const size = entryP->width * entryP->height;
         unsigned int const bpp  =
             entryP->bitcount ? entryP->bitcount : entryP->ih->bitcount;
@@ -682,12 +680,12 @@ getBestQualityIcon(MS_Ico MSIconData)
 
 
 static void
-writeXors(FILE *   const multiOutF,
-          char *   const outputFileBase,
-          IC_Entry const entryP,
-          int      const entryNum,
-          bool     const multiple,
-          bool     const xor) {
+writeXors(FILE *     const multiOutF,
+          char *     const outputFileBase,
+          IC_Entry * const entryP,
+          int        const entryNum,
+          bool       const multiple,
+          bool       const xor) {
 /*----------------------------------------------------------------------------
    Write an "xor" image (i.e. the main image) out.
 
@@ -751,7 +749,7 @@ writeXors(FILE *   const multiOutF,
                     pm_error("Invalid color index %u (max is %u)",
                               colorIndex, entryP->color_count - 1);
                 } else {
-                    IC_Color const colorP = entryP->colors[colorIndex];
+                    IC_Color * const colorP = entryP->colors[colorIndex];
                     PPM_ASSIGN(pixArray[row][col],
                                colorP->red, colorP->green, colorP->blue);
                 }
@@ -775,7 +773,7 @@ writeXors(FILE *   const multiOutF,
 static void
 writeAnds(FILE *       const multiOutF,
           char         const outputFileBase[],
-          IC_Entry     const entryP,
+          IC_Entry *   const entryP,
           unsigned int const entryNum,
           bool         const multiple) {
 /*----------------------------------------------------------------------------
@@ -866,7 +864,7 @@ openMultiAnd(char    const outputFileBase[],
 
 
 static void
-freeIconentry(IC_Entry const entryP) {
+freeIconentry(IC_Entry * const entryP) {
 
     if (entryP->colors && entryP->color_count) {
         unsigned int i;
@@ -883,7 +881,7 @@ freeIconentry(IC_Entry const entryP) {
 
 
 static void
-freeIcondata(MS_Ico const MSIconDataP) {
+freeIcondata(MS_Ico * const MSIconDataP) {
 
     unsigned int i;
     for (i = 0; i < MSIconDataP->count; ++i)
@@ -900,7 +898,7 @@ main(int argc, const char *argv[]) {
     struct cmdlineInfo cmdline;
     FILE * ifP;
     unsigned int startEntry, endEntry;
-    MS_Ico MSIconDataP;
+    MS_Ico * MSIconDataP;
     char * outputFileBase;
     FILE * multiOutF;
     FILE * multiAndOutF;
@@ -961,7 +959,7 @@ main(int argc, const char *argv[]) {
         unsigned int entryNum;
 
         for (entryNum = startEntry; entryNum < endEntry; ++entryNum) {
-            IC_Entry const entryP = MSIconDataP->entries[entryNum];
+            IC_Entry * const entryP = MSIconDataP->entries[entryNum];
 
             writeXors(multiOutF, outputFileBase, entryP, entryNum,
                       cmdline.allicons, cmdline.writeands);
@@ -980,3 +978,6 @@ main(int argc, const char *argv[]) {
 
     return 0;
 }
+
+
+
diff --git a/converter/ppm/ximtoppm.c b/converter/ppm/ximtoppm.c
index d839e770..c5ba7e80 100644
--- a/converter/ppm/ximtoppm.c
+++ b/converter/ppm/ximtoppm.c
@@ -17,6 +17,7 @@
 #include <string.h>
 
 #include "pm_c_util.h"
+#include "mallocvar.h"
 #include "ppm.h"
 #include "xim.h"
 #include "shhopt.h"
@@ -28,9 +29,9 @@ struct CmdlineInfo {
     /* All the information the user supplied in the command line,
        in a form easy for the program to use.
     */
-    const char *input_filename;
-    const char *alpha_filename;
-    bool alpha_stdout;
+    const char * inputFilename;
+    const char * alphaFilename;
+    bool         alphaStdout;
 };
 
 
@@ -53,31 +54,31 @@ parseCommandLine(int argc, const char ** argv,
 
     option_def_index = 0;   /* incremented by OPTENT3 */
     OPTENT3(0,   "alphaout",   OPT_STRING,
-            &cmdlineP->alpha_filename, &alphaoutSpec, 0);
+            &cmdlineP->alphaFilename, &alphaoutSpec, 0);
 
     opt.opt_table = option_def;
-    opt.short_allowed = FALSE;  /* We have no short (old-fashioned) options */
-    opt.allowNegNum = FALSE;  /* We have no parms that are negative numbers */
+    opt.short_allowed = false;  /* We have no short (old-fashioned) options */
+    opt.allowNegNum = false;  /* We have no parms that are negative numbers */
 
-    pm_optParseOptions3(&argc, (char**)argv, opt, sizeof(opt), 0);
+    pm_optParseOptions4(&argc, argv, opt, sizeof(opt), 0);
         /* Uses and sets argc, argv, and all of *cmdlineP. */
 
     if (!alphaoutSpec)
-        cmdlineP->alpha_filename = NULL;
+        cmdlineP->alphaFilename = NULL;
 
     if (argc - 1 == 0)
-        cmdlineP->input_filename = "-";  /* he wants stdin */
+        cmdlineP->inputFilename = "-";  /* he wants stdin */
     else if (argc - 1 == 1)
-        cmdlineP->input_filename = strdup(argv[1]);
+        cmdlineP->inputFilename = pm_strdup(argv[1]);
     else
         pm_error("Too many arguments.  The only argument accepted "
                  "is the input file specification");
 
-    if (cmdlineP->alpha_filename &&
-        streq(cmdlineP->alpha_filename, "-"))
-        cmdlineP->alpha_stdout = TRUE;
+    if (cmdlineP->alphaFilename &&
+        streq(cmdlineP->alphaFilename, "-"))
+        cmdlineP->alphaStdout = true;
     else
-        cmdlineP->alpha_stdout = FALSE;
+        cmdlineP->alphaStdout = false;
 }
 
 
@@ -87,191 +88,202 @@ parseCommandLine(int argc, const char ** argv,
 */
 
 static int
-ReadXimHeader(FILE *     const in_fp,
-              XimImage * const header) {
+readXimHeader(FILE *     const ifP,
+              XimImage * const headerP) {
 
-    int  i;
-    char *cp;
-    XimAsciiHeader  a_head;
+    unsigned int  i;
+    XimAsciiHeader  aHead;
 
-    cp = (char *) header;
-    for (i = 0; i < sizeof(XimImage); ++i )
-    *cp++ = 0;
+    {
+        unsigned char * cp;
+        cp = (unsigned char *)headerP;
+        for (i = 0; i < sizeof(XimImage); ++i)
+            *cp++ = 0;
+    }
     /* Read header and verify image file formats */
-    if (fread((char *)&a_head, sizeof(ImageHeader), 1, in_fp) != 1) {
+    if (fread((char *)&aHead, sizeof(ImageHeader), 1, ifP) != 1) {
         pm_message("ReadXimHeader: unable to read file header" );
-        return(0);
+        return 0;
     }
     /* Force broken ASCIIZ strings to at least be valid ASCIIZ */
-    a_head.author [sizeof(a_head.author)  - 1] = '\0';
-    a_head.date   [sizeof(a_head.date)    - 1] = '\0';
-    a_head.program[sizeof(a_head.program) - 1] = '\0';
+    aHead.author [sizeof(aHead.author)  - 1] = '\0';
+    aHead.date   [sizeof(aHead.date)    - 1] = '\0';
+    aHead.program[sizeof(aHead.program) - 1] = '\0';
 
-    if (atoi(a_head.header_size) != sizeof(ImageHeader)) {
+    if (atoi(aHead.header_size) != sizeof(ImageHeader)) {
         pm_message("ReadXimHeader: header size mismatch" );
         return(0);
     }
-    if (atoi(a_head.file_version) != IMAGE_VERSION) {
+    if (atoi(aHead.file_version) != IMAGE_VERSION) {
         pm_message("ReadXimHeader: incorrect Image_file version" );
         return(0);
     }
-    header->width = atoi(a_head.image_width);
-    header->height = atoi(a_head.image_height);
-    header->ncolors = atoi(a_head.num_colors);
-    header->nchannels = atoi(a_head.num_channels);
-    header->bytes_per_line = atoi(a_head.bytes_per_line);
+    headerP->width          = atoi(aHead.image_width);
+    headerP->height         = atoi(aHead.image_height);
+    headerP->ncolors        = atoi(aHead.num_colors);
+    headerP->nchannels      = atoi(aHead.num_channels);
+    headerP->bytes_per_line = atoi(aHead.bytes_per_line);
 #if 0
-    header->npics = atoi(a_head.num_pictures);
+    headerP->npics          = atoi(aHead.num_pictures);
 #endif
-    header->bits_channel = atoi(a_head.bits_per_channel);
-    header->alpha_flag = atoi(a_head.alpha_channel);
-    header->author = pm_strdup(a_head.author);
-    header->date = pm_strdup(a_head.date);
-    header->program = pm_strdup(a_head.program);
+    headerP->bits_channel   = atoi(aHead.bits_per_channel);
+    headerP->alpha_flag     = atoi(aHead.alpha_channel);
+    headerP->author         = pm_strdup(aHead.author);
+    headerP->date           = pm_strdup(aHead.date);
+    headerP->program        = pm_strdup(aHead.program);
 
     /* Do double checking for backwards compatibility */
-    if (header->npics == 0)
-        header->npics = 1;
-    if (header->bits_channel == 0)
-        header->bits_channel = 8;
-    else if (header->bits_channel == 24) {
-        header->nchannels = 3;
-        header->bits_channel = 8;
+    if (headerP->npics == 0)
+        headerP->npics = 1;
+    if (headerP->bits_channel == 0)
+        headerP->bits_channel = 8;
+    else if (headerP->bits_channel == 24) {
+        headerP->nchannels = 3;
+        headerP->bits_channel = 8;
     }
-    if ((int)header->bytes_per_line == 0)
-        header->bytes_per_line =
-            (header->bits_channel == 1 && header->nchannels == 1) ?
-                (header->width + 7) / 8 :
-                header->width;
-    header->datasize =(unsigned int)header->bytes_per_line * header->height;
-    if (header->nchannels == 3 && header->bits_channel == 8)
-        header->ncolors = 0;
-    else if (header->nchannels == 1 && header->bits_channel == 8) {
-        header->colors = (Color *)calloc((unsigned int)header->ncolors,
-                sizeof(Color));
-        if (header->colors == NULL) {
-            pm_message("ReadXimHeader: can't calloc colors" );
-            return(0);
-        }
-        for (i=0; i < header->ncolors; i++) {
-            header->colors[i].red = a_head.c_map[i][0];
-            header->colors[i].grn = a_head.c_map[i][1];
-            header->colors[i].blu = a_head.c_map[i][2];
+    if (headerP->bytes_per_line == 0)
+        headerP->bytes_per_line =
+            (headerP->bits_channel == 1 && headerP->nchannels == 1) ?
+                (headerP->width + 7) / 8 :
+                headerP->width;
+    headerP->datasize =
+        (unsigned int)headerP->bytes_per_line * headerP->height;
+    if (headerP->nchannels == 3 && headerP->bits_channel == 8)
+        headerP->ncolors = 0;
+    else if (headerP->nchannels == 1 && headerP->bits_channel == 8) {
+        unsigned int i;
+
+        MALLOCARRAY_NOFAIL(headerP->colors, headerP->ncolors);
+
+        for (i=0; i < headerP->ncolors; ++i) {
+            headerP->colors[i].red = aHead.c_map[i][0];
+            headerP->colors[i].grn = aHead.c_map[i][1];
+            headerP->colors[i].blu = aHead.c_map[i][2];
         }
     }
-    return(1);
+    return 1;
 }
 
 
 
 static int
-ReadImageChannel(FILE *         const infp,
+readImageChannel(FILE *         const ifP,
                  byte *         const buf,
-                 unsigned int * const bufsize,
-                 int            const encoded) {
+                 unsigned int * const bufsizeP,
+                 bool           const encoded) {
 
-    int  i, runlen, nbytes;
-    unsigned int  j;
-    byte *line;
+    unsigned int j;
     long  marker;
 
     if (!encoded)
-        j = fread((char *)buf, 1, (int)*bufsize, infp);
+        j = fread((char *)buf, 1, (int)*bufsizeP, ifP);
     else {
-        if ((line=(byte *)malloc((unsigned int)BUFSIZ)) == NULL) {
+        byte * line;
+
+        MALLOCARRAY(line, BUFSIZ);
+        if (!line) {
             pm_message("ReadImageChannel: can't malloc() fread string" );
-            return(0);
-        }
-        /* Unrunlength encode data */
-        marker = ftell(infp);
-        j = 0;
-        while (((nbytes=fread((char *)line, 1, BUFSIZ, infp)) > 0) &&
-            (j < *bufsize)) {
-            for (i=0; (i < nbytes) && (j < *bufsize); i++) {
-                runlen = (int)line[i]+1;
-                i++;
-                while (runlen--)
-                    buf[j++] = line[i];
+            return 0;
+        } else {
+            /* Unrunlength encode data */
+            unsigned int byteCt;
+
+            marker = ftell(ifP);
+            j = 0;
+            while (((byteCt = fread((char *)line, 1, BUFSIZ, ifP)) > 0) &&
+                   (j < *bufsizeP)) {
+                unsigned int i;
+                for (i=0; (i < byteCt) && (j < *bufsizeP); ++i) {
+                    unsigned int runlen;
+                    runlen = (unsigned int)line[i] + 1;
+                    ++i;
+                    while (runlen--)
+                        buf[j++] = line[i];
+                }
+                marker += i;
             }
-            marker += i;
-        }
-        /* return to the beginning of the next image's buffer */
-        if (fseek(infp, marker, 0) == -1) {
-            pm_message("ReadImageChannel: can't fseek to location "
-                       "in image buffer");
-            return(0);
+            /* return to the beginning of the next image's buffer */
+            if (fseek(ifP, marker, 0) == -1) {
+                pm_message("ReadImageChannel: can't fseek to location "
+                           "in image buffer");
+                return 0;
+            }
+            free(line);
         }
-        free((char *)line);
     }
-    if (j != *bufsize) {
-        pm_message("unable to complete channel: %u / %u (%d%%)",
-            j, *bufsize, (int)(j*100.0 / *bufsize) );
-        *bufsize = j;
+    if (j != *bufsizeP) {
+        pm_message("unable to complete channel: %u / %u (%f%%)",
+                   j, *bufsizeP, j * 100.0 / *bufsizeP);
+        *bufsizeP = j;
     }
-    return(1);
+    return 1;
 }
 
 
 
 static int
-ReadXimImage(FILE *     const in_fp,
-             XimImage * const xim) {
+readXimImage(FILE *     const ifP,
+             XimImage * const ximP) {
 
-    if (xim->data) {
-        free((char *)xim->data);
-        xim->data = (byte *)0;
+    if (ximP->data) {
+        free(ximP->data);
+        ximP->data = NULL;
     }
-    if (xim->grn_data) {
-        free((char *)xim->grn_data);
-        xim->grn_data = (byte *)0;
+    if (ximP->grn_data) {
+        free(ximP->grn_data);
+        ximP->grn_data = NULL;
     }
-    if (xim->blu_data) {
-        free((char *)xim->blu_data);
-        xim->blu_data = (byte *)0;
+    if (ximP->blu_data) {
+        free(ximP->blu_data);
+        ximP->blu_data = NULL;
     }
-    if (xim->other) {
-        free((char *)xim->other);
-        xim->other = (byte *)0;
+    if (ximP->other) {
+        free(ximP->other);
+        ximP->other = NULL;
     }
-    xim->npics = 0;
-    if (!(xim->data = (byte *)calloc(xim->datasize, 1))) {
-        pm_message("ReadXimImage: can't malloc pixmap data" );
-        return(0);
+    ximP->npics = 0;
+    MALLOCARRAY(ximP->data, ximP->datasize);
+    if (!ximP->data) {
+        pm_message("ReadXimImage: can't malloc pixmap data");
+        return 0;
     }
-    if (!ReadImageChannel(in_fp, xim->data, &xim->datasize, 0)) {
-        pm_message("ReadXimImage: end of the images" );
-        return(0);
+    if (!readImageChannel(ifP, ximP->data, &ximP->datasize, false)) {
+        pm_message("ReadXimImage: end of the images");
+        return 0;
     }
-    if (xim->nchannels == 3) {
-        xim->grn_data = (byte *)malloc(xim->datasize);
-        xim->blu_data = (byte *)malloc(xim->datasize);
-        if (xim->grn_data == NULL || xim->blu_data == NULL) {
-            pm_message("ReadXimImage: can't malloc rgb channel data" );
-            free((char *)xim->data);
-            if (xim->grn_data)  free((char *)xim->grn_data);
-            if (xim->blu_data)  free((char *)xim->blu_data);
-            xim->data = xim->grn_data = xim->blu_data = (byte*)0;
-            return(0);
+    if (ximP->nchannels == 3) {
+        MALLOCARRAY(ximP->grn_data, ximP->datasize);
+        MALLOCARRAY(ximP->blu_data, ximP->datasize);
+        if (!ximP->grn_data || !ximP->blu_data) {
+            pm_message("ReadXimImage: can't malloc rgb channel data");
+            free(ximP->data);
+            if (ximP->grn_data)
+                free(ximP->grn_data);
+            if (ximP->blu_data)
+                free(ximP->blu_data);
+            ximP->data = ximP->grn_data = ximP->blu_data = NULL;
+            return 0;
         }
-        if (!ReadImageChannel(in_fp, xim->grn_data, &xim->datasize, 0))
-            return(0);
-        if (!ReadImageChannel(in_fp, xim->blu_data, &xim->datasize, 0))
-            return(0);
-    }
-    if (xim->nchannels > 3) {
-        /* In theory, this can be any fourth channel, but the only one we
-           know about is an Alpha channel, so we'll call it that, even
-           though we process it generically.
-           */
-        if ((xim->other = (byte *)malloc(xim->datasize)) == NULL) {
-            pm_message("ReadXimImage: can't malloc alpha data" );
-            return(0);
+        if (!readImageChannel(ifP, ximP->grn_data, &ximP->datasize, false))
+            return 0;
+        if (!readImageChannel(ifP, ximP->blu_data, &ximP->datasize, false))
+            return 0;
+    } else if (ximP->nchannels > 3) {
+        /* In theory, this can be any fourth channel, but the only one we know
+           about is an Alpha channel, so we'll call it that, even though we
+           process it generically.
+        */
+        MALLOCARRAY(ximP->other, ximP->datasize);
+        if (!ximP->other) {
+            pm_message("ReadXimImage: can't malloc alpha data");
+            return 0;
         }
-        if (!ReadImageChannel(in_fp, xim->other, &xim->datasize, 0))
+        if (!readImageChannel(ifP, ximP->other, &ximP->datasize, false))
             return(0);
     }
-    xim->npics = 1;
-    return(1);
+    ximP->npics = 1;
+
+    return 1;
 }
 
 
@@ -307,17 +319,21 @@ ReadXimImage(FILE *     const in_fp,
 ***********************************************************************/
 
 static int
-ReadXim(FILE *     const in_fp,
-        XimImage * const xim) {
+readXim(FILE *     const ifP,
+        XimImage * const ximP) {
 
-    if (!ReadXimHeader(in_fp, xim)) {
-        pm_message("can't read xim header" );
-        return 0;
-    } else if (!ReadXimImage(in_fp, xim)) {
-        pm_message("can't read xim data" );
-        return 0;
+    int retval;
+
+    if (!readXimHeader(ifP, ximP)) {
+        pm_message("can't read xim header");
+        retval = 0;
+    } else if (!readXimImage(ifP, ximP)) {
+        pm_message("can't read xim data");
+        retval = 0;
     } else
-        return 1;
+        retval = 1;
+
+    return retval;
 }
 
 
@@ -327,44 +343,48 @@ main(int          argc,
      const char **argv) {
 
     struct CmdlineInfo cmdline;
-    FILE *ifP, *imageout_file, *alpha_file;
+    FILE * ifP;
+    FILE * imageoutFileP;
+    FILE * alphaFileP;
     XimImage xim;
-    pixel *pixelrow, colormap[256];
-    gray *alpharow;
-        /* The alpha channel of the row we're currently converting, in
-           pgm fmt
+    pixel * pixelrow;
+    pixel colormap[256];
+    gray * alpharow;
+        /* The alpha channel of the row we're currently converting, in PGM fmt
         */
-    int rows, cols, row, mapped;
+    unsigned int rows, cols;
+    unsigned int row;
+    bool mapped;
     pixval maxval;
-    bool success;
+    bool succeeded;
 
     pm_proginit(&argc, argv);
 
     parseCommandLine(argc, argv, &cmdline);
 
-    ifP = pm_openr(cmdline.input_filename);
+    ifP = pm_openr(cmdline.inputFilename);
 
-    if (cmdline.alpha_stdout)
-        alpha_file = stdout;
-    else if (cmdline.alpha_filename == NULL)
-        alpha_file = NULL;
+    if (cmdline.alphaStdout)
+        alphaFileP = stdout;
+    else if (cmdline.alphaFilename == NULL)
+        alphaFileP = NULL;
     else
-        alpha_file = pm_openw(cmdline.alpha_filename);
+        alphaFileP = pm_openw(cmdline.alphaFilename);
 
-    if (cmdline.alpha_stdout)
-        imageout_file = NULL;
+    if (cmdline.alphaStdout)
+        imageoutFileP = NULL;
     else
-        imageout_file = stdout;
+        imageoutFileP = stdout;
 
-    success = ReadXim(ifP, &xim);
-    if (!success)
+    succeeded = readXim(ifP, &xim);
+    if (!succeeded)
         pm_error("can't read Xim file");
 
     rows = xim.height;
     cols = xim.width;
 
     if (xim.nchannels == 1 && xim.bits_channel == 8) {
-        int i;
+        unsigned int i;
 
         mapped = true;
         maxval = 255;
@@ -382,27 +402,29 @@ main(int          argc,
             "unknown Xim file type, nchannels == %d, bits_channel == %d",
             xim.nchannels, xim.bits_channel);
 
-    if (imageout_file)
-        ppm_writeppminit(imageout_file, cols, rows, maxval, 0);
-    if (alpha_file)
-        pgm_writepgminit(alpha_file, cols, rows, maxval, 0);
+    if (imageoutFileP)
+        ppm_writeppminit(imageoutFileP, cols, rows, maxval, 0);
+    if (alphaFileP)
+        pgm_writepgminit(alphaFileP, cols, rows, maxval, 0);
 
     pixelrow = ppm_allocrow(cols);
     alpharow = pgm_allocrow(cols);
 
     for (row = 0; row < rows; ++row) {
         if (mapped) {
-            byte * const ximrow = xim.data + row * xim.bytes_per_line;
+            byte * const ximrow = &xim.data[row * xim.bytes_per_line];
+
             unsigned int col;
 
             for (col = 0; col < cols; ++col)
                 pixelrow[col] = colormap[ximrow[col]];
+
             alpharow[col] = 0;
         } else {
-            byte * const redrow = xim.data     + row * xim.bytes_per_line;
-            byte * const grnrow = xim.grn_data + row * xim.bytes_per_line;
-            byte * const blurow = xim.blu_data + row * xim.bytes_per_line;
-            byte * const othrow = xim.other    + row * xim.bytes_per_line;
+            byte * const redrow = &xim.data     [row * xim.bytes_per_line];
+            byte * const grnrow = &xim.grn_data [row * xim.bytes_per_line];
+            byte * const blurow = &xim.blu_data [row * xim.bytes_per_line];
+            byte * const othrow = &xim.other    [row * xim.bytes_per_line];
 
             unsigned int col;
 
@@ -415,16 +437,16 @@ main(int          argc,
                     alpharow[col] = 0;
             }
         }
-        if (imageout_file)
-            ppm_writeppmrow(imageout_file, pixelrow, cols, maxval, 0);
-        if (alpha_file)
-            pgm_writepgmrow(alpha_file, alpharow, cols, maxval, 0);
+        if (imageoutFileP)
+            ppm_writeppmrow(imageoutFileP, pixelrow, cols, maxval, 0);
+        if (alphaFileP)
+            pgm_writepgmrow(alphaFileP, alpharow, cols, maxval, 0);
     }
     pm_close(ifP);
-    if (imageout_file)
-        pm_close(imageout_file);
-    if (alpha_file)
-        pm_close(alpha_file);
+    if (imageoutFileP)
+        pm_close(imageoutFileP);
+    if (alphaFileP)
+        pm_close(alphaFileP);
 
     return 0;
 }
diff --git a/converter/ppm/yuvsplittoppm.c b/converter/ppm/yuvsplittoppm.c
index 5343a21e..b734be91 100644
--- a/converter/ppm/yuvsplittoppm.c
+++ b/converter/ppm/yuvsplittoppm.c
@@ -43,12 +43,12 @@ struct cmdlineInfo {
 
 
 static void
-parseCommandLine(int                 argc, 
+parseCommandLine(int                 argc,
                  char **             argv,
                  struct cmdlineInfo *cmdlineP ) {
 /*----------------------------------------------------------------------------
    Parse program command line described in Unix standard form by argc
-   and argv.  Return the information in the options as *cmdlineP.  
+   and argv.  Return the information in the options as *cmdlineP.
 
    If command line is internally inconsistent (invalid options, etc.),
    issue error message to stderr and abort program.
@@ -64,7 +64,7 @@ parseCommandLine(int                 argc,
     unsigned int option_def_index;
 
     option_def_index = 0;   /* incremented by OPTENT3 */
-    OPTENT3(0, "ccir601",     OPT_FLAG,   NULL,                  
+    OPTENT3(0, "ccir601",     OPT_FLAG,   NULL,
             &cmdlineP->ccir601,       0);
 
     opt.opt_table = option_def;
@@ -103,13 +103,13 @@ computeTwoOutputRows(int             const cols,
                      unsigned char * const vbuf,
                      pixel *         const pixelrow1,
                      pixel *         const pixelrow2) {
-                     
+
     int col;
 
     for (col = 0; col < cols; col += 2) {
         long int r0,g0,b0,r1,g1,b1,r2,g2,b2,r3,g3,b3;
         long int  u,v,y0,y1,y2,y3,u0,u1,u2,u3,v0,v1,v2,v3;
-        
+
         y0 = y1buf[col];
         y1 = y1buf[col+1];
         y2 = y2buf[col];
@@ -117,7 +117,7 @@ computeTwoOutputRows(int             const cols,
 
         u = ubuf[col/2] - 128;
         v = vbuf[col/2] - 128;
-        
+
         if (ccir601) {
             y0 = ((y0-16)*255)/219;
             y1 = ((y1-16)*255)/219;
@@ -128,7 +128,7 @@ computeTwoOutputRows(int             const cols,
             v  = (v*255)/224 ;
         }
         /* mean the chroma for subsampling */
-        
+
         u0=u1=u2=u3=u;
         v0=v1=v2=v3=v;
 
@@ -138,25 +138,25 @@ computeTwoOutputRows(int             const cols,
            [Y]   [65496        0   91880] [R]
            [U] = [65533   -22580  -46799] [G]
            [V]   [65537   116128      -8] [B]
-           
+
         */
 
         r0 = 65536 * y0               + 91880 * v0;
         g0 = 65536 * y0 -  22580 * u0 - 46799 * v0;
         b0 = 65536 * y0 + 116128 * u0             ;
-        
+
         r1 = 65536 * y1               + 91880 * v1;
         g1 = 65536 * y1 -  22580 * u1 - 46799 * v1;
         b1 = 65536 * y1 + 116128 * u1             ;
-        
+
         r2 = 65536 * y2               + 91880 * v2;
         g2 = 65536 * y2 -  22580 * u2 - 46799 * v2;
         b2 = 65536 * y2 + 116128 * u2             ;
-        
+
         r3 = 65536 * y3               + 91880 * v3;
         g3 = 65536 * y3 -  22580 * u3 - 46799 * v3;
         b3 = 65536 * y3 + 116128 * u3             ;
-        
+
         r0 = limit(r0);
         r1 = limit(r1);
         r2 = limit(r2);
@@ -195,7 +195,7 @@ main(int argc, char **argv) {
     ppm_init(&argc, argv);
 
     parseCommandLine(argc, argv, &cmdline);
-        
+
     pm_asprintf(&ufname, "%s.U", cmdline.filenameBase);
     pm_asprintf(&vfname, "%s.V", cmdline.filenameBase);
     pm_asprintf(&yfname, "%s.Y", cmdline.filenameBase);
@@ -215,7 +215,7 @@ main(int argc, char **argv) {
     if (cmdline.height % 2 != 0) {
         pm_message("Warning: odd height; last row ignored");
         rows = cmdline.height - 1;
-    } else 
+    } else
         rows = cmdline.height;
 
     pixelrow1 = ppm_allocrow(cols);
@@ -251,3 +251,6 @@ main(int argc, char **argv) {
 
     exit(0);
 }
+
+
+
diff --git a/converter/ppm/yuvtoppm.c b/converter/ppm/yuvtoppm.c
index 9c5d79c4..5ee250e2 100644
--- a/converter/ppm/yuvtoppm.c
+++ b/converter/ppm/yuvtoppm.c
@@ -2,7 +2,7 @@
 **
 ** by Marc Boucher
 ** Internet: marc@PostImage.COM
-** 
+**
 ** Based on Example Conversion Program, A60/A64 Digital Video Interface
 ** Manual, page 69
 **
@@ -43,7 +43,6 @@ parseCommandLine(int argc, const char ** argv,
                  struct CmdlineInfo * const cmdlineP) {
 
     optEntry * option_def;
-        /* Instructions to OptParseOptions3 on how to parse our options */
     optStruct3 opt;
     unsigned int option_def_index;
 
@@ -55,7 +54,7 @@ parseCommandLine(int argc, const char ** argv,
     opt.short_allowed = FALSE;  /* We have no short (old-fashioned) options */
     opt.allowNegNum = FALSE;  /* We have no parms that are negative numbers */
 
-    pm_optParseOptions3(&argc, (char **)argv, opt, sizeof(opt), 0);
+    pm_optParseOptions4(&argc, argv, opt, sizeof(opt), 0);
         /* Uses and sets argc, argv, and some of *cmdlineP and others. */
 
     if (argc-1 < 2)
@@ -72,7 +71,7 @@ parseCommandLine(int argc, const char ** argv,
 
         cmdlineP->cols = widthArg;
         cmdlineP->rows = heightArg;
-                 
+
         if (cmdlineP->cols % 2 != 0)
             pm_error("Number of columns (%u) is odd.  "
                      "A YUV image must have an "
@@ -213,9 +212,12 @@ main (int argc, const char ** argv) {
     ifP = pm_openr(cmdline.inputFileName);
 
     yuvtoppm(ifP, cmdline.cols, cmdline.rows, stdout);
-    
+
     pm_close(ifP);
     pm_close(stdout);
 
     return 0;
 }
+
+
+
diff --git a/doc/COPYRIGHT.PATENT b/doc/COPYRIGHT.PATENT
index dd1d91e6..5e4db7d7 100644
--- a/doc/COPYRIGHT.PATENT
+++ b/doc/COPYRIGHT.PATENT
@@ -25,6 +25,13 @@ at appropriate places within the package.  A slightly out of date
 summary of all the copyrights is in the file 'doc/copyright_summary'
 in the Netpbm source tree.
 
+Each component is a package of code and documentation; e.g. the 'pamcomp'
+program and the pamcomp user manual go together and are licensed to the public
+as a package.  The Netpbm manual is just a hyperlinked collection of such
+component manuals.  Parts of the manual that are not tied to a particular
+component of code and do not carry a copyright notice are in the public
+domain.
+
 As with most public open source software, no one really knows for sure
 where the code came from.  It is possible that a contributor copied it
 without license to do so.  That might mean any user of the code owes
diff --git a/doc/HISTORY b/doc/HISTORY
index 86fa0ae1..259e9dbd 100644
--- a/doc/HISTORY
+++ b/doc/HISTORY
@@ -4,6 +4,509 @@ Netpbm.
 CHANGE HISTORY 
 --------------
 
+not yet  BJH  Release 11.07.00
+
+              libnetpbm: Fix double free crash when memory allocation via
+              REALLOCARRAY fails.  Introduced in Netpbm 10.40 (September
+              2007).
+
+              libnetpbm: Allow color dictionary with more than 1000 entries.
+
+              ppmhist, ppmtoxpm: Work with color dictionary with more than
+              1000 color entries.
+
+              rgb.txt: Add Resene paint colors, 2010.
+
+24.03.30 BJH  Release 11.06.00
+
+              pamcut: add -reportonly.
+
+              infotopam: Add input validation.
+
+              infotopam: Remove input file name from messages.  Add -verbose
+              and issue informational message only if it is specified.
+
+              libnetpbm: Don't ignore garbage at the end of a color specifier
+              (e.g. rgbi:0/.5/1xyz).
+
+              color database: change names of "Spring Green", "Lamp Black",
+              and "light grey" to "SpringGreen", "LampBlack", and "LightGrey"
+              to be consistent with other color names.
+
+              pamcut: fix incorrect output when rectangle to cut is entirely
+              above the input image.  Invisible junk after image.  Always
+              broken.  (The ability to cut outside the input image was new in
+              pamcut's predecessor pnmcut in Netpbm 9.7 (August 2000).
+
+              pamcut: fix incorrect output with PBM input when rectangle to
+              cut is entirely below the input image.  Invisible junk after
+              image.  Broken in Netpbm 10.44 (September 2008).
+
+              ppmtowinicon: fix array overrun with 4 and 8 bits per pixel.
+              Broken in Netpbm 11.05 (December 2023).
+
+              infotopam: fix incorrect output -- columns always in wrong
+              place.  Always broken.  (infotopam was new in Netpbm 10.22 (May
+              2004)).
+
+              pamseq: fix typo in error message.
+
+              build: makeman: fix warning about backslashes in strings.
+
+23.12.28 BJH  Release 11.05.00
+
+              pnmpad: Add -color, -promote, -extend-edge, -detect-background .
+
+              pnmconvol: Restore ability of convolution matrix to be a
+              pseudo-plain-PNM with samples that exceed the maxval.  Lost in
+              10.30 (October 2005) because maxval-checking code was added to
+              libnetpbm.  (Was fixed in 10.47.08 in November 2010, but only in
+              the 10.47 series).
+
+              pnmindex: Improve failure mode when -size or -across is zero.
+
+              pnmindex: Make -plain work.
+
+              pnmpad: fix behavior with -left, -right, and -width together or
+              -top, -bottom, -height together: ignores -width where it should
+              fail.  Broken in Netpbm 10.72 (September 2015).
+
+              pamtosvg: fix "zero determinant" failure.  Introduced in
+              Netpbm 11.04 (September 2023).
+
+              pjtoppm: fix crash based on uninitialized variable.
+              Introduced in Netpbm 11.04 (September 2023).
+
+              ppmtopcxl: fix incorrect output with > 256 colors.  Always
+              broken.  (Program was added in primordial Netpbm in 1990).
+
+              pbmtext: fix buffer overrun with insanely large input.
+
+              picttoppm: fix buffer overrun with insanely wide input.
+
+              ppmtoxpm: fix incorrect output with insanely large number of
+              colors.
+
+              pnmscalefixed: fix incorrect output with really big image and
+              -pixels option.
+
+              ppmdither: fix buffer overrun with insanely large dithering
+              matrix.
+
+              pnmpad: no longer accept old-style options (e.g. -t50).
+
+              libnetpbm: Add pm_feed_from_file, pm_accept_to_files,
+              pm_accept_to_filestream Standard Input feeder, Output accepter
+              for pm_system.
+
+              libnetpbm, programs that use color maps: fix buffer overrun
+              with insanely deep images.
+
+              merge build: Fix 'pnmcat'.  Introduced in Netpbm 11.00
+              (September 2023).
+
+              Build: Fix compile error on systems without 'asprintf'.
+              Introduced in Netpbm 11.04 (September 2023).
+
+              Build: Fix building of jpeg2ktopam and pamtojpeg2k with
+              assertion checking by default.
+
+23.09.27 BJH  Release 11.04.00
+
+              pamaddnoise: add -salt.
+
+              pamaddnoise: reject options that aren't meaningful for the type
+              of noise specified rather than just ignore them.
+
+              ppmtosixel: Add -7bit, so it works on more terminals, including
+              xterms.  Thanks Scott Pakin.
+
+              g3topbm: Add -correctlong
+
+              build: Add COMPILED_BY environment variable to control the
+              "compiled by" value from --version common option.  This helps
+              with creating reproducible builds.
+
+              pnmtojpeg: minor improvement to error messages about bad files.
+
+              pammixmulti: Remove disclaimer of patent license.
+
+              pamstack: Fix bug: acts like -firstmaxval specified when it
+              wasn't.  Introduced in Netpbm 11.03 (June 2023).
+
+              pamstack: Fix -lcmmaxval: chooses wrong maxval.  Always
+              broken (-lcmmaxval was new in Netpbm 11.03 (June 2023)).
+
+              pamstack: Fail gracefully when total number of planes is too
+              large for unsigned integer.  Always broken (Pamstack was new in
+              Netpbm 10.0 (June 2002).
+
+              pamtosvg: fix hang.
+
+              ppmfade: fix "file not found" crash for most fade modes.
+              Introduced in Netpbm 10.98 (March 2022).
+
+              ppmfade: fix incorrect block mode fade.  Always broken
+              (ppmfade was new in Netpbm 8.4 (April 2000)).
+
+              pamaddnoise: fix very incorrect noise added for all types.
+              Introduced in Netpbm 10.94 (March 2021).
+
+              ppmrough: fix buffer overrun.  Always broken (Ppmrough was new
+              in Netpbm 10.9 (September 2002).
+
+              ppmrough: fix excessive roughness.  Introduced in Netpbm 10.94
+              (March 2021).
+
+              pgmtexture: Fix buffer overflow with maxval > 255.  Always
+              broken.  Maxvals > 255 were possible starting in Netpbm 9.0
+              (April 2000).
+
+              pgmtexture: Fix bug: ignores -d.  Introduced in Netpbm 10.56
+              (September 2011).
+
+              xwdtopnm Fix spurious output with really wide/deep rows.
+
+              imgtoppm: Fix spurious output with really wide/deep rows.
+
+              pbmtopgm: Fix error message for excessive -width.
+
+              pbmtoxbm: Fix spurious output with really wide rows.
+
+              tifftopnm: Fix incorrect output with insanely wide/deep rows.
+
+              thinkjettopbm: Fix incorrect output with insanely wide rows.
+
+              ybmtopbm: Fix incorrect output with insanely wide rows.
+
+              pjtoppm: Fix incorrect output with insanely large number of rows.
+
+              library: add check of maxval for computable size.
+
+              Build: Include LDFLAGS in link of shared library.
+
+23.06.28 BJH  Release 11.03.00
+
+              pamstack: Add -firstmaxval, -lcmmaxval
+
+              pnmcolormap: make result independent of how system's qsort
+              orders records with equal keys.  Affects pnmquant.
+
+              pamtopng: fix typo in error message about -chroma option.
+
+              pamtopng, pnmtopng, pngtopam: fix error message when something
+              fails in libpng.  Always broken (the programs were new in Netpbm
+              8.1 (March 2000)).
+
+23.03.25 BJH  Release 11.02.00
+
+              jpegtopnm: Add -traceexif
+
+              pbmtextps: Add -asciihex, -ascii85.
+
+              pcdovtoppm: remove dependency on obsolete 'tempfile' program.
+
+              jpegtopnm: Many fixes to -dumpexif.  Always broken.
+              (-dumpexif was new in Netpbm 9.18 (September 2001))
+
+              pamtopng: fix -chroma option: always rejected.  Always broken.
+              (pamtopng was new in Netpbm 10.70 (June 2015)).
+
+              pnmtopng: fix -rgb option: always rejected.  Always broken
+              (-rgb was new in Netpbm 10.30 (October 2005)).
+
+              build: change the way you add the separately distributed
+              'hpcdtoppm' code to the build.
+
+22.12.31 BJH  Release 11.01.00
+
+              pamcat: Add -listfile .
+
+              pamtojpeg2k: add -size option.  Doesn't precisely work (and
+              -compression has never worked precisely either); should be
+              fixed some day.
+
+              ppmtompeg: Fix crash with resize option because of invalid
+              memory free.
+
+              fitstopnm: fix invalid memory reference (nonterminated ASCIIZ
+              string).
+
+              packaging: Fix library minor number to 100 + Netpbm minor number
+              so it is higher than previous ones in library major 100.
+              I.e. libnetpbm.so.100.101 instead of libnetpbm.so.100.1.
+              Introduced in Netpbm 11.00.00.
+
+22.09.28 BJH  Release 11.00.00
+
+              (No significance to new major number; just ran out of 2-digit
+              minor numbers).
+
+              Add pamcat.
+
+              pamtable: add -tuple.
+
+              pamtable: add -hex.
+
+              pbmtextps: improve error messages.
+
+              pnmtofits: fix arbitrary behavior when FITS input lacks
+              required fields in header.  Always broken.  Pnmtofits'
+              predecessor was in primordial Netpbm (1989).
+
+              ppmtoicr: Fix bug: all options cause bogus command line parsing
+              errors.  Always broken.  Ppmtoicr was new in 1991.
+
+              ppmtoicr: Fix arithmetic overflows.
+
+              ppmtoicr: make -rle option issue an error message saying it no
+              longer exists (it did, sort of, before 2015).
+
+              ppmforge: Fix arbitrary output with really large -power.
+              
+              pnmindex: fix shell injection vulnerabilities.  Broken since
+              Netpbm 10.28 (June 2005).
+
+              pnmmargin: fix shell injection vulnerability.  Always broken
+              (Program was added in primordial Netpbm in 1990).
+
+              build: Create backward compatibility symbolic link for
+              pnminterp-gen, missing for over 20 years.
+
+22.06.24 BJH  Release 10.99.00
+
+              Add pamrestack.
+
+              Add pamshuffle.
+
+              Add pamtoqoi, qoitopam.
+
+              palmtopnm: Fix failure with bogus claim of invalid input on
+              architectures that do not use two's complement negative numbers.
+              Always broken.  (Ability to convert PackBits input was new in
+              Netpbm 10.27 (March 2005).
+
+              pnmgamma -srgbtobt709, -bt709tosrgb: fix bug; incorrect output.
+              Always broken (These options were new in Netpbm 10.32 (February
+              2006)).  Thanks Alexander Shpilkin <ashpilkin@gmail.com>.
+
+              pamdice: Fix incorrect output file name with PAM input.  Always
+              broken (pamdice was new in Netpbm 9.25 (March 2002).
+
+              libnetpbm: Stop bogus runtime error check failure in pmfileio.c
+              shifts.
+
+22.03.27 BJH  Release 10.98.00
+
+              pamtopdbimg: Add -fixedtime.
+
+              ppmfade: Use temporary files securely.
+              
+              pnmtosir: Set some possibly meaningless bits in output to zero
+              so output is repeatable.
+
+              pamx: Fix bug: top-justifies image in all cases where it should
+              bottom-justify.  Always broken.  (pamx was new in Netpbm 10.34
+              (June 2006).
+
+              pnmtorle: Fix bug: -h works only on first image.
+
+              pamsistoaglyph: Fix invalid memory reference and incorrect
+              output on depth 1 input.  Always broken.  (pamsistoaglyph was
+              new in Netpbm 10.47 (June 2009).  Thanks Scott Pakin.
+
+              pambayer: Fix bogus colors at edges.  Always Broken (pambayer
+              was new in Release 10.30 (October 2005)).
+
+              libnetpbm, various programs: fix bug: bogus warning that a color
+              specified on command line cannot be represented exactly with the
+              maxval being used.  Introduced in Netpbm 10.83 (June 2018).
+
+              pnmtopsnr: Fix typo in error message.  Always broken (pnmpsnr
+              was new in Netpbm 9.6 (July 2000).
+
+              ppmtoilbm: Remove -floyd (aka -fs) option, which hasn't worked
+              in a long time if ever and is inappropriate function for this
+              program.  And the broken code is inconsistent with new random
+              number logic elsewhere in the package.
+
+              ppmtoapplevol: Fix bug: reads from Standard Input even when you
+              specify the input file argument.  Always broken.  (ppmtoapplevol
+              was new in Netpbm 10.54 (March 2011).
+
+              ppmtoapplevol: Fix bug: produces garbage with input image wider
+              than 255.  Always broken.  (ppmtoapplevol was new in Netpbm
+              10.54 (March 2011).
+
+              pgmmedian: fix crash when median matrix is wider or higher than
+              the input image.
+
+              picttoppm: Fix incorrect output for 32 bit per pixel images
+              that have only 3 planes.  Broken in Netpbm 10.34 (June 2006).
+
+              pamendian: fix bogus "sample exceeds maxval" failure.
+              Introduced in Netpbm 10.66 (March 2014).
+
+              ppmtoilbm: Fix wild memory references and hangs with -map .
+              Introduced in Netpbm 9.12 (March 2001).
+
+              pgmtexture: Fix incorrect output.  Always broken.  (Program was
+              added in primordial Netpbm in 1991).
+              
+              pgmabel: Fix incorrect output.  Always broken.  (Program was
+              new in Netpbm 10.3 (July 2002).
+
+              Remove Floyd-Steinberg dithering functions (ppm_fs_*) from
+              libnetpbm (libppmfloyd).  No longer used.  Floyd-Steinberg
+              dithering logic can be found in pnmremap.  libppmfloyd
+              was previously used by ppmtoilbm.
+
+21.12.27 BJH  Release 10.97.00
+
+              Add pbmnoise.
+
+              pnmpad: Use -halign with -mwidth and default to centering the
+              image instead of left-justifying when no other padding is being
+              added.  Same with -mheight, -valign, and top-justifying.
+
+              xwdtopnm: Add ability to process bit depth 32.
+
+              pgmtoppm: Add -black, -white.
+
+              ppmpat: Add -mesh.
+
+              pampaintspill: Add -near.  Thanks Scott Pakin.
+
+              pamtogif: Fix bug: doesn't ignore the input alpha mask when user
+              specified -transparent.  Broken in Netpbm 10.37 (December 2006).
+
+              palmtopnm: Fix bug: fails with PackBits input on platform with
+              default unsigned char, such as ppc64.  Always broken.  (Ability
+              to convert PackBits input was new in Netpbm 10.27 (March 2005).
+              
+              pamrubber: Fix bug: random behavior with -quad when you specify
+              both points for source or target and the second one is lower in
+              the image than the first.  Always broken (Pamrubber was new in
+              Netpbm 10.54 (March 2011)).
+
+              sunicontopnm, escp2topbm, mgrtopbm, ybmtopbm, pamcut, pbmpscale,
+              pnmcat, pnmpad: Fix arithmetic overrun with ridiculously large
+              image.
+
+              pbmclean: Fix overallocation of memory (waste).
+
+              libnetbm: Add pnm_writepamrowpart, pnm_formatPamtuples.
+
+              libnetpbm: When validating computable size of width and height,
+              allow for adding up to 10 instead of 2, to account for rounding
+              up to a multiple of 8 in processing bit maps.
+
+              Build: Don't attempt to build 'pamexec' on systems without
+              Unix process management.  Bug introduced in Netpbm 10.94
+              (March 2021) and supposedly fixed in 10.95, but not really.
+
+21.09.25 BJH  Release 10.96.00
+
+              pgmtoppm: Eliminate dependency on color dictionary when user
+              does not specify any colors by name.
+
+              pamstereogram: Fix crash with -xbegin=0.  Thanks Scott Pakin.
+              Introduced in Netpbm 10.94.
+
+21.06.30 BJH  Release 10.95.00
+
+              pamtopng: Fix rejection of all BLACKANDWHITE_ALPHA images with
+              message about wrong depth.  Always broken (pamtopng was new in
+              Netpbm 10.71 (June 2015)).  Thanks Karol Kosek
+              <krkk@krkk.ct8.pl>.
+
+              pamtopng: Fix failure with GRAYSCALE_ALPHA images with maxval
+              less than 255.  Always broken (pamtopng was new in Netpbm 10.71
+              (June 2015)).  Thanks Karol Kosek <krkk@krkk.ct8.pl>.
+              
+              pamtopng: Fix: treats all tuple types that start with BLA as
+              BLACKANDWHITE.  Always broken (pamtopng was new in Netpbm 10.71
+              (June 2015)).
+
+              pamtopng: Fix -transparent option - program recognized
+              -transparency instead.  Always broken (pamtopng was new in
+              Netpbm 10.71 (June 2015)).
+
+              pamtogif: Fix failure with bogus message about wrong depth with
+              grayscale and black and white PAM images with transparency.
+              Always broken (pamtogif was new in Netpbm 10.37 (December 2006)).
+              Thanks Karol Kosek <krkk@krkk.ct8.pl>.
+
+              ppmtogif: Same as 'pamtogif' fix above, but with -alpha option.
+              
+              Build: Fix build failure due to missing 'random' function on
+              Mingw platform.  Bug introduced in Netpbm 10.94 (March 2021).
+
+              Build: Don't attempt to build 'pamexec' on systems without
+              Unix process management.  Bug introduced in Netpbm 10.94
+              (March 2021).
+
+              Build: Make it work on systems that don't have date +%s.  Broken
+              in Netpbm 10.78 (March 2017).  Thanks Claes Nästén
+              (pekdon@gmail.com).
+
+              Build: Fix for MacOS build failures with missing sprintf and
+              vasprintf in broken build environment.
+              
+              Mkdeb: fix failure with message about unrecognized format of
+              VERSION file.  Introduced in Netpbm 10.90 (March 2020).
+
+21.03.27 BJH  Release 10.94.00
+
+              Add pamhomography:  Thanks Scott Pakin.
+
+              pamstereogram: Add -yfillshift .
+
+              pamtowinicon: Add BMP/PNG encoding to verbose output.
+
+              Use internal random number generator everywhere random numbers
+              are used except ppmtoilbm, so seeded results are the same on
+              all platforms.
+
+              pamexec: Issue message instead of being killed by a signal when
+              the exec'ed program does not read the whole image"
+
+              ppmforge: Fail if -dimension is greater than 5, which is
+              useless.
+
+              pamscale: Fix bogus "bad magic number" or similar failure most
+              of the time with -nomix.  Broken since Netpbm 10.49 (December
+              2009).
+
+              pnmtopng: Fix incorrect transparency in output when requesting
+              transparency.  Introduced after Netpbm 10.35 (August 2006) but
+              not after Netpbm 10.47 (June 2009).
+
+              pnmtopng: Fix buffer overrun or bogus "too many color/
+              transparency pairs" failure when requesting transparency.
+              Introduced after Netpbm 10.26 (January 2005) but not after
+              Netpbm 10.35 (August 2006).
+
+              pamtojpeg2k: Fix constant failure with message about file
+              close failing.
+
+              libnetpbm: pm_system: Fix bug: standard input feeder process
+              repositions unrelated files.  Always broken (pm_system was new
+              in Netpbm 10.13 (September 2003).
+
+              Pamtowinicon: Fix crash or incorrect output with PNG encoding
+              (result of pm_system bug above).  Always broken (Pamtowinicon
+              was new in Netpbm 10.63 (June 2013).
+
+              pnmtopng: Fix trivial memory leaks.
+
+              pnmtops: Fix incorrect output (arithmetic overflow) when
+              bounding box is exactly INT_MAX high or wide.  Always broken.
+              Pnmtops was in primordial Netpbm.
+
+              make package: fix no such file pcdovtoppm.exe failure on
+              Windows.
+
 20.12.28 BJH  Release 10.93.00
 
               pamarith: Add -equal.
@@ -12,18 +515,18 @@ CHANGE HISTORY
               it makes sense (all but -subtract, -difference, -compare,
               -divide, -shiftleft, and -shiftright).
 
-              pamrith: fail if operand images have different depth and not
+              pamarith: fail if operand images have different depth and not
               depth 1.
 
               ppmshift: Add -seed .
 
               pamaddnoise: Fix incorrect output for -type poisson.  Always
-              broken.  (pamaddnoise was new to Netpbm in Netpbm 10.29 (August
-              2005)).
+              broken.  (pamaddnoise's precursor pnmaddnoise was new to Netpbm
+              in Netpbm 10.29 (August 2005)).
 
               pamaddnoise: fix bug: garbage output with -type impulse.  Always
-              broken (pamaddnoise's precursors pnmaddnoise was new to Netpbm
-              in Netpbm 10.29 (August 2005).
+              broken (pamaddnoise's precursor pnmaddnoise was new to Netpbm
+              in Netpbm 10.29 (August 2005)).
 
 20.09.26 BJH  Release 10.92.00
 
@@ -215,7 +718,7 @@ CHANGE HISTORY
               won't accept it.
 
               Install: Use e.g. "10.90.00" for version in pkg-config and
-              config file, intead of e.g. "Netpbm 10.90.00".
+              config file, instead of e.g. "Netpbm 10.90.00".
 
 19.12.29 BJH  Release 10.89.00
 
@@ -231,7 +734,7 @@ CHANGE HISTORY
               than just pick one.
 
               pamrubber: Fix bug: -frame doesn't work.  Always broken.
-              (Pamrubber was new in Netpbm 10.54 (March 2011).
+              (Pamrubber was new in Netpbm 10.54 (March 2011)).
 
 19.09.28 BJH  Release 10.88.00
 
@@ -4970,6 +5473,9 @@ CHANGE HISTORY
               pnmpad: Add -width, -height, -halign, -valign options.
               Thanks M. van Beilen <mvb@iradis.org>.
 
+              pnmpad: Issue warning about old-style options (e.g. "-t50"
+              instead of "-t 50").
+
               ppmhist: remove 100,000 color limit.
 
               pnmnlfilt: works with multi-image streams.  Thanks 
@@ -5600,7 +6106,7 @@ CHANGE HISTORY
 
 00.07.12 BJH  Release 9.6
 
-              Add pnmtofiasco, fiascotopnm, psnpsnr.  Thanks to Ullrich
+              Add pnmtofiasco, fiascotopnm, pnmpnsr.  Thanks to Ullrich
               Hafner.
 
               Make Pnmcrop use a temporary file instead of huge amounts
diff --git a/doc/INSTALL b/doc/INSTALL
index c20d372e..0d49f441 100644
--- a/doc/INSTALL
+++ b/doc/INSTALL
@@ -109,8 +109,8 @@ If you use the 'configure' program, be sure to edit config.mk _after_ you
 run 'configure', since 'configure' generates config.mk.
 
 
-COMPILED-IN BUILD DATETIME
---------------------------
+COMPILED-IN BUILD DATETIME AND USER
+-----------------------------------
 
 By default, the Netpbm build system builds the datetime that you built it
 into libnetpbm, so the --version global command line option can display it.
@@ -137,6 +137,13 @@ The name and meaning of the environment variable is taken from a standard
 described at https://reproducible-builds.org/specs/source-date-epoch/ on March
 16, 2017.
 
+Likewise, the Netpbm build system builds the identity of the party who did the
+build in libnetpbm.  This is normally a userid, the output of the 'whoami'
+program, unless overridden by USER or LOGNAME environment variables.  You can
+also override 'whoami', USER, and LOGNAME with the COMPILED_BY environment
+variable.  This value is just for display, so it need not be a userid; any
+single word that does not contain quotation marks is acceptable.
+
 
 AUTOMATING THE BUILD
 --------------------
@@ -162,6 +169,12 @@ contents.  You can also run Configure interactively and use its output
 as an example.
 
 
+COMPILER REQUIREMENTS
+---------------------
+
+The compiler must be able to compile C99 code.
+
+
 THE PREREQUISITE LIBRARIES
 --------------------------
 
diff --git a/doc/Netpbm.programming b/doc/Netpbm.programming
deleted file mode 100644
index c4d38ed4..00000000
--- a/doc/Netpbm.programming
+++ /dev/null
@@ -1,425 +0,0 @@
-This file is an attempt to give some basic guidelines for those who
-wish to write new Netpbm programs.  The guidelines ensure:
-
-  A) Your program functions consistently with the rest of the package.
-
-  B) Your program works in myriad environments on which you can't test it.
-
-  C) You don't miss an important detail of the Netpbm formats.
-
-  D) Your program is immune to small changes in the Netpbm formats.
-
-The easiest way to write your own Netpbm program is to take an
-existing one, similar to the one you want to write, and to modify
-it.  This saves a lot of time, and ensures conformity with these rules.
-But pick a recent one (check the file modification date and the
-doc/HISTORY file), because many things you see in old programs are
-grandfathered in.  Pamtopnm is good example of a thoroughly modern
-Netpbm program.  Pamcut is another good one.
-
-
-COLLECTION PARAMETERS
----------------------
-
-The philosophy that guides what goes into Netpbm and what doesn't is
-one of maximum distribution of function.  Contributions to Netpbm are
-refused very rarely, and usually because there is already some better
-way to do what the contribution attempts to do, so that the
-contribution would just make the package more confusing and thus
-harder to use.  The second most common reason for declining a
-contribution is that it falls well outside Netpbm's scope.  That too
-would make the package more confusing and thus harder to use.
-
-"Nobody will use that" is not a reason for leaving something out of
-Netpbm.
-
-"That's different from how other Netpbm programs work" is similarly 
-not an excuse for refusing distribution of a feature.  (But it's a
-good reason to accept a change to make a feature consistent!)
-
-The standard for adding something to Netpbm isn't that it be perfect,
-or even a net improvement.  The standard is that it not make Netpbm
-worse.  Poor quality additions are made all the time, because a
-program that doesn't work well is usually no worse than no program at
-all.
-
-
-DEVELOPMENT PROCESS
--------------------
-
-Just email your code to the Netpbm maintainer.  Base it on the most recent
-Netpbm Development release if possible.
-
-The preferred form for changes to existing files is a unified diff patch --
-the conventional Unix means of communicating code changes.  A Subversion
-'svn diff' creates that easily.
-
-You should update or create documentation too.  But if you don't, the Netpbm
-maintainer will do the update before releasing your code.  The source files
-for the documentation are the HTML files in the 'userguide' directory of the
-Netpbm Subversion repository: https://svn.code.sf.net/p/netpbm/code/userguide.
-The identical files are at http://netpbm.sourceforge.net/doc/ .
-
-There are some automated tests in the package - shell scripts in files
-named such as "pbmtog3.test".  You can use those to verify your
-changes.  You should also add to these tests and create new ones.  But
-most developers don't.
-
-As you code and test, do 'make dep' to create the header file dependency files
-(depend.mk).  Do it after 'configure' and every time you change the
-dependencies.  If you don't, 'make' won't know to recompile things when you
-change the header files.  For the convenience of users who are just building,
-and not changing anything, the make files do work without a 'make dep', but do
-so by automatically generating empty depend.mk files.  This is not what you
-want as a developer.
-
-
-CODING GUIDELINES
------------------
-
-The Netpbm maintainer accepts programs that do not meet these guidelines,
-so don't feel you need to hold back a contribution because you wrote it
-before you read these.
-
-* See the Netpbm library documentation to see what library functions
-  you should be using and how.  You can find it at:
-
-  http://netpbm.sourceforge.net/doc/libnetpbm.html
-
-* See the specifications of the Netpbm formats at:
-
-  http://netpbm.sourceforge.net/doc/pbm.html
-  http://netpbm.sourceforge.net/doc/pgm.html
-  http://netpbm.sourceforge.net/doc/ppm.html
-  http://netpbm.sourceforge.net/doc/pam.html
-
-  but don't depend very much on these; use the library functions
-  instead to read and write the image files.
-
-* You should try to use the "pam" library functions, which are newer than the
-  "pbm", "pgm", and "pnm" ones.  The "pam" functions read and write all four
-  Netpbm formats and make code easier to write and to read.
-
-* A new program should generate PAM output.  Note that any program that uses
-  the modern Netpbm library can read PAM even if it was designed for the older
-  formats.  For other programs, one can convert PAM to the older formats
-  with 'pamtopnm'.
-
-* If your program involves transparency (alpha masks), you have two
-  alternatives.  The older method is to use a separate PGM file for the
-  alpha mask, in the style of Pngtopnm/Pnmtopng and Giftopnm/Pnmtogif,
-  and use command syntax like those programs.  See the PGM format spec
-  for details.
-  
-  A newer method involves a PAM image with an alpha plane (tuple type
-  RGB_ALPHA, etc.).  This is preferred because it's easier for users
-  to pipe stuff around.  Pamtotga is an example of this.
-
-* Declare all your symbols except 'main' as static so that they won't
-  cause problems to other programs when you do a "merge build" of 
-  Netpbm.
-
-* Always start the code in main() with a call to pm_proginit().
-
-* Use shhopt for option processing.  i.e. call optParseOptions3().
-  This is really easy if you just copy the parseCommandLine() function
-  and struct cmdlineInfo declaration from pamcut.c and adapt it to 
-  your program. 
-
-  When you do this, you get a command line syntax consistent with all the
-  other Netpbm programs, you save coding time and debugging time, and it
-  is trivial to add options later on.
-
-  Do not use shhopt's short option alternative unless you need to be
-  compatible with another program that has short options.  Short
-  options are traditional one-character Unix options, which can be
-  stacked up like "foo -cderx myfile", and they are far too unfriendly
-  to be accepted by the Netpbm philosophy.  Note that long options in
-  shhopt can always be abbreviated to the shortest unique prefix, even
-  one character.
-
-  In messages and examples in documentation, always refer to an option
-  by its full name, not the abbreviation you usually use.  E.g. if you have
-  a "-width" option which can be abbreviated "-w", don't use -w in 
-  documentation.  -width is far clearer.
-  
-* Use pm_error() and pm_message() for error messages and other messages.
-  Note that the universal -quiet option (processed by p?m_init()) causes
-  messages issued via pm_message() to be suppressed.  And that's what
-  Netpbm's architecture requires.
-
-* The argument to pm_error() and pm_message() is a string of text, not
-  a formatted message.  Don't put newlines or other formatting characters
-  in it.  These subroutines are designed to be flexible in how they issue
-  the messages.
-
-* Use MALLOCARRAY() to allocate space for an array and MALLOCVAR to allocate
-  space for a non-array variable.  In fact, you usually want to save some
-  programming tedium and use the NOFAIL versions of these (they never fail
-  because they abort the program if memory is not available).  These avoid
-  array bounds violations.
-
-* Use pm_tmpfile() to make a temporary file.  This avoids races that can
-  be used to compromise security.
-
-* Properly use maxvals.  As explained in the format specifications, every
-  sample value in an image must be interpreted relative to the image's
-  maxval.  For example, a pixel with value 24 in an image with maxval 24
-  is the same brightness as a pixel with value 255 in an image with a
-  maxval of 255.
-
-  255 is a popular maxval (use the PPM_MAXMAXVAL etc. macros) because it
-  makes samples fit in a single byte and at one time was the maximum 
-  possible maxval in the format.
-
-  Note that the Pamdepth program converts an image from one maxval to another.
-
-* Don't include extra function.  If you can already do something by 
-  piping the input or output of your program through another Netpbm
-  program, don't make an option on your program to do it.  That's the
-  Netpbm philosophy -- simple building blocks.
-
-  Similarly, if your program does two things which would be useful
-  separately, write two programs and advise users to pipe them
-  together.  Or add a third program that simply runs the first two.
-
-* Your program should, if appropriate, allow the user to use Standard
-  Input and Output for images.  This is because Netpbm users commonly
-  use pipes.  As an alternative to Standard Input, the user should be able
-  to name the input file as a non-option program argument.  But the user
-  should not be able to name the output file if Standard Output is
-  feasible.  That's just the Netpbm tradition.
-
-* Don't forget to write a proper html documentation page.  Get an
-  example to use as a template from
-  <http://netpbm.sourceforge.net/doc/directory.html>.
-
-* No Netpbm source code may contain tab characters.  If you
-  generate such a file, the Netpbm maintainer will convert it to spaces
-  and possibly change all your indenting at the same time.  Tabs are not
-  appropriate for code that multiple people must edit because they don't
-  necessarily look the same in every editing environment, and in most
-  editing environments, you can't even tell which spaces are actually in
-  the file and which came from the editor, expanding tabs.  Spaces, on
-  the other hand, look the same for everyone.  Modern editors let you
-  compose code just as easily with spaces as with tabs.
-
-* Limit your C code to original ANSI C.  Not C99.  Not C89.  Not C++.  Don't
-  use // for comments or put declarations in the interior of a block.
-  Interpreted languages are OK, with Perl being preferred.
-
-* Make output invariant with input.  The program should produce the same output
-  when fed the same input.  This helps with testing and also reduces the chance
-  of bugs being encountered randomly.
-
-  This is an issue when there are "don't care" bits in the output.  You should
-  normally make those zero.
-
-  The valgrind utility helps you identify instances of undefined bits and
-  bytes getting to output.
-
-  A common place to find "don't care" bits is padding at the end of a raster
-  row.  You can use pbm_cleanrowend_packed() to clear padding bits when you
-  use pbm_writepbmrow_packed().
-
-  Some programs are designed to produce random output.  For those, include a
-  -seed option to specify the seed of the random number generator so that a
-  tester can make the output predictable.
-
-
-* Never assume that input will be valid; make sure your program can
-  handle corrupt input gracefully.
-
-  Watch out for arithmetic overflows caused by large numbers in the input.
-
-  Be careful when writing decoders.  Make sure that corruptions in the
-  input image do not cause buffer overruns.
-
-
-
-
-DISCONTINUED CODING GUIDELINES
-------------------------------
-
-Here are some things you will see in old Netpbm programs, but they are
-obsolete and you shouldn't propagate them into a new program:
-
-* Use of pbm_init(), pgm_init(), ppm_init(), and pnm_init().  We use
-  pm_proginit() now.
-
-* Tolerating non-standard C libraries.  You may assume all users have
-  ANSI and POSIX compliant C libraries.  E.g. use strrchr() and forget
-  about rindex().
-
-* pm_keymatch() for option processing.  Use shhopt instead, as described
-  above.
-
-* optParseOptions() and optParseOptions2().  These are obsoleted
-  by optParseOptions3(), which is easier to use and more powerful.
-
-* K&R C function declarations.  Always use ANSI function declarations
-  exclusively (e.g. use 
-
-      void foo(int arg1){} 
-
-  instead of 
-
-       void foo(arg1)
-           int arg1;
-           {}
-
-* for (col=0, xP = row; col < cols; col++, xP++)
-      foo(*xP);
-
-  This was done in the days before optimizing compilers because it ran faster
-  than the more readable:
-
-    for (col=0; col < cols; col++)
-        foo(row[col]);
-
-  Now, just use the latter.
-
-
-CODING STYLE
-------------
-
-We do not generally mandate any basic coding style in these
-guidelines.  Where you put your braces is a matter of personal style
-and other people working with your code will just have to live with
-it.  However, people working with your code might just recode it into
-another style if it makes it easier for them to read the code and
-have confidence in their changes.
-
-But if you have no preference, the following is what the Netpbm
-maintainer currently prefers.  Essentially, it is clean, elegant
-computer science-type code rather than brute force engineering-type
-code.  Modular and structured above all.
-
-* No gotos.  This includes all variations of goto:  break, continue, leave,
-  mid-function return.  An exception: aborting the entire program in the 
-  middle of something is allowed.
-
-* No functions with side effects.  This is a tough one, since
-  functions with side effects is highly traditional C.  In fact, the
-  creators of C didn't even have a concept of a subroutine.  However,
-  the average human brain, especially one trained in math, cannot
-  easily follow code where a function both computes a value and does
-  other stuff.
-  
-  For the purpose of this discussion, we say that a C function whose return
-  type is void is not a "function," but a "subroutine."
-
-  So a function should never change anything in the program.  All it does
-  is compute a value.
-
-  Where you have to call an external function that has side effects (virtually
-  anything in the standard C library, for example), put it in a simple
-  assignment function that captures its return value and otherwise consider
-  it a subroutine:
-
-    rc = fopen(...)
-    if (rc ...)
-
-* No reuse of variables.  Most variables should be set at most once.
-  Don't say "A is 5" and then later on, "no, A is 6."  A reader
-  should be able to take that first "A is 5" as a statement of fact
-  and not hunt for all the places it might be contradicted.  A
-  variable that represents the state of execution of an algorithm is an
-  obvious exception.
-
-  Use "const" everywhere you possibly can.
-
-  Especially never modify the argument of a function.  All function arguments
-  should be "const".
-
-  Don't use initializers except for with constants.  The first value a
-  variable has is a property of the algorithm that uses the variable, not of
-  the variable.  A reader expects to see the whole algorithm in one place, as
-  opposed to having part of it hidden in the declaration of the algorithm
-  variables.
-
-* Avoid global variables.  Sometimes, a value is truly global and
-  passing it as a parameter just muddies the code.  But most of the
-  time, any external value to which a function refers should be one of
-  its arguments.  
-
-  Declare a variable in the most local scope possible.
-
-  Global constants are OK.
-
-* Do not use static variables, except for global constants.
-
-* Keep subroutines small.  Generally under 50 lines.  But if the
-  routine is a long sequence of simple, similar things, it's OK for it
-  run on ad infinitem.
-
-* Use the type "bool" for boolean variables.  "bool" is defined in Netpbm
-  headers.  Use TRUE and FALSE as its values.
-
-* Do not say "if (a)" when you mean "if (a != 0)".  Use "if (a)" only if a is
-  a boolean variable.  Or where it's defined so that zero is a special value
-  that means "doesn't exist".
-
-* Do multiword variable names in camel case: "multiWordName".  Underscores
-  waste valuable screen real estate.
-
-* If a variable's value is a pointer to something, it's name should reflect
-  that, as opposed to lying and saying the value is the thing pointed to.  A
-  "P" on the end is the conventional way to say "pointer to."  E.g. if a
-  variable's value is a pointer to a color value, name it "colorP", not
-  "color".
-
-* A variable that represents the number of widgets should be "widgetCt",
-  ("widget count"), not "widgets".  The latter should represent the actual
-  widgets instead.
-
-* Put "const" as close as possible to the thing that is constant.
-  "int const width", not "const int width".  When pointers to
-  constants are involved, it makes it much easier to read.
-
-* Free something in the same subroutine that allocates it.  Have exactly 
-  one free per allocate (this comes naturally if you eliminate gotos).
-
-* Dynamically allocate buffers, for example raster buffers, rather than use
-  automatic variables.  Accidentally overrunning an automatic variable,
-  typically stored on the stack, is much more dangerous than overrunning a
-  variable stored in the heap.
-
-* Use pm_asprintf() to compose strings, instead of sprintf(), strcat(), and
-  strcpy().  pm_asprintf() is essentially the same as GNU asprintf(), i.e.
-  sprintf(), except it dynamically allocates the result memory.  This
-  effortlessly makes it impossible to overrun the result buffer.  Use
-  pm_strfree() to free the result memory.  You usually need not worry about
-  the pathological case that there is no memory available for the result,
-  because in that case, pm_asprintf() returns a constant string "OUT OF MEMORY"
-  and in most cases, that won't cause a disaster - just incorrect behavior that
-  is reasonable in the face of such a pathological situation.
-
-* Do not use the "register" qualifier of a variable.
-
-
-MISCELLANEOUS
--------------
-
-Object code immutability across compilations
---------------------------------------------
-
-In a normal build process the same source code always produces the same object
-code.  (Of course this depends on your compiler and its settings: if your
-compiler writes time stamps into the objects, they will naturally be different
-with each compilation.)
-
-The file lib/compile.h has a time stamp which gets written into libnetpbm.a
-and libnetpbm.so .  This will affect individual binary executables if they are
-statically linked.
-
-If compile.h does not exist it will be created by the program
-buildtools/stamp-date.  Once created, compile.h will stay unchanged until you
-do "make clean".
-
-If you make alterations to source which are entirely cosmetic (for example,
-changes to comments or amount of indentation) and need to confirm that the
-actual program logic is not affected, compare the object files.  If you need
-to compare library files (or for some reason, statically linked binaries) make
-sure that the same compile.h is used throughout.
-
diff --git a/doc/copyright_summary b/doc/copyright_summary
index 9ab3a784..84fa9397 100644
--- a/doc/copyright_summary
+++ b/doc/copyright_summary
@@ -1,4 +1,4 @@
-Here is an analysys of Netpbm copyrights done by Steve McIntyre
+Here is an analysis of Netpbm copyrights done by Steve McIntyre
 <stevem@chiark.greenend.org.uk> finishing on October 7, 2001.
 
 It is based on Netpbm 9.20, so it doesn't cover material added since
diff --git a/editor/Makefile b/editor/Makefile
index 88409dad..5929fc71 100644
--- a/editor/Makefile
+++ b/editor/Makefile
@@ -16,17 +16,18 @@ SUBDIRS = pamflip specialty
 # This package is so big, it's useful even when some parts won't 
 # build.
 
-PORTBINARIES = pamaddnoise pamaltsat pambackground pambrighten pamcomp pamcut \
-	       pamdice pamditherbw pamedge \
-	       pamenlarge \
-	       pamfunc pamhue pamlevels pammasksharpen pammixmulti \
-	       pamperspective pamrecolor pamrubber \
-	       pamscale pamsistoaglyph pamstretch pamthreshold pamundice \
-	       pamwipeout \
+PORTBINARIES = pamaddnoise pamaltsat pambackground pambrighten \
+	       pamcat pamcomp pamcut \
+	       pamdice pamditherbw pamedge pamenlarge \
+	       pamfunc pamhomography pamhue pamlevels \
+	       pammasksharpen pammixmulti \
+	       pamperspective pamrecolor pamrestack pamrubber \
+	       pamscale pamshuffle pamsistoaglyph pamstretch pamthreshold \
+	       pamundice pamwipeout \
 	       pbmclean pbmmask pbmpscale pbmreduce \
 	       pgmdeshadow pgmenhance \
 	       pgmmedian \
-	       pnmalias pnmcat pnmconvol pnmcrop \
+	       pnmalias pnmconvol pnmcrop \
 	       pnmgamma \
 	       pnmhisteq pnminvert pnmmontage \
 	       pnmnlfilt pnmnorm pnmpad pnmpaste \
@@ -63,10 +64,15 @@ install.bin install.merge: install.bin.local
 .PHONY: install.bin.local
 install.bin.local: $(PKGDIR)/bin
 # Remember that $(SYMLINK) might just be a copy command.
-# backward compatibility: program used to be pnminterp
+
+# In December 2001, pamstretch replaced pnminterp and pamstretch-getn
+# replaced pnminterp-gen
 	cd $(PKGDIR)/bin ; \
 	rm -f pnminterp$(EXE); \
 	$(SYMLINK) pamstretch$(EXE) pnminterp$(EXE)
+	cd $(PKGDIR)/bin ; \
+	rm -f pnminterp-gen$(EXE); \
+	$(SYMLINK) pamstretch-gen$(EXE) pnminterp-gen$(EXE)
 # In March 2002, pnmnorm replaced ppmnorm and pgmnorm
 	cd $(PKGDIR)/bin ; \
 	rm -f ppmnorm$(EXE) ; \
@@ -100,6 +106,10 @@ install.bin.local: $(PKGDIR)/bin
 	cd $(PKGDIR)/bin ; \
 	rm -f pnmcomp$(EXE) ; \
 	$(SYMLINK) pamcomp$(EXE) pnmcomp$(EXE)
+# In August 2022, pamcat replaced pnmcat
+	cd $(PKGDIR)/bin ; \
+	rm -f pnmcat$(EXE) ; \
+	$(SYMLINK) pamcat$(EXE) pnmcat$(EXE)
 
 mergecomptrylist:
 	cat /dev/null >$@
@@ -111,4 +121,5 @@ mergecomptrylist:
 	echo "TRY(\"pnmcut\",     main_pamcut);"     >>$@
 	echo "TRY(\"pnmscale\",   main_pamscale);"   >>$@
 	echo "TRY(\"pnmcomp\",    main_pamcomp);"    >>$@
+	echo "TRY(\"pnmcat\",     main_pamcat);"     >>$@
 
diff --git a/editor/pamaddnoise.c b/editor/pamaddnoise.c
index 20c68d99..b662aa96 100644
--- a/editor/pamaddnoise.c
+++ b/editor/pamaddnoise.c
@@ -33,20 +33,20 @@
 
 #include "pm_c_util.h"
 #include "mallocvar.h"
+#include "rand.h"
 #include "shhopt.h"
 #include "pm_gamma.h"
 #include "pam.h"
 
 static double const EPSILON = 1.0e-5;
 
-
-
-static double
-rand1() {
-
-    return (double)rand()/RAND_MAX;
-}
-
+static double const SIGMA1_DEFAULT  = 4.0;
+static double const SIGMA2_DEFAULT  = 20.0;
+static double const MGSIGMA_DEFAULT = 0.5;
+static double const LSIGMA_DEFAULT  = 10.0;
+static double const TOLERANCE_DEFAULT  = 0.10;
+static double const SALT_RATIO_DEFAULT = 0.5;
+static double const LAMBDA_DEFAULT  = 12.0;
 
 
 enum NoiseType {
@@ -67,6 +67,7 @@ struct CmdlineInfo {
 
     enum NoiseType noiseType;
 
+    unsigned int seedSpec;
     unsigned int seed;
 
     float lambda;
@@ -75,6 +76,7 @@ struct CmdlineInfo {
     float sigma1;
     float sigma2;
     float tolerance;
+    float saltRatio;
 };
 
 
@@ -119,8 +121,8 @@ parseCommandLine(int argc, const char ** const argv,
 
     unsigned int option_def_index;
 
-    unsigned int typeSpec, seedSpec, lambdaSpec, lsigmaSpec, mgsigmaSpec,
-        sigma1Spec, sigma2Spec, toleranceSpec;
+    unsigned int typeSpec, lambdaSpec, lsigmaSpec, mgsigmaSpec,
+      sigma1Spec, sigma2Spec, toleranceSpec, saltRatioSpec;
 
     const char * type;
 
@@ -128,21 +130,23 @@ parseCommandLine(int argc, const char ** const argv,
 
     option_def_index = 0;   /* incremented by OPTENT3 */
     OPTENT3(0,   "type",            OPT_STRING,   &type,
-            &typeSpec,         0);
+            &typeSpec,           0);
     OPTENT3(0,   "seed",            OPT_UINT,     &cmdlineP->seed,
-            &seedSpec,         0);
+            &cmdlineP->seedSpec, 0);
     OPTENT3(0,   "lambda",          OPT_FLOAT,    &cmdlineP->lambda,
-            &lambdaSpec,       0);
+            &lambdaSpec,         0);
     OPTENT3(0,   "lsigma",          OPT_FLOAT,    &cmdlineP->lsigma,
-            &lsigmaSpec,       0);
+            &lsigmaSpec,         0);
     OPTENT3(0,   "mgsigma",         OPT_FLOAT,    &cmdlineP->mgsigma,
-            &mgsigmaSpec,      0);
+            &mgsigmaSpec,        0);
     OPTENT3(0,   "sigma1",          OPT_FLOAT,    &cmdlineP->sigma1,
-            &sigma1Spec,       0);
+            &sigma1Spec,         0);
     OPTENT3(0,   "sigma2",          OPT_FLOAT,    &cmdlineP->sigma2,
-            &sigma2Spec,       0);
+            &sigma2Spec,         0);
     OPTENT3(0,   "tolerance",       OPT_FLOAT,    &cmdlineP->tolerance,
-            &toleranceSpec,    0);
+            &toleranceSpec,      0);
+    OPTENT3(0,   "salt",            OPT_FLOAT,    &cmdlineP->saltRatio,
+            &saltRatioSpec,      0);
 
     opt.opt_table = option_def;
     opt.short_allowed = FALSE;  /* We have no short (old-fashioned) options */
@@ -156,44 +160,84 @@ parseCommandLine(int argc, const char ** const argv,
     else
         cmdlineP->noiseType = typeFmName(type);
 
-    if (sigma1Spec && cmdlineP->noiseType != NOISETYPE_GAUSSIAN)
-        pm_error("-sigma1 is valid only with -type=gaussian");
+    if (sigma1Spec) {
+        if (cmdlineP->noiseType != NOISETYPE_GAUSSIAN)
+            pm_error("-sigma1 is valid only with -type=gaussian");
+        else if (cmdlineP->sigma1 < 0)
+            pm_error("-sigma1 value must be non-negative.  You specified %f",
+                     cmdlineP->sigma1);
+    }
+
+    if (sigma2Spec) {
+        if (cmdlineP->noiseType != NOISETYPE_GAUSSIAN)
+            pm_error("-sigma2 is valid only with -type=gaussian");
+        else if (cmdlineP->sigma2 < 0)
+            pm_error("-sigma2 value must be non-negative.  You specified %f",
+                     cmdlineP->sigma2);
+    }
 
-    if (sigma2Spec && cmdlineP->noiseType != NOISETYPE_GAUSSIAN)
-        pm_error("-sigma2 is valid only with -type=gaussian");
+    if (mgsigmaSpec) {
+        if (cmdlineP->noiseType != NOISETYPE_MULTIPLICATIVE_GAUSSIAN)
+            pm_error("-mgsigma is valid only with -type=multiplicative_guassian");
+        else if (cmdlineP->mgsigma < 0)
+            pm_error("-mgsigma value must be non-negative.  You specified %f",
+                     cmdlineP->mgsigma);
+    }
 
-    if (mgsigmaSpec &&
-        cmdlineP->noiseType != NOISETYPE_MULTIPLICATIVE_GAUSSIAN)
-        pm_error("-mgsigma is valid only with -type=multiplicative_guassian");
+    if (toleranceSpec) {
+        if (cmdlineP->noiseType != NOISETYPE_IMPULSE)
+            pm_error("-tolerance is valid only with -type=impulse");
+        else if (cmdlineP->tolerance < 0 || cmdlineP->tolerance > 1.0)
+            pm_error("-tolerance value must be between 0.0 and 1.0.  "
+                     "You specified %f",  cmdlineP->tolerance);
+    }
 
-    if (toleranceSpec && cmdlineP->noiseType != NOISETYPE_IMPULSE)
-        pm_error("-tolerance is valid only with -type=impulse");
+    if (saltRatioSpec) {
+        if (cmdlineP->noiseType != NOISETYPE_IMPULSE)
+            pm_error("-salt is valid only with -type=impulse");
+        else if (cmdlineP->saltRatio < 0 || cmdlineP->saltRatio > 1.0)
+            pm_error("-salt value must be between 0.0 and 1.0.  "
+                     "You specified %f",  cmdlineP->saltRatio);
+    }
 
-    if (lsigmaSpec && cmdlineP->noiseType != NOISETYPE_LAPLACIAN)
+    if (lsigmaSpec) {
+        if (cmdlineP->noiseType != NOISETYPE_LAPLACIAN)
         pm_error("-lsigma is valid only with -type=laplacian");
+        else if (cmdlineP->lsigma <= 0)
+            pm_error("-lsigma value must be positive.  You specified %f",
+                     cmdlineP->lsigma);
+    }
 
-    if (lambdaSpec && cmdlineP->noiseType != NOISETYPE_POISSON)
+    if (lambdaSpec) {
+        if (cmdlineP->noiseType != NOISETYPE_POISSON)
         pm_error("-lambda is valid only with -type=poisson");
+        else if (cmdlineP->lambda <= 0)
+            pm_error("-lambda value must be positive.  You specified %f",
+                     cmdlineP->lambda);
+    }
 
     if (!lambdaSpec)
-        cmdlineP->lambda = 12.0;
+        cmdlineP->lambda = LAMBDA_DEFAULT;
 
     if (!lsigmaSpec)
-        cmdlineP->lsigma = 10.0;
+        cmdlineP->lsigma = LSIGMA_DEFAULT;
 
     if (!mgsigmaSpec)
-        cmdlineP->mgsigma = 0.5;
+        cmdlineP->mgsigma = MGSIGMA_DEFAULT;
 
     if (!sigma1Spec)
-        cmdlineP->sigma1 = 4.0;
+        cmdlineP->sigma1 = SIGMA1_DEFAULT;
 
     if (!sigma2Spec)
-        cmdlineP->sigma2 = 20.0;
+        cmdlineP->sigma2 = SIGMA2_DEFAULT;
 
     if (!toleranceSpec)
-        cmdlineP->tolerance = 0.10;
+        cmdlineP->tolerance = TOLERANCE_DEFAULT;
+
+    if (!saltRatioSpec)
+        cmdlineP->saltRatio = SALT_RATIO_DEFAULT;
 
-    if (!seedSpec)
+    if (!cmdlineP->seedSpec)
         cmdlineP->seed = pm_randseed();
 
     if (argc-1 > 1)
@@ -211,30 +255,25 @@ parseCommandLine(int argc, const char ** const argv,
 
 
 static void
-addGaussianNoise(sample   const maxval,
-                 sample   const origSample,
-                 sample * const newSampleP,
-                 float    const sigma1,
-                 float    const sigma2) {
+addGaussianNoise(sample             const maxval,
+                 sample             const origSample,
+                 sample *           const newSampleP,
+                 float              const sigma1,
+                 float              const sigma2,
+                 struct pm_randSt * const randStP) {
 /*----------------------------------------------------------------------------
    Add Gaussian noise.
 
    Based on Kasturi/Algorithms of the ACM
 -----------------------------------------------------------------------------*/
 
-    double x1, x2, xn, yn;
+    double grnd1, grnd2; /* Gaussian random numbers.  mean=0 sigma=1 */
     double rawNewSample;
 
-    x1 = rand1();
-
-    if (x1 == 0.0)
-        x1 = 1.0;
-    x2 = rand1();
-    xn = sqrt(-2.0 * log(x1)) * cos(2.0 * M_PI * x2);
-    yn = sqrt(-2.0 * log(x1)) * sin(2.0 * M_PI * x2);
+    pm_gaussrand2(randStP, &grnd1, &grnd2);
 
     rawNewSample =
-        origSample + (sqrt((double) origSample) * sigma1 * xn) + (sigma2 * yn);
+      origSample + (sqrt((double) origSample) * sigma1 * grnd1) + (sigma2 * grnd2);
 
     *newSampleP = MAX(MIN((int)rawNewSample, maxval), 0);
 }
@@ -242,40 +281,42 @@ addGaussianNoise(sample   const maxval,
 
 
 static void
-addImpulseNoise(sample   const maxval,
-                sample   const origSample,
-                sample * const newSampleP,
-                float    const tolerance) {
+addImpulseNoise(sample             const maxval,
+                sample             const origSample,
+                sample *           const newSampleP,
+                float              const tolerance,
+                double             const saltRatio,
+                struct pm_randSt * const randStP) {
 /*----------------------------------------------------------------------------
    Add impulse (salt and pepper) noise
 -----------------------------------------------------------------------------*/
 
-    double const low_tol  = tolerance / 2.0;
-    double const high_tol = 1.0 - (tolerance / 2.0);
-    double const sap = rand1();
+    double const pepperRatio = 1.0 - saltRatio;
+    double const loTolerance = tolerance * pepperRatio;
+    double const hiTolerance = 1.0 - tolerance * saltRatio;
+    double const sap         = pm_drand(randStP);
 
-    if (sap < low_tol)
-        *newSampleP = 0;
-    else if ( sap >= high_tol )
-        *newSampleP = maxval;
-    else
-        *newSampleP = origSample;
+    *newSampleP =
+        sap < loTolerance ? 0 :
+        sap >= hiTolerance? maxval :
+        origSample;
 }
 
 
 
 static void
-addLaplacianNoise(sample   const maxval,
-                  double   const infinity,
-                  sample   const origSample,
-                  sample * const newSampleP,
-                  float    const lsigma) {
+addLaplacianNoise(sample             const maxval,
+                  double             const infinity,
+                  sample             const origSample,
+                  sample *           const newSampleP,
+                  float              const lsigma,
+                  struct pm_randSt * const randStP) {
 /*----------------------------------------------------------------------------
    Add Laplacian noise
 
    From Pitas' book.
 -----------------------------------------------------------------------------*/
-    double const u = rand1();
+    double const u = pm_drand(randStP);
 
     double rawNewSample;
 
@@ -297,31 +338,21 @@ addLaplacianNoise(sample   const maxval,
 
 
 static void
-addMultiplicativeGaussianNoise(sample   const maxval,
-                               double   const infinity,
-                               sample   const origSample,
-                               sample * const newSampleP,
-                               float    const mgsigma) {
+addMultiplicativeGaussianNoise(sample             const maxval,
+                               double             const infinity,
+                               sample             const origSample,
+                               sample *           const newSampleP,
+                               float              const mgsigma,
+                               struct pm_randSt * const randStP) {
 /*----------------------------------------------------------------------------
    Add multiplicative Gaussian noise
 
    From Pitas' book.
 -----------------------------------------------------------------------------*/
-    double rayleigh, gauss;
+
     double rawNewSample;
 
-    {
-        double const uniform = rand1();
-        if (uniform <= EPSILON)
-            rayleigh = infinity;
-        else
-            rayleigh = sqrt(-2.0 * log( uniform));
-    }
-    {
-        double const uniform = rand1();
-        gauss = rayleigh * cos(2.0 * M_PI * uniform);
-    }
-    rawNewSample = origSample + (origSample * mgsigma * gauss);
+    rawNewSample = origSample + (origSample * mgsigma * pm_gaussrand(randStP));
 
     *newSampleP = MIN(MAX((int)rawNewSample, 0), maxval);
 }
@@ -363,10 +394,11 @@ poissonPmf(double       const lambda,
 
 
 static void
-addPoissonNoise(struct pam * const pamP,
-                sample       const origSample,
-                sample *     const newSampleP,
-                float        const lambdaOfMaxval) {
+addPoissonNoise(struct pam *       const pamP,
+                sample             const origSample,
+                sample *           const newSampleP,
+                float              const lambdaOfMaxval,
+                struct pm_randSt * const randStP) {
 /*----------------------------------------------------------------------------
    Add Poisson noise
 -----------------------------------------------------------------------------*/
@@ -376,7 +408,7 @@ addPoissonNoise(struct pam * const pamP,
 
     double const lambda  = origSampleIntensity * lambdaOfMaxval;
 
-    double const u = rand1();
+    double const u = pm_drand(randStP);
 
     /* We now apply the inverse CDF (cumulative distribution function) of the
        Poisson distribution to uniform random variable 'u' to get a Poisson
@@ -416,12 +448,14 @@ main(int argc, const char ** argv) {
     const tuple * newtuplerow;
     unsigned int row;
     double infinity;
+    struct pm_randSt randSt;
 
     pm_proginit(&argc, argv);
 
     parseCommandLine(argc, argv, &cmdline);
 
-    srand(cmdline.seed);
+    pm_randinit(&randSt);
+    pm_srand2(&randSt, cmdline.seedSpec, cmdline.seed);
 
     ifP = pm_openr(cmdline.inputFileName);
 
@@ -448,35 +482,40 @@ main(int argc, const char ** argv) {
                     addGaussianNoise(inpam.maxval,
                                      tuplerow[col][plane],
                                      &newtuplerow[col][plane],
-                                     cmdline.sigma1, cmdline.sigma2);
+                                     cmdline.sigma1, cmdline.sigma2,
+                                     &randSt);
                     break;
 
                 case NOISETYPE_IMPULSE:
                     addImpulseNoise(inpam.maxval,
                                     tuplerow[col][plane],
                                     &newtuplerow[col][plane],
-                                    cmdline.tolerance);
+                                    cmdline.tolerance, cmdline.saltRatio,
+                                    &randSt);
                    break;
 
                 case NOISETYPE_LAPLACIAN:
                     addLaplacianNoise(inpam.maxval, infinity,
                                       tuplerow[col][plane],
                                       &newtuplerow[col][plane],
-                                      cmdline.lsigma);
+                                      cmdline.lsigma,
+                                      &randSt);
                     break;
 
                 case NOISETYPE_MULTIPLICATIVE_GAUSSIAN:
                     addMultiplicativeGaussianNoise(inpam.maxval, infinity,
                                                    tuplerow[col][plane],
                                                    &newtuplerow[col][plane],
-                                                   cmdline.mgsigma);
+                                                   cmdline.mgsigma,
+                                                   &randSt);
                     break;
 
                 case NOISETYPE_POISSON:
                     addPoissonNoise(&inpam,
                                     tuplerow[col][plane],
                                     &newtuplerow[col][plane],
-                                    cmdline.lambda);
+                                    cmdline.lambda,
+                                    &randSt);
                     break;
 
                 }
@@ -484,6 +523,7 @@ main(int argc, const char ** argv) {
         }
         pnm_writepamrow(&outpam, newtuplerow);
     }
+    pm_randterm(&randSt);
     pnm_freepamrow(newtuplerow);
     pnm_freepamrow(tuplerow);
 
diff --git a/editor/pambackground.c b/editor/pambackground.c
index b4941042..2aed88c1 100644
--- a/editor/pambackground.c
+++ b/editor/pambackground.c
@@ -4,25 +4,25 @@
 #include "shhopt.h"
 #include "pam.h"
 
-struct cmdlineInfo {
+struct CmdlineInfo {
     /* All the information the user supplied in the command line,
        in a form easy for the program to use.
     */
-    const char * inputFileName;  
+    const char * inputFileName;
     unsigned int verbose;
 };
 
 
 
 static void
-parseCommandLine(int argc, char ** const argv,
-                 struct cmdlineInfo * const cmdlineP) {
+parseCommandLine(int argc, const char ** const argv,
+                 struct CmdlineInfo * const cmdlineP) {
 /*----------------------------------------------------------------------------
    Note that the file spec array we return is stored in the storage that
    was passed to us as the argv array.
 -----------------------------------------------------------------------------*/
     optEntry *option_def;
-        /* Instructions to OptParseOptions2 on how to parse our options.
+        /* Instructions to OptParseOptions3 on how to parse our options.
          */
     optStruct3 opt;
 
@@ -37,7 +37,7 @@ parseCommandLine(int argc, char ** const argv,
     opt.short_allowed = FALSE;  /* We have no short (old-fashioned) options */
     opt.allowNegNum = FALSE;  /* We have no parms that are negative numbers */
 
-    pm_optParseOptions3(&argc, argv, opt, sizeof(opt), 0);
+    pm_optParseOptions3(&argc, (char **)argv, opt, sizeof(opt), 0);
         /* Uses and sets argc, argv, and some of *cmdlineP and others. */
 
     if (argc-1 < 1)
@@ -48,7 +48,7 @@ parseCommandLine(int argc, char ** const argv,
             pm_error("There is at most one argument:  input file name.  "
                      "You specified %d", argc-1);
     }
-}        
+}
 
 
 
@@ -83,7 +83,7 @@ allocateOutputPointerRow(unsigned int const width,
 
 
 static void
-createWhiteTuple(const struct pam * const pamP, 
+createWhiteTuple(const struct pam * const pamP,
                  tuple *            const whiteTupleP) {
 /*----------------------------------------------------------------------------
    Create a "white" tuple.  By that we mean a tuple all of whose elements
@@ -134,7 +134,7 @@ selectBackground(struct pam * const pamP,
             bg = ul;
         }
     }
-    
+
     *bgColorP = pnm_allocpamtuple(pamP);
     pnm_assigntuple(pamP, *bgColorP, bg);
 }
@@ -301,8 +301,8 @@ expandBackgroundHoriz(unsigned char ** const pi,
                       unsigned int     const height,
                       bool *           const expandedP) {
 /*----------------------------------------------------------------------------
-   In every row, expand the background rightward from any known background
-   pixel through all consecutive unknown pixels.
+   In every row except top and bottom, expand the background rightward from
+   any known background pixel through all consecutive unknown pixels.
 
    Then do the same thing leftward.
 
@@ -343,8 +343,9 @@ expandBackgroundVert(unsigned char ** const pi,
                      unsigned int     const height,
                      bool *           const expandedP) {
 /*----------------------------------------------------------------------------
-   In every column, expand the background downward from any known background
-   pixel through all consecutive unknown pixels.
+   In every column except leftmost and rightmost, expand the background
+   downward from any known background pixel through all consecutive unknown
+   pixels.
 
    Then do the same thing upward.
 
@@ -400,7 +401,7 @@ findBackgroundPixels(struct pam *                   const inpamP,
 -----------------------------------------------------------------------------*/
     unsigned char ** pi;
     bool backgroundComplete;
-    unsigned int passes;
+    unsigned int passCt;
 
     pi = newPi(inpamP->width, inpamP->height);
 
@@ -409,29 +410,29 @@ findBackgroundPixels(struct pam *                   const inpamP,
     setEdges(pi, inpamP->width, inpamP->height);
 
     backgroundComplete = FALSE;
-    passes = 0;
-    
+    passCt = 0;
+
     while (!backgroundComplete) {
         bool expandedHoriz, expandedVert;
 
         expandBackgroundHoriz(pi, inpamP->width, inpamP->height,
                               &expandedHoriz);
-    
+
         expandBackgroundVert(pi, inpamP->width, inpamP->height,
                              &expandedVert);
 
         backgroundComplete = !expandedHoriz && !expandedVert;
 
-        ++passes;
+        ++passCt;
     }
 
     if (verbose)
-        pm_message("Background found in %u passes", passes);
+        pm_message("Background found in %u passes", passCt);
 
     *piP = (const unsigned char * const *)pi;
 }
 
-                     
+
 
 static void
 writeOutput(const struct pam *            const inpamP,
@@ -468,16 +469,16 @@ writeOutput(const struct pam *            const inpamP,
 
 
 int
-main(int argc, char *argv[]) {
+main(int argc, const char *argv[]) {
 
-    struct cmdlineInfo cmdline;
+    struct CmdlineInfo cmdline;
     struct pam inpam;
     FILE * ifP;
     pm_filepos rasterpos;
     tuple backgroundColor;
     const unsigned char * const * pi;
-    
-    pnm_init(&argc, argv);
+
+    pm_proginit(&argc, argv);
 
     parseCommandLine(argc, argv, &cmdline);
 
@@ -500,6 +501,9 @@ main(int argc, char *argv[]) {
     pm_close(ifP);
 
     pnm_freepamtuple(backgroundColor);
-    
+
     return 0;
 }
+
+
+
diff --git a/editor/pamcat.c b/editor/pamcat.c
new file mode 100644
index 00000000..7823bdfc
--- /dev/null
+++ b/editor/pamcat.c
@@ -0,0 +1,1461 @@
+/*=============================================================================
+                                   pamcat
+===============================================================================
+
+  Concatenate images.
+
+  By Bryan Henderson and Akira Urushibata.  Contributed to the public domain
+  by its authors.
+
+=============================================================================*/
+
+#include <stdio.h>
+#include <limits.h>
+#include <assert.h>
+
+#include "pm_c_util.h"
+#include "mallocvar.h"
+#include "shhopt.h"
+#include "bitarith.h"
+#include "nstring.h"
+#include "pam.h"
+#include "pbm.h"
+
+#define LEFTBITS pm_byteLeftBits
+#define RIGHTBITS pm_byteRightBits
+
+enum PadColorMethod {PAD_BLACK, PAD_WHITE, PAD_AUTO};
+  /* The method of determining the color of padding when images are not the
+     same height or width.  Always white (maxval samples) always black (zero
+     samples) or determined from what looks like background for the image in
+     question.
+  */
+
+
+enum Orientation {TOPBOTTOM, LEFTRIGHT};
+  /* Direction of concatenation */
+
+enum Justification {JUST_CENTER, JUST_MIN, JUST_MAX};
+  /* Justification of images in concatenation */
+
+/* FOPEN_MAX is usually defined in stdio.h, PATH_MAX in limits.h
+   Given below are typical values.  Adjust as necessary.
+ */
+
+#ifndef FOPEN_MAX
+  #define FOPEN_MAX 16
+#endif
+
+#ifndef PATH_MAX
+  #define PATH_MAX 255
+#endif
+
+
+static const char **
+copyOfStringList(const char ** const list,
+                 unsigned int  const size) {
+
+    const char ** retval;
+    unsigned int i;
+
+    MALLOCARRAY_NOFAIL(retval, size);
+
+    for (i = 0; i < size; ++i)
+        retval[i] = pm_strdup(list[i]);
+
+    return retval;
+}
+
+
+
+struct CmdlineInfo {
+    /* All the information the user supplied in the command line,
+       in a form easy for the program to use.
+    */
+    const char **       inputFileName;
+    unsigned int        inputFileCt;
+    const char *        listfile;  /* NULL if not specified */
+    enum PadColorMethod padColorMethod;
+    enum Orientation    orientation;
+    enum Justification  justification;
+    unsigned int        verbose;
+};
+
+
+static void
+parseCommandLine(int argc, const char ** const argv,
+                 struct CmdlineInfo * const cmdlineP) {
+/*----------------------------------------------------------------------------
+   Note that the file spec array we return is stored in the storage that
+   was passed to us as the argv array.
+-----------------------------------------------------------------------------*/
+    optEntry * option_def;
+        /* Instructions to OptParseOptions3() on how to parse our options.
+         */
+    optStruct3 opt;
+
+    unsigned int option_def_index;
+
+    unsigned int leftright, topbottom;
+    unsigned int black, white;
+    unsigned int jtop, jbottom, jleft, jright, jcenter;
+    unsigned int listfileSpec;
+
+    MALLOCARRAY_NOFAIL(option_def, 100);
+
+    option_def_index = 0;   /* incremented by OPTENT3 */
+    OPTENT3(0, "leftright",   OPT_FLAG,   NULL, &leftright,         0);
+    OPTENT3(0, "lr",          OPT_FLAG,   NULL, &leftright,         0);
+    OPTENT3(0, "topbottom",   OPT_FLAG,   NULL, &topbottom,         0);
+    OPTENT3(0, "tb",          OPT_FLAG,   NULL, &topbottom,         0);
+    OPTENT3(0, "black",       OPT_FLAG,   NULL, &black,             0);
+    OPTENT3(0, "white",       OPT_FLAG,   NULL, &white,             0);
+    OPTENT3(0, "jtop",        OPT_FLAG,   NULL, &jtop,              0);
+    OPTENT3(0, "jbottom",     OPT_FLAG,   NULL, &jbottom,           0);
+    OPTENT3(0, "jleft",       OPT_FLAG,   NULL, &jleft,             0);
+    OPTENT3(0, "jright",      OPT_FLAG,   NULL, &jright,            0);
+    OPTENT3(0, "jcenter",     OPT_FLAG,   NULL, &jcenter,           0);
+    OPTENT3(0, "listfile",    OPT_STRING, &cmdlineP->listfile,
+            &listfileSpec,      0);
+    OPTENT3(0, "verbose",     OPT_FLAG,   NULL, &cmdlineP->verbose, 0);
+
+    opt.opt_table = option_def;
+    opt.short_allowed = FALSE;  /* We have no short (old-fashioned) options */
+    opt.allowNegNum = FALSE;  /* We have no parms that are negative numbers */
+
+    pm_optParseOptions3(&argc, (char **)argv, opt, sizeof(opt), 0);
+        /* Uses and sets argc, argv, and some of *cmdlineP and others. */
+
+    free(option_def);
+
+    if (leftright + topbottom > 1)
+        pm_error("You may specify only one of -topbottom (-tb) and "
+                 "-leftright (-lr)");
+    else if (leftright)
+        cmdlineP->orientation = LEFTRIGHT;
+    else if (topbottom)
+        cmdlineP->orientation = TOPBOTTOM;
+    else
+        pm_error("You must specify either -leftright or -topbottom");
+
+    if (black + white > 1)
+        pm_error("You may specify only one of -black and -white");
+    else if (black)
+        cmdlineP->padColorMethod = PAD_BLACK;
+    else if (white)
+        cmdlineP->padColorMethod = PAD_WHITE;
+    else
+        cmdlineP->padColorMethod = PAD_AUTO;
+
+    if (jtop + jbottom + jleft + jright + jcenter > 1)
+        pm_error("You may specify only one of -jtop, -jbottom, "
+                 "-jleft, and -jright");
+    else {
+        switch (cmdlineP->orientation) {
+        case LEFTRIGHT:
+            if (jleft)
+                pm_error("-jleft is invalid with -leftright");
+            if (jright)
+                pm_error("-jright is invalid with -leftright");
+            if (jtop)
+                cmdlineP->justification = JUST_MIN;
+            else if (jbottom)
+                cmdlineP->justification = JUST_MAX;
+            else if (jcenter)
+                cmdlineP->justification = JUST_CENTER;
+            else
+                cmdlineP->justification = JUST_CENTER;
+            break;
+        case TOPBOTTOM:
+            if (jtop)
+                pm_error("-jtop is invalid with -topbottom");
+            if (jbottom)
+                pm_error("-jbottom is invalid with -topbottom");
+            if (jleft)
+                cmdlineP->justification = JUST_MIN;
+            else if (jright)
+                cmdlineP->justification = JUST_MAX;
+            else if (jcenter)
+                cmdlineP->justification = JUST_CENTER;
+            else
+                cmdlineP->justification = JUST_CENTER;
+            break;
+        }
+    }
+
+    if (listfileSpec) {
+        if (argc-1 > 0)
+          pm_error ("You can not specify files on the command line and "
+                    "also -listfile.");
+    } else {
+        cmdlineP->listfile = NULL;
+
+        if (argc-1 < 1) {
+            MALLOCARRAY_NOFAIL(cmdlineP->inputFileName, 1);
+            cmdlineP->inputFileName[0] = "-";
+            cmdlineP->inputFileCt = 1;
+        } else {
+            unsigned int i;
+            unsigned int stdinCt;
+            /* Number of input files user specified as Standard Input */
+
+            MALLOCARRAY_NOFAIL(cmdlineP->inputFileName, argc-1);
+
+            for (i = 0, stdinCt = 0; i < argc-1; ++i) {
+                cmdlineP->inputFileName[i] = argv[1+i];
+                if (streq(argv[1+i], "-"))
+                    ++stdinCt;
+            }
+            cmdlineP->inputFileCt = argc-1;
+            if (stdinCt > 1)
+                pm_error("At most one input image can come from "
+                         "Standard Input.  You specified %u", stdinCt);
+        }
+    }
+}
+
+
+
+static void
+freeCmdLine(struct CmdlineInfo const cmdline) {
+
+    if (!cmdline.listfile)
+        free(cmdline.inputFileName);
+}
+
+
+
+static void
+createInFileListFmFile(const char  *        const listFileNm,
+                       bool                 const verbose,
+                       const char ***       const inputFileNmP,
+                       unsigned int *       const inputFileCtP) {
+
+    FILE * const lfP = pm_openr(listFileNm);
+
+    const char ** inputFileNm;
+    unsigned int inputFileCt;
+    unsigned int emptyLineCt;
+    unsigned int stdinCt;
+    int eof;
+
+    MALLOCARRAY_NOFAIL(inputFileNm, FOPEN_MAX);
+
+    for (inputFileCt = emptyLineCt = stdinCt = eof = 0; !eof; ) {
+
+        size_t lineLen;
+        char * buf;
+        size_t bufferSz;
+
+        buf = NULL;  /* initial value */
+        bufferSz = 0;  /* initial value */
+
+        pm_getline(lfP, &buf, &bufferSz, &eof, &lineLen);
+
+        if (!eof) {
+            if (lineLen == 0)
+                ++emptyLineCt;
+            else if (lineLen > PATH_MAX)
+                pm_error("Path/file name in list file is too long "
+                         "(%u bytes).  Maximum is %u bytes",
+                         (unsigned)lineLen, PATH_MAX);
+            else /* 0 < lineLen < PATH_MAX */ {
+                if (inputFileCt >= FOPEN_MAX)
+                    pm_error("Too many files in list file.  Maximum is %u",
+                             FOPEN_MAX);
+                else {
+                    inputFileNm[inputFileCt] = buf;
+                    ++inputFileCt;
+                    if (streq(buf, "-"))
+                        ++stdinCt;
+                }
+            }
+        }
+    }
+
+    pm_close(lfP);
+
+    if (stdinCt > 1)
+        pm_error("At most one input image can come from Standard Input.  "
+                 "You specified %u", stdinCt);
+
+    if (inputFileCt == 0)
+        pm_error("No files specified in list file.");
+
+    if (verbose) {
+        pm_message("%u files specified and %u blank lines in list file",
+                   inputFileCt, emptyLineCt);
+    }
+
+    *inputFileCtP = inputFileCt;
+    *inputFileNmP = inputFileNm;
+}
+
+
+
+static void
+createInFileList(struct CmdlineInfo const cmdline,
+                 bool               const verbose,
+                 const char ***     const inputFileNmP,
+                 unsigned int *     const inputFileCtP) {
+
+    if (cmdline.listfile)
+        createInFileListFmFile(cmdline.listfile, verbose,
+                               inputFileNmP, inputFileCtP);
+    else {
+        *inputFileCtP = cmdline.inputFileCt;
+        *inputFileNmP = copyOfStringList(cmdline.inputFileName,
+                                         cmdline.inputFileCt);
+    }
+}
+
+
+
+static void
+freeInFileList(const char ** const inputFileNm,
+               unsigned int  const inputFileCt) {
+
+    unsigned int i;
+
+    for (i = 0; i < inputFileCt; ++i)
+        pm_strfree(inputFileNm[i]);
+
+    free(inputFileNm);
+}
+
+
+
+static const char *
+tupletypeX(bool         const allVisual,
+           unsigned int const colorDepth,
+           sample       const maxMaxval,
+           bool         const haveOpacity) {
+
+    const char * retval;
+
+    if (allVisual) {
+        switch (colorDepth) {
+        case 1:
+            if (maxMaxval == 1)
+                retval = haveOpacity ? "BLACKANDWHITE_ALPHA" : "BLACKANDWHITE";
+            else
+                retval = haveOpacity ? "GRAYSCALE_ALPHA"     : "GRAYSCALE";
+            break;
+        case 3:
+            retval = haveOpacity ? "RGB_ALPHA"           : "RGB";
+            break;
+        default:
+            assert(false);
+        }
+    } else
+        retval = "";
+
+    return retval;
+}
+
+
+
+typedef struct {
+    /* This describes a transformation from one tuple type to another,
+       e.g. from BLACKANDWHITE to GRAY_ALPHA.
+
+       For transformations bewteen the defined ones for visual images,
+       only the "up" transformations are covered.
+    */
+    bool mustPromoteColor;
+        /* Plane 0, which is the black/white or grayscale plane and also
+           the red plane must be copied as the red, green, and blue planes
+           (0, 1, and 2).
+        */
+    bool mustPromoteOpacity;
+        /* Plane 1, which is the opacity plane for black and white or
+           grayscale tuples, must be copied as the RGB opacity plane (3).
+        */
+    bool mustCreateOpacity;
+        /* The opacity plane value must be set to opaque */
+
+    bool mustPadZero;
+        /* Where the target tuple type is deeper than the source tuple
+           type, all higher numbered planes must be cleared to zero.
+
+           This is mutually exclusive with the rest of the musts.
+        */
+
+} TtTransform;
+
+
+
+static TtTransform
+ttXformForImg(const struct pam * const inpamP,
+              const struct pam * const outpamP) {
+/*----------------------------------------------------------------------------
+  The transform required to transform tuples of the kind described by *inpamP
+  to tuples of the kind described by *outpamP (e.g. from grayscale to RGB,
+  which involves replicating one plane into three).
+
+  We assume *outpamP tuples are of a type that is at least as expressive as
+  *inpamP tuples.  So e.g. outpamP->tuple_type cannot be "GRAYSCALE" if
+  inpamP->tuple_type is "RGB".
+-----------------------------------------------------------------------------*/
+    TtTransform retval;
+
+    if (inpamP->visual && outpamP->visual) {
+        retval.mustPromoteColor   =
+            (outpamP->color_depth > inpamP->color_depth);
+        retval.mustPromoteOpacity =
+            (outpamP->color_depth > inpamP->color_depth &&
+             (outpamP->have_opacity && inpamP->have_opacity));
+        retval.mustCreateOpacity  =
+            (outpamP->have_opacity && !inpamP->have_opacity);
+        retval.mustPadZero = false;
+    } else {
+        retval.mustPromoteColor   = false;
+        retval.mustPromoteOpacity = false;
+        retval.mustCreateOpacity  = false;
+        retval.mustPadZero        = true;
+    }
+    return retval;
+}
+
+
+
+static void
+reportPlans(unsigned int       const fileCt,
+            const struct pam * const outpamP) {
+
+    pm_message("Concatenating %u input images", fileCt);
+
+    pm_message("Output width, height, depth: %u x %u x %u",
+               outpamP->width, outpamP->height, outpamP->depth);
+
+    if (outpamP->format == RPBM_FORMAT)
+        pm_message("Using PBM fast path and producing raw PBM output");
+    else if (outpamP->format == PBM_FORMAT)
+        pm_message("Output format: Plain PBM");
+    else {
+        pm_message("Output maxval (max of all inputs): %lu", outpamP->maxval);
+
+        switch (outpamP->format) {
+        case PGM_FORMAT:
+            pm_message("Output format: Plain PGM");
+            break;
+        case RPGM_FORMAT:
+            pm_message("Output format: Raw PGM");
+            break;
+        case PPM_FORMAT:
+            pm_message("Output format: Plain PPM");
+            break;
+        case RPPM_FORMAT:
+            pm_message("Output format: Raw PPM");
+            break;
+        case PAM_FORMAT:
+            pm_message("Output format: PAM");
+
+            if (strlen(outpamP->tuple_type) > 0)
+                pm_message("Output tuple type: '%s'", outpamP->tuple_type);
+            else
+                pm_message("Output tuple type is null string because "
+                           "input images have various non-visual tuple types");
+            break;
+        }
+    }
+}
+
+
+
+static void
+computeOutputParms(unsigned int       const fileCt,
+                   enum Orientation   const orientation,
+                   const struct pam * const inpam,  /* array */
+                   bool               const verbose,
+                   struct pam *       const outpamP) {
+
+    double newCols, newRows;
+    unsigned int maxDepth;
+    sample maxMaxval;
+    int newFormat;
+    const char * firstTupletype;
+    bool allSameTt;
+    bool allVisual;
+    unsigned int maxColorDepth;
+    bool haveOpacity;
+    unsigned int fileSeq;
+
+    for (fileSeq = 0, newCols = 0, newRows = 0, maxDepth = 0, maxMaxval = 0,
+             newFormat = 0,
+             allVisual = true, maxColorDepth = 0, haveOpacity = false,
+             firstTupletype = NULL, allSameTt = true;
+         fileSeq < fileCt;
+         ++fileSeq) {
+
+        const struct pam * const inpamP = &inpam[fileSeq];
+
+        switch (orientation) {
+        case LEFTRIGHT:
+            newCols += inpamP->width;
+            newRows = MAX(newRows, inpamP->height);
+            break;
+        case TOPBOTTOM:
+            newRows += inpamP->height;
+            newCols = MAX(newCols, inpamP->width);
+            break;
+        }
+
+        if (!firstTupletype)
+            firstTupletype = inpamP->tuple_type;
+        if (inpamP->tuple_type != firstTupletype)
+            allSameTt = false;
+
+        if (inpamP->visual) {
+            maxColorDepth = MAX(maxColorDepth, inpamP->color_depth);
+
+            if (inpamP->have_opacity)
+                haveOpacity = true;
+        } else
+            allVisual = false;
+
+        maxDepth      = MAX(maxDepth,      inpamP->depth);
+        maxMaxval     = MAX(maxMaxval,     inpamP->maxval);
+
+        if (PAM_FORMAT_TYPE(inpamP->format) > PAM_FORMAT_TYPE(newFormat))
+            newFormat = inpamP->format;
+    }
+    assert(newCols       > 0);
+    assert(newRows       > 0);
+    assert(maxMaxval     > 0);
+    assert(newFormat     > 0);
+
+    if (newCols > INT_MAX)
+       pm_error("Output width too large: %.0f.", newCols);
+    if (newRows > INT_MAX)
+       pm_error("Output height too large: %.0f.", newRows);
+
+    outpamP->size = sizeof(*outpamP);
+    outpamP->len  = PAM_STRUCT_SIZE(tuple_type);
+
+    /* Note that while 'double' is not in general a precise numerical type,
+       in the case of a sum of integers which is less than INT_MAX, it
+       is exact, because double's precision is greater than int's.
+    */
+    outpamP->height           = (unsigned int)newRows;
+    outpamP->width            = (unsigned int)newCols;
+    if (allVisual)
+        outpamP->depth        = MAX(maxDepth,
+                                    maxColorDepth + (haveOpacity ? 1 : 0));
+    else
+        outpamP->depth        = maxDepth;
+    outpamP->allocation_depth = 0;  /* This means same as depth */
+    outpamP->maxval           = maxMaxval;
+    outpamP->format           = newFormat;
+    if (allSameTt)
+        STRSCPY(outpamP->tuple_type, firstTupletype);
+    else
+        STRSCPY(outpamP->tuple_type,
+                tupletypeX(allVisual, maxColorDepth, maxMaxval, haveOpacity));
+    outpamP->comment_p        = NULL;
+    outpamP->plainformat      = false;
+
+    if (verbose)
+        reportPlans(fileCt, outpamP);
+}
+
+
+
+static void
+copyBitrow(const unsigned char * const source,
+           unsigned char *       const destBitrow,
+           unsigned int          const cols,
+           unsigned int          const offset) {
+/*----------------------------------------------------------------------------
+  Copy from source to destBitrow, without shifting.  Preserve
+  surrounding image data.
+-----------------------------------------------------------------------------*/
+    unsigned char * const dest = & destBitrow[ offset/8 ];
+        /* Copy destination, with leading full bytes ignored. */
+    unsigned int const rs = offset % 8;
+        /* The "little offset", as measured from start of dest.  Source
+           is already shifted by this value.
+        */
+    unsigned int const trs = (cols + rs) % 8;
+        /* The number of partial bits in the final char. */
+    unsigned int const colByteCnt = pbm_packed_bytes(cols + rs);
+        /* # bytes to process, including partial ones on both ends. */
+    unsigned int const last = colByteCnt - 1;
+
+    unsigned char const origHead = dest[0];
+    unsigned char const origEnd  = dest[last];
+
+    unsigned int i;
+
+    assert(colByteCnt >= 1);
+
+    for (i = 0; i < colByteCnt; ++i)
+        dest[i] = source[i];
+
+    if (rs > 0)
+        dest[0] = LEFTBITS(origHead, rs) | RIGHTBITS(dest[0], 8-rs);
+
+    if (trs > 0)
+        dest[last] = LEFTBITS(dest[last], trs) | RIGHTBITS(origEnd, 8-trs);
+}
+
+
+
+static void
+padFillBitrow(unsigned char * const destBitrow,
+              unsigned char   const padColor,
+              unsigned int    const cols,
+              unsigned int    const offset) {
+/*----------------------------------------------------------------------------
+   Fill destBitrow, starting at offset, with padColor.  padColor is a
+   byte -- 0x00 or 0xff -- not a single bit.
+-----------------------------------------------------------------------------*/
+    unsigned char * const dest = &destBitrow[offset/8];
+    unsigned int const rs = offset % 8;
+    unsigned int const trs = (cols + rs) % 8;
+    unsigned int const colByteCnt = pbm_packed_bytes(cols + rs);
+    unsigned int const last = colByteCnt - 1;
+
+    unsigned char const origHead = dest[0];
+    unsigned char const origEnd  = dest[last];
+
+    unsigned int i;
+
+    assert(colByteCnt > 0);
+
+    for (i = 0; i < colByteCnt; ++i)
+        dest[i] = padColor;
+
+    if (rs > 0)
+        dest[0] = LEFTBITS(origHead, rs) | RIGHTBITS(dest[0], 8-rs);
+
+    if (trs > 0)
+        dest[last] = LEFTBITS(dest[last], trs) | RIGHTBITS(origEnd, 8-trs);
+}
+
+
+
+/* concatenateLeftRightPbm() and concatenateLeftRightGen()
+   employ almost identical algorithms.
+   The difference is in the data types and functions.
+
+   Same for concatenateTopBottomPbm() and concatenateTopBottomGen().
+*/
+
+
+typedef struct {
+    /* Information about one image */
+    unsigned char * proberow;
+        /* Top row of image, when background color is
+           auto-determined.
+        */
+    unsigned int offset;
+        /* start position of image, in bits, counting from left
+           edge
+        */
+    unsigned char background;
+        /* Background color.  0x00 means white; 0xff means black */
+    unsigned int padtop;
+        /* Top padding amount */
+} LrImgCtlPbm;
+
+
+
+static void
+createLrImgCtlPbm(const struct pam *  const inpam,  /* array */
+                  unsigned int        const fileCt,
+                  unsigned int        const outHeight,
+                  enum Justification  const justification,
+                  enum PadColorMethod const padColorMethod,
+                  LrImgCtlPbm **      const imgCtlP) {
+/*----------------------------------------------------------------------------
+   Read the first row of each image in inpam[] and return that and additional
+   information about images as *imgCtlP.
+-----------------------------------------------------------------------------*/
+    LrImgCtlPbm * imgCtl;  /* array, size 'fileCt' */
+    unsigned int fileSeq;
+
+    MALLOCARRAY_NOFAIL(imgCtl, fileCt);
+
+    for (fileSeq = 0; fileSeq < fileCt; ++fileSeq) {
+        LrImgCtlPbm *      const imgCtlP = &imgCtl[fileSeq];
+        const struct pam * const inpamP  = &inpam[fileSeq];
+
+        switch (justification) {
+        case JUST_MIN:
+            imgCtlP->padtop = 0;
+            break;
+        case JUST_MAX:
+            imgCtlP->padtop = outHeight - inpam[fileSeq].height;
+            break;
+        case JUST_CENTER:
+            imgCtlP->padtop = (outHeight - inpamP->height) / 2;
+            break;
+        }
+
+        imgCtlP->offset =
+            (fileSeq == 0) ?
+                0 : imgCtl[fileSeq-1].offset + inpam[fileSeq-1].width;
+
+        if (inpamP->height == outHeight)  /* no padding */
+            imgCtlP->proberow = NULL;
+        else {                   /* determine pad color for image i */
+            switch (padColorMethod) {
+            case PAD_AUTO: {
+                bit bgBit;
+                imgCtlP->proberow =
+                    pbm_allocrow_packed((unsigned int)inpamP->width + 7);
+                pbm_readpbmrow_bitoffset(
+                    inpamP->file, imgCtlP->proberow,
+                    inpamP->width, inpamP->format, imgCtlP->offset % 8);
+
+                bgBit = pbm_backgroundbitrow(
+                    imgCtlP->proberow, inpamP->width,
+                    imgCtlP->offset % 8);
+
+                imgCtlP->background = bgBit == PBM_BLACK ? 0xff : 0x00;
+            } break;
+            case PAD_BLACK:
+                imgCtlP->proberow   = NULL;
+                imgCtlP->background = 0xff;
+                break;
+            case PAD_WHITE:
+                imgCtlP->proberow   = NULL;
+                imgCtlP->background = 0x00;
+                break;
+            }
+        }
+    }
+    *imgCtlP = imgCtl;
+}
+
+
+
+static void
+destroyPbmImgCtl(LrImgCtlPbm * const imgCtl,  /* array */
+                 unsigned int  const fileCt) {
+
+    unsigned int i;
+
+    for (i = 0; i < fileCt; ++i) {
+        if (imgCtl[i].proberow)
+            free(imgCtl[i].proberow);
+    }
+    free(imgCtl);
+}
+
+
+
+static void
+concatenateLeftRightPbm(struct pam *        const outpamP,
+                        const struct pam *  const inpam,  /* array */
+                        unsigned int        const fileCt,
+                        enum Justification  const justification,
+                        enum PadColorMethod const padColorMethod) {
+
+    unsigned char * const outrow = pbm_allocrow_packed(outpamP->width);
+        /* We use just one outrow.  All padding and image data (with the
+           exception of following imgCtl.proberow) goes directly into this
+           packed PBM row.
+        */
+
+    LrImgCtlPbm * imgCtl;
+        /* malloc'ed array, one element per image.  Shadows inpam[] */
+    unsigned int row;
+
+    createLrImgCtlPbm(inpam, fileCt, outpamP->height,
+                      justification, padColorMethod,
+                      &imgCtl);
+
+    outrow[pbm_packed_bytes(outpamP->width)-1] = 0x00;
+
+    for (row = 0; row < outpamP->height; ++row) {
+        unsigned int fileSeq;
+
+        for (fileSeq = 0; fileSeq < fileCt; ++fileSeq) {
+            const LrImgCtlPbm * const imgCtlP = &imgCtl[fileSeq];
+            const struct pam *  const inpamP  = &inpam[fileSeq];
+
+            if ((row == 0 && imgCtlP->padtop > 0) ||
+                row == imgCtlP->padtop + inpamP->height) {
+
+                /* This row begins a run of padding, either above or below
+                   file 'i', so set 'outrow' to padding.
+                */
+                padFillBitrow(outrow, imgCtlP->background, inpamP->width,
+                              imgCtlP->offset);
+            }
+
+            if (row == imgCtlP->padtop && imgCtlP->proberow != NULL) {
+                /* Top row has been read to proberow[] to determine
+                   background.  Copy it to outrow[].
+                */
+                copyBitrow(imgCtlP->proberow, outrow,
+                           inpamP->width, imgCtlP->offset);
+            } else if (row >= imgCtlP->padtop &&
+                       row < imgCtlP->padtop + inpamP->height) {
+                pbm_readpbmrow_bitoffset(
+                    inpamP->file, outrow, inpamP->width, inpamP->format,
+                    imgCtlP->offset);
+            } else {
+                /* It's a row of padding, so outrow[] is already set
+                   appropriately.
+                */
+            }
+        }
+        pbm_writepbmrow_packed(outpamP->file, outrow, outpamP->width, 0);
+    }
+
+    destroyPbmImgCtl(imgCtl, fileCt);
+
+    pbm_freerow_packed(outrow);
+}
+
+
+
+static void
+concatenateTopBottomPbm(const struct pam *  const outpamP,
+                        const struct pam *  const inpam,  /* array */
+                        unsigned int        const fileCt,
+                        enum Justification  const justification,
+                        enum PadColorMethod const padColorMethod) {
+
+    unsigned char * const outrow = pbm_allocrow_packed(outpamP->width);
+        /* Like the left-right PBM case, all padding and image data
+           goes directly into outrow.  There is no proberow.
+        */
+    unsigned char background, backgroundPrev;
+        /* 0x00 means white; 0xff means black */
+    unsigned int  padleft;
+    bool          backChange;
+        /* Background color is different from that of the previous
+           input image.
+        */
+
+    unsigned int fileSeq;
+    unsigned int row, startRow;
+
+    outrow[pbm_packed_bytes(outpamP->width)-1] = 0x00;
+
+    switch (padColorMethod){
+    case PAD_AUTO:   /* do nothing */    break;
+    case PAD_BLACK:  background = 0xff;  break;
+    case PAD_WHITE:  background = 0x00;  break;
+    }
+
+    for (fileSeq = 0; fileSeq < fileCt; ++fileSeq) {
+        const struct pam * const inpamP = &inpam[fileSeq];
+
+        if (inpamP->width == outpamP->width) {
+            /* No padding */
+            startRow   = 0;
+            backChange = FALSE;
+            padleft    = 0;
+            outrow[pbm_packed_bytes(outpamP->width)-1] = 0x00;
+        } else {
+            /* Determine amount of padding and color */
+            switch (justification) {
+            case JUST_MIN:
+                padleft = 0;
+                break;
+            case JUST_MAX:
+                padleft = outpamP->width - inpamP->width;
+                break;
+            case JUST_CENTER:
+                padleft = (outpamP->width - inpamP->width) / 2;
+                break;
+            }
+
+            switch (padColorMethod) {
+            case PAD_AUTO: {
+                bit bgBit;
+
+                startRow = 1;
+
+                pbm_readpbmrow_bitoffset(
+                    inpamP->file, outrow, inpamP->width, inpamP->format,
+                    padleft);
+
+                bgBit = pbm_backgroundbitrow(outrow, inpamP->width, padleft);
+                background = bgBit == PBM_BLACK ? 0xff : 0x00;
+
+                backChange = (fileSeq == 0 || background != backgroundPrev);
+            } break;
+            case PAD_WHITE:
+            case PAD_BLACK:
+                startRow = 0;
+                backChange = (fileSeq == 0);
+                break;
+            }
+
+            if (backChange ||
+                (fileSeq > 0 && inpam[fileSeq-1].width > inpamP->width)) {
+                unsigned int const padright =
+                    outpamP->width - padleft - inpamP->width;
+
+                if (padleft > 0)
+                    padFillBitrow(outrow, background, padleft, 0);
+
+                if (padright > 0)
+                    padFillBitrow(outrow, background, padright,
+                                  padleft + inpamP->width);
+
+            }
+        }
+
+        if (startRow == 1)
+            /* Top row already read for auto background color
+               determination.  Write it out.
+            */
+            pbm_writepbmrow_packed(outpamP->file, outrow, outpamP->width, 0);
+
+        for (row = startRow; row < inpamP->height; ++row) {
+            pbm_readpbmrow_bitoffset(inpamP->file, outrow, inpamP->width,
+                                     inpamP->format, padleft);
+            pbm_writepbmrow_packed(outpamP->file, outrow, outpamP->width, 0);
+        }
+
+        backgroundPrev = background;
+    }
+    pbm_freerow_packed(outrow);
+}
+
+
+
+static void
+padPlanesRow(const struct pam *  const inpamP,
+             tuple *             const outrow,
+             const struct pam *  const outpamP) {
+/*----------------------------------------------------------------------------
+  Rearrange the planes of *outrow as needed to transform them into tuples
+  as described by *outpamP from tuples as described by *inpamP.
+-----------------------------------------------------------------------------*/
+    TtTransform const ttTransform = ttXformForImg(inpamP, outpamP);
+
+    assert(inpamP->allocation_depth >= outpamP->depth);
+
+    if (ttTransform.mustPromoteOpacity) {
+        unsigned int col;
+
+        assert(outpamP->depth >= PAM_TRN_PLANE);
+
+        for (col = 0; col < inpamP->width; ++col) {
+            outrow[col][outpamP->opacity_plane] =
+                outrow[col][inpamP->opacity_plane];
+        }
+    }
+    if (ttTransform.mustPromoteColor) {
+        unsigned int col;
+
+        assert(outpamP->depth >= PAM_GRN_PLANE);
+        assert(outpamP->depth >= PAM_BLU_PLANE);
+
+        for (col = 0; col < inpamP->width; ++col) {
+            assert(PAM_RED_PLANE == 0);
+            outrow[col][PAM_GRN_PLANE] = outrow[col][0];
+            outrow[col][PAM_BLU_PLANE] = outrow[col][0];
+        }
+    }
+
+    if (ttTransform.mustCreateOpacity) {
+        unsigned int col;
+
+        for (col = 0; col < inpamP->width; ++col)
+            outrow[col][outpamP->opacity_plane] = outpamP->maxval;
+    }
+
+    if (ttTransform.mustPadZero) {
+        unsigned int plane;
+
+        for (plane = inpamP->depth; plane < outpamP->depth; ++plane) {
+            unsigned int col;
+
+            for (col = 0; col < inpamP->width; ++col)
+                outrow[col][plane] = 0;
+        }
+    }
+}
+
+
+
+typedef struct {
+/*----------------------------------------------------------------------------
+   Parameters and state for placing a row of a particular input image in
+   the output in a left-right concatenation.
+-----------------------------------------------------------------------------*/
+    tuple *      cachedRow;
+        /* Contents of the current row of the image, with depth and maxval
+           adjusted for output, in malloc'ed space belonging to this object.
+           Input file is positioned past this row.  Null if data not present
+           and input file is positioned to the current row.
+        */
+    tuple *      out;
+        /* Point in output row buffer where the row from this image goes */
+    tuple        background;
+    unsigned int padtop;
+        /* Number of rows of padding that go above this image in the output */
+} LrImgCtl;
+
+
+
+static void
+createLrImgCtlArray(const struct pam *  const inpam,  /* array */
+                    unsigned int        const fileCt,
+                    tuple *             const newTuplerow,
+                    const struct pam *  const outpamP,
+                    enum Justification  const justification,
+                    enum PadColorMethod const padColorMethod,
+                    LrImgCtl **         const imgCtlP) {
+
+    LrImgCtl * imgCtl;  /* array */
+    unsigned int fileSeq;
+
+    MALLOCARRAY_NOFAIL(imgCtl, fileCt);
+
+    for (fileSeq = 0; fileSeq < fileCt; ++fileSeq) {
+        LrImgCtl *         const thisEntryP = &imgCtl[fileSeq];
+        const struct pam * const inpamP     = &inpam[fileSeq];
+
+        switch (justification) {  /* Determine top padding */
+            case JUST_MIN:
+                thisEntryP->padtop = 0;
+                break;
+            case JUST_MAX:
+                thisEntryP->padtop = outpamP->height - inpamP->height;
+                break;
+            case JUST_CENTER:
+                thisEntryP->padtop = (outpamP->height - inpamP->height) / 2;
+                break;
+        }
+
+        thisEntryP->out =
+            (fileSeq == 0 ?
+             &newTuplerow[0] : imgCtl[fileSeq-1].out + inpam[fileSeq-1].width);
+
+        if (inpamP->height == outpamP->height) { /* no vertical padding */
+            thisEntryP->cachedRow  = NULL;
+            pnm_createBlackTuple(outpamP, &thisEntryP->background);
+                /* Meaningless because no padding */
+        } else {
+            /* Determine pad color */
+            switch (padColorMethod){
+            case PAD_AUTO:
+                thisEntryP->cachedRow = pnm_allocpamrow(inpamP);
+                pnm_readpamrow(inpamP, thisEntryP->cachedRow);
+                pnm_scaletuplerow(inpamP, thisEntryP->cachedRow,
+                                  thisEntryP->cachedRow, outpamP->maxval);
+                padPlanesRow(inpamP, thisEntryP->cachedRow, outpamP);
+                {
+                    struct pam cachedRowPam;
+                    cachedRowPam = *outpamP;
+                    cachedRowPam.width = inpamP->width;
+                    thisEntryP->background = pnm_backgroundtuplerow(
+                        &cachedRowPam, thisEntryP->cachedRow);
+                }
+                break;
+            case PAD_BLACK:
+                thisEntryP->cachedRow = NULL;
+                pnm_createBlackTuple(outpamP, &thisEntryP->background);
+                break;
+            case PAD_WHITE:
+                thisEntryP->cachedRow = NULL;
+                pnm_createWhiteTuple(outpamP, &thisEntryP->background);
+                break;
+            }
+        }
+        if (outpamP->visual) {
+            /* Any opacity sample in background color tuple is meaningless at
+               this point; make it opaque.
+            */
+            if (outpamP->have_opacity) {
+                thisEntryP->background[outpamP->opacity_plane] =
+                    outpamP->maxval;
+            }
+        }
+
+    }
+    *imgCtlP = imgCtl;
+}
+
+
+
+static void
+destroyLrImgCtlArray(LrImgCtl *   const imgCtl,  /* array */
+                     unsigned int const fileCt) {
+
+    unsigned int fileSeq;
+
+    for (fileSeq = 0; fileSeq < fileCt; ++fileSeq) {
+        LrImgCtl * const thisEntryP = &imgCtl[fileSeq];
+
+        pnm_freepamtuple(thisEntryP->background);
+        pnm_freepamrow(thisEntryP->cachedRow);
+    }
+
+    free(imgCtl);
+}
+
+
+
+static void
+concatenateLeftRightGen(const struct pam *  const outpamP,
+                        const struct pam *  const inpam,  /* array */
+                        unsigned int        const fileCt,
+                        enum Justification  const justification,
+                        enum PadColorMethod const padColorMethod) {
+
+    tuple * const outrow = pnm_allocpamrow(outpamP);
+
+    LrImgCtl *   imgCtl;
+    unsigned int row;
+
+    createLrImgCtlArray(inpam, fileCt, outrow, outpamP,
+                        justification, padColorMethod,
+                        &imgCtl);
+
+    for (row = 0; row < outpamP->height; ++row) {
+        unsigned int fileSeq;
+
+        for (fileSeq = 0; fileSeq < fileCt; ++fileSeq) {
+            LrImgCtl *   const thisEntryP   = &imgCtl[fileSeq];
+            const struct pam * const inpamP = &inpam[fileSeq];
+
+            if ((row == 0 && thisEntryP->padtop > 0) ||
+                row == thisEntryP->padtop + inpamP->height) {
+                /* This row begins a run of padding, either above or below
+                   image 'fileSeq', so set its part of outrow[] to padding.
+                */
+                unsigned int col;
+                for (col = 0; col < inpamP->width; ++col) {
+                    pnm_assigntuple(outpamP, thisEntryP->out[col],
+                                    thisEntryP->background);
+                }
+            }
+            if (row == thisEntryP->padtop && thisEntryP->cachedRow) {
+                /* We're at the top row of image 'fileSeq', and that row
+                   has already been read to cachedRow[] to determine
+                   background.  Copy it to image fileseq's part of outrow[].
+                */
+                unsigned int col;
+                for (col = 0; col < inpamP->width; ++col) {
+                    pnm_assigntuple(outpamP, thisEntryP->out[col],
+                                    thisEntryP->cachedRow[col]);
+                }
+                free(thisEntryP->cachedRow);
+                thisEntryP->cachedRow = NULL;
+            } else if (row >= thisEntryP->padtop &&
+                       row < thisEntryP->padtop + inpamP->height) {
+                pnm_readpamrow(inpamP, thisEntryP->out);
+                pnm_scaletuplerow(inpamP, thisEntryP->out,
+                                  thisEntryP->out, outpamP->maxval);
+                padPlanesRow(inpamP, thisEntryP->out, outpamP);
+            } else {
+                /* It's a row of padding, so image filesSeq's part of outrow[]
+                   is already set appropriately.
+                */
+            }
+        }
+        /* Note that imgCtl[N].out[] is an alias to part of outrow[], so
+           outrow[] has been set.
+        */
+        pnm_writepamrow(outpamP, outrow);
+    }
+    destroyLrImgCtlArray(imgCtl, fileCt);
+
+    pnm_freepamrow(outrow);
+}
+
+
+
+static tuple
+initialBackgroundColor(const struct pam *  const outpamP,
+                       enum PadColorMethod const padColorMethod) {
+
+    tuple retval;
+
+    switch (padColorMethod) {
+    case PAD_AUTO:
+        /* Background is different for each input image */
+        retval = pnm_allocpamtuple(outpamP);
+            /* Dummy value; just need something to free */
+        break;
+    case PAD_BLACK:
+        pnm_createBlackTuple(outpamP, &retval);
+        break;
+    case PAD_WHITE:
+        pnm_createWhiteTuple(outpamP, &retval);
+        break;
+    }
+
+    if (outpamP->visual) {
+        /* Any opacity sample in background color tuple is meaningless at this
+           point; make it opaque.
+        */
+        if (outpamP->have_opacity)
+            retval[outpamP->opacity_plane] = outpamP->maxval;
+    }
+
+    return retval;
+}
+
+
+
+static unsigned int
+leftPadAmount(const struct pam * const outpamP,
+              const struct pam * const inpamP,
+              enum Justification const justification) {
+
+    switch (justification) {
+    case JUST_MIN:    return 0;
+    case JUST_MAX:    return outpamP->width - inpamP->width;
+    case JUST_CENTER: return (outpamP->width - inpamP->width) / 2;
+    }
+    assert(false);
+}
+
+
+
+static void
+setHorizPadding(tuple *            const newTuplerow,
+                const struct pam * const outpamP,
+                bool               const backChanged,
+                const struct pam * const inpam,  /* array */
+                unsigned int       const imageSeq,
+                unsigned int       const padLeft,
+                tuple              const background) {
+/*----------------------------------------------------------------------------
+   Set the left and right padding for an output row in a top-bottom
+   concatenation.
+
+   'newTuplerow' is where we set the padding (and also assumed to hold the
+   contents of the previous output row).  *outpamP describes it.
+
+   'backChanged' means the background color is different for the current row
+   from that of the previous row.
+
+   inpam[] is the array of descriptors for all the input images.  'imageSeq'
+   is the index into this array for the current image.
+
+   'background' is the background color to set.
+-----------------------------------------------------------------------------*/
+    if (backChanged ||
+        (imageSeq > 0 && inpam[imageSeq-1].width > inpam[imageSeq].width)) {
+        unsigned int col;
+
+        for (col = 0; col < padLeft; ++col)
+            pnm_assigntuple(outpamP, newTuplerow[col], background);
+        for (col = padLeft + inpam[imageSeq].width;
+             col < outpamP->width;
+             ++col) {
+            pnm_assigntuple(outpamP, newTuplerow[col], background);
+        }
+    } else {
+        /* No need to pad because newTuplerow[] already contains the
+           correct padding from the previous row.
+        */
+    }
+}
+
+
+
+static void
+readFirstTBRowAndDetermineBackground(const struct pam *  const inpamP,
+                                     const struct pam *  const outpamP,
+                                     tuple *             const out,
+                                     tuple *             const backgroundP) {
+/*----------------------------------------------------------------------------
+   Read the first row of an input image into 'out', adjusting it to conform
+   to the output depth and maxval described by *outpamP.
+
+   The image is positioned to the first row at entry.
+
+   From this row, determine the background color for the input image and
+   return it as *backgroundP (a newly malloced tuple).
+-----------------------------------------------------------------------------*/
+    pnm_readpamrow(inpamP, out);
+
+    pnm_scaletuplerow(inpamP, out, out, outpamP->maxval);
+
+    padPlanesRow(inpamP, out, outpamP);
+
+    {
+        struct pam partialOutpam;
+            /* Descriptor for the input image with depth and maxval adjusted to
+               that of the output image.
+            */
+        tuple background;
+
+        partialOutpam = *outpamP;
+        partialOutpam.width = inpamP->width;
+
+        background = pnm_backgroundtuplerow(&partialOutpam, out);
+
+        if (outpamP->visual) {
+            /* Make the background opaque. */
+            if (outpamP->have_opacity)
+                background[outpamP->opacity_plane] = outpamP->maxval;
+        }
+
+        *backgroundP = background;
+    }
+}
+
+
+
+static void
+concatenateTopBottomGen(const struct pam *  const outpamP,
+                        const struct pam *  const inpam,  /* array */
+                        unsigned int        const fileCt,
+                        enum Justification  const justification,
+                        enum PadColorMethod const padColorMethod) {
+
+    tuple * const newTuplerow = pnm_allocpamrow(outpamP);
+    tuple * out;
+        /* The location in newTuplerow[] that the row from the current
+           input image goes.
+        */
+    unsigned int fileSeq;
+    tuple background;
+    tuple backgroundPrev;
+
+    background = initialBackgroundColor(outpamP, padColorMethod);
+
+    for (fileSeq = 0; fileSeq < fileCt; ++fileSeq) {
+        const struct pam * const inpamP = &inpam[fileSeq];
+
+        unsigned int row;
+        unsigned int startRow;
+        bool backChanged;
+            /* The background color is different from that of the previous
+               input image.
+            */
+
+        if (inpamP->width == outpamP->width) {
+            /* no padding */
+            startRow = 0;
+            backChanged = false;
+            out = &newTuplerow[0];
+        } else {
+            unsigned int const padLeft =
+                leftPadAmount(outpamP, inpamP, justification);
+
+            if (padColorMethod == PAD_AUTO) {
+                out = &newTuplerow[padLeft];
+                backgroundPrev = background;
+                readFirstTBRowAndDetermineBackground(
+                    inpamP, outpamP, out, &background);
+
+                backChanged =
+                    fileSeq == 0 ||
+                        pnm_tupleequal(outpamP, background, backgroundPrev);
+                pnm_freepamtuple(backgroundPrev);
+
+                startRow = 1;
+            } else {
+                /* Background color is constant: black or white */
+                startRow = 0;
+                out = &newTuplerow[padLeft];
+                backChanged = (fileSeq == 0);
+            }
+
+            setHorizPadding(newTuplerow, outpamP, backChanged, inpam, fileSeq,
+                            padLeft, background);
+        }
+
+        if (startRow == 1)
+            /* Top row was already read for auto background color
+               determination.  Write it out.
+            */
+            pnm_writepamrow(outpamP, newTuplerow);
+
+        for (row = startRow; row < inpamP->height; ++row) {
+            pnm_readpamrow(inpamP, out);
+
+            pnm_scaletuplerow(inpamP, out, out, outpamP->maxval);
+
+            padPlanesRow(inpamP, out, outpamP);
+
+            pnm_writepamrow(outpamP, newTuplerow);
+        }
+    }
+    pnm_freepamtuple(background);
+    pnm_freepamrow(newTuplerow);
+}
+
+
+
+int
+main(int           argc,
+     const char ** argv) {
+
+    struct CmdlineInfo cmdline;
+    const char ** inputFileNm;
+    unsigned int inputFileCt;
+    struct pam * inpam;  /* malloc'ed array */
+    struct pam outpam;
+    unsigned int i;
+
+    pm_proginit(&argc, argv);
+
+    parseCommandLine(argc, argv, &cmdline);
+
+    createInFileList(cmdline, !!cmdline.verbose, &inputFileNm, &inputFileCt);
+
+    MALLOCARRAY_NOFAIL(inpam, inputFileCt);
+
+    for (i = 0; i < inputFileCt; ++i) {
+        FILE *  ifP;
+        ifP = pm_openr(inputFileNm[i]);
+        inpam[i].comment_p = NULL;  /* Don't want to see the comments */
+        pnm_readpaminit(ifP, &inpam[i], PAM_STRUCT_SIZE(opacity_plane));
+    }
+
+    computeOutputParms(inputFileCt, cmdline.orientation, inpam,
+                       cmdline.verbose, &outpam);
+
+    outpam.file = stdout;
+
+    for (i = 0; i < inputFileCt; ++i)
+        pnm_setminallocationdepth(&inpam[i], outpam.depth);
+
+    pnm_writepaminit(&outpam);
+
+    if (outpam.format == RPBM_FORMAT) {
+        switch (cmdline.orientation) {
+        case LEFTRIGHT:
+            concatenateLeftRightPbm(&outpam, inpam, inputFileCt,
+                                    cmdline.justification,
+                                    cmdline.padColorMethod);
+            break;
+        case TOPBOTTOM:
+            concatenateTopBottomPbm(&outpam, inpam, inputFileCt,
+                                    cmdline.justification,
+                                    cmdline.padColorMethod);
+            break;
+        }
+    } else {
+        switch (cmdline.orientation) {
+        case LEFTRIGHT:
+            concatenateLeftRightGen(&outpam, inpam, inputFileCt,
+                                    cmdline.justification,
+                                    cmdline.padColorMethod);
+            break;
+        case TOPBOTTOM:
+            concatenateTopBottomGen(&outpam, inpam, inputFileCt,
+                                    cmdline.justification,
+                                    cmdline.padColorMethod);
+            break;
+        }
+    }
+    for (i = 0; i < inputFileCt; ++i)
+        pm_close(inpam[i].file);
+    free(inpam);
+    freeInFileList(inputFileNm, inputFileCt);
+    freeCmdLine(cmdline);
+    pm_close(stdout);
+
+    return 0;
+}
+
+
+
diff --git a/editor/pamcut.c b/editor/pamcut.c
index 1fc9d9b2..b6190098 100644
--- a/editor/pamcut.c
+++ b/editor/pamcut.c
@@ -74,6 +74,7 @@ struct CmdlineInfo {
     unsigned int heightSpec;
     unsigned int height;
     unsigned int pad;
+    unsigned int reportonly;
     unsigned int verbose;
 };
 
@@ -185,6 +186,8 @@ parseCommandLine(int argc, const char ** const argv,
     OPTENT3(0,   "height",     OPT_UINT,   &cmdlineP->height,
             &cmdlineP->heightSpec,      0);
     OPTENT3(0,   "pad",        OPT_FLAG,   NULL, &cmdlineP->pad,           0);
+    OPTENT3(0,   "reportonly", OPT_FLAG,   NULL,
+            &cmdlineP->reportonly, 0);
     OPTENT3(0,   "verbose",    OPT_FLAG,   NULL, &cmdlineP->verbose,       0);
 
     opt.opt_table = option_def;
@@ -318,6 +321,55 @@ near(Location     const loc,
 
 
 static void
+computeCutBoundsOneDim(unsigned int const origSz,
+                       Location     const nearArg,
+                       Location     const farArg,
+                       bool         const dimSpec,
+                       unsigned int const dimArg,
+                       int *        const nearLocP,
+                       int *        const farLocP) {
+/*----------------------------------------------------------------------------
+   Do one dimension (vertical or horizontal) of the function of
+   'computeCutBounds'.
+-----------------------------------------------------------------------------*/
+    if (dimSpec)
+        assert(dimArg > 0);
+
+    if (nearArg.locType == LOCTYPE_NONE) {
+        if (farArg.locType == LOCTYPE_NONE) {
+            *nearLocP = 0;
+            if (dimSpec)
+                *farLocP = 0 + (int)dimArg - 1;
+            else
+                *farLocP = (int)origSz - 1;
+        } else {
+            *farLocP = near(farArg, origSz);
+            if (dimSpec)
+                *nearLocP = near(farArg, origSz) - (int)dimArg + 1;
+            else
+                *nearLocP = 0;
+        }
+    } else {
+        *nearLocP = near(nearArg, origSz);
+        if (farArg.locType == LOCTYPE_NONE) {
+            if (dimSpec)
+                *farLocP = near(nearArg, origSz) + (int)dimArg - 1;
+            else
+                *farLocP = (int)origSz - 1;
+        } else {
+            if (dimSpec) {
+                pm_error("You may not specify left, right, and width "
+                         "or top, bottom, and height.  "
+                         "Choose at most two of each of these sets.");
+            } else
+                *farLocP = near(farArg, origSz);
+        }
+    }
+}
+
+
+
+static void
 computeCutBounds(unsigned int const cols,
                  unsigned int const rows,
                  Location     const leftArg,
@@ -341,75 +393,11 @@ computeCutBounds(unsigned int const cols,
    *botrowP.  Any of these can be outside the image, including by being
    negative.
 -----------------------------------------------------------------------------*/
-    /* Find left and right bounds */
+    computeCutBoundsOneDim(cols, leftArg, rghtArg, widthSpec,  widthArg,
+                           leftColP, rghtColP);
 
-    if (widthSpec)
-        assert(widthArg > 0);
-
-    if (leftArg.locType == LOCTYPE_NONE) {
-        if (rghtArg.locType == LOCTYPE_NONE) {
-            *leftColP = 0;
-            if (widthSpec)
-                *rghtColP = 0 + (int)widthArg - 1;
-            else
-                *rghtColP = (int)cols - 1;
-        } else {
-            *rghtColP = near(rghtArg, cols);
-            if (widthSpec)
-                *leftColP = near(rghtArg, cols) - (int)widthArg + 1;
-            else
-                *leftColP = 0;
-        }
-    } else {
-        *leftColP = near(leftArg, cols);
-        if (rghtArg.locType == LOCTYPE_NONE) {
-            if (widthSpec)
-                *rghtColP = near(leftArg, cols) + (int)widthArg - 1;
-            else
-                *rghtColP = (int)cols - 1;
-        } else {
-            if (widthSpec) {
-                pm_error("You may not specify left, right, and width.  "
-                         "Choose at most two of these.");
-            } else
-                *rghtColP = near(rghtArg, cols);
-        }
-    }
-
-    /* Find top and bottom bounds */
-
-    if (heightSpec)
-        assert(heightArg > 0);
-
-    if (topArg.locType == LOCTYPE_NONE) {
-        if (botArg.locType == LOCTYPE_NONE) {
-            *topRowP = 0;
-            if (heightSpec)
-                *botRowP = 0 + (int)heightArg - 1;
-            else
-                *botRowP = (int)rows - 1;
-        } else {
-            *botRowP = near(botArg, rows);
-            if (heightSpec)
-                *topRowP = near(botArg, rows) - (int)heightArg + 1;
-            else
-                *topRowP = 0;
-        }
-    } else {
-        *topRowP = near(topArg, rows);
-        if (botArg.locType == LOCTYPE_NONE) {
-            if (heightSpec)
-                *botRowP = near(topArg, rows) + (int)heightArg - 1;
-            else
-                *botRowP = (int)rows - 1;
-        } else {
-            if (heightSpec) {
-                pm_error("You may not specify top, bottom, and height.  "
-                         "Choose at most two of these.");
-            } else
-                *botRowP = near(botArg, rows);
-        }
-    }
+    computeCutBoundsOneDim(rows, topArg,  botArg,  heightSpec, heightArg,
+                           topRowP,  botRowP);
 }
 
 
@@ -466,6 +454,46 @@ rejectOutOfBounds(unsigned int const cols,
 
 
 static void
+reportCuts(int          const leftCol,
+           int          const rghtCol,
+           int          const topRow,
+           int          const botRow,
+           unsigned int const oldWidth,
+           unsigned int const oldHeight) {
+
+    /* N.B. column and row numbers can be outside the input image, even
+       negative, which implies padding is required.
+    */
+
+    unsigned int const newWidth  = rghtCol - leftCol + 1;
+    unsigned int const newHeight = botRow  - topRow  + 1;
+
+    assert (rghtCol >= leftCol);
+    assert (botRow  >= topRow );
+
+    printf("%d %d %d %d %u %u %u %u\n",
+           leftCol, rghtCol, topRow, botRow,
+           oldWidth, oldHeight, newWidth, newHeight);
+}
+
+
+
+static void
+drainRaster(const struct pam * const inpamP) {
+/*----------------------------------------------------------------------------
+   Read through the input image described by *inpamP, which is positioned
+   to the raster, so the input stream is properly positioned for whatever
+   is next.
+-----------------------------------------------------------------------------*/
+    unsigned int row;
+
+    for (row = 0; row < inpamP->height; ++row)
+        pnm_readpamrow(inpamP, NULL);
+}
+
+
+
+static void
 writeBlackRows(const struct pam * const outpamP,
                int                const rows) {
 /*----------------------------------------------------------------------------
@@ -495,7 +523,7 @@ writeBlackRows(const struct pam * const outpamP,
 
 
 
-struct rowCutter {
+typedef struct {
 /*----------------------------------------------------------------------------
    This is an object that gives you pointers you can use to effect the
    horizontal cutting and padding of a row just by doing one
@@ -537,7 +565,7 @@ struct rowCutter {
     tuple * copyTuples;
     tuple blackTuple;
     tuple discardTuple;
-};
+} RowCutter;
 
 
 
@@ -554,13 +582,13 @@ struct rowCutter {
 
 
 static void
-createRowCutter(const struct pam *  const inpamP,
-                const struct pam *  const outpamP,
-                int                 const leftcol,
-                int                 const rightcol,
-                struct rowCutter ** const rowCutterPP) {
+createRowCutter(const struct pam * const inpamP,
+                const struct pam * const outpamP,
+                int                const leftcol,
+                int                const rightcol,
+                RowCutter **       const rowCutterPP) {
 
-    struct rowCutter * rowCutterP;
+    RowCutter * rowCutterP;
     tuple * inputPointers;
     tuple * outputPointers;
     tuple * copyTuples;
@@ -624,7 +652,7 @@ createRowCutter(const struct pam *  const inpamP,
 
 
 static void
-destroyRowCutter(struct rowCutter * const rowCutterP) {
+destroyRowCutter(RowCutter * const rowCutterP) {
 
     pnm_freepamrow(rowCutterP->copyTuples);
     pnm_freepamtuple(rowCutterP->blackTuple);
@@ -645,12 +673,12 @@ extractRowsGen(const struct pam * const inpamP,
                int                const toprow,
                int                const bottomrow) {
 
-    struct rowCutter * rowCutterP;
+    RowCutter * rowCutterP;
     int row;
 
     /* Write out top padding */
-    if (0 - toprow > 0)
-        writeBlackRows(outpamP, 0 - toprow);
+    if (toprow < 0)
+        writeBlackRows(outpamP, MIN(0, bottomrow+1) - toprow);
 
     createRowCutter(inpamP, outpamP, leftcol, rightcol, &rowCutterP);
 
@@ -671,14 +699,15 @@ extractRowsGen(const struct pam * const inpamP,
     destroyRowCutter(rowCutterP);
 
     /* Write out bottom padding */
-    if ((bottomrow - (inpamP->height-1)) > 0)
-        writeBlackRows(outpamP, bottomrow - (inpamP->height-1));
+    if (bottomrow >= inpamP->height)
+        writeBlackRows(outpamP, bottomrow - MAX(inpamP->height, toprow) + 1);
+
 }
 
 
 
 static void
-makeBlackPBMRow(unsigned char * const bitrow,
+makeBlackPbmRow(unsigned char * const bitrow,
                 unsigned int    const cols) {
 
     unsigned int const colByteCnt = pbm_packed_bytes(cols);
@@ -695,14 +724,14 @@ makeBlackPBMRow(unsigned char * const bitrow,
 
 
 static void
-extractRowsPBM(const struct pam * const inpamP,
+extractRowsPbm(const struct pam * const inpamP,
                const struct pam * const outpamP,
                int                const leftcol,
                int                const rightcol,
                int                const toprow,
                int                const bottomrow) {
 
-    unsigned char * bitrow;
+    unsigned char * bitrow;   /* read/write buffer */
     int             readOffset, writeOffset;
     int             row;
     unsigned int    totalWidth;
@@ -712,7 +741,7 @@ extractRowsPBM(const struct pam * const inpamP,
 
     if (leftcol > 0) {
         totalWidth = MAX(rightcol+1, inpamP->width) + 7;
-        if (totalWidth > INT_MAX)
+        if (totalWidth > INT_MAX - 10)
             /* Prevent overflows in pbm_allocrow_packed() */
             pm_error("Specified right edge is too far "
                      "from the right end of input image");
@@ -721,7 +750,7 @@ extractRowsPBM(const struct pam * const inpamP,
         writeOffset = leftcol;
     } else {
         totalWidth = -leftcol + MAX(rightcol+1, inpamP->width);
-        if (totalWidth > INT_MAX)
+        if (totalWidth > INT_MAX - 10)
             pm_error("Specified left/right edge is too far "
                      "from the left/right end of input image");
 
@@ -730,17 +759,16 @@ extractRowsPBM(const struct pam * const inpamP,
     }
 
     bitrow = pbm_allocrow_packed(totalWidth);
+      /* Initialize row buffer to all black for top and side padding */
 
-    if (toprow < 0 || leftcol < 0 || rightcol >= inpamP->width){
-        makeBlackPBMRow(bitrow, totalWidth);
-        if (toprow < 0) {
-            int row;
-            for (row=0; row < 0 - toprow; ++row)
-                pbm_writepbmrow_packed(outpamP->file, bitrow,
-                                       outpamP->width, 0);
-        }
+    /* Write out top padding */
+    if (toprow < 0) {
+        makeBlackPbmRow(bitrow, outpamP->width);
+        for (row = toprow; row < MIN(0, bottomrow+1); ++row)
+            pbm_writepbmrow_packed(outpamP->file, bitrow, outpamP->width, 0);
     }
 
+    makeBlackPbmRow(bitrow, totalWidth);
     for (row = 0; row < inpamP->height; ++row){
         if (row >= toprow && row <= bottomrow) {
             pbm_readpbmrow_bitoffset(inpamP->file, bitrow, inpamP->width,
@@ -757,12 +785,13 @@ extractRowsPBM(const struct pam * const inpamP,
             pnm_readpamrow(inpamP, NULL);    /* read and discard */
     }
 
-    if (bottomrow - (inpamP->height-1) > 0) {
-        int row;
-        makeBlackPBMRow(bitrow, outpamP->width);
-        for (row = 0; row < bottomrow - (inpamP->height-1); ++row)
-            pbm_writepbmrow_packed(outpamP->file, bitrow, outpamP->width, 0);
+    /* Write out bottom padding */
+    if (bottomrow >= inpamP->height) {
+        makeBlackPbmRow(bitrow, outpamP->width);
+        for (row = MAX(inpamP->height, toprow); row < bottomrow+1; ++row)
+             pbm_writepbmrow_packed(outpamP->file, bitrow, outpamP->width, 0);
     }
+
     pbm_freerow_packed(bitrow);
 }
 
@@ -797,23 +826,31 @@ cutOneImage(FILE *             const ifP,
                    toprow, leftcol, bottomrow, rightcol);
     }
 
-    outpam = inpam;    /* Initial value -- most fields should be same */
-    outpam.file   = ofP;
-    outpam.width  = rightcol - leftcol + 1;
-    outpam.height = bottomrow - toprow + 1;
-
-    pnm_writepaminit(&outpam);
-
-    if (PNM_FORMAT_TYPE(outpam.format) == PBM_TYPE)
-        extractRowsPBM(&inpam, &outpam, leftcol, rightcol, toprow, bottomrow);
-    else
-        extractRowsGen(&inpam, &outpam, leftcol, rightcol, toprow, bottomrow);
+    if (cmdline.reportonly) {
+        reportCuts(leftcol, rightcol, toprow, bottomrow,
+                   inpam.width, inpam.height);
+        drainRaster(&inpam);
+    } else {
+        outpam = inpam;    /* Initial value -- most fields should be same */
+        outpam.file   = ofP;
+        outpam.width  = rightcol - leftcol + 1;
+        outpam.height = bottomrow - toprow + 1;
+
+        pnm_writepaminit(&outpam);
+
+        if (PNM_FORMAT_TYPE(outpam.format) == PBM_TYPE)
+            extractRowsPbm(&inpam, &outpam,
+                           leftcol, rightcol, toprow, bottomrow);
+        else
+            extractRowsGen(&inpam, &outpam,
+                           leftcol, rightcol, toprow, bottomrow);
+    }
 }
 
 
 
 int
-main(int argc, const char *argv[]) {
+main(int argc, const char ** const argv) {
 
     FILE * const ofP = stdout;
 
@@ -838,3 +875,5 @@ main(int argc, const char *argv[]) {
 
     return 0;
 }
+
+
diff --git a/editor/pamdice.c b/editor/pamdice.c
index 9063c4bd..58e24e5b 100644
--- a/editor/pamdice.c
+++ b/editor/pamdice.c
@@ -227,12 +227,14 @@ computeOutputFilenameFormat(int           const format,
 
     const char * filenameSuffix;
 
-    switch(PNM_FORMAT_TYPE(format)) {
+    switch(PAM_FORMAT_TYPE(format)) {
     case PPM_TYPE: filenameSuffix = "ppm"; break;
     case PGM_TYPE: filenameSuffix = "pgm"; break;
     case PBM_TYPE: filenameSuffix = "pbm"; break;
     case PAM_TYPE: filenameSuffix = "pam"; break;
-    default:       filenameSuffix = "";    break;
+    default:
+        pm_error("INTERNAL ERROR: impossible value for libnetpbm image "
+                 "fomat code: %d", format);
     }
 
     pm_asprintf(filenameFormatP, "%%s_%%0%uu_%%0%uu.%s",
diff --git a/editor/pamditherbw.c b/editor/pamditherbw.c
index ae91a26f..4de14b43 100644
--- a/editor/pamditherbw.c
+++ b/editor/pamditherbw.c
@@ -14,32 +14,34 @@
 #include <string.h>
 
 #include "pm_c_util.h"
-#include "pam.h"
-#include "dithers.h"
+#include "rand.h"
 #include "mallocvar.h"
 #include "shhopt.h"
+#include "pam.h"
+#include "dithers.h"
 #include "pm_gamma.h"
 
-enum halftone {QT_FS,
+
+enum Halftone {QT_FS,
                QT_ATKINSON,
                QT_THRESH,
                QT_DITHER8,
                QT_CLUSTER,
                QT_HILBERT};
 
-enum ditherType {DT_REGULAR, DT_CLUSTER};
+enum DitherType {DT_REGULAR, DT_CLUSTER};
 
 static sample blackSample = (sample) PAM_BLACK;
 static sample whiteSample = (sample) PAM_BW_WHITE;
 static tuple  const blackTuple = &blackSample;
 static tuple  const whiteTuple = &whiteSample;
 
-struct cmdlineInfo {
+struct CmdlineInfo {
     /* All the information the user supplied in the command line,
        in a form easy for the program to use.
     */
-    const char *  inputFilespec;
-    enum halftone halftone;
+    const char *  inputFileNm;
+    enum Halftone halftone;
     unsigned int  clumpSize;
         /* Defined only for halftone == QT_HILBERT */
     unsigned int  clusterRadius;
@@ -53,13 +55,13 @@ struct cmdlineInfo {
 
 
 static void
-parseCommandLine(int argc, char ** argv,
-                 struct cmdlineInfo *cmdlineP) {
+parseCommandLine(int argc, const char ** const argv,
+                 struct CmdlineInfo * const cmdlineP) {
 /*----------------------------------------------------------------------------
    Note that the file spec array we return is stored in the storage that
    was passed to us as the argv array.
 -----------------------------------------------------------------------------*/
-    optEntry *option_def;
+    optEntry * option_def;
         /* Instructions to pm_optParseOptions3 on how to parse our options.
          */
     optStruct3 opt;
@@ -96,7 +98,7 @@ parseCommandLine(int argc, char ** argv,
     opt.short_allowed = FALSE;  /* We have no short (old-fashioned) options */
     opt.allowNegNum = FALSE;  /* We may have parms that are negative numbers */
 
-    pm_optParseOptions3(&argc, argv, opt, sizeof(opt), 0);
+    pm_optParseOptions3(&argc, (char **)argv, opt, sizeof(opt), 0);
         /* Uses and sets argc, argv, and some of *cmdlineP and others. */
 
     free(option_def);
@@ -158,9 +160,9 @@ parseCommandLine(int argc, char ** argv,
                  "non-option argument:  the file name",
                  argc-1);
     else if (argc-1 == 1)
-        cmdlineP->inputFilespec = argv[1];
+        cmdlineP->inputFileNm = argv[1];
     else
-        cmdlineP->inputFilespec = "-";
+        cmdlineP->inputFileNm = "-";
 }
 
 
@@ -171,15 +173,15 @@ makeOutputPam(unsigned int const width,
 
     struct pam outpam;
 
-    outpam.size = sizeof(outpam);
-    outpam.len = PAM_STRUCT_SIZE(tuple_type);
-    outpam.file = stdout;
-    outpam.format = PAM_FORMAT;
-    outpam.plainformat = 0;
-    outpam.height = height;
-    outpam.width = width;
-    outpam.depth = 1;
-    outpam.maxval = 1;
+    outpam.size             = sizeof(outpam);
+    outpam.len              = PAM_STRUCT_SIZE(tuple_type);
+    outpam.file             = stdout;
+    outpam.format           = PAM_FORMAT;
+    outpam.plainformat      = 0;
+    outpam.height           = height;
+    outpam.width            = width;
+    outpam.depth            = 1;
+    outpam.maxval           = 1;
     outpam.bytes_per_sample = 1;
     strcpy(outpam.tuple_type, "BLACKANDWHITE");
 
@@ -469,12 +471,12 @@ doHilbert(FILE *       const ifP,
 
 
 
-struct converter {
-    void (*convertRow)(struct converter * const converterP,
+struct Converter {
+    void (*convertRow)(struct Converter * const converterP,
                        unsigned int       const row,
                        tuplen                   grayrow[],
                        tuple                    bitrow[]);
-    void (*destroy)(struct converter * const converterP);
+    void (*destroy)(struct Converter * const converterP);
     unsigned int cols;
     void * stateP;
 };
@@ -503,7 +505,7 @@ struct fsState {
 
 
 static void
-fsConvertRow(struct converter * const converterP,
+fsConvertRow(struct Converter * const converterP,
              unsigned int       const row,
              tuplen                   grayrow[],
              tuple                    bitrow[]) {
@@ -574,7 +576,7 @@ fsConvertRow(struct converter * const converterP,
 
 
 static void
-fsDestroy(struct converter * const converterP) {
+fsDestroy(struct Converter * const converterP) {
 
     struct fsState * const stateP = converterP->stateP;
 
@@ -586,12 +588,14 @@ fsDestroy(struct converter * const converterP) {
 
 
 
-static struct converter
+static struct Converter
 createFsConverter(struct pam * const graypamP,
-                  float        const threshFraction) {
+                  float        const threshFraction,
+                  bool         const randomseedSpec,
+                  unsigned int const randomseed) {
 
     struct fsState * stateP;
-    struct converter converter;
+    struct Converter converter;
 
     converter.cols       = graypamP->width;
     converter.convertRow = &fsConvertRow;
@@ -605,9 +609,17 @@ createFsConverter(struct pam * const graypamP,
 
     {
         /* (random errors in [-1/8 .. 1/8]) */
+
         unsigned int col;
+        struct pm_randSt randSt;
+
+        pm_randinit(&randSt);
+        pm_srand2(&randSt, randomseedSpec, randomseed);
+
         for (col = 0; col < graypamP->width + 2; ++col)
-            stateP->thiserr[col] = ((float)rand()/RAND_MAX - 0.5) / 4;
+            stateP->thiserr[col] = (pm_drand(&randSt) - 0.5) / 4;
+
+        pm_randterm(&randSt);
     }
 
     stateP->halfWhite = threshFraction;
@@ -643,7 +655,7 @@ struct atkinsonState {
 
 
 static void
-moveAtkinsonErrorWindowDown(struct converter * const converterP) {
+moveAtkinsonErrorWindowDown(struct Converter * const converterP) {
 
     struct atkinsonState * const stateP = converterP->stateP;
 
@@ -664,7 +676,7 @@ moveAtkinsonErrorWindowDown(struct converter * const converterP) {
 
 
 static void
-atkinsonConvertRow(struct converter * const converterP,
+atkinsonConvertRow(struct Converter * const converterP,
                    unsigned int       const row,
                    tuplen                   grayrow[],
                    tuple                    bitrow[]) {
@@ -709,7 +721,7 @@ atkinsonConvertRow(struct converter * const converterP,
 
 
 static void
-atkinsonDestroy(struct converter * const converterP) {
+atkinsonDestroy(struct Converter * const converterP) {
 
     struct atkinsonState * const stateP = converterP->stateP;
 
@@ -723,12 +735,14 @@ atkinsonDestroy(struct converter * const converterP) {
 
 
 
-static struct converter
+static struct Converter
 createAtkinsonConverter(struct pam * const graypamP,
-                        float        const threshFraction) {
+                        float        const threshFraction,
+                        bool         const randomseedSpec,
+                        unsigned int const randomseed) {
 
     struct atkinsonState * stateP;
-    struct converter converter;
+    struct Converter converter;
     unsigned int relRow;
 
     converter.cols       = graypamP->width;
@@ -743,11 +757,18 @@ createAtkinsonConverter(struct pam * const graypamP,
     {
         /* (random errors in [-1/8 .. 1/8]) */
         unsigned int col;
+        struct pm_randSt randSt;
+
+        pm_randinit(&randSt);
+        pm_srand2(&randSt, randomseedSpec, randomseed);
+
         for (col = 0; col < graypamP->width + 2; ++col) {
-            stateP->error[0][col] = ((float)rand()/RAND_MAX - 0.5) / 4;
+            stateP->error[0][col] = (pm_drand(&randSt) - 0.5) / 4;
             stateP->error[1][col] = 0.0;
             stateP->error[2][col] = 0.0;
         }
+
+        pm_randterm(&randSt);
     }
 
     stateP->halfWhite = threshFraction;
@@ -766,7 +787,7 @@ struct threshState {
 
 
 static void
-threshConvertRow(struct converter * const converterP,
+threshConvertRow(struct Converter * const converterP,
                  unsigned int       const row,
                  tuplen                   grayrow[],
                  tuple                    bitrow[]) {
@@ -782,18 +803,18 @@ threshConvertRow(struct converter * const converterP,
 
 
 static void
-threshDestroy(struct converter * const converterP) {
+threshDestroy(struct Converter * const converterP) {
     free(converterP->stateP);
 }
 
 
 
-static struct converter
+static struct Converter
 createThreshConverter(struct pam * const graypamP,
                       float        const threshFraction) {
 
     struct threshState * stateP;
-    struct converter converter;
+    struct Converter converter;
 
     MALLOCVAR_NOFAIL(stateP);
 
@@ -817,7 +838,7 @@ struct clusterState {
 
 
 static void
-clusterConvertRow(struct converter * const converterP,
+clusterConvertRow(struct Converter * const converterP,
                   unsigned int       const row,
                   tuplen                   grayrow[],
                   tuple                    bitrow[]) {
@@ -838,7 +859,7 @@ clusterConvertRow(struct converter * const converterP,
 
 
 static void
-clusterDestroy(struct converter * const converterP) {
+clusterDestroy(struct Converter * const converterP) {
 
     struct clusterState * const stateP = converterP->stateP;
     unsigned int const diameter = 2 * stateP->radius;
@@ -855,9 +876,9 @@ clusterDestroy(struct converter * const converterP) {
 
 
 
-static struct converter
+static struct Converter
 createClusterConverter(struct pam *    const graypamP,
-                       enum ditherType const ditherType,
+                       enum DitherType const ditherType,
                        unsigned int    const radius) {
 
     /* TODO: We create a floating point normalized, gamma-adjusted
@@ -870,7 +891,7 @@ createClusterConverter(struct pam *    const graypamP,
     int const clusterNormalizer = radius * radius * 2;
     unsigned int const diameter = 2 * radius;
 
-    struct converter converter;
+    struct Converter converter;
     struct clusterState * stateP;
     unsigned int row;
 
@@ -925,23 +946,21 @@ createClusterConverter(struct pam *    const graypamP,
 
 
 int
-main(int argc, char *argv[]) {
+main(int argc, const char ** const argv) {
 
-    struct cmdlineInfo cmdline;
-    FILE* ifP;
+    struct CmdlineInfo cmdline;
+    FILE * ifP;
 
-    pgm_init(&argc, argv);
+    pm_proginit(&argc, argv);
 
     parseCommandLine(argc, argv, &cmdline);
 
-    srand(cmdline.randomseedSpec ? cmdline.randomseed : pm_randseed());
-
-    ifP = pm_openr(cmdline.inputFilespec);
+    ifP = pm_openr(cmdline.inputFileNm);
 
     if (cmdline.halftone == QT_HILBERT)
         doHilbert(ifP, cmdline.clumpSize);
     else {
-        struct converter converter;
+        struct Converter converter;
         struct pam graypam;
         struct pam bitpam;
         tuplen * grayrow;
@@ -956,10 +975,14 @@ main(int argc, char *argv[]) {
 
         switch (cmdline.halftone) {
         case QT_FS:
-            converter = createFsConverter(&graypam, cmdline.threshval);
+            converter = createFsConverter(&graypam, cmdline.threshval,
+                                          cmdline.randomseedSpec,
+                                          cmdline.randomseed);
             break;
         case QT_ATKINSON:
-            converter = createAtkinsonConverter(&graypam, cmdline.threshval);
+            converter = createAtkinsonConverter(&graypam, cmdline.threshval,
+                                                cmdline.randomseedSpec,
+                                                cmdline.randomseed);
             break;
         case QT_THRESH:
             converter = createThreshConverter(&graypam, cmdline.threshval);
@@ -999,3 +1022,6 @@ main(int argc, char *argv[]) {
 
     return 0;
 }
+
+
+
diff --git a/editor/pamedge.c b/editor/pamedge.c
index f4384535..ca742573 100644
--- a/editor/pamedge.c
+++ b/editor/pamedge.c
@@ -30,7 +30,7 @@ writeBlackRow(struct pam * const pamP) {
             tuplerow[col][plane] = 0;
     }
     pnm_writepamrow(pamP, tuplerow);
-} 
+}
 
 
 
@@ -92,12 +92,12 @@ computeOneRow(struct pam * const inpamP,
         orow[0][plane] = 0;
 
         for (col = 1; col < inpamP->width - 1; ++col) {
-            double const grad1 = 
+            double const grad1 =
                 1 * horizGradient(row0, col, plane) +
                 2 * horizGradient(row1, col, plane) +
                 1 * horizGradient(row2, col, plane);
 
-            double const grad2 = 
+            double const grad2 =
                 horizAvg(row2, col, plane) - horizAvg(row0, col, plane);
 
             double const gradient = sqrt(SQR(grad1) + SQR(grad2));
@@ -163,7 +163,7 @@ main(int argc, const char ** argv) {
 
     pm_proginit(&argc, argv);
 
-    if (argc-1 == 1) 
+    if (argc-1 == 1)
         ifP = pm_openr(argv[1]);
     else if (argc-1 == 0)
         ifP = stdin;
diff --git a/editor/pamenlarge.c b/editor/pamenlarge.c
index 56a8c6f7..eb3b6ba2 100644
--- a/editor/pamenlarge.c
+++ b/editor/pamenlarge.c
@@ -690,6 +690,7 @@ enlargePbm(struct pam * const inpamP,
         unsigned int const rightPadding =
             scaleMethod == METHOD_GENERAL ? 0 : (xScaleFactor - 1) * 8;
 
+        assert (outcols < UINT_MAX - rightPadding);
         outrow = pbm_allocrow_packed(outcols + rightPadding);
 
         if (scaleMethod == METHOD_GENERAL)
diff --git a/editor/pamhomography.c b/editor/pamhomography.c
new file mode 100644
index 00000000..02c0fd72
--- /dev/null
+++ b/editor/pamhomography.c
@@ -0,0 +1,799 @@
+/* ----------------------------------------------------------------------
+ *
+ * Map one quadrilateral to another
+ * by Scott Pakin <scott+pbm@pakin.org>
+ *
+ * ----------------------------------------------------------------------
+ *
+ * Copyright (C) 2020 Scott Pakin <scott+pbm@pakin.org>
+ *
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
+ * 3. The name of the author may not be used to endorse or promote products
+ *    derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR "AS IS" AND ANY EXPRESS OR
+ * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
+ * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
+ * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+ * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ * ----------------------------------------------------------------------
+ */
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <ctype.h>
+#include <errno.h>
+#include <math.h>
+#include "pm_c_util.h"
+#include "shhopt.h"
+#include "mallocvar.h"
+#include "pam.h"
+
+#define MIN4(A, B, C, D) MIN(MIN(A, B), MIN(C, D))
+#define MAX4(A, B, C, D) MAX(MAX(A, B), MAX(C, D))
+
+typedef struct {
+/*----------------------------------------------------------------------------
+  A point on the image plane.  It may or may not lie within the
+  bounds of the image itself.
+-----------------------------------------------------------------------------*/
+    int x;
+    int y;
+} Point;
+
+
+static Point
+pointXy(int const x,
+        int const y) {
+
+    Point retval;
+
+    retval.x = x;
+    retval.y = y;
+
+    return retval;
+}
+
+
+
+typedef struct {
+/*----------------------------------------------------------------------------
+  A quadrilateral on the image plane.
+-----------------------------------------------------------------------------*/
+    Point ul;
+    Point ur;
+    Point lr;
+    Point ll;
+} Quad;
+
+typedef struct {
+/*----------------------------------------------------------------------------
+  A specification of a quadrilateral on the image plane, either explicitly
+  or just as "the whole image".
+-----------------------------------------------------------------------------*/
+    bool wholeImage;
+    Quad explicit;  /* Meaningful only if 'wholeImage' is false */
+} QuadSpec;
+
+typedef struct {
+/*----------------------------------------------------------------------------
+   Specification of a mapping from one quadrilateral to another
+-----------------------------------------------------------------------------*/
+    QuadSpec from;
+    QuadSpec to;
+} QuadMap;
+
+struct CmdlineInfo {
+    /* All the information the user supplied in the command line,
+       in a form easy for the program to use.
+    */
+    const char * inputFilespec;  /* "-" if stdin */
+    QuadMap      qmap;
+        /* Source and target quadrilaterals as specified by -to and -from;
+           Note that the file identified by 'mapfile' also supplies such
+           information.
+        */
+    QuadSpec     view;
+        /* Bounding box for the target image */
+    const char * mapfile;        /* Null if not specified */
+    const char * fill;           /* Null if not specified */
+    unsigned int verbose;
+};
+
+
+
+static void
+parseCoords(const char *   const str,
+            int *          const coords,
+            unsigned int * const nP) {
+/*----------------------------------------------------------------------------
+  Parse a list of up to 16 integers.  Return as *nP how may there are.
+-----------------------------------------------------------------------------*/
+    const char * p;
+    char * pnext;
+    unsigned int i;
+
+    for (i = 0, p = str; i < 16; ++i, p = pnext) {
+        long int val;
+
+        /* Skip punctuation, except "+" and "-", and white space. */
+        while (*p != '\0' && *p != '+' && *p != '-' &&
+               (isspace(*p) || ispunct(*p)))
+            ++p;
+
+        /* Parse the next integer. */
+        errno = 0;  /* strtol() sets errno on error. */
+        val = strtol(p, &pnext, 10);
+        if (errno == ERANGE)
+            break;  /* Integer lies out of long int range */
+        if (errno != 0 || pnext == p)
+            break;  /* Too few integers */
+        coords[i] = (int)val;
+        if ((long int)coords[i] != val)
+            break;  /* Integer lies out of int range */
+    }
+    *nP = i;
+}
+
+
+
+static Quad
+quadFmViewString(const char * const str) {
+/*----------------------------------------------------------------------------
+  Parse a list of four integers in the order {ulx, uly, lrx, lry} into a
+  quadrilateral.
+
+  Abort the program if 'str' is not valid.
+-----------------------------------------------------------------------------*/
+    Quad retval;
+    int coords[16];
+    unsigned int nCoord;
+
+    parseCoords(str, coords, &nCoord);
+
+    if (nCoord != 4)
+        pm_error("failed to parse '%s' as a list of four integers", str);
+
+    retval.ul.x = retval.ll.x = coords[0];
+    retval.ul.y = retval.ur.y = coords[1];
+    retval.lr.x = retval.ur.x = coords[2];
+    retval.lr.y = retval.ll.y = coords[3];
+
+    return retval;
+}
+
+
+
+static Quad
+quadFmIntList(const int * const coords) {
+    Quad retval;
+
+    retval.ul.x = coords[0];
+    retval.ul.y = coords[1];
+    retval.ur.x = coords[2];
+    retval.ur.y = coords[3];
+    retval.lr.x = coords[4];
+    retval.lr.y = coords[5];
+    retval.ll.x = coords[6];
+    retval.ll.y = coords[7];
+
+    return retval;
+}
+
+
+
+static Quad
+quadFmString(const char * const str) {
+/*----------------------------------------------------------------------------
+  Parse a list of eight integers in the order {ulx, uly, urx, ury,
+  lrx, lry, llx, lly} into a quadrilateral.
+
+  Abort the program if 'str' is not a valid list of eight integers.
+-----------------------------------------------------------------------------*/
+    int coords[16];
+    unsigned int nCoord;
+
+    parseCoords(str, coords, &nCoord);
+
+    if (nCoord != 8)
+        pm_error("failed to parse '%s' as a list of eight integers", str);
+
+    return quadFmIntList(coords);
+}
+
+
+
+static void
+parseCommandLine(int                        argc,
+                 const char **        const argv,
+                 struct CmdlineInfo * const cmdlineP ) {
+/*----------------------------------------------------------------------------
+   Parse program command line described in Unix standard form by argc
+   and argv.  Return the information in the options as *cmdlineP.
+
+   If command line is internally inconsistent (invalid options, etc.),
+   issue error message to stderr and abort program.
+-----------------------------------------------------------------------------*/
+
+    optEntry *option_def;
+        /* Instructions to pm_optParseOptions3 on how to parse our options.
+         */
+    optStruct3 opt;
+
+    unsigned int option_def_index;
+
+    unsigned int mapfileSpec, fromSpec, toSpec, viewSpec, fillSpec;
+    const char * from;
+    const char * to;
+    const char * view;
+
+    MALLOCARRAY_NOFAIL(option_def, 100);
+
+    option_def_index = 0;   /* incremented by OPTENT3 */
+    OPTENT3(0, "mapfile",         OPT_STRING, &cmdlineP->mapfile,
+            &mapfileSpec,             0);
+    OPTENT3(0, "from",            OPT_STRING, &from,
+            &fromSpec,                0);
+    OPTENT3(0, "to",              OPT_STRING, &to,
+            &toSpec,                  0);
+    OPTENT3(0, "view",            OPT_STRING, &view,
+            &viewSpec,                0);
+    OPTENT3(0, "fill",            OPT_STRING, &cmdlineP->fill,
+            &fillSpec,                0);
+    OPTENT3(0, "verbose",         OPT_FLAG,   NULL,
+            &cmdlineP->verbose,       0);
+
+    opt.opt_table = option_def;
+    opt.short_allowed = FALSE;  /* We have no short (old-fashioned) options */
+    opt.allowNegNum = FALSE;  /* We have no parms that are negative numbers */
+
+    pm_optParseOptions3(&argc, (char **)argv, opt, sizeof(opt), 0);
+        /* Uses and sets argc, argv, and local variables. */
+
+    if (!fillSpec)
+        cmdlineP->fill = NULL;
+
+    if (!mapfileSpec)
+        cmdlineP->mapfile = NULL;
+
+    if (fromSpec) {
+        cmdlineP->qmap.from.wholeImage = false;
+        cmdlineP->qmap.from.explicit = quadFmString(from);
+    } else
+        cmdlineP->qmap.from.wholeImage = true;
+
+    if (toSpec) {
+        cmdlineP->qmap.to.wholeImage = false;
+        cmdlineP->qmap.to.explicit = quadFmString(to);
+    } else
+        cmdlineP->qmap.to.wholeImage = true;
+
+    if (viewSpec) {
+        cmdlineP->view.wholeImage = false;
+        cmdlineP->view.explicit   = quadFmViewString(view);
+    } else
+        cmdlineP->view.wholeImage = true;
+
+    if (argc < 2)
+        cmdlineP->inputFilespec = "-";
+    else if (argc == 2)
+        cmdlineP->inputFilespec = argv[1];
+    else
+        pm_error("Too many non-option arguments: %u.  "
+                 "Only possible argument is input file name", argc - 1);
+
+    free((void *) option_def);
+}
+
+
+
+static void
+readMapFile(const char * const fname,
+            QuadMap *    const qmapP) {
+/*----------------------------------------------------------------------------
+  Read from a file either 16 numbers in the order {ulx1, uly1, urx1, ury1,
+  lrx1, lry1, llx1, lly1, ulx2, uly2, urx2, ury2, lrx2, lry2, llx2, lly2}
+  or 8 numbers in the order {ulx2, uly2, urx2, ury2, lrx2, lry2, llx2,
+  lly2}.
+
+  Abort the program if the file does not contain data in this format.
+-----------------------------------------------------------------------------*/
+    FILE * fp;
+    char * str;      /* Entire file contents */
+    int coords[16];  /* File as a list of up to 16 coordinates */
+    unsigned int nCoord;
+    long int nread;
+
+    /* Read the entire file. */
+    fp = pm_openr(fname);
+    str = pm_read_unknown_size(fp, &nread);
+    REALLOCARRAY_NOFAIL(str, nread + 1);
+    str[nread] = '\0';
+    pm_close(fp);
+
+    {
+        unsigned int i;
+        /* Replace newlines and tabs with spaces to prettify error
+           reporting.
+        */
+        for (i = 0; str[i]; ++i)
+            if (isspace(str[i]))
+                str[i] = ' ';
+    }
+    parseCoords(str, coords, &nCoord);
+
+    /* Read either {from, to} or just a {to} quadrilateral. */
+    switch (nCoord) {
+    case 16:
+        /* 16 integers: assign both the "from" and the "to" quadrilateral. */
+        qmapP->from.wholeImage = false;
+        qmapP->from.explicit   = quadFmIntList(&coords[0]);
+        qmapP->to.wholeImage   = false;
+        qmapP->to.explicit     = quadFmIntList(&coords[8]);
+        break;
+    case 8:
+        /* 8 integers: assign only the "to" quadrilateral. */
+        qmapP->from.wholeImage = true;
+        qmapP->to.explicit     = quadFmIntList(coords);
+        break;
+    default:
+        /* Not valid input */
+        pm_error("failed to parse contents of map file '%s' ('%s') "
+                 "as a list of either 8 or 16 integers",
+                 fname, str);
+        break;
+    }
+
+    free(str);
+}
+
+
+
+static void
+reportQuads(Quad const qfrom,
+            Quad const qto) {
+
+    pm_message("Copying from ((%d,%d),(%d,%d),(%d,%d),(%d,%d)) "
+               "to ((%d,%d),(%d,%d),(%d,%d),(%d,%d))",
+               qfrom.ul.x, qfrom.ul.y,
+               qfrom.ur.x, qfrom.ur.y,
+               qfrom.lr.x, qfrom.lr.y,
+               qfrom.ll.x, qfrom.ll.y,
+               qto.ul.x,   qto.ul.y,
+               qto.ur.x,   qto.ur.y,
+               qto.lr.x,   qto.lr.y,
+               qto.ll.x,   qto.ll.y
+        );
+}
+
+
+
+static void
+reportBbox(Quad const bbox) {
+
+    pm_message("The bounding box is ((%d,%d),(%d,%d),(%d,%d),(%d,%d))",
+               bbox.ul.x, bbox.ul.y,
+               bbox.ur.x, bbox.ur.y,
+               bbox.lr.x, bbox.lr.y,
+               bbox.ll.x, bbox.ll.y
+        );
+}
+
+
+
+static tuple
+parseFillColor(const struct pam * const pamP,
+               const char *       const fillColorSpec) {
+/*----------------------------------------------------------------------------
+  Parse the fill color into the correct format for the given PAM metadata.
+-----------------------------------------------------------------------------*/
+    tuple retval;
+
+    if (!fillColorSpec)
+        pnm_createBlackTuple(pamP, &retval);
+    else {
+        tuple const rgb = pnm_parsecolor(fillColorSpec, pamP->maxval);
+
+        retval = pnm_allocpamtuple(pamP);
+
+        switch (pamP->depth) {
+        case 1:
+            /* Grayscale */
+            retval[0] = (rgb[PAM_RED_PLANE]*299 +
+                         rgb[PAM_GRN_PLANE]*587 +
+                         rgb[PAM_BLU_PLANE]*114)/1000;
+            break;
+        case 2:
+            /* Grayscale + alpha */
+            retval[0] = (rgb[PAM_RED_PLANE]*299 +
+                         rgb[PAM_GRN_PLANE]*587 +
+                         rgb[PAM_BLU_PLANE]*114)/1000;
+            retval[PAM_GRAY_TRN_PLANE] = pamP->maxval;
+            break;
+        case 3:
+            /* RGB */
+            pnm_assigntuple(pamP, retval, rgb);
+            break;
+        case 4:
+            /* RGB + alpha */
+            pnm_assigntuple(pamP, retval, rgb);
+            retval[PAM_TRN_PLANE] = pamP->maxval;
+            break;
+        default:
+            pm_error("unexpected image depth %d", pamP->depth);
+            break;
+        }
+    }
+    return retval;
+}
+
+
+
+static tuple **
+initOutputImage(const struct pam * const pamP,
+                const char *       const fillColorSpec) {
+/*----------------------------------------------------------------------------
+  Allocate and initialize the output image data structure.
+-----------------------------------------------------------------------------*/
+    tuple fillColor;    /* Fill color to use for unused coordinates */
+    tuple ** outImg;    /* Output image */
+    unsigned int row;
+
+    outImg = pnm_allocpamarray(pamP);
+
+    fillColor = parseFillColor(pamP, fillColorSpec);
+    for (row = 0; row < pamP->height; ++row) {
+        unsigned int col;
+
+        for (col = 0; col < pamP->width; ++col) {
+            pnm_assigntuple(pamP, outImg[row][col], fillColor);
+        }
+    }
+
+    free((void *) fillColor);
+    return outImg;
+}
+
+
+
+static void
+computeSteps(Quad     const qfrom,
+             Quad     const qto,
+             double * const ustepP,
+             double * const vstepP) {
+/*----------------------------------------------------------------------------
+  Compute increments for u and v as these range from 0.0 to 1.0.
+-----------------------------------------------------------------------------*/
+    double fx0, fx1, fxd;
+    double tx0, tx1, txd;
+    double fy0, fy1, fyd;
+    double ty0, ty1, tyd;
+
+    /* Compute ustep as the inverse of the maximum possible x delta across
+       either the "from" or "to" quadrilateral.
+    */
+    fx0 = MIN4((double)qfrom.ur.x,
+               (double)qfrom.ul.x,
+               (double)qfrom.lr.x,
+               (double)qfrom.ll.x);
+    fx1 = MAX4((double)qfrom.ur.x,
+               (double)qfrom.ul.x,
+               (double)qfrom.lr.x,
+               (double)qfrom.ll.x);
+    fxd = fx1 - fx0;
+
+    tx0 = MIN4((double)qto.ur.x,
+               (double)qto.ul.x,
+               (double)qto.lr.x,
+               (double)qto.ll.x);
+    tx1 = MAX4((double)qto.ur.x,
+               (double)qto.ul.x,
+               (double)qto.lr.x,
+               (double)qto.ll.x);
+    txd = tx1 - tx0;
+
+    if (fxd == 0.0 && txd == 0.0)
+        *ustepP = 1.0;  /* Arbitrary nonzero step */
+    else
+        *ustepP = 0.5/MAX(fxd, txd);
+            /* Divide into 0.5 instead of 1.0 for additional smoothing. */
+
+    /* Compute vstep as the inverse of the maximum possible y delta across
+       either the "from" or "to" quadrilateral.
+    */
+    fy0 = MIN4((double)qfrom.ur.y,
+               (double)qfrom.ul.y,
+               (double)qfrom.lr.y,
+               (double)qfrom.ll.y);
+    fy1 = MAX4((double)qfrom.ur.y,
+               (double)qfrom.ul.y,
+               (double)qfrom.lr.y,
+               (double)qfrom.ll.y);
+    fyd = fy1 - fy0;
+    ty0 = MIN4((double)qto.ur.y,
+               (double)qto.ul.y,
+               (double)qto.lr.y,
+               (double)qto.ll.y);
+    ty1 = MAX4((double)qto.ur.y,
+               (double)qto.ul.y,
+               (double)qto.lr.y,
+               (double)qto.ll.y);
+    tyd = ty1 - ty0;
+
+    if (fyd == 0.0 && tyd == 0.0)
+        *vstepP = 1.0;  /* Arbitrary nonzero step */
+    else
+        *vstepP = 0.5/MAX(fyd, tyd);
+            /* Divide into 0.5 instead of 1.0 for additional smoothing. */
+}
+
+
+
+static Quad
+quadrilateralFmSpec(const struct pam * const pamP,
+                    QuadSpec           const qdata) {
+/*----------------------------------------------------------------------------
+  The quadrilateral specified by 'qdata'.
+-----------------------------------------------------------------------------*/
+    Quad retval;
+
+    if (qdata.wholeImage) {
+        /* Set the quadrilateral to the image's bounding box. */
+        retval.ul = pointXy(0,               0               );
+        retval.ur = pointXy(pamP->width - 1, 0               );
+        retval.ll = pointXy(0,               pamP->height - 1);
+        retval.lr = pointXy(pamP->width - 1, pamP->height - 1);
+    } else {
+        /* Use the quadrilateral as specified. */
+        retval = qdata.explicit;
+    }
+
+    return retval;
+}
+
+
+
+static Point
+coordsAtPercent(Quad   const quad,
+                double const u,
+                double const v) {
+/*----------------------------------------------------------------------------
+  Return the (x, y) coordinates that lie at (u%, v%) from the upper left to
+  the lower right of a given quadrilateral.
+-----------------------------------------------------------------------------*/
+    return pointXy(
+        (int) nearbyint((1.0 - u) * (1.0 - v) * quad.ul.x +   /* x */
+                        u * (1.0 - v) * quad.ur.x +
+                        u * v * quad.lr.x +
+                        (1.0 - u) * v * quad.ll.x),
+        (int) nearbyint((1.0 - u) * (1.0 - v) * quad.ul.y +   /* y */
+                        u * (1.0 - v) * quad.ur.y +
+                        u * v * quad.lr.y +
+                        (1.0 - u) * v * quad.ll.y)
+        );
+}
+
+
+
+static Quad
+boundingBoxOfQuadrilateral(Quad const q) {
+/*----------------------------------------------------------------------------
+  The bounding box of quadrilateral 'q'.
+-----------------------------------------------------------------------------*/
+    Quad retval;
+
+    int const leftLimit = MIN4(q.ul.x, q.ur.x, q.lr.x, q.ll.x);
+    int const rghtLimit = MAX4(q.ul.x, q.ur.x, q.lr.x, q.ll.x);
+    int const topLimit  = MIN4(q.ul.y, q.ur.y, q.lr.y, q.ll.y);
+    int const botLimit  = MAX4(q.ul.y, q.ur.y, q.lr.y, q.ll.y);
+
+    retval.ul = pointXy(leftLimit, topLimit);
+    retval.ur = pointXy(rghtLimit, topLimit);
+    retval.ll = pointXy(leftLimit, botLimit);
+    retval.lr = pointXy(rghtLimit, botLimit);
+
+    return retval;
+}
+
+
+
+static void
+mapQuadrilaterals(const struct pam * const inPamP,
+                  const struct pam * const outPamP,
+                  Quad               const qfrom,
+                  Quad               const qto,
+                  tuple **           const inImg,
+                  tuple **           const outImg,
+                  int                const xofs,
+                  int                const yofs) {
+/*----------------------------------------------------------------------------
+  Map the quadrilateral in the source image to the quadrilateral in the
+  target image.  This is the function that implemens pamhomography's
+  primary functionality.
+-----------------------------------------------------------------------------*/
+    sample ** channel;
+        /* Aggregated values for a single channel */
+    unsigned long ** tally;
+        /* Number of values at each coordinate in the above */
+    double ustep, vstep;
+        /* Steps to use when iterating from 0.0 to 1.0 */
+    unsigned int plane;
+
+    MALLOCARRAY2_NOFAIL(channel, outPamP->height, outPamP->width);
+    MALLOCARRAY2_NOFAIL(tally,   outPamP->height, outPamP->width);
+
+    computeSteps(qfrom, qto, &ustep, &vstep);
+
+    for (plane = 0; plane < outPamP->depth; ++plane) {
+        /* Reset the channel colors and tally for each plane, */
+        unsigned int row;
+        double v;
+        for (row = 0; row < outPamP->height; ++row) {
+            unsigned int col;
+            for (col = 0; col < outPamP->width; ++col) {
+                channel[row][col] = 0;
+                tally  [row][col] = 0;
+            }
+        }
+        /* Iterate from 0% to 100% in the y dimension. */
+        for (v = 0.0; v <= 1.0; v += vstep) {
+            /* Iterate from 0% to 100% in the x dimension. */
+            double u;
+            for (u = 0.0; u <= 1.0; u += ustep) {
+                Point from;  /* "From" coordinate */
+                Point to;    /* "To" coordinate */
+
+                /* Map (u%, v%) of one quadrilateral to (u%, v%) of the other
+                   quadrilateral.
+                */
+                from = coordsAtPercent(qfrom, u, v);
+                to   = coordsAtPercent(qto,   u, v);
+
+                /* Copy the source image's 'from' pixel as the destination
+                   image's 'to' pixel in the current plane.
+                */
+                to.x += xofs;
+                to.y += yofs;
+                if (from.x >= 0 && from.y >= 0 &&
+                    from.x < inPamP->width && from.y < inPamP->height &&
+                    to.x >= 0 && to.y >= 0 &&
+                    to.x < outPamP->width && to.y < outPamP->height) {
+
+                    channel[to.y][to.x] += inImg[from.y][from.x][plane];
+                    ++tally[to.y][to.x];
+                }
+            }
+        }
+
+        /* Assign the current plane in the output image the average color
+           at each point. */
+        for (row = 0; row < outPamP->height; ++row) {
+            unsigned int col;
+            for (col = 0; col < outPamP->width; ++col) {
+                if (tally[row][col] != 0)
+                    outImg[row][col][plane] =
+                        (channel[row][col] + tally[row][col]/2) /
+                        tally[row][col];
+            }
+        }
+    }
+
+    pm_freearray2((void ** const)tally);
+    pm_freearray2((void ** const)channel);
+}
+
+
+
+static void
+processFile(FILE *       const ifP,
+            QuadMap      const qmap,
+            QuadSpec     const view,
+            const char * const fillColorSpec,
+            bool         const verbose) {
+/*----------------------------------------------------------------------------
+  Read the input image, create the output image, and map a quadrilateral in
+  the former to a quadrilateral in the latter.
+-----------------------------------------------------------------------------*/
+    struct pam inPam;    /* PAM metadata for the input file */
+    struct pam outPam;   /* PAM metadata for the output file */
+    tuple ** inImg;      /* Input image */
+    tuple ** outImg;     /* Output image */
+    Quad qfrom, qto;     /* Source and target quadrilaterals */
+    Quad bbox;           /* Bounding box around the transformed input image */
+
+    inImg = pnm_readpam(ifP, &inPam, PAM_STRUCT_SIZE(tuple_type));
+
+    /* Extract quadrilaterals and populate them with the image bounds
+       if necessary. */
+    qfrom = quadrilateralFmSpec(&inPam, qmap.from);
+    qto   = quadrilateralFmSpec(&inPam, qmap.to);
+
+    if (verbose)
+        reportQuads(qfrom, qto);
+
+    /* Allocate storage for the target image. */
+    if (view.wholeImage)
+        bbox = boundingBoxOfQuadrilateral(qto);
+    else
+        bbox = view.explicit;
+
+    if (verbose)
+        reportBbox(bbox);
+
+    outPam = inPam;  /* initial value */
+    outPam.file   = stdout;
+    outPam.width  = bbox.lr.x - bbox.ul.x + 1;
+    outPam.height = bbox.lr.y - bbox.ul.y + 1;
+    outImg        = initOutputImage(&outPam, fillColorSpec);
+
+    mapQuadrilaterals(&inPam, &outPam,
+                      qfrom, qto,
+                      inImg, outImg,
+                      -bbox.ul.x, -bbox.ul.y);
+
+    pnm_writepam(&outPam, outImg);
+
+    pnm_freepamarray(outImg, &outPam);
+    pnm_freepamarray(inImg, &inPam);
+}
+
+
+
+int
+main(int argc, const char *argv[]) {
+
+    struct CmdlineInfo cmdline;      /* Parsed command line */
+    FILE * ifP;
+    QuadMap qmap;
+
+    pm_proginit(&argc, argv);
+
+    parseCommandLine(argc, argv, &cmdline);
+
+    if (cmdline.mapfile) {
+        /* Use the from and/or to values from the map file where the user
+           didn't explicitly state them
+        */
+        QuadMap mapFileValue;
+
+        readMapFile(cmdline.mapfile, &mapFileValue);
+
+        if (cmdline.qmap.from.wholeImage)
+            qmap.from = mapFileValue.from;
+        else
+            qmap.from = cmdline.qmap.from;
+
+        if (cmdline.qmap.to.wholeImage)
+            qmap.to = mapFileValue.to;
+        else
+            qmap.to = cmdline.qmap.to;
+    } else
+        qmap = cmdline.qmap;
+
+    ifP = pm_openr(cmdline.inputFilespec);
+
+    processFile(ifP, qmap, cmdline.view, cmdline.fill, !!cmdline.verbose);
+
+    pm_close(ifP);
+
+    return 0;
+}
+
+
diff --git a/editor/pamlevels.c b/editor/pamlevels.c
index a282751a..de2afc45 100644
--- a/editor/pamlevels.c
+++ b/editor/pamlevels.c
@@ -5,7 +5,6 @@
 #include <stdlib.h>
 
 #include "netpbm/pam.h"
-#include "netpbm/pm_system.h"
 #include "netpbm/pm_gamma.h"
 #include "netpbm/nstring.h"
 #include "netpbm/ppm.h"
diff --git a/editor/pammasksharpen.c b/editor/pammasksharpen.c
index 6e34ab20..51bdedd9 100644
--- a/editor/pammasksharpen.c
+++ b/editor/pammasksharpen.c
@@ -7,8 +7,8 @@ struct cmdlineInfo {
     /* All the information the user supplied in the command line,
        in a form easy for the program to use.
     */
-    const char * inputFilespec;  
-    const char * maskFilespec;  
+    const char * inputFilespec;
+    const char * maskFilespec;
     unsigned int verbose;
     float        sharpness;
     float        threshold;
@@ -24,14 +24,14 @@ parseCommandLine(int argc, const char ** const argv,
    was passed to us as the argv array.
 -----------------------------------------------------------------------------*/
     optEntry *option_def;
-        /* Instructions to OptParseOptions2 on how to parse our options.
+        /* Instructions to OptParseOptions3 on how to parse our options.
          */
     optStruct3 opt;
 
     unsigned int option_def_index;
 
     unsigned int sharpSpec, thresholdSpec;
-    
+
     MALLOCARRAY_NOFAIL(option_def, 100);
 
     option_def_index = 0;   /* incremented by OPTENTRY */
@@ -75,13 +75,13 @@ parseCommandLine(int argc, const char ** const argv,
             cmdlineP->inputFilespec = "-";
         else {
             cmdlineP->inputFilespec = argv[2];
-        
+
             if (argc-1 > 2)
                 pm_error("There are at most two arguments:  mask file name "
                          "and input file name.  You specified %d", argc-1);
         }
     }
-}        
+}
 
 
 
@@ -98,7 +98,7 @@ sharpened(sample const inputSample,
 
     if (abs(edgeness) > threshold) {
         float const rawResult = inputSample + edgeness * sharpness;
-        
+
         retval = MIN(maxval, (unsigned)MAX(0, (int)(rawResult+0.5)));
     } else
         retval = inputSample;
@@ -125,9 +125,9 @@ main(int argc, const char * *argv) {
         /* Magnitude of difference between image and unsharp mask below
            which they will be considered identical.
         */
-    
+
     pm_proginit(&argc, argv);
-    
+
     parseCommandLine(argc, argv, &cmdline);
 
     ifP = pm_openr(cmdline.inputFilespec);
@@ -136,7 +136,7 @@ main(int argc, const char * *argv) {
     pnm_readpaminit(ifP, &inpam, PAM_STRUCT_SIZE(tuple_type));
     pnm_readpaminit(maskfP, &maskpam, PAM_STRUCT_SIZE(tuple_type));
 
-    if (inpam.width  != maskpam.width || 
+    if (inpam.width  != maskpam.width ||
         inpam.height != maskpam.height ||
         inpam.depth  != maskpam.depth)
         pm_error("The mask image must be the same dimensions as the "
@@ -165,10 +165,10 @@ main(int argc, const char * *argv) {
         unsigned int col;
         pnm_readpamrow(&inpam,   inputTuplerow);
         pnm_readpamrow(&maskpam, maskTuplerow);
-        
+
         for (col = 0; col < outpam.width; ++col) {
             unsigned int plane;
-            
+
             for (plane = 0; plane < outpam.depth; ++plane) {
                 outputTuplerow[col][plane] =
                     sharpened(inputTuplerow[col][plane],
@@ -187,6 +187,6 @@ main(int argc, const char * *argv) {
     pnm_freepamrow(inputTuplerow);
     pnm_freepamrow(maskTuplerow);
     pnm_freepamrow(outputTuplerow);
-    
+
     return 0;
 }
diff --git a/editor/pammixmulti.c b/editor/pammixmulti.c
index f5012d7a..27390ec6 100644
--- a/editor/pammixmulti.c
+++ b/editor/pammixmulti.c
@@ -13,6 +13,7 @@
 #include "shhopt.h"
 #include "mallocvar.h"
 #include "nstring.h"
+#include "rand.h"
 
 typedef enum {
     BLEND_AVERAGE,   /* Take the average color of all pixels */
@@ -36,6 +37,8 @@ struct ProgramState {
         /* Standard deviation when selecting images via a mask */
     unsigned long ** imageWeights;
         /* Per-image weights as a function of grayscale level */
+    struct pm_randSt randSt;
+        /* Random number generator parameters and internal state */
 };
 
 
@@ -134,9 +137,9 @@ parseCommandLine(int argc, const char ** argv,
 }
 
 static void
-openInputFiles(unsigned int          const inFileCt,
-               const char **         const inFileName,
-               struct ProgramState * const stateP) {
+initInput(unsigned int          const inFileCt,
+          const char **         const inFileName,
+          struct ProgramState * const stateP) {
 /*----------------------------------------------------------------------------
   Open all of the input files.
 
@@ -180,6 +183,25 @@ openInputFiles(unsigned int          const inFileCt,
 }
 
 
+
+static void
+termInput(struct ProgramState * const stateP) {
+/*----------------------------------------------------------------------------
+  Deallocate all of the resources we allocated.
+-----------------------------------------------------------------------------*/
+    unsigned int i;
+
+    for (i = 0; i < stateP->inFileCt; ++i) {
+        pnm_freepamrow(stateP->inTupleRows[i]);
+        pm_close(stateP->inPam[i].file);
+    }
+
+    free(stateP->inTupleRows);
+    free(stateP->inPam);
+}
+
+
+
 static void
 initMask(const char *          const maskFileName,
          struct ProgramState * const stateP) {
@@ -233,6 +255,15 @@ initOutput(FILE *                const ofP,
 }
 
 
+static void
+termOutput(struct ProgramState * const stateP) {
+
+    free(stateP->outTupleRow);
+
+    pm_close(stateP->outPam.file);
+}
+
+
 
 static void
 blendTuplesRandom(struct ProgramState * const stateP,
@@ -243,8 +274,8 @@ blendTuplesRandom(struct ProgramState * const stateP,
   from a random input image.
 -----------------------------------------------------------------------------*/
     unsigned int const depth = stateP->inPam[0].depth;
-    unsigned int const img = (unsigned int) (rand() % stateP->inFileCt);
-
+    unsigned int const img = (unsigned int) (pm_rand(&stateP->randSt) %
+                                             stateP->inFileCt);
     unsigned int samp;
 
     for (samp = 0; samp < depth; ++samp)
@@ -277,26 +308,6 @@ blendTuplesAverage(struct ProgramState * const stateP,
 
 
 static void
-randomNormal2(double * const r1P,
-              double * const r2P) {
-/*----------------------------------------------------------------------------
-  Return two normally distributed random numbers.
------------------------------------------------------------------------------*/
-    double u1, u2;
-
-    do {
-        u1 = drand48();
-        u2 = drand48();
-    }
-    while (u1 <= DBL_EPSILON);
-
-    *r1P = sqrt(-2.0*log(u1)) * cos(2.0*M_PI*u2);
-    *r2P = sqrt(-2.0*log(u1)) * sin(2.0*M_PI*u2);
-}
-
-
-
-static void
 precomputeImageWeights(struct ProgramState * const stateP,
                        double                const sigma) {
 /*----------------------------------------------------------------------------
@@ -332,7 +343,8 @@ precomputeImageWeights(struct ProgramState * const stateP,
             double r[2];
             unsigned int k;
 
-            randomNormal2(&r[0], &r[1]);
+            pm_gaussrand2(&stateP->randSt, &r[0], &r[1]);
+
             for (k = 0; k < 2; ++k) {
                 int const img =
                     r[k] * sigma + pctGray * stateP->inFileCt * 0.999999;
@@ -453,26 +465,6 @@ blendImages(BlendType             const blend,
 
 
 
-static void
-termState(struct ProgramState * const stateP) {
-/*----------------------------------------------------------------------------
-  Deallocate all of the resources we allocated.
------------------------------------------------------------------------------*/
-    unsigned int i;
-
-    for (i = 0; i < stateP->inFileCt; ++i) {
-        pnm_freepamrow(stateP->inTupleRows[i]);
-        pm_close(stateP->inPam[i].file);
-    }
-
-    free(stateP->outTupleRow);
-    free(stateP->inTupleRows);
-    free(stateP->inPam);
-    pm_close(stateP->outPam.file);
-}
-
-
-
 int
 main(int argc, const char * argv[]) {
 
@@ -483,13 +475,14 @@ main(int argc, const char * argv[]) {
 
     parseCommandLine(argc, argv, &cmdline);
 
-    srand(cmdline.randomseedSpec ? cmdline.randomseed : pm_randseed());
-
-    openInputFiles(cmdline.inFileNameCt, cmdline.inFileName, &state);
+    initInput(cmdline.inFileNameCt, cmdline.inFileName, &state);
 
     if (cmdline.blend == BLEND_MASK)
         initMask(cmdline.maskfile, &state);
 
+    pm_randinit(&state.randSt);
+    pm_srand2(&state.randSt, cmdline.randomseedSpec, cmdline.randomseed);
+
     initOutput(stdout, &state);
 
     if (cmdline.blend == BLEND_MASK)
@@ -497,10 +490,14 @@ main(int argc, const char * argv[]) {
 
     blendImages(cmdline.blend, &state);
 
+    termOutput(&state);
+
+    pm_randterm(&state.randSt);
+
     if (cmdline.blend == BLEND_MASK)
         termMask(&state);
 
-    termState(&state);
+    termInput(&state);
 
     freeCmdline(&cmdline);
 
@@ -510,34 +507,34 @@ main(int argc, const char * argv[]) {
 
 /*  COPYRIGHT LICENSE and WARRANTY DISCLAIMER
 
-Copyright (c) 2018 Scott Pakin
+Copyright (c) 2018-2023 Scott Pakin
 All rights reserved
 
 Redistribution and use in source and binary forms, with or without
-modification, are permitted (subject to the limitations in the disclaimer
-below) provided that the following conditions are met:
-
-  Redistributions of source code must retain the above copyright notice,
-  this list of conditions and the following disclaimer.
-
-  Redistributions in binary form must reproduce the above copyright notice,
-  this list of conditions and the following disclaimer in the documentation
-  and/or other materials provided with the distribution.
-
-  Neither the names of the oopyright owners nor the names of its contributors
-  may be used to endorse or promote products derived from this software
-  without specific prior written permission.
-
-  NO EXPRESS OR IMPLIED LICENSES TO ANY PARTY'S PATENT RIGHTS ARE GRANTED BY
-  THIS LICENSE. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
-  CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT
-  NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
-  PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
-  CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
-  EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
-  PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
-  OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
-  WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
-  OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
-  ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+modification, are permitted provided that the following conditions are
+met:
+
+1. Redistributions of source code must retain the above copyright
+   notice, this list of conditions and the following disclaimer.
+
+2. Redistributions in binary form must reproduce the above copyright
+   notice, this list of conditions and the following disclaimer in the
+   documentation and/or other materials provided with the
+   distribution.
+
+3. Neither the name of the copyright holder nor the names of its
+   contributors may be used to endorse or promote products derived
+   from this software without specific prior written permission.
+
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+“AS IS†AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */
diff --git a/editor/pamperspective.c b/editor/pamperspective.c
index a8b1cf8f..487025bc 100644
--- a/editor/pamperspective.c
+++ b/editor/pamperspective.c
@@ -154,7 +154,7 @@ typedef struct {
 
 
 /* The collection of properties that correspond to the four specified
-   vertices 
+   vertices
 */
 
 typedef struct {
@@ -172,18 +172,18 @@ typedef struct {
      center of projection, that is the pixel the camera "looks at".  It
      turned out, maybe surprisingly, that this does not have any
      effect. So now this center is moved to (0,0).
-     
+
      Another original plan was to correct the output parameters
      depending on the lengths of the paralellograms sides or its
      angles.  This is, however, not possible without knowing something
      like the camera angle or focal length (in pixels).
   */
-  
+
   /* The coefficients for the map from output to world coordinates.
 
      The actual mapping is
      u,v -> (ax+bx*u+cx*v, ay+by*u+cy*v, az+bz*u+cz*v)
-  */     
+  */
   number ax,bx,cx, ay,by,cy, az,bz,cz;
 
 } world_data;
@@ -331,7 +331,7 @@ parseFloat(const char * const text) {
     char * end;
     number num;
     char * buffer;
-    
+
     buffer = strdup(text);
     if (!buffer)
         pm_error("Out of memory");
@@ -432,7 +432,7 @@ static void parse_include_points(const char * const include_opt,
              sem_seek++);
 
         hit_end = (*sem_seek == '\0');
-            
+
         *sem_seek = '\0';
         parse_include_point(cursor, include_pointsP);
 
@@ -735,15 +735,15 @@ static void determine_world_parallelogram (world_data *const world,
                                            const option *const options)
 /*----------------------------------------------------------------------------
   Construct xw_ul,...,zw_lr from xi_ul,...,yi_lr
-     
+
   This is a solution of a linear equation system.
-  
+
   We first solve 4 equations for 4 variables (the 4 z-coordinates):
   Each z-coordinate determines the corresponding x- and y-coordinates
   in a linear fashion, where the coefficients are taken from the image
   coordinates.  This corresponds to the fact that a point of an image
   determines a line in the world.
-  
+
   3 equations state that the 4 points form a parallelogram.  The 4th
   equation is for normalization and states that the center of the
   parallelogram has a z-coordinate of 1.
@@ -948,7 +948,7 @@ static number norm_side (number const x1, number const y1, number const z1,
   This is similar to norm_vector. But now the norm of the derivative
   is computed at both endpoints of the movement and the maximum is
   returned.
-  
+
   Why do we do this? The return value n is in fact the maximum of the
   norm of the derivative ALONG the movement. So we know that if we
   divide the movement into at least n steps, we will encounter every
@@ -1022,7 +1022,7 @@ static void determine_coefficients_lattice (world_data *const world,
                                             const option *const options)
 /*----------------------------------------------------------------------------
   Constructs ax,...,cz from xw_ul,...,zw_lr
-     
+
   The calculations assume lattice coordinates, that is the point ul
   corresponds to the upper left corner of the pixel (0,0) and the
   point lr corresponds to the lower left corner of the pixel
@@ -1052,7 +1052,7 @@ static void determine_coefficients_pixel (world_data *const world,
                                           const option *const options)
 /*----------------------------------------------------------------------------
   Constructs ax,...,cz from xw_ul,...,zw_lr
-     
+
   The calculations assume pixel coordinates, that is the point ul
   corresponds to the center of the pixel (0,0) and the point lr
   corresponds to the center of the pixel (width-1,height-1)
@@ -1086,7 +1086,7 @@ static void determine_coefficients_pixel (world_data *const world,
 
 static void
 outpixelToInPos(int                const outCol,
-                int                const outRow, 
+                int                const outRow,
                 number *           const inColP,
                 number *           const inRowP,
                 const world_data * const worldP) {
@@ -1149,7 +1149,7 @@ boundedRow(int                const unboundedRow,
    It doesn't work because the actual image generation produces rows
    in the middle that are derived from lines in the input quadrilateral
    with greater slope than either the top or bottom edge.  I.e. to
-   compute one output row, it needs more rows of input than this 
+   compute one output row, it needs more rows of input than this
    calculation provides.
 
    I don't know if that means the computation of the output is wrong
@@ -1162,7 +1162,7 @@ boundedRow(int                const unboundedRow,
 
    - Bryan Henderson 08.07.27.
 */
-   
+
 
 static unsigned int
 windowHeight(const world_data * const worldP,
@@ -1177,7 +1177,7 @@ windowHeight(const world_data * const worldP,
     yur = outpixelToInRow(outpamP->width-1, 0, worldP);
     yll = outpixelToInRow(0, outpamP->height-1, worldP);
     ylr = outpixelToInRow(outpamP->width-1, outpamP->height-1, worldP);
-    
+
     y_min = MIN(MIN(yul, yur), MIN(yll, ylr));
     numRows = MAX(MAX(diff(yul, yur),
                       diff(yll, ylr)),
@@ -1210,7 +1210,7 @@ windowHeight(const world_data * const worldP,
 
     unsigned int outRow;
     unsigned int maxRowWindowHeight;
-    
+
     maxRowWindowHeight = 1;  /* initial value */
 
     for (outRow = 0; outRow < outpamP->height; ++outRow) {
@@ -1220,12 +1220,12 @@ windowHeight(const world_data * const worldP,
             boundedRow(outpixelToInRow(leftCol, outRow, worldP), outpamP);
         unsigned int const rghtInRow =
             boundedRow(outpixelToInRow(rghtCol, outRow, worldP), outpamP);
-        
+
         unsigned int const rowWindowHeight = distance(leftInRow, rghtInRow);
 
         maxRowWindowHeight = MAX(maxRowWindowHeight, rowWindowHeight);
     }
-    
+
     /* We add 2 for rounding */
 
     return maxRowWindowHeight + 2;
@@ -1297,7 +1297,7 @@ buffer_getRow(buffer *     const bufferP,
     n = bufferP->nextImageRow - imageRow;
 
     assert(n <= bufferP->numRows);
-    
+
     if (n <= bufferP->nextBufferRow)
         bufferRow = bufferP->nextBufferRow - n;
     else
@@ -1328,7 +1328,7 @@ buffer_term(buffer * const bufferP) {
 
     for (i = 0; i < bufferP->numRows; ++i)
         pnm_freepamrow(bufferP->rows[i]);
-    
+
     free(bufferP->rows);
 }
 
@@ -1412,7 +1412,7 @@ takeNearest(tuple  const dest,
 
 
 static void
-linearInterpolation(tuple  const dest, 
+linearInterpolation(tuple  const dest,
                     number const x,
                     number const y) {
 
diff --git a/editor/pamrecolor.c b/editor/pamrecolor.c
index 8c5bce12..60ed29a4 100644
--- a/editor/pamrecolor.c
+++ b/editor/pamrecolor.c
@@ -32,6 +32,7 @@
 
 #include "mallocvar.h"
 #include "nstring.h"
+#include "rand.h"
 #include "shhopt.h"
 #include "pam.h"
 
@@ -42,7 +43,7 @@
 #define CLAMPxy(N, A, B) MAX(MIN((float)(N), (float)(B)), (float)(A))
 
 
-struct rgbfrac {
+struct Rgbfrac {
     /* This structure represents red, green, and blue, each expressed
        as a fraction from 0.0 to 1.0.
     */
@@ -51,19 +52,19 @@ struct rgbfrac {
     float bfrac;
 };
 
-struct cmdlineInfo {
+struct CmdlineInfo {
     /* This structure represents all of the information the user
        supplied in the command line but in a form that's easy for the
        program to use.
     */
     const char *    inputFileName;  /* '-' if stdin */
     const char *    colorfile;      /* NULL if unspecified */
-    struct rgbfrac  color2gray;
+    struct Rgbfrac  color2gray;
         /* colorspace/rmult/gmult/bmult options.  Negative numbers if
            unspecified.
         */
     unsigned int    targetcolorSpec;
-    struct rgbfrac  targetcolor;
+    struct Rgbfrac  targetcolor;
     unsigned int    randomseed;
     unsigned int    randomseedSpec;
 };
@@ -71,7 +72,7 @@ struct cmdlineInfo {
 
 
 static float
-rgb2gray(struct rgbfrac * const color2grayP,
+rgb2gray(struct Rgbfrac * const color2grayP,
          float            const red,
          float            const grn,
          float            const blu) {
@@ -122,7 +123,7 @@ getColorRow(struct pam  * const pamP,
 
 static void
 convertRowToGray(struct pam     * const pamP,
-                 struct rgbfrac * const color2gray,
+                 struct Rgbfrac * const color2gray,
                  tuplen         * const tupleRow,
                  samplen        * const grayRow) {
 /*----------------------------------------------------------------------
@@ -160,7 +161,7 @@ convertRowToGray(struct pam     * const pamP,
 static void
 explicitlyColorRow(struct pam *   const pamP,
                    tuplen *       const rowData,
-                   struct rgbfrac const tint) {
+                   struct Rgbfrac const tint) {
 
     unsigned int col;
 
@@ -175,17 +176,25 @@ explicitlyColorRow(struct pam *   const pamP,
 
 static void
 randomlyColorRow(struct pam *   const pamP,
-                 tuplen *       const rowData) {
+                 tuplen *       const rowData,
+                 bool           const randomseedSpec,
+                 unsigned int   const randomseed) {
 /*----------------------------------------------------------------------
   Assign each tuple in a row a random color.
 ------------------------------------------------------------------------*/
     unsigned int col;
+    struct pm_randSt randSt;
+
+    pm_randinit(&randSt);
+    pm_srand2(&randSt, randomseedSpec, randomseed);
 
     for (col = 0; col < pamP->width; ++col) {
-        rowData[col][PAM_RED_PLANE] = rand() / (float)RAND_MAX;
-        rowData[col][PAM_GRN_PLANE] = rand() / (float)RAND_MAX;
-        rowData[col][PAM_BLU_PLANE] = rand() / (float)RAND_MAX;
+        rowData[col][PAM_RED_PLANE] = pm_drand(&randSt);
+        rowData[col][PAM_GRN_PLANE] = pm_drand(&randSt);
+        rowData[col][PAM_BLU_PLANE] = pm_drand(&randSt);
     }
+
+    pm_randterm(&randSt);
 }
 
 
@@ -193,7 +202,7 @@ randomlyColorRow(struct pam *   const pamP,
 static void
 recolorRow(struct pam     * const inPamP,
            tuplen         * const inRow,
-           struct rgbfrac * const color2grayP,
+           struct Rgbfrac * const color2grayP,
            tuplen         * const colorRow,
            struct pam     * const outPamP,
            tuplen         * const outRow) {
@@ -293,10 +302,10 @@ recolorRow(struct pam     * const inPamP,
 
 
 
-static struct rgbfrac
+static struct Rgbfrac
 color2GrayFromCsName(const char * const csName) {
 
-    struct rgbfrac retval;
+    struct Rgbfrac retval;
 
     /* Thanks to
        http://www.brucelindbloom.com/index.html?Eqn_RGB_XYZ_Matrix.html
@@ -352,7 +361,7 @@ color2GrayFromCsName(const char * const csName) {
 
 static void
 parseCommandLine(int argc, const char ** const argv,
-                 struct cmdlineInfo * const cmdlineP ) {
+                 struct CmdlineInfo * const cmdlineP ) {
 
     optEntry     * option_def;
         /* Instructions to OptParseOptions3 on how to parse our options */
@@ -445,7 +454,7 @@ parseCommandLine(int argc, const char ** const argv,
 
 int
 main(int argc, const char *argv[]) {
-    struct cmdlineInfo cmdline;          /* Command-line parameters */
+    struct CmdlineInfo cmdline;          /* Command-line parameters */
     struct pam         inPam;
     struct pam         outPam;
     struct pam         colorPam;
@@ -462,8 +471,6 @@ main(int argc, const char *argv[]) {
 
     parseCommandLine(argc, argv, &cmdline);
 
-    srand(cmdline.randomseedSpec ? cmdline.randomseed : pm_randseed());
-
     ifP = pm_openr(cmdline.inputFileName);
     inPam.comment_p = &comments;
     pnm_readpaminit(ifP, &inPam, PAM_STRUCT_SIZE(comment_p));
@@ -474,7 +481,6 @@ main(int argc, const char *argv[]) {
     outPam.depth = 4 - (inPam.depth % 2);
     outPam.allocation_depth = outPam.depth;
     strcpy(outPam.tuple_type, PAM_PPM_TUPLETYPE);
-    pnm_writepaminit(&outPam);
 
     if (cmdline.colorfile) {
         colorfP = pm_openr(cmdline.colorfile);
@@ -492,6 +498,8 @@ main(int argc, const char *argv[]) {
 
     colorRowBuffer = pnm_allocpamrown(&outPam);
 
+    pnm_writepaminit(&outPam);
+
     for (row = 0; row < inPam.height; ++row) {
         tuplen * colorRow;
 
@@ -505,7 +513,8 @@ main(int argc, const char *argv[]) {
             if (cmdline.targetcolorSpec)
                 explicitlyColorRow(&colorPam, colorRow, cmdline.targetcolor);
             else
-                randomlyColorRow(&colorPam, colorRow);
+                randomlyColorRow(&colorPam, colorRow,
+                                 cmdline.randomseedSpec, cmdline.randomseed);
         }
         recolorRow(&inPam, inRow,
                    &cmdline.color2gray, colorRow,
diff --git a/editor/pamrestack.c b/editor/pamrestack.c
new file mode 100644
index 00000000..46321774
--- /dev/null
+++ b/editor/pamrestack.c
@@ -0,0 +1,472 @@
+/*=============================================================================
+                               pamrestack
+===============================================================================
+  Part of the Netpbm package.
+
+  Rearrange pixels of a Netpbm image into different size rows.
+
+  E.g. if an image is 100 pixels wide and 50 pixels high, you can rearrange it
+  to 125 wide and 40 high.  In that case, 25 pixels from the 2nd row of the
+  input would be moved to the end of the 1st row of input, 50 pixels from the
+  3rd row would be moved to the 2nd row, etc.
+
+  If new width is less than the input image width, move the excess pixels
+  to the start (=left edge) of the next row.
+
+  If new width is larger, complete row by bringing pixels from the start
+  of the next row.
+
+  By Akira F. Urushibata
+
+  Contributed to the public domain by its author.
+=============================================================================*/
+
+#include <assert.h>
+#include <math.h>
+#include <limits.h>
+#include "pm_c_util.h"
+#include "mallocvar.h"
+#include "nstring.h"
+#include "pam.h"
+#include "shhopt.h"
+
+static unsigned int const maxSize = INT_MAX - 10;
+
+static void
+validateWidth(double       const width,
+              const char * const message) {
+/*----------------------------------------------------------------------------
+  Check width.  Ensure it is a value accepted by other Netpbm programs.
+-----------------------------------------------------------------------------*/
+    assert(maxSize < INT_MAX);
+
+    if (width > maxSize)
+        pm_error("%s %.0f is too large.", message, width);
+}
+
+
+
+static void
+validateHeight(double const height) {
+/*----------------------------------------------------------------------------
+  Fail if image height of 'height' is too great for the computations in
+  this program to work.
+-----------------------------------------------------------------------------*/
+    if (height > maxSize)
+        pm_error("Input image is large and -width value is small."
+                 "Calulated height %.0f is too large.", height);
+}
+
+
+
+enum TrimMode {TRIMMODE_NOP, TRIMMODE_FILL, TRIMMODE_CROP, TRIMMODE_ABORT};
+
+struct CmdlineInfo {
+    /* All the information the user supplied in the command line,
+       in a form easy for the program to use.
+    */
+    const char *  inputFileName;
+    unsigned int  width;
+    unsigned int  widthSpec;
+    enum TrimMode trim;
+    unsigned int  verbose;
+};
+
+static void
+parseCommandLine(int argc, const char ** const argv,
+                 struct CmdlineInfo * const cmdlineP) {
+/*----------------------------------------------------------------------------
+   Note that the file spec array we return is stored in the storage that
+   was passed to us as the argv array.
+-----------------------------------------------------------------------------*/
+    optEntry * option_def;
+        /* Instructions to OptParseOptions3 on how to parse our options. */
+    optStruct3 opt;
+
+    const char * trimOpt;
+    unsigned int trimSpec;
+
+    unsigned int option_def_index;
+
+    MALLOCARRAY(option_def, 100);
+
+    opt.opt_table = option_def;
+    opt.short_allowed = false;  /* We have no short (old-fashioned) options */
+    opt.allowNegNum = true;  /* We have no parms that are negative numbers */
+
+    option_def_index = 0;   /* incremented by OPTENT3 */
+    OPTENT3(0, "width",         OPT_UINT,    &cmdlineP->width,
+            &cmdlineP->widthSpec,     0);
+    OPTENT3(0, "trim",          OPT_STRING, &trimOpt,
+            &trimSpec,                0);
+    OPTENT3(0, "verbose",       OPT_FLAG,   NULL,
+            &cmdlineP->verbose,       0);
+
+    pm_optParseOptions3(&argc, (char **)argv, opt, sizeof(opt), 0);
+    /* Uses and sets argc, argv, and some of *cmdlineP and others. */
+
+    free(option_def);
+
+    if (cmdlineP->widthSpec) {
+        if (cmdlineP->width == 0)
+            pm_error("Width value must be positive.  You specified 0");
+        else
+            validateWidth((double) cmdlineP->width,
+                          "Specified -width value");
+    }
+
+    if (trimSpec) {
+        if (streq(trimOpt, "fill")) {
+            cmdlineP->trim = TRIMMODE_FILL;
+        } else if (streq(trimOpt, "crop")) {
+            cmdlineP->trim = TRIMMODE_CROP;
+        } else if (streq(trimOpt, "abort")) {
+            cmdlineP->trim = TRIMMODE_ABORT;
+        } else
+            /* NOP is not specified from the command line */
+            pm_error("Invalid value for -trim: '%s'", trimOpt);
+    } else
+        cmdlineP->trim = TRIMMODE_FILL;  /* default */
+
+    if (argc-1 < 1)
+        cmdlineP->inputFileName = "-";
+    else {
+        cmdlineP->inputFileName = argv[1];
+
+        if (argc-1 > 1)
+            pm_error("Too many arguments (%u). "
+                     "The only possible argument is the input file name.",
+                     argc-1);
+    }
+}
+
+
+
+static void
+adjustTrimMode(double          const inPixels,
+               double          const outWidth,
+               double          const outHeight,
+               bool            const verbose,
+               enum TrimMode   const originalMode,
+               enum TrimMode * const adjustedModeP) {
+/*----------------------------------------------------------------------------
+   Adjust trim mode, taking into account the number of pixels in the
+   input image and the width and height of the output image.
+
+   Check whether conditions are met for abort.
+   Set mode to NOP if all output rows will be full.
+-----------------------------------------------------------------------------*/
+    double const outPixels = outWidth * outHeight;
+
+    enum TrimMode adjustedMode;
+
+    if (inPixels == outPixels)
+        adjustedMode = TRIMMODE_NOP;
+    else {
+        if (originalMode == TRIMMODE_ABORT)
+            pm_error("Abort mode specified and input image has %.0f pixels "
+                     "which is %s specified width value %.0f",
+                     inPixels,
+                     inPixels < outWidth ? "less than" : "not a multiple of",
+                     outWidth);
+        else
+            adjustedMode = originalMode;
+    }
+
+    validateHeight(outHeight + (adjustedMode == TRIMMODE_FILL) ? 1 : 0);
+
+    switch (adjustedMode) {
+    case TRIMMODE_NOP:
+        if (verbose)
+            pm_message("Input image and output image have the same "
+                       "number of pixels.");
+        break;
+    case TRIMMODE_FILL:
+        if (verbose)
+            pm_message("Output image will have %.0f more pixels "
+                       "than input image.  Incomplete final row "
+                       "will be padded.", inPixels - outPixels);
+        break;
+    case TRIMMODE_CROP:
+        if (outHeight == 0)
+            pm_error("No row left after cropping incomplete row. "
+                     "Aborting.");
+        else if (verbose)
+            pm_message("Incomplete final row will be cropped.  %.0f "
+                       "pixels lost.", inPixels - outPixels);
+        break;
+    case TRIMMODE_ABORT:
+        pm_error("internal error");  /* Suppress compiler warning */
+        break;
+    }
+
+    *adjustedModeP = adjustedMode;
+}
+
+
+
+/*----------------------------------------------------------------------------
+  Width conversion using pointer arrays
+
+  This program reads input rows and converts to output rows of desired
+  width using a device which employs pointer arrays on both sides.
+  Conceptually similar, yet more simple, devices are used in pamcut,
+  pnmpad, pamflip and pnmcat.
+
+  inputPointers[] is an expanded version of incols[] seen in many pam
+  programs.  It reads multiple rows: as many rows as necessary to
+  complete at least one output row.
+
+  The read positions within inputPointers[] are fixed.  For example, if
+  the input row width is 100 and inputPointers has 400 elements, the read
+  positions will be: 0-99, 100-199, 200-299, 300-399.
+
+  The outPointers[] array is set up to allow selecting elements for
+  write from inputPointers[].  outPointers[] is at least as large as
+  inPointers[].  The write position migrates as necessary in a cycle.
+  If input width and output width are coprime and output has a
+  sufficient number of rows, all positions within outPointers[]
+  will be utilized.
+
+  Once set up, the conversion device is not altered until the input image
+  is completely read.
+
+  The following are special cases in which inPointers[] and outPointers[]
+  are set to the same size:
+
+  (1) Input width and output width are equal.
+  (2) Output width is an integer multiple of input width.
+  (3) Input width is an integer multiple of output width.
+
+  In cases (1) (2), the output position is fixed.
+  In case (3) the output position is mobile, but all of them will start
+  at integer multiples of output width.
+
+  Note that width, height and width * height variables are of type
+  "double" as a safeguard against overflows.
+-----------------------------------------------------------------------------*/
+
+
+
+static void
+setOutputDimensions(struct CmdlineInfo * const cmdlineP,
+                    double               const inPixelCt,
+                    int *                const outWidthP,
+                    int *                const outHeightP,
+                    enum TrimMode *      const trimModeP) {
+/*-----------------------------------------------------------------------------
+  Calculate the width and height of output from the number of pixels in
+  the input and command line arguments, most notably desired width.
+-----------------------------------------------------------------------------*/
+    double outWidth, outHeight;
+    enum TrimMode adjustedMode;
+
+    if (!cmdlineP->widthSpec) {
+        outWidth = inPixelCt;
+        outHeight = 1;
+        validateWidth(outWidth,
+                      "Input image is large and -width not specified. "
+                      "Output width");
+        adjustedMode = cmdlineP->trim;
+    } else {
+        double preAdjustedOutHeight;
+
+        outWidth  = cmdlineP->width;
+        preAdjustedOutHeight = floor(inPixelCt / outWidth);
+
+        adjustTrimMode(inPixelCt, outWidth, preAdjustedOutHeight,
+                       cmdlineP->verbose,
+                       cmdlineP->trim, &adjustedMode);
+
+        outHeight = adjustedMode == TRIMMODE_FILL ?
+            preAdjustedOutHeight + 1 : preAdjustedOutHeight;
+    }
+
+    *outWidthP  = (unsigned int)outWidth;
+    *outHeightP = (unsigned int)outHeight;
+    *trimModeP  = adjustedMode;
+}
+
+
+
+static void
+calculateInOutSize(unsigned int   const inWidth,
+                   unsigned int   const outWidth,
+                   unsigned int * const inputPointersWidthP,
+                   unsigned int * const outputPointersWidthP) {
+/*----------------------------------------------------------------------------
+  Calculate array size of inPointers[] and outPointers[] from
+  input width and output width.
+-----------------------------------------------------------------------------*/
+    double inputPointersWidth;
+    double outputPointersWidth;
+
+    if (outWidth > inWidth) {
+        if (outWidth % inWidth == 0)
+            inputPointersWidth = outputPointersWidth = outWidth;
+        else {
+            inputPointersWidth =
+              (outWidth / inWidth + 1) * inWidth * 2;
+            outputPointersWidth = inputPointersWidth + outWidth - 1;
+        }
+    }
+    else if (outWidth == inWidth)
+            inputPointersWidth = outputPointersWidth = outWidth;
+    else { /* outWidth < inWidth) */
+        if (inWidth % outWidth == 0)
+            inputPointersWidth = outputPointersWidth = inWidth;
+        else {
+            inputPointersWidth = inWidth * 2;
+            outputPointersWidth = inputPointersWidth + outWidth - 1;
+        }
+    }
+
+    if(inputPointersWidth > SIZE_MAX || outputPointersWidth > SIZE_MAX)
+        pm_error("Failed to set up conversion array.  Either input width, "
+                 "output width or their difference is too large.");
+
+    *inputPointersWidthP  = (unsigned int) inputPointersWidth;
+    *outputPointersWidthP = (unsigned int) outputPointersWidth;
+}
+
+
+
+static void
+restack(struct pam    * const inpamP,
+        struct pam    * const outpamP,
+        tuple         * const inputPointers,
+        tuple         * const outputPointers,
+        unsigned int    const inputPointersWidth,
+        unsigned int    const outputPointersWidth,
+        enum TrimMode   const trimMode) {
+/*----------------------------------------------------------------------------
+  Convert image, using inputPointers[] and outputPointers[]
+-----------------------------------------------------------------------------*/
+    unsigned int inoffset;
+    unsigned int outoffset;
+    unsigned int inPixelCt; /* Count of pixels read since last write */
+    unsigned int row;
+
+    /* Read all input and write all rows with the exception of the final
+       partial row */
+
+    for (row = 0, inoffset = 0, outoffset = 0, inPixelCt = 0;
+         row < inpamP->height; ++row) {
+
+        pnm_readpamrow(inpamP, &inputPointers[inoffset]);
+        inPixelCt += inpamP->width;
+
+        for ( ; inPixelCt >= outpamP->width; inPixelCt -= outpamP->width) {
+            pnm_writepamrow(outpamP, &outputPointers[outoffset]);
+            outoffset = (outoffset + outpamP->width ) % inputPointersWidth;
+        }
+        inoffset = (inoffset + inpamP->width) % inputPointersWidth;
+    }
+
+    /* Fill remainder of last row with black pixels and output */
+
+    if (inPixelCt > 0 && trimMode == TRIMMODE_FILL) {
+        tuple blackTuple;
+        unsigned int col;
+
+        pnm_createBlackTuple(outpamP, &blackTuple);
+
+        for (col = inPixelCt; col < outpamP->width; ++col) {
+            unsigned int const outoffset2 =
+                (outoffset + col) % outputPointersWidth;
+            outputPointers[outoffset2] = blackTuple;
+        }
+
+        /* output final row */
+        pnm_writepamrow(outpamP, &outputPointers[outoffset]);
+    }
+}
+
+
+
+static void
+restackSingleImage(FILE *               const ifP,
+                   struct CmdlineInfo * const cmdlineP) {
+
+    struct pam inpam;   /* Input PAM image */
+    struct pam mpam;    /* Adjusted PAM structure to read multiple rows */
+    struct pam outpam;  /* Output PAM image */
+
+    double        inPixelCt;
+    enum TrimMode trimMode;
+    tuple *       inputPointers;
+    tuple *       outputPointers;
+    unsigned int  inputPointersWidth;
+    unsigned int  outputPointersWidth;
+
+    pnm_readpaminit(ifP, &inpam, PAM_STRUCT_SIZE(tuple_type));
+
+    inPixelCt = inpam.width * inpam.height;
+
+    outpam = inpam;
+
+    setOutputDimensions(cmdlineP, inPixelCt, &outpam.width, &outpam.height,
+                        &trimMode);
+
+    outpam.file = stdout;
+
+    pnm_writepaminit(&outpam);
+
+    calculateInOutSize(inpam.width, outpam.width,
+                       &inputPointersWidth, &outputPointersWidth);
+
+    mpam = inpam;
+    mpam.width = inputPointersWidth;
+
+    inputPointers = pnm_allocpamrow(&mpam);
+
+    if (outputPointersWidth > inputPointersWidth) {
+        unsigned int col;
+
+        MALLOCARRAY(outputPointers, outputPointersWidth);
+
+        if (!outputPointers) {
+            pm_error("Unable to allocate memory for %u output pointers",
+                     outputPointersWidth);
+        }
+
+        /* Copy pointers as far as inputPointers[] goes, then wrap around */
+        for (col = 0; col < outputPointersWidth; ++col)
+            outputPointers[col] = inputPointers[col % inputPointersWidth];
+
+    } else
+        outputPointers = inputPointers;
+
+    restack(&inpam, &outpam, inputPointers, outputPointers,
+            inputPointersWidth, outputPointersWidth, trimMode);
+
+    if (inputPointers != outputPointers)
+        free(outputPointers);
+
+    pnm_freepamrow(inputPointers);
+}
+
+
+
+int
+main(int argc, const char * argv[]) {
+
+    struct CmdlineInfo cmdline;
+    FILE * ifP;
+    int    eof;     /* no more images in input stream */
+
+    pm_proginit(&argc, argv);
+
+    parseCommandLine(argc, argv, &cmdline);
+
+    ifP = pm_openr(cmdline.inputFileName);
+
+    for (eof = false; !eof; ) {
+        restackSingleImage(ifP, &cmdline);
+        pnm_nextimage(ifP, &eof);
+    }
+
+    pm_close(ifP);
+
+    return 0;
+}
diff --git a/editor/pamrubber.c b/editor/pamrubber.c
index 602701ec..f68e36fe 100644
--- a/editor/pamrubber.c
+++ b/editor/pamrubber.c
@@ -1,20 +1,18 @@
-/*----------------------------------------------------------------------------*/
-
-/* pamrubber.c - transform images using Rubber Sheeting algorithm
-**               see: http://www.schaik.com/netpbm/rubber/
-**
-** Copyright (C) 2011 by Willem van Schaik (willem@schaik.com)
-**
-** Permission to use, copy, modify, and distribute this software and its
-** documentation for any purpose and without fee is hereby granted, provided
-** that the above copyright notice appear in all copies and that both that
-** copyright notice and this permission notice appear in supporting
-** documentation.  This software is provided "as is" without express or
-** implied warranty.
-*/
-
-/*----------------------------------------------------------------------------*/
-
+/*=============================================================================
+                              pamrubber
+===============================================================================
+  Transform images using Rubber Sheeting algorithm
+  See: http://www.schaik.com/netpbm/rubber/
+
+  Copyright (C) 2011 by Willem van Schaik (willem@schaik.com)
+
+  Permission to use, copy, modify, and distribute this software and its
+  documentation for any purpose and without fee is hereby granted, provided
+  that the above copyright notice appear in all copies and that both that
+  copyright notice and this permission notice appear in supporting
+  documentation.  This software is provided "as is" without express or
+  implied warranty.
+=============================================================================*/
 #include <stdio.h>
 #include <stdlib.h>
 #include <unistd.h>
@@ -25,12 +23,12 @@
 
 #include "pm_c_util.h"
 #include "mallocvar.h"
+#include "rand.h"
 #include "shhopt.h"
 #include "pam.h"
 #include "pamdraw.h"
 
 
-
 typedef struct {
   double x;
   double y;
@@ -54,7 +52,7 @@ typedef struct {
     point br;  /* bottom right */
 } quadrilateral;
 
-struct cmdlineInfo {
+struct CmdlineInfo {
     unsigned int nCP;
     point        oldCP[4];
     point        newCP[4];
@@ -64,14 +62,14 @@ struct cmdlineInfo {
     unsigned int frame;
     unsigned int linear;
     unsigned int verbose;
-    unsigned int randseedSpec;
-    unsigned int randseed;
+    unsigned int randomseedSpec;
+    unsigned int randomseed;
 };
 
 
 static void
 parseCmdline(int argc, const char ** argv,
-             struct cmdlineInfo * const cmdlineP) {
+             struct CmdlineInfo * const cmdlineP) {
 
 /* parse all parameters from the command line */
 
@@ -92,10 +90,10 @@ parseCmdline(int argc, const char ** argv,
     OPTENT3(0, "frame",    OPT_FLAG, NULL, &cmdlineP->frame,    0);
     OPTENT3(0, "linear",   OPT_FLAG, NULL, &cmdlineP->linear,   0);
     OPTENT3(0, "verbose",  OPT_FLAG, NULL, &cmdlineP->verbose,  0);
-    OPTENT3(0, "randseed", OPT_UINT, &cmdlineP->randseed,
-            &cmdlineP->randseedSpec, 0);
-    OPTENT3(0, "randomseed", OPT_UINT, &cmdlineP->randseed,
-            &cmdlineP->randseedSpec, 0);
+    OPTENT3(0, "randseed", OPT_UINT, &cmdlineP->randomseed,
+            &cmdlineP->randomseedSpec, 0);
+    OPTENT3(0, "randomseed", OPT_UINT, &cmdlineP->randomseed,
+            &cmdlineP->randomseedSpec, 0);
 
     opt.opt_table = option_def;
     opt.short_allowed = FALSE;  /* we have no short (old-fashioned) options */
@@ -195,38 +193,39 @@ makeline(point const p1,
 
 
 
-static bool
-intersect(line *  const l1P,
-          line *  const l2P,
-          point * const pP) {
+static void
+findIntersection(const line *  const l1P,
+                 const line *  const l2P,
+                 bool *        const theyIntersectP,
+                 point *       const intersectionP) {
 
-    bool cross;
+    bool theyIntersect;
 
     if (((l2P->p2.y - l2P->p1.y) * (l1P->p2.x - l1P->p1.x) -
          (l2P->p2.x - l2P->p1.x) * (l1P->p2.y - l1P->p1.y)) == 0) {
         /* parallel lines */
 
-        cross = false;
+        theyIntersect = false;
 
         if ((l1P->p1.x == l1P->p2.x) && (l2P->p1.x == l2P->p2.x)) {
             /* two vertical lines */
-            pP->x = (l1P->p1.x + l2P->p1.x) / 2.0;
-            pP->y = 1e10;
+            intersectionP->x = (l1P->p1.x + l2P->p1.x) / 2.0;
+            intersectionP->y = 1e10;
         } else if ((l1P->p1.y == l1P->p2.y) && (l2P->p1.y == l2P->p2.y)) {
             /* two horizontal lines */
-            pP->x = 1e10;
-            pP->y = (l1P->p1.y + l2P->p1.y) / 2.0;
+            intersectionP->x = 1e10;
+            intersectionP->y = (l1P->p1.y + l2P->p1.y) / 2.0;
         } else {
             if (fabs(l1P->p2.y - l1P->p1.y) > fabs(l1P->p2.x - l1P->p1.x)) {
                 /* steep slope */
-                pP->y = 1e10;
-                pP->x = (l1P->p2.x - l1P->p1.x) / (l1P->p2.y - l1P->p1.y)
-                    * 1e10;
+                intersectionP->y = 1e10;
+                intersectionP->x =
+                    (l1P->p2.x - l1P->p1.x) / (l1P->p2.y - l1P->p1.y) * 1e10;
             } else {
                 /* even slope */
-                pP->x = 1e10;
-                pP->y = (l1P->p2.y - l1P->p1.y) / (l1P->p2.x - l1P->p1.x)
-                    * 1e10;
+                intersectionP->x = 1e10;
+                intersectionP->y =
+                    (l1P->p2.y - l1P->p1.y) / (l1P->p2.x - l1P->p1.x) * 1e10;
             }
         }
     } else {
@@ -244,16 +243,16 @@ intersect(line *  const l1P,
                * (l1P->p2.x - l1P->p1.x) - (l2P->p2.x - l2P->p1.x)
                * (l1P->p2.y - l1P->p1.y));
 
-        pP->x = l1P->p1.x + ua * (l1P->p2.x - l1P->p1.x);
-        pP->y = l1P->p1.y + ua * (l1P->p2.y - l1P->p1.y);
+        intersectionP->x = l1P->p1.x + ua * (l1P->p2.x - l1P->p1.x);
+        intersectionP->y = l1P->p1.y + ua * (l1P->p2.y - l1P->p1.y);
 
         if ((ua >= 0.0) && (ua <= 1.0) && (ub >= 0.0) && (ub <= 1.0))
-            cross = true;
+            theyIntersect = true;
         else
-            cross = false;
+            theyIntersect = false;
     }
-
-    return cross;
+    if (theyIntersectP)
+        *theyIntersectP = theyIntersect;
 }
 
 
@@ -309,28 +308,29 @@ insidetri(triangle * const triP,
 
 
 static bool
-windtriangle(triangle * const tP,
+windtriangle(triangle * const triP,
              point      const p1,
              point      const p2,
              point      const p3) {
     point f, c;
-    line le, lv;
     bool cw;
 
     /* find cross of vertical through p3 and the edge p1-p2 */
     f.x = p3.x;
     f.y = -1.0;
-    lv = makeline(p3, f);
-    le = makeline(p1, p2);
-    intersect(&le, &lv, &c);
+    {
+        line const lv = makeline(p3, f);
+        line const le = makeline(p1, p2);
+        findIntersection(&le, &lv, NULL, &c);
+    }
 
     /* check for clockwise winding triangle */
     if (((p1.x > p2.x) && (p3.y < c.y)) ||
         ((p1.x < p2.x) && (p3.y > c.y))) {
-        *tP = maketriangle(p1, p2, p3);
+        *triP = maketriangle(p1, p2, p3);
         cw = true;
     } else { /* p1/2/3 were counter clockwise */
-        *tP = maketriangle(p1, p3, p2);
+        *triP = maketriangle(p1, p3, p2);
         cw = false;
     }
     return cw;
@@ -339,28 +339,29 @@ windtriangle(triangle * const tP,
 
 
 static double
-tiny(void) {
+tiny(struct pm_randSt * const randStP) {
 
-    if (rand() % 2)
-        return +1E-6 * (double) ((rand() % 90) + 9);
+    if (pm_rand(randStP) % 2)
+        return +1E-6 * (double) ((pm_rand(randStP) % 90) + 9);
     else
-        return -1E-6 * (double) ((rand() % 90) + 9);
+        return -1E-6 * (double) ((pm_rand(randStP) % 90) + 9);
 }
 
 
 
 static void
 angle(point * const p1P,
-      point * const p2P) {
+      point * const p2P,
+      struct pm_randSt * const randStP) {
 /*----------------------------------------------------------------------------
    Move *p2P slightly if necessary to make sure the line (*p1P, *p2P)
    is not horizontal or vertical.
 -----------------------------------------------------------------------------*/
     if (p1P->x == p2P->x) { /* vertical line */
-        p2P->x += tiny();
+        p2P->x += tiny(randStP);
     }
     if (p1P->y == p2P->y) { /* horizontal line */
-        p2P->y += tiny();
+        p2P->y += tiny(randStP);
     }
 }
 
@@ -613,12 +614,16 @@ quadCorner(point           const p0,
 
     /* p0-p1 and p2-p3 are the diagonals */
 
+    triangle tri;
+
     if (fabs(p0.x - p1.x) + fabs(p0.y - p1.y) >=
         fabs(p2.x - p3.x) + fabs(p2.y - p3.y)) {
-        quadCornerSized(p0, p1, p2, p3, mid, quadP, triP);
+        quadCornerSized(p0, p1, p2, p3, mid, quadP, &tri);
     } else {
-        quadCornerSized(p2, p3, p0, p1, mid, quadP, triP);
+        quadCornerSized(p2, p3, p0, p1, mid, quadP, &tri);
     }
+    if (triP)
+        *triP = tri;
 }
 
 
@@ -720,8 +725,10 @@ static void drawClippedTriangle(const struct pam * const pamP,
 
 
 static void
-prepTrig(int const wd,
-         int const ht) {
+prepTrig(int          const wd,
+         int          const ht,
+         bool         const randomseedSpec,
+         unsigned int const randomseed) {
 
 /* create triangles using control points */
 
@@ -729,18 +736,21 @@ prepTrig(int const wd,
     point rtl2, rtr2, rbl2, rbr2;
     point c1p1, c1p2, c1p3, c1p4;
     point c2p1, c2p2, c2p3, c2p4;
-    line l1, l2;
     point p0;
+    struct pm_randSt randSt;
+
+    pm_randinit(&randSt);
+    pm_srand2(&randSt, randomseedSpec, randomseed);
 
-    rtl1 = makepoint(0.0 + tiny(),               0.0 + tiny());
-    rtr1 = makepoint((double) wd - 1.0 + tiny(), 0.0 + tiny());
-    rbl1 = makepoint(0.0 + tiny(),               (double) ht - 1.0 + tiny());
-    rbr1 = makepoint((double) wd - 1.0 + tiny(), (double) ht - 1.0 + tiny());
+    rtl1 = makepoint(0.0 + tiny(&randSt),               0.0 + tiny(&randSt));
+    rtr1 = makepoint((double) wd - 1.0 + tiny(&randSt), 0.0 + tiny(&randSt));
+    rbl1 = makepoint(0.0 + tiny(&randSt),               (double) ht - 1.0 + tiny(&randSt));
+    rbr1 = makepoint((double) wd - 1.0 + tiny(&randSt), (double) ht - 1.0 + tiny(&randSt));
 
-    rtl2 = makepoint(0.0 + tiny(),               0.0 + tiny());
-    rtr2 = makepoint((double) wd - 1.0 + tiny(), 0.0 + tiny());
-    rbl2 = makepoint(0.0 + tiny(),               (double) ht - 1.0 + tiny());
-    rbr2 = makepoint((double) wd - 1.0 + tiny(), (double) ht - 1.0 + tiny());
+    rtl2 = makepoint(0.0 + tiny(&randSt),               0.0 + tiny(&randSt));
+    rtr2 = makepoint((double) wd - 1.0 + tiny(&randSt), 0.0 + tiny(&randSt));
+    rbl2 = makepoint(0.0 + tiny(&randSt),               (double) ht - 1.0 + tiny(&randSt));
+    rbr2 = makepoint((double) wd - 1.0 + tiny(&randSt), (double) ht - 1.0 + tiny(&randSt));
 
     if (nCP == 1) {
         c1p1 = oldCP[0];
@@ -772,8 +782,8 @@ prepTrig(int const wd,
         c2p2 = newCP[1];
 
         /* check for hor/ver edges */
-        angle (&c1p1, &c1p2);
-        angle (&c2p1, &c2p2);
+        angle (&c1p1, &c1p2, &randSt);
+        angle (&c2p1, &c2p2, &randSt);
 
         /* connect two control points to corners to get 6 triangles */
         /* left side */
@@ -811,13 +821,13 @@ prepTrig(int const wd,
         /* Move vertices slightly if necessary to make sure no edge is
            horizontal or vertical.
         */
-        angle(&c1p1, &c1p2);
-        angle(&c1p2, &c1p3);
-        angle(&c1p3, &c1p1);
+        angle(&c1p1, &c1p2, &randSt);
+        angle(&c1p2, &c1p3, &randSt);
+        angle(&c1p3, &c1p1, &randSt);
 
-        angle(&c2p1, &c2p2);
-        angle(&c2p2, &c2p3);
-        angle(&c2p3, &c2p1);
+        angle(&c2p1, &c2p2, &randSt);
+        angle(&c2p2, &c2p3, &randSt);
+        angle(&c2p3, &c2p1, &randSt);
 
         if (windtriangle(&tri1s[0], c1p1, c1p2, c1p3)) {
             tri2s[0] = maketriangle(c2p1, c2p2, c2p3);
@@ -871,19 +881,19 @@ prepTrig(int const wd,
         c2p4 = newCP[3];
 
         /* check for hor/ver edges */
-        angle (&c1p1, &c1p2);
-        angle (&c1p2, &c1p3);
-        angle (&c1p3, &c1p4);
-        angle (&c1p4, &c1p1);
-        angle (&c1p1, &c1p3);
-        angle (&c1p2, &c1p4);
-
-        angle (&c2p1, &c2p2);
-        angle (&c2p2, &c2p3);
-        angle (&c2p3, &c2p4);
-        angle (&c2p4, &c2p1);
-        angle (&c2p1, &c2p3);
-        angle (&c2p2, &c2p4);
+        angle (&c1p1, &c1p2, &randSt);
+        angle (&c1p2, &c1p3, &randSt);
+        angle (&c1p3, &c1p4, &randSt);
+        angle (&c1p4, &c1p1, &randSt);
+        angle (&c1p1, &c1p3, &randSt);
+        angle (&c1p2, &c1p4, &randSt);
+
+        angle (&c2p1, &c2p2, &randSt);
+        angle (&c2p2, &c2p3, &randSt);
+        angle (&c2p3, &c2p4, &randSt);
+        angle (&c2p4, &c2p1, &randSt);
+        angle (&c2p1, &c2p3, &randSt);
+        angle (&c2p2, &c2p4, &randSt);
 
         /*-------------------------------------------------------------------*/
         /*        -1-      -2-        -3-      -4-        -5-      -6-       */
@@ -892,47 +902,58 @@ prepTrig(int const wd,
         /*       3   4    2   4      4   3    2   3      4   2    3   2      */
         /*-------------------------------------------------------------------*/
 
-        /* center two triangles */
-        l1 = makeline(c1p1, c1p4);
-        l2 = makeline(c1p2, c1p3);
-        if (intersect(&l1, &l2, &p0)) {
-            if (windtriangle(&tri1s[0], c1p1, c1p2, c1p3)) {
-                tri1s[1] = maketriangle(c1p4, c1p3, c1p2);
-                tri2s[0] = maketriangle(c2p1, c2p2, c2p3);
-                tri2s[1] = maketriangle(c2p4, c2p3, c2p2);
-            } else {
-                tri1s[1] = maketriangle(c1p4, c1p2, c1p3);
-                tri2s[0] = maketriangle(c2p1, c2p3, c2p2);
-                tri2s[1] = maketriangle(c2p4, c2p2, c2p3);
+        {
+            /* center two triangles */
+            line const l1 = makeline(c1p1, c1p4);
+            line const l2 = makeline(c1p2, c1p3);
+            bool theyIntersect;
+            findIntersection(&l1, &l2, &theyIntersect, &p0);
+            if (theyIntersect) {
+                if (windtriangle(&tri1s[0], c1p1, c1p2, c1p3)) {
+                    tri1s[1] = maketriangle(c1p4, c1p3, c1p2);
+                    tri2s[0] = maketriangle(c2p1, c2p2, c2p3);
+                    tri2s[1] = maketriangle(c2p4, c2p3, c2p2);
+                } else {
+                    tri1s[1] = maketriangle(c1p4, c1p2, c1p3);
+                    tri2s[0] = maketriangle(c2p1, c2p3, c2p2);
+                    tri2s[1] = maketriangle(c2p4, c2p2, c2p3);
+                }
             }
         }
-        l1 = makeline(c1p1, c1p3);
-        l2 = makeline(c1p2, c1p4);
-        if (intersect(&l1, &l2, &p0)) {
-            if (windtriangle(&tri1s[0], c1p1, c1p2, c1p4)) {
-                tri1s[1] = maketriangle(c1p3, c1p4, c1p2);
-                tri2s[0] = maketriangle(c2p1, c2p2, c2p4);
-                tri2s[1] = maketriangle(c2p3, c2p4, c2p2);
-            } else {
-                tri1s[1] = maketriangle(c1p3, c1p2, c1p4);
-                tri2s[0] = maketriangle(c2p1, c2p4, c2p2);
-                tri2s[1] = maketriangle(c2p3, c2p2, c2p4);
+        {
+            line const l1 = makeline(c1p1, c1p3);
+            line const l2 = makeline(c1p2, c1p4);
+            bool theyIntersect;
+            findIntersection(&l1, &l2, &theyIntersect, &p0);
+            if (theyIntersect) {
+                if (windtriangle(&tri1s[0], c1p1, c1p2, c1p4)) {
+                    tri1s[1] = maketriangle(c1p3, c1p4, c1p2);
+                    tri2s[0] = maketriangle(c2p1, c2p2, c2p4);
+                    tri2s[1] = maketriangle(c2p3, c2p4, c2p2);
+                } else {
+                    tri1s[1] = maketriangle(c1p3, c1p2, c1p4);
+                    tri2s[0] = maketriangle(c2p1, c2p4, c2p2);
+                    tri2s[1] = maketriangle(c2p3, c2p2, c2p4);
+                }
             }
         }
-        l1 = makeline(c1p1, c1p2);
-        l2 = makeline(c1p3, c1p4);
-        if (intersect(&l1, &l2, &p0)) {
-            if (windtriangle(&tri1s[0], c1p1, c1p3, c1p4)) {
-                tri1s[1] = maketriangle(c1p2, c1p4, c1p3);
-                tri2s[0] = maketriangle(c2p1, c2p3, c2p4);
-                tri2s[1] = maketriangle(c2p2, c2p4, c2p3);
-            } else {
-                tri1s[1] = maketriangle(c1p2, c1p3, c1p4);
-                tri2s[0] = maketriangle(c2p1, c2p4, c2p3);
-                tri2s[1] = maketriangle(c2p2, c2p3, c2p4);
+        {
+            line const l1 = makeline(c1p1, c1p2);
+            line const l2 = makeline(c1p3, c1p4);
+            bool theyIntersect;
+            findIntersection(&l1, &l2, &theyIntersect, &p0);
+            if (theyIntersect) {
+                if (windtriangle(&tri1s[0], c1p1, c1p3, c1p4)) {
+                    tri1s[1] = maketriangle(c1p2, c1p4, c1p3);
+                    tri2s[0] = maketriangle(c2p1, c2p3, c2p4);
+                    tri2s[1] = maketriangle(c2p2, c2p4, c2p3);
+                } else {
+                    tri1s[1] = maketriangle(c1p2, c1p3, c1p4);
+                    tri2s[0] = maketriangle(c2p1, c2p4, c2p3);
+                    tri2s[1] = maketriangle(c2p2, c2p3, c2p4);
+                }
             }
         }
-
         /* control points in correct orientation */
         c1p1 = tri1s[0].p1;
         c1p2 = tri1s[0].p2;
@@ -979,6 +1000,8 @@ prepTrig(int const wd,
                      &tri2s[9], c2p3, c2p1, rtl2, rtr2, rbl2, rbr2);
         nTri = 10;
     }
+
+    pm_randterm(&randSt);
 }
 
 
@@ -988,11 +1011,6 @@ prepQuad(void) {
 
 /* order quad control points */
 
-    double d01, d12, d20;
-    line l1, l2;
-    point mid;
-    triangle tri;
-
     if (nCP == 1) {
         /* create a rectangle from top-left corner of image and control
            point
@@ -1007,10 +1025,10 @@ prepQuad(void) {
         } else if ((oldCP[0].x > oldCP[1].x) && (oldCP[0].y < oldCP[1].y)) {
             /* top-right and bottom-left */
             quad1 = quadRect(oldCP[1].x, oldCP[0].x, oldCP[0].y, oldCP[1].y);
-        } else if ((oldCP[0].x < oldCP[1].x) && (oldCP[0].y < oldCP[1].y)) {
+        } else if ((oldCP[0].x < oldCP[1].x) && (oldCP[0].y > oldCP[1].y)) {
             /* bottom-left and top-right */
             quad1 = quadRect(oldCP[0].x, oldCP[1].x, oldCP[1].y, oldCP[0].y);
-        } else if ((oldCP[0].x > oldCP[1].x) && (oldCP[0].y < oldCP[1].y)) {
+        } else if ((oldCP[0].x > oldCP[1].x) && (oldCP[0].y > oldCP[1].y)) {
             /* bottom-right and top-left */
             quad1 = quadRect(oldCP[1].x, oldCP[0].x, oldCP[1].y, oldCP[0].y);
         }
@@ -1021,10 +1039,10 @@ prepQuad(void) {
         } else if ((newCP[0].x > newCP[1].x) && (newCP[0].y < newCP[1].y)) {
             /* top-right and bottom-left */
             quad2 = quadRect(newCP[1].x, newCP[0].x, newCP[0].y, newCP[1].y);
-        } else if ((newCP[0].x < newCP[1].x) && (newCP[0].y < newCP[1].y)) {
+        } else if ((newCP[0].x < newCP[1].x) && (newCP[0].y > newCP[1].y)) {
             /* bottom-left and top-right */
             quad2 = quadRect(newCP[0].x, newCP[1].x, newCP[1].y, newCP[0].y);
-        } else if ((newCP[0].x > newCP[1].x) && (newCP[0].y < newCP[1].y)) {
+        } else if ((newCP[0].x > newCP[1].x) && (newCP[0].y > newCP[1].y)) {
             /* bottom-right and top-left */
             quad2 = quadRect(newCP[1].x, newCP[0].x, newCP[1].y, newCP[0].y);
         }
@@ -1035,9 +1053,9 @@ prepQuad(void) {
                furthest apart
             */
 
-            d01 = distance(newCP[0], newCP[1]);
-            d12 = distance(newCP[1], newCP[2]);
-            d20 = distance(newCP[2], newCP[0]);
+            double const d01 = distance(newCP[0], newCP[1]);
+            double const d12 = distance(newCP[1], newCP[2]);
+            double const d20 = distance(newCP[2], newCP[0]);
 
             if ((d01 > d12) && (d01 > d20)) {
                 oldCP[3].x = oldCP[0].x + oldCP[1].x - oldCP[2].x;
@@ -1067,51 +1085,72 @@ prepQuad(void) {
 
         /* nCP = 3 or 4 */
 
-        /* find the intersection of the diagonals */
-        l1 = makeline(oldCP[0], oldCP[1]);
-        l2 = makeline(oldCP[2], oldCP[3]);
-        if (intersect(&l1, &l2, &mid)) {
-            quadCorner(oldCP[0], oldCP[1], oldCP[2], oldCP[3],
-                       mid, &quad1, &tri);
-        } else {
-            l1 = makeline(oldCP[0], oldCP[2]);
-            l2 = makeline(oldCP[1], oldCP[3]);
-            if (intersect(&l1, &l2, &mid))
-                quadCorner(oldCP[0], oldCP[2], oldCP[1], oldCP[3],
-                           mid, &quad1, &tri);
+        {
+            /* find the intersection of the diagonals */
+            line const l1 = makeline(oldCP[0], oldCP[1]);
+            line const l2 = makeline(oldCP[2], oldCP[3]);
+            bool theyIntersect;
+            point mid;
+            findIntersection(&l1, &l2, &theyIntersect, &mid);
+            if (theyIntersect)
+                quadCorner(oldCP[0], oldCP[1], oldCP[2], oldCP[3],
+                           mid, &quad1, NULL);
             else {
-                l1 = makeline(oldCP[0], oldCP[3]);
-                l2 = makeline(oldCP[1], oldCP[2]);
-                if (intersect(&l1, &l2, &mid))
-                    quadCorner(oldCP[0], oldCP[3],
-                               oldCP[1], oldCP[2], mid, &quad1, &tri);
-                else
-                    pm_error("The four old control points don't seem "
-                             "to be corners.");
+                line const l1 = makeline(oldCP[0], oldCP[2]);
+                line const l2 = makeline(oldCP[1], oldCP[3]);
+                bool theyIntersect;
+                point mid;
+                findIntersection(&l1, &l2, &theyIntersect, &mid);
+                if (theyIntersect)
+                    quadCorner(oldCP[0], oldCP[2], oldCP[1], oldCP[3],
+                               mid, &quad1, NULL);
+                else {
+                    line const l1 = makeline(oldCP[0], oldCP[3]);
+                    line const l2 = makeline(oldCP[1], oldCP[2]);
+                    bool theyIntersect;
+                    point mid;
+                    findIntersection(&l1, &l2, &theyIntersect, &mid);
+                    if (theyIntersect)
+                        quadCorner(oldCP[0], oldCP[3],
+                                   oldCP[1], oldCP[2], mid, &quad1, NULL);
+                    else
+                        pm_error("The four old control points don't seem "
+                                 "to be corners.");
+                }
             }
         }
-
-        /* repeat for the "to-be" control points */
-        l1 = makeline(newCP[0], newCP[1]);
-        l2 = makeline(newCP[2], newCP[3]);
-        if (intersect(&l1, &l2, &mid))
-            quadCorner(newCP[0], newCP[1], newCP[2], newCP[3],
-                       mid, &quad2, &tri);
-        else {
-            l1 = makeline(newCP[0], newCP[2]);
-            l2 = makeline(newCP[1], newCP[3]);
-            if (intersect(&l1, &l2, &mid))
-                quadCorner(newCP[0], newCP[2], newCP[1], newCP[3],
-                           mid, &quad2, &tri);
+        {
+            /* repeat for the "to-be" control points */
+            line const l1 = makeline(newCP[0], newCP[1]);
+            line const l2 = makeline(newCP[2], newCP[3]);
+            bool theyIntersect;
+            point mid;
+            findIntersection(&l1, &l2, &theyIntersect, &mid);
+            if (theyIntersect)
+                quadCorner(newCP[0], newCP[1], newCP[2], newCP[3],
+                           mid, &quad2, NULL);
             else {
-                l1 = makeline(newCP[0], newCP[3]);
-                l2 = makeline(newCP[1], newCP[2]);
-                if (intersect(&l1, &l2, &mid))
-                    quadCorner(newCP[0], newCP[3],
-                               newCP[1], newCP[2], mid, &quad2, &tri);
-                else
-                    pm_error("The four new control points don't seem "
-                             "to be corners.");
+                line const l1 = makeline(newCP[0], newCP[2]);
+                line const l2 = makeline(newCP[1], newCP[3]);
+                bool theyIntersect;
+                point mid;
+                findIntersection(&l1, &l2, &theyIntersect, &mid);
+                if (theyIntersect)
+                    quadCorner(newCP[0], newCP[2], newCP[1], newCP[3],
+                               mid, &quad2, NULL);
+                else {
+                    line const l1 = makeline(newCP[0], newCP[3]);
+                    line const l2 = makeline(newCP[1], newCP[2]);
+                    bool theyIntersect;
+                    point mid;
+                    findIntersection(&l1, &l2, &theyIntersect, &mid);
+                    if (theyIntersect)
+                        quadCorner(newCP[0], newCP[3],
+                                   newCP[1], newCP[2], mid, &quad2, NULL);
+                    else
+                        pm_error("The four new control points don't seem "
+                                 "to be corners.");
+                }
             }
         }
     }
@@ -1127,14 +1166,11 @@ warpTrig(point   const p2,
 
     point e1p1, e1p2, e1p3;
     point e2p1, e2p2, e2p3;
-    line lp, le;
-    line l1, l2, l3;
-    double d1, d2, d3;
-    int i;
+    unsigned int i;
 
     /* find in which triangle p2 lies */
-    for (i = 0; i < nTri; i++) {
-        if (insidetri (&tri2s[i], p2))
+    for (i = 0; i < nTri; ++i) {
+        if (insidetri(&tri2s[i], p2))
             break;
     }
 
@@ -1142,25 +1178,33 @@ warpTrig(point   const p2,
         *p1P = makepoint(0.0, 0.0);
     else {
         /* where in triangle is point */
-        d1 = fabs (p2.x - tri2s[i].p1.x) + fabs (p2.y - tri2s[i].p1.y);
-        d2 = fabs (p2.x - tri2s[i].p2.x) + fabs (p2.y - tri2s[i].p2.y);
-        d3 = fabs (p2.x - tri2s[i].p3.x) + fabs (p2.y - tri2s[i].p3.y);
-
-        /* line through p1 and p intersecting with edge p2-p3 */
-        lp = makeline(tri2s[i].p1, p2);
-        le = makeline(tri2s[i].p2, tri2s[i].p3);
-        intersect (&lp, &le, &e2p1);
-
-        /* line through p2 and p intersecting with edge p3-p1 */
-        lp = makeline(tri2s[i].p2, p2);
-        le = makeline(tri2s[i].p3, tri2s[i].p1);
-        intersect (&lp, &le, &e2p2);
+        double const d1 =
+            fabs (p2.x - tri2s[i].p1.x) + fabs (p2.y - tri2s[i].p1.y);
+        double const d2 =
+            fabs (p2.x - tri2s[i].p2.x) + fabs (p2.y - tri2s[i].p2.y);
+        double const d3 =
+            fabs (p2.x - tri2s[i].p3.x) + fabs (p2.y - tri2s[i].p3.y);
+
+        {
+            /* line through p1 and p intersecting with edge p2-p3 */
+            line const lp = makeline(tri2s[i].p1, p2);
+            line const le = makeline(tri2s[i].p2, tri2s[i].p3);
+            findIntersection(&lp, &le, NULL, &e2p1);
+        }
 
-        /* line through p3 and p intersecting with edge p1-p2 */
-        lp = makeline(tri2s[i].p3, p2);
-        le = makeline(tri2s[i].p1, tri2s[i].p2);
-        intersect (&lp, &le, &e2p3);
+        {
+            /* line through p2 and p intersecting with edge p3-p1 */
+            line const lp = makeline(tri2s[i].p2, p2);
+            line const le = makeline(tri2s[i].p3, tri2s[i].p1);
+            findIntersection(&lp, &le, NULL, &e2p2);
+        }
 
+        {
+            /* line through p3 and p intersecting with edge p1-p2 */
+            line const lp = makeline(tri2s[i].p3, p2);
+            line const le = makeline(tri2s[i].p1, tri2s[i].p2);
+            findIntersection(&lp, &le, NULL, &e2p3);
+        }
         /* map target control points to source control points */
         e1p1.x = tri1s[i].p2.x
             + (e2p1.x - tri2s[i].p2.x)/(tri2s[i].p3.x - tri2s[i].p2.x)
@@ -1181,17 +1225,19 @@ warpTrig(point   const p2,
             + (e2p3.y - tri2s[i].p1.y)/(tri2s[i].p2.y - tri2s[i].p1.y)
             * (tri1s[i].p2.y - tri1s[i].p1.y);
 
-        /* intersect grid lines in source */
-        l1 = makeline(tri1s[i].p1, e1p1);
-        l2 = makeline(tri1s[i].p2, e1p2);
-        l3 = makeline(tri1s[i].p3, e1p3);
-
-        if ((d1 < d2) && (d1 < d3))
-            intersect (&l2, &l3, p1P);
-        else if (d2 < d3)
-            intersect (&l1, &l3, p1P);
-        else
-            intersect (&l1, &l2, p1P);
+        {
+            /* intersect grid lines in source */
+            line const l1 = makeline(tri1s[i].p1, e1p1);
+            line const l2 = makeline(tri1s[i].p2, e1p2);
+            line const l3 = makeline(tri1s[i].p3, e1p3);
+
+            if ((d1 < d2) && (d1 < d3))
+                findIntersection(&l2, &l3, NULL, p1P);
+            else if (d2 < d3)
+                findIntersection(&l1, &l3, NULL, p1P);
+            else
+                findIntersection(&l1, &l2, NULL, p1P);
+        }
     }
 }
 
@@ -1208,8 +1254,6 @@ warpQuad(point   const p2,
     point c2tl, c2tr, c2bl, c2br;
     point e1t, e1b, e1l, e1r;
     point e2t, e2b, e2l, e2r;
-    line l2t, l2b, l2l, l2r;
-    line lh, lv;
 
     c1tl = quad1.tl;
     c1tr = quad1.tr;
@@ -1221,24 +1265,27 @@ warpQuad(point   const p2,
     c2bl = quad2.bl;
     c2br = quad2.br;
 
-    l2t = makeline(c2tl, c2tr);
-    l2b = makeline(c2bl, c2br);
-    l2l = makeline(c2tl, c2bl);
-    l2r = makeline(c2tr, c2br);
-
-    /* find intersections of lines through control points */
-    intersect (&l2t, &l2b, &h2);
-    intersect (&l2l, &l2r, &v2);
-
-    /* find intersections of axes through P with control point box */
-    lv = makeline(p2, v2);
-    intersect (&l2t, &lv, &e2t);
-    intersect (&l2b, &lv, &e2b);
-
-    lh = makeline(p2, h2);
-    intersect (&l2l, &lh, &e2l);
-    intersect (&l2r, &lh, &e2r);
-
+    {
+        line const l2t = makeline(c2tl, c2tr);
+        line const l2b = makeline(c2bl, c2br);
+        line const l2l = makeline(c2tl, c2bl);
+        line const l2r = makeline(c2tr, c2br);
+
+        /* find intersections of lines through control points */
+        findIntersection(&l2t, &l2b, NULL, &h2);
+        findIntersection(&l2l, &l2r, NULL, &v2);
+
+        {
+            /* find intersections of axes through P with control point box */
+            line const lv = makeline(p2, v2);
+            line const lh = makeline(p2, h2);
+
+            findIntersection(&l2t, &lv, NULL, &e2t);
+            findIntersection(&l2b, &lv, NULL, &e2b);
+            findIntersection(&l2l, &lh, NULL, &e2l);
+            findIntersection(&l2r, &lh, NULL, &e2r);
+        }
+    }
     /* map target control points to source control points */
     e1t.x = c1tl.x + (e2t.x - c2tl.x)/(c2tr.x - c2tl.x) * (c1tr.x - c1tl.x);
     if (c1tl.y == c1tr.y)
@@ -1268,16 +1315,18 @@ warpQuad(point   const p2,
             = c1tr.x + (e2r.y - c2tr.y)/(c2br.y - c2tr.y) * (c1br.x - c1tr.x);
     e1r.y = c1tr.y + (e2r.y - c2tr.y)/(c2br.y - c2tr.y) * (c1br.y - c1tr.y);
 
-    /* intersect grid lines in source */
-    lv = makeline(e1t, e1b);
-    lh = makeline(e1l, e1r);
-    intersect (&lh, &lv, p1P);
+    {
+        /* intersect grid lines in source */
+        line const lv = makeline(e1t, e1b);
+        line const lh = makeline(e1l, e1r);
+        findIntersection(&lh, &lv, NULL, p1P);
+    }
 }
 
 
 
 static void
-setGlobalCP(struct cmdlineInfo const cmdline) {
+setGlobalCP(struct CmdlineInfo const cmdline) {
 
     unsigned int i;
 
@@ -1392,7 +1441,7 @@ pix(tuple **     const tuples,
 int
 main(int argc, const char ** const argv) {
 
-    struct cmdlineInfo cmdline;
+    struct CmdlineInfo cmdline;
     FILE * ifP;
     struct pam inpam, outpam;
     tuple ** inTuples;
@@ -1405,8 +1454,6 @@ main(int argc, const char ** const argv) {
 
     setGlobalCP(cmdline);
 
-    srand(cmdline.randseedSpec ? cmdline.randseed : pm_randseed());
-
     ifP = pm_openr(cmdline.fileName);
 
     inTuples = pnm_readpam(ifP, &inpam, PAM_STRUCT_SIZE(tuple_type));
@@ -1421,7 +1468,8 @@ main(int argc, const char ** const argv) {
     makeAllWhite(&outpam, outTuples);
 
     if (cmdline.tri)
-        prepTrig(inpam.width, inpam.height);
+        prepTrig(inpam.width, inpam.height,
+                 cmdline.randomseedSpec, cmdline.randomseed);
     if (cmdline.quad)
         prepQuad();
 
diff --git a/editor/pamscale.c b/editor/pamscale.c
index d8436689..8a51b2be 100644
--- a/editor/pamscale.c
+++ b/editor/pamscale.c
@@ -636,7 +636,6 @@ parseCommandLine(int argc,
 --------------------------------------------------------------------------*/
     optEntry * option_def;
     optStruct3 opt;
-        /* Instructions to pm_optParseOptions3 on how to parse our options. */
 
     unsigned int option_def_index;
     unsigned int xyfit, xyfill;
@@ -675,7 +674,7 @@ parseCommandLine(int argc,
     opt.short_allowed = false;  /* We have no short (old-fashioned) options */
     opt.allowNegNum = false;   /* We have no parms that are negative numbers */
 
-    pm_optParseOptions3(&argc, (char **)argv, opt, sizeof(opt), 0);
+    pm_optParseOptions4(&argc, argv, opt, sizeof(opt), 0);
     /* Uses and sets argc, argv, and some of *cmdlineP and others. */
 
     if (cmdlineP->nomix && filterSpec)
@@ -2108,33 +2107,45 @@ scaleWithoutMixing(const struct pam * const inpamP,
 -----------------------------------------------------------------------------*/
     tuple * tuplerow;  /* An input row */
     tuple * newtuplerow;
-    int row;
-    int rowInInput;
+    unsigned int row;
+        /* The number of the next row to be output */
+    unsigned int rowInInput;
+        /* The number of the next row to be read from the input */
 
     assert(outpamP->maxval == inpamP->maxval);
     assert(outpamP->depth  == inpamP->depth);
 
     tuplerow = pnm_allocpamrow(inpamP);
-    rowInInput = -1;
+    rowInInput = 0;
 
     newtuplerow = pnm_allocpamrow(outpamP);
 
     for (row = 0; row < outpamP->height; ++row) {
-        int col;
+        unsigned int col;
 
-        int const inputRow = (int) (row / yscale);
+        unsigned int const inputRow = (int) (row / yscale);
+            /* The number of the input row that we will use for this output
+               row.
+            */
 
-        for (; rowInInput < inputRow; ++rowInInput)
+        for (; rowInInput <= inputRow; ++rowInInput)
             pnm_readpamrow(inpamP, tuplerow);
 
         for (col = 0; col < outpamP->width; ++col) {
-            int const inputCol = (int) (col / xscale);
+            unsigned int const inputCol = (int) (col / xscale);
 
             pnm_assigntuple(inpamP, newtuplerow[col], tuplerow[inputCol]);
         }
 
         pnm_writepamrow(outpamP, newtuplerow);
     }
+    /* Read off and discard rest of rows, because whatever is supplying the
+       input stream may expect it to be consumed and because Caller will expect
+       the stream to be positioned to the next image.
+    */
+    for (; rowInInput < inpamP->height; ++rowInInput)
+        pnm_readpamrow(inpamP, tuplerow);
+
     pnm_freepamrow(tuplerow);
     pnm_freepamrow(newtuplerow);
 }
@@ -2239,7 +2250,7 @@ pamscale(FILE *             const ifP,
 
 
 int
-main(int argc, const char **argv ) {
+main(int argc, const char ** const argv) {
 
     struct CmdlineInfo cmdline;
     FILE * ifP;
diff --git a/editor/pamshuffle.c b/editor/pamshuffle.c
new file mode 100644
index 00000000..bffb79c5
--- /dev/null
+++ b/editor/pamshuffle.c
@@ -0,0 +1,155 @@
+/*=============================================================================
+                               pamshuffle
+===============================================================================
+  Part of the Netpbm package.
+
+  Relocate pixels in row, randomly, using Fisher-Yates shuffling.
+
+  By Akira F. Urushibata
+
+  Contributed to the public domain by its author.
+=============================================================================*/
+
+#include <assert.h>
+#include "pm_c_util.h"
+#include "pam.h"
+#include "rand.h"
+#include "shhopt.h"
+
+struct CmdlineInfo {
+    /* All the information the user supplied in the command line,
+       in a form easy for the program to use.
+    */
+    const char * inputFileName;
+    unsigned int column;
+    unsigned int randomseedSpec;
+    unsigned int randomseed;
+};
+
+static void
+parseCommandLine(int argc, const char ** const argv,
+                 struct CmdlineInfo * const cmdlineP) {
+/*----------------------------------------------------------------------------
+   Note that the file spec array we return is stored in the storage that
+   was passed to us as the argv array.
+-----------------------------------------------------------------------------*/
+    optEntry * option_def;
+        /* Instructions to OptParseOptions3 on how to parse our options. */
+    optStruct3 opt;
+
+    unsigned int option_def_index;
+
+    MALLOCARRAY(option_def, 100);
+
+    opt.opt_table = option_def;
+    opt.short_allowed = false;  /* We have no short (old-fashioned) options */
+    opt.allowNegNum = true;  /* We have no parms that are negative numbers */
+
+    option_def_index = 0;   /* incremented by OPTENT3 */
+    OPTENT3(0,   "column",     OPT_FLAG,   NULL,
+                               &cmdlineP->column,                    0);
+    OPTENT3(0,   "randomseed", OPT_UINT,   &cmdlineP->randomseed,
+                               &cmdlineP->randomseedSpec,            0);
+
+    pm_optParseOptions3(&argc, (char **)argv, opt, sizeof(opt), 0);
+        /* Uses and sets argc, argv, and some of *cmdlineP and others. */
+
+    free(option_def);
+
+    if (argc-1 > 1)
+        pm_error("Too many arguments (%u). "
+                 "The only possible argument is the input file name.", argc-1);
+    else if (argc-1 < 1)
+        cmdlineP->inputFileName = "-";
+    else
+        cmdlineP->inputFileName = argv[1];
+
+}
+
+
+
+static void
+shuffleRow(tuple *            const tuplerow,
+           unsigned int       const cols,
+           struct pm_randSt * const randStP) {
+
+    unsigned int col;
+
+    for (col = 0; col + 1 < cols; ++col) {
+        tuple        const temp    = tuplerow[col];
+        unsigned int const randcol = col + pm_rand(randStP) % (cols - col);
+
+        assert(randcol >= col );
+        assert(randcol < cols);
+
+        /* swap */
+        tuplerow[col]     = tuplerow[randcol];
+        tuplerow[randcol] = temp;
+    }
+}
+
+
+
+int
+main(int argc, const char * argv[]) {
+
+    FILE * ifP;
+    int    eof;     /* no more images in input stream */
+
+    struct CmdlineInfo cmdline;
+    struct pam inpam;   /* Input PAM image */
+    struct pam outpam;  /* Output PAM image */
+    struct pm_randSt randSt;
+
+    pm_proginit(&argc, argv);
+
+    parseCommandLine(argc, argv, &cmdline);
+
+    ifP = pm_openr(cmdline.inputFileName);
+
+    pm_randinit(&randSt);
+    pm_srand2(&randSt, cmdline.randomseedSpec, cmdline.randomseed);
+
+    for (eof = FALSE; !eof;) {
+        tuple * inrow;   /* Input row buffer */
+        tuple * outrow;  /* Pointers into the input row buffer to reorder it */
+        unsigned int row, col;
+
+        pnm_readpaminit(ifP, &inpam, PAM_STRUCT_SIZE(tuple_type));
+
+        outpam = inpam;
+        outpam.file = stdout;
+
+        pnm_writepaminit(&outpam);
+
+        inrow = pnm_allocpamrow(&inpam);
+
+        MALLOCARRAY(outrow, inpam.width);
+
+        if (!outrow)
+            pm_error("Unable to allocate memory for %u-column output buffer",
+                     inpam.width);
+
+        for (col = 0; col < inpam.width; ++col)
+            outrow[col] = inrow[col];
+
+        for (row = 0; row < inpam.height; ++row) {
+            pnm_readpamrow(&inpam, inrow);
+
+            if (cmdline.column && row > 0) {
+                /* Use the same shuffle ('outrow') as the previous row */
+            } else
+                shuffleRow(outrow, inpam.width, &randSt);
+
+            pnm_writepamrow(&outpam, outrow);
+        }
+
+        pnm_freepamrow(inrow);
+        free(outrow);
+        pnm_nextimage(ifP, &eof);
+    }
+
+    pm_randterm(&randSt);
+
+    return 0;
+}
diff --git a/editor/pamsistoaglyph.c b/editor/pamsistoaglyph.c
index 6b093520..cac1f99f 100644
--- a/editor/pamsistoaglyph.c
+++ b/editor/pamsistoaglyph.c
@@ -6,7 +6,7 @@
  *
  * ----------------------------------------------------------------------
  *
- * Copyright (C) 2009 Scott Pakin <scott+pbm@pakin.org>
+ * Copyright (C) 2009-2022 Scott Pakin <scott+pbm@pakin.org>
  *
  * This program is free software: you can redistribute it and/or modify
  * it under the terms of the GNU General Public License as published by
@@ -127,7 +127,10 @@ readAsGray( const char * const fileName,
         for (col = 0; col < pamP->width; ++col) {
             double YP, CbP, CrP;
 
-            pnm_YCbCrtuple( tuplerow[col], &YP, &CbP, &CrP );
+            if (pamP->depth >= 3)
+                pnm_YCbCrtuple(tuplerow[col], &YP, &CbP, &CrP);
+            else
+                YP = (double) tuplerow[col][0];
             grayArray[row][col] = (gray)
                 (YP * maxGrayVal / (double)pamP->maxval);
         }
@@ -148,7 +151,7 @@ bestEyeSepWeEncountered(int const bestSeparation[3],
     for (i = 2; i >= 0; --i) {
         if (bestSeparation[i] != 0)
             return bestSeparation[i];
-    }    
+    }
     return altBestSeparation;
 }
 
@@ -426,3 +429,4 @@ main(int argc, const char *argv[]) {
     return 0;
 }
 
+
diff --git a/editor/pamwipeout.c b/editor/pamwipeout.c
index 0fff3fca..5510c22e 100644
--- a/editor/pamwipeout.c
+++ b/editor/pamwipeout.c
@@ -34,12 +34,12 @@ struct cmdlineInfo {
 
 
 static void
-parseCommandLine(int                        argc, 
+parseCommandLine(int                        argc,
                  const char **              argv,
                  struct cmdlineInfo * const cmdlineP ) {
 /*----------------------------------------------------------------------------
    Parse program command line described in Unix standard form by argc
-   and argv.  Return the information in the options as *cmdlineP.  
+   and argv.  Return the information in the options as *cmdlineP.
 
    If command line is internally inconsistent (invalid options, etc.),
    issue error message to stderr and abort program.
@@ -59,9 +59,9 @@ parseCommandLine(int                        argc,
     MALLOCARRAY_NOFAIL(option_def, 100);
 
     option_def_index = 0;   /* incremented by OPTENT3 */
-    OPTENT3(0, "lr",     OPT_FLAG,   NULL,                  
+    OPTENT3(0, "lr",     OPT_FLAG,   NULL,
             &lr,       0);
-    OPTENT3(0, "tb",     OPT_FLAG,   NULL,                  
+    OPTENT3(0, "tb",     OPT_FLAG,   NULL,
             &tb,       0);
 
     opt.opt_table = option_def;
@@ -75,7 +75,7 @@ parseCommandLine(int                        argc,
         pm_error("You must specify either -lr or -tb");
     else if (lr && tb)
         pm_error("You may not specify both -lr and -tb");
-    else 
+    else
         cmdlineP->direction = lr ? DIR_LR : DIR_TB;
 
 
@@ -93,8 +93,8 @@ parseCommandLine(int                        argc,
 
 
 
-static void 
-wipeImgByRow (struct pam const inpam, 
+static void
+wipeImgByRow (struct pam const inpam,
               tuple **   const tuples) {
 
     double const h = (double) inpam.height;
@@ -120,9 +120,9 @@ wipeImgByRow (struct pam const inpam,
 
 
 
-static void 
-wipeRowByCol(struct pam const inpam, 
-             tuple **   const tuples, 
+static void
+wipeRowByCol(struct pam const inpam,
+             tuple **   const tuples,
              tuple *    const tuplerow) {
 
     double const w = (double) inpam.width;
@@ -153,16 +153,16 @@ wipeoutTb(FILE * const ifP,
 
     struct pam inpam, outpam;
     tuple ** tuples;
-    
+
     tuples = pnm_readpam(ifP, &inpam, PAM_STRUCT_SIZE(tuple_type));
 
-    outpam = inpam; 
+    outpam = inpam;
     outpam.file = ofP;
 
     wipeImgByRow(inpam, tuples);
 
     pnm_writepam(&outpam, tuples);
-       
+
     pnm_freepamarray(tuples, &inpam);
 }
 
@@ -171,7 +171,7 @@ wipeoutTb(FILE * const ifP,
 static void
 wipeoutLr(FILE * const ifP,
           FILE * const ofP) {
-    
+
     /* left-right we can read row-by-row */
 
     struct pam inpam, outpam;
diff --git a/editor/pbmclean.c b/editor/pbmclean.c
index 08f410c0..47c775e5 100644
--- a/editor/pbmclean.c
+++ b/editor/pbmclean.c
@@ -381,7 +381,7 @@ cleanSimple(FILE *             const ifP,
    Do the traditional clean where you look only at the immediate neighboring
    pixels of a subject pixel to determine whether to erase that pixel.
 -----------------------------------------------------------------------------*/
-    bit ** buffer;
+    bit ** buffer;  /* one bit per pixel */
         /* The rows of the input relevant to our current processing:
            the current row and the one above and below it.
         */
@@ -399,7 +399,7 @@ cleanSimple(FILE *             const ifP,
     setupInputBuffers(ifP, cols, format, &buffer, &edgeRow,
                       &thisRow, &nextRow);
 
-    outRow = pbm_allocrow(cols);
+    outRow = pbm_allocrow_packed(cols);
 
     pbm_writepbminit(ofP, cols, rows, 0) ;
 
@@ -756,12 +756,12 @@ cleanExtended(FILE *             const ifP,
    We erase (flip) every pixel in every trivial blob.  A trivial blob is
    one with 'trivialSize' pixels or fewer.
 -----------------------------------------------------------------------------*/
-    bit ** pixels;
+    bit ** pixels;    /* one byte per pixel */
     int cols, rows;
 
     pixels = pbm_readpbm(ifP, &cols, &rows);
 
-	cleanPixels(pixels, cols, rows, foregroundColor, trivialSize, nFlippedP);
+        cleanPixels(pixels, cols, rows, foregroundColor, trivialSize, nFlippedP);
 
     pbm_writepbm(ofP, pixels, cols, rows, 0);
 
diff --git a/editor/pbmpscale.c b/editor/pbmpscale.c
index 9ab89350..434c7965 100644
--- a/editor/pbmpscale.c
+++ b/editor/pbmpscale.c
@@ -12,7 +12,7 @@
 #define LEFTBITS pm_byteLeftBits
 #define RIGHTBITS pm_byteRightBits
 
-/* Table for translating bit pattern into "corners" flag element */ 
+/* Table for translating bit pattern into "corners" flag element */
 
 unsigned char const
 transTable[512] = {
@@ -141,7 +141,7 @@ validateComputableDimensions(unsigned int const width,
    See validateComputetableSize() in libpam.c
    and pbm_readpbminitrest() in libpbm2.c
 -----------------------------------------------------------------------------*/
-    unsigned int const maxWidthHeight = INT_MAX - 2;
+    unsigned int const maxWidthHeight = INT_MAX - 10;
     unsigned int const maxScaleFactor = maxWidthHeight / MAX(height, width);
 
     if (scaleFactor > maxScaleFactor)
@@ -154,8 +154,8 @@ validateComputableDimensions(unsigned int const width,
 
 static void
 writeBitSpan(unsigned char * const packedBitrow,
-             int             const cols,
-             int             const offset,
+             unsigned int    const cols,
+             unsigned int    const offset,
              int             const color) {
 /*----------------------------------------------------------------------------
    Write white (color="0") or black (="1") bits into packedBitrow[],
@@ -191,8 +191,8 @@ setFlags(const bit *     const prevrow,
          unsigned char * const flags,
          unsigned int    const cols ) {
 /*----------------------------------------------------------------------------
-   Scan one row, examining the row above and row below, and determine 
-   whether there are "corners" for each pixel.  Feed a 9 bit sample into 
+   Scan one row, examining the row above and row below, and determine
+   whether there are "corners" for each pixel.  Feed a 9 bit sample into
    pre-calculated array transTable[512] to calculate all four corner statuses
    at once.
 
@@ -220,7 +220,7 @@ setFlags(const bit *     const prevrow,
        The high byte of the patterns is a mask, which determines which bits are
        not ignored.
     */
-    uint16_t const patterns[] 
+    uint16_t const patterns[]
         = { 0x0000,   0xd555,            /* no corner */
             0x0001,   0xffc1, 0xd514,    /* normal corner */
             0x0002,   0xd554, 0xd515, 0xbea2, 0xdfc0, 0xfd81, 0xfd80, 0xdf80,
@@ -230,7 +230,7 @@ setFlags(const bit *     const prevrow,
     /*
       For example, the NE corner is examined with the following 8 bit sample:
       Current : W : NW : N : NE : E : SE : S
-      (SW is the "square behind") 
+      (SW is the "square behind")
       */
 #endif
 
@@ -257,7 +257,7 @@ setFlags(const bit *     const prevrow,
         sample = ( ( prevrow24 >> ( 8 -offset) ) & 0x01c0 )
             | ( ( thisrow24 >> (11 -offset) ) & 0x0038 )
             | ( ( nextrow24 >> (14 -offset) ) & 0x0007 );
-        
+
         flags[col] =  transTable[sample];
     }
 }
@@ -275,14 +275,14 @@ expandRow(const bit *     const thisrow,
           int             const ucutoff) {
 /*----------------------------------------------------------------------------
   Process one row, using flags array as reference.  If pixel has no corners
-  output a NxN square of the given color, otherwise output with the 
+  output a NxN square of the given color, otherwise output with the
   specified corner area(s) clipped off.
 -----------------------------------------------------------------------------*/
     unsigned int const outcols = cols * scale;
 
     unsigned int i;
     unsigned int col;
-    
+
     for (i = 0; i < scale; ++i) {
         int const zone = (i > ucutoff) - (i < cutoff);
         int const cut1 =
@@ -297,7 +297,7 @@ expandRow(const bit *     const thisrow,
         cut[1] = cut1;
         cut[2] = cut1 ? cut1 - 1 : 0;
         cut[3] = (cut1 && cutoff > 1) ? cut1 - 1 : cut1;
-      
+
         for (col = 0; col < cols; ++col) {
             unsigned int const col8 = col / 8;
             unsigned int const offset = col % 8;
@@ -309,11 +309,11 @@ expandRow(const bit *     const thisrow,
             if (flag == 0x00) {
                 /* There are no corners, no color change */
                 outcol += scale;
-            } else { 
+            } else {
                 switch (zone) {
                 case -1:
                     if (i==0 && flag == 0xff) {
-                        /* No corners, color changed */ 
+                        /* No corners, color changed */
                         cutl = cutr = 0;
                         flags[col] = 0x00;
                             /* Use above skip procedure next cycle */
@@ -330,7 +330,7 @@ expandRow(const bit *     const thisrow,
                     cutr = cut[SE(flag)];
                     break;
                 }
-                
+
                 if (cutl > 0) {
                     writeBitSpan(outrow, cutl, outcol, !pix);
                     outcol += cutl;
@@ -384,10 +384,10 @@ main(int argc, const char ** argv) {
 
     pbm_readpbminit(ifP, &cols, &rows, &format) ;
 
-    validateComputableDimensions(cols, rows, cmdline.scale); 
+    validateComputableDimensions(cols, rows, cmdline.scale);
 
     outcols = cols * cmdline.scale;
-    outrows = rows * cmdline.scale; 
+    outrows = rows * cmdline.scale;
 
     /* Initialize input buffers.
        We add a margin of 8 bits on the right of the three rows.
@@ -402,7 +402,7 @@ main(int argc, const char ** argv) {
     for (i = 0; i < pbm_packed_bytes(cols + 8); ++i)
         edgerow[i] = 0x00;
 
-    /* Add blank bytes at right edges */ 
+    /* Add blank bytes at right edges */
     for (i = 0; i < 3; ++i)
         buffer[i][pbm_packed_bytes(cols + 8) - 1] = 0x00;
 
diff --git a/editor/pbmreduce.c b/editor/pbmreduce.c
index 3a0968fe..70caa581 100644
--- a/editor/pbmreduce.c
+++ b/editor/pbmreduce.c
@@ -11,9 +11,11 @@
 */
 
 #include "pm_c_util.h"
-#include "pbm.h"
 #include "mallocvar.h"
+#include "rand.h"
 #include "shhopt.h"
+#include "pbm.h"
+
 #include <assert.h>
 
 #define SCALE 1024
@@ -105,7 +107,7 @@ parseCommandLine(int argc, const char ** argv,
         unsigned int scale;
 
         scale = strtol(argv[1], &endptr, 10);
-        if (*argv[1] == '\0') 
+        if (*argv[1] == '\0')
             pm_error("Scale argument is a null string.  Must be a number.");
         else if (*endptr != '\0')
             pm_error("Scale argument contains non-numeric character '%c'.",
@@ -115,7 +117,7 @@ parseCommandLine(int argc, const char ** argv,
                      "You specified %d", scale);
         else if (scale > INT_MAX / scale)
             pm_error("Scale argument too large.  You specified %d", scale);
-        else 
+        else
             cmdlineP->scale = scale;
 
         if (argc-1 > 1) {
@@ -145,10 +147,11 @@ struct FS {
 static void
 initializeFloydSteinberg(struct FS  * const fsP,
                          int          const newcols,
-                         unsigned int const seed,
-                         bool         const seedSpec) {
+                         bool         const seedSpec,
+                         unsigned int const seed) {
 
     unsigned int col;
+    struct pm_randSt randSt;
 
     MALLOCARRAY(fsP->thiserr, newcols + 2);
     MALLOCARRAY(fsP->nexterr, newcols + 2);
@@ -156,33 +159,36 @@ initializeFloydSteinberg(struct FS  * const fsP,
     if (fsP->thiserr == NULL || fsP->nexterr == NULL)
         pm_error("out of memory");
 
-    srand(seedSpec ? seed : pm_randseed());
+    pm_randinit(&randSt);
+    pm_srand2(&randSt, seedSpec, seed);
 
     for (col = 0; col < newcols + 2; ++col)
-        fsP->thiserr[col] = (rand() % SCALE - HALFSCALE) / 4;
+        fsP->thiserr[col] = ((int) (pm_rand(&randSt) % SCALE) - HALFSCALE) / 4;
         /* (random errors in [-SCALE/8 .. SCALE/8]) */
+
+    pm_randterm(&randSt);
 }
 
 
 
 /*
     Scanning method
-    
+
     In Floyd-Steinberg dithering mode horizontal direction of scan alternates
     between rows; this is called "serpentine scanning".
-    
+
     Example input (14 x 7), N=3:
-    
+
     111222333444xx    Fractional pixels on the right edge and bottom edge (x)
-    111222333444xx    are ignored; their values do not influence output. 
+    111222333444xx    are ignored; their values do not influence output.
     111222333444xx
     888777666555xx
     888777666555xx
     888777666555xx
     xxxxxxxxxxxxxx
-    
+
     Output (4 x 2):
-    
+
     1234
     8765
 
@@ -196,11 +202,14 @@ enum Direction { RIGHT_TO_LEFT, LEFT_TO_RIGHT };
 static enum Direction
 oppositeDir(enum Direction const arg) {
 
+    enum Direction retval;
+
     switch (arg) {
-    case LEFT_TO_RIGHT: return RIGHT_TO_LEFT;
-    case RIGHT_TO_LEFT: return LEFT_TO_RIGHT;
+    case LEFT_TO_RIGHT: retval = RIGHT_TO_LEFT; break;
+    case RIGHT_TO_LEFT: retval = LEFT_TO_RIGHT; break;
     }
-    assert(false);  /* All cases handled above */
+
+    return retval;
 }
 
 
@@ -240,7 +249,7 @@ main(int argc, const char * argv[]) {
 
     if (cmdline.halftone == QT_FS)
         initializeFloydSteinberg(&fs, newcols,
-                                 cmdline.randomseed, cmdline.randomseedSpec);
+                                 cmdline.randomseedSpec, cmdline.randomseed);
     else {
         /* These variables are meaningless in this case, and the values
            should never be used.
@@ -258,10 +267,10 @@ main(int argc, const char * argv[]) {
         int limitCol;
         int startCol;
         int step;
-   
+
         for (colChar = 0; colChar < colChars; ++colChar)
             newbitrow[colChar] = 0x00;  /* Clear to white */
- 
+
         for (subrow = 0; subrow < cmdline.scale; ++subrow)
             pbm_readpbmrow(ifP, bitslice[subrow], cols, format);
 
@@ -274,7 +283,7 @@ main(int argc, const char * argv[]) {
         case LEFT_TO_RIGHT: {
             startCol = 0;
             limitCol = newcols;
-            step = +1;  
+            step = +1;
         } break;
         case RIGHT_TO_LEFT: {
             startCol = newcols - 1;
diff --git a/editor/pgmdeshadow.c b/editor/pgmdeshadow.c
index 2c3a90f8..42f94254 100644
--- a/editor/pgmdeshadow.c
+++ b/editor/pgmdeshadow.c
@@ -117,7 +117,7 @@ initializeDeshadowMarker(gray **      const inputPixels,
 -----------------------------------------------------------------------------*/
     { /* Make middle white */
         unsigned int row;
-        
+
         for (row = 1; row < rows-1; ++row) {
             unsigned int col;
             for (col = 1; col < cols-1; ++col)
@@ -154,7 +154,7 @@ min5(gray const a,
      gray const c,
      gray const d,
      gray const e) {
-    
+
     return MIN(a,MIN(b,MIN(c,MIN(d,e))));
 }
 
@@ -229,16 +229,16 @@ estimateBackground(gray **      const inputPixels,
                     stable = FALSE;
                 } else
                     markerPixels[row][col] = inputPixels[row][col];
-            }       
+            }
         }
         /* scan in anti-raster order */
-        
+
         for (row = rows-2; row >= 0; --row) {
             int col;
             for (col = cols-2; col > 0; --col) {
                 gray const minpixel =
                     minSouthwestPixel(markerPixels, col, row);
-                
+
                 if (minpixel > inputPixels[row][col]) {
                     markerPixels[row][col] = minpixel;
                     stable = FALSE;
@@ -285,7 +285,7 @@ divide(gray **      const dividendPixels,
                     quotient =
                         MIN(maxval,
                             maxval * (dividend + dividend/2) / divisor);
-            }        
+            }
             dividendPixels[row][col] = quotient;
         }
     }
@@ -307,9 +307,9 @@ deshadow(gray **      const inputPixels,
     markerPixels = pgm_allocarray(cols, rows);
 
     initializeDeshadowMarker(inputPixels, markerPixels, cols, rows, maxval);
-    
+
     estimateBackground(inputPixels, markerPixels, cols, rows, maxval);
-    
+
     divide(inputPixels, markerPixels, cols, rows, maxval);
 
     pgm_freearray(markerPixels, rows);
@@ -331,12 +331,12 @@ main(int argc, char* argv[]) {
     parseCommandLine(argc, argv, &cmdline);
 
     ifP = pm_openr(cmdline.inputFileName);
-    
+
     pixels = pgm_readpgm(ifP, &cols, &rows, &maxval);
     pm_close(ifP);
-    
+
     deshadow(pixels, cols, rows, maxval);
-    
+
     pgm_writepgm(stdout, pixels, cols, rows, maxval, 0);
 
     pgm_freearray(pixels, rows);
diff --git a/editor/pgmenhance.c b/editor/pgmenhance.c
index 83670568..23cfbb9e 100644
--- a/editor/pgmenhance.c
+++ b/editor/pgmenhance.c
@@ -77,7 +77,7 @@ main(int argc, char * argv[] ) {
         thisrow = nextrow;
         nextrow = temprow;
         pgm_readpgmrow( ifp, nextrow, cols, maxval, format );
-        
+
         newrow[0] = thisrow[0];
         for (col = 1; col < cols - 1; col++) {
             /* Compute the sum of the neighborhood. */
@@ -102,7 +102,7 @@ main(int argc, char * argv[] ) {
         pgm_writepgmrow( stdout, newrow, cols, maxval, 0 );
     }
     pm_close( ifp );
-    
+
     /* Last row. */
     pgm_writepgmrow( stdout, nextrow, cols, maxval, 0 );
 
diff --git a/editor/pgmmedian.c b/editor/pgmmedian.c
index cdd94629..60605713 100644
--- a/editor/pgmmedian.c
+++ b/editor/pgmmedian.c
@@ -25,6 +25,7 @@
 ** Image Processing Algorithms" by Ioannis Pitas.
 */
 
+#include <assert.h>
 
 #include "pm_c_util.h"
 #include "pgm.h"
@@ -32,10 +33,10 @@
 #include "mallocvar.h"
 #include "nstring.h"
 
-enum medianMethod {MEDIAN_UNSPECIFIED, SELECT_MEDIAN, HISTOGRAM_SORT_MEDIAN};
+enum MedianMethod {MEDIAN_UNSPECIFIED, SELECT_MEDIAN, HISTOGRAM_SORT_MEDIAN};
 #define MAX_MEDIAN_TYPES      2
 
-struct cmdlineInfo {
+struct CmdlineInfo {
     /* All the information the user supplied in the command line,
        in a form easy for the program to use.
     */
@@ -43,24 +44,28 @@ struct cmdlineInfo {
     unsigned int width;
     unsigned int height;
     unsigned int cutoff;
-    enum medianMethod type;
+    enum MedianMethod type;
 };
 
 
-/* Global variables common to each median sort routine. */
 static int const forceplain = 0;
-static int format;
-static gray maxval;
-static gray **grays;
-static gray *grayrow;
-static int ccolso2, crowso2;
-static int row;
+
+
+
+/* Global variables common to each median sort routine. */
+static gray ** grays;
+    /* The convolution buffer.  This is a circular buffer that contains the
+       rows of the input image that are being convolved into the current
+       output row.
+    */
+static gray * grayrow;
+    /* A buffer for building the current output row */
 
 
 
 static void
-parseCommandLine(int argc, char ** argv,
-                 struct cmdlineInfo * const cmdlineP) {
+parseCommandLine(int argc, const char ** argv,
+                 struct CmdlineInfo * const cmdlineP) {
 /*----------------------------------------------------------------------------
    Note that the file spec array we return is stored in the storage that
    was passed to us as the argv array.
@@ -91,13 +96,21 @@ parseCommandLine(int argc, char ** argv,
     opt.short_allowed = FALSE;  /* We have no short (old-fashioned) options */
     opt.allowNegNum = FALSE;  /* We may have parms that are negative numbers */
 
-    pm_optParseOptions3(&argc, argv, opt, sizeof(opt), 0);
+    pm_optParseOptions3(&argc, (char **)argv, opt, sizeof(opt), 0);
         /* Uses and sets argc, argv, and some of *cmdlineP and others. */
 
-    if (!widthSpec)
+    if (widthSpec) {
+        if (cmdlineP->width < 1)
+            pm_error("-width must be at least 1");
+    } else
         cmdlineP->width = 3;
-    if (!heightSpec)
+
+    if (heightSpec) {
+        if (cmdlineP->height < 1)
+            pm_error("-height must be at least 1");
+    } else
         cmdlineP->height = 3;
+
     if (!cutoffSpec)
         cmdlineP->cutoff = 250;
 
@@ -125,6 +138,32 @@ parseCommandLine(int argc, char ** argv,
 
 
 static void
+setWindow(gray **      const convBuffer,
+          unsigned int const crows,
+          gray **      const cgrayrow,
+          unsigned int const lastRow) {
+/*----------------------------------------------------------------------------
+   Set 'cgrayrow' so it points into the circular buffer 'convBuffer' such
+   that cgrayrow[0] is the topmost row in the buffer, given that the
+   bottommost row in the buffer is row number 'lastRow'.
+-----------------------------------------------------------------------------*/
+    unsigned int const windowTopRow = (lastRow + 1) % crows;
+
+    unsigned int bufferRow;
+    unsigned int wrow;
+
+    wrow = 0;
+
+    for (bufferRow = windowTopRow; bufferRow < crows; ++wrow, ++bufferRow)
+        cgrayrow[wrow] = grays[bufferRow];
+
+    for (bufferRow = 0; bufferRow < windowTopRow; ++wrow, ++bufferRow)
+        cgrayrow[wrow] = grays[bufferRow];
+}
+
+
+
+static void
 select489(gray * const a,
           int *  const parray,
           int    const n,
@@ -184,7 +223,13 @@ selectMedian(FILE *       const ifP,
              unsigned int const crows,
              unsigned int const cols,
              unsigned int const rows,
-             unsigned int const median) {
+             int          const format,
+             gray         const maxval,
+             unsigned int const median,
+             unsigned int const firstRow) {
+
+    unsigned int const ccolso2 = ccols / 2;
+    unsigned int const crowso2 = crows / 2;
 
     unsigned int const numValues = crows * ccols;
 
@@ -192,45 +237,39 @@ selectMedian(FILE *       const ifP,
     gray * garray;  /* Array of the currently gray values */
     int * parray;
     int * subcol;
-    gray ** rowptr;
+    gray ** cgrayrow;
+    unsigned int row;
 
     garray = pgm_allocrow(numValues);
 
-    MALLOCARRAY(rowptr, crows);
+    MALLOCARRAY(cgrayrow, crows);
     MALLOCARRAY(parray, numValues);
     MALLOCARRAY(subcol, cols);
 
-    if (rowptr == NULL || parray == NULL || subcol == NULL)
+    if (cgrayrow == NULL || parray == NULL || subcol == NULL)
         pm_error("Unable to allocate memory");
 
     for (col = 0; col < cols; ++col)
         subcol[col] = (col - (ccolso2 + 1)) % ccols;
 
     /* Apply median to main part of image. */
-    for ( ; row < rows; ++row) {
-        int crow;
-        int rownum, irow, temprow;
+    for (row = firstRow; row < rows; ++row) {
+        unsigned int crow;
         unsigned int col;
 
         pgm_readpgmrow(ifP, grays[row % crows], cols, maxval, format);
 
-        /* Rotate pointers to rows, so rows can be accessed in order. */
-        temprow = (row + 1) % crows;
-        rownum = 0;
-        for (irow = temprow; irow < crows; ++rownum, ++irow)
-            rowptr[rownum] = grays[irow];
-        for (irow = 0; irow < temprow; ++rownum, ++irow)
-            rowptr[rownum] = grays[irow];
+        setWindow(grays, crows, cgrayrow, row);
 
         for (col = 0; col < cols; ++col) {
             if (col < ccolso2 || col >= cols - ccolso2) {
-                grayrow[col] = rowptr[crowso2][col];
+                grayrow[col] = cgrayrow[crowso2][col];
             } else if (col == ccolso2) {
                 unsigned int const leftcol = col - ccolso2;
                 unsigned int i;
                 i = 0;
                 for (crow = 0; crow < crows; ++crow) {
-                    gray * const temprptr = rowptr[crow] + leftcol;
+                    gray * const temprptr = cgrayrow[crow] + leftcol;
                     unsigned int ccol;
                     for (ccol = 0; ccol < ccols; ++ccol) {
                         garray[i] = *(temprptr + ccol);
@@ -245,23 +284,16 @@ selectMedian(FILE *       const ifP,
                 unsigned int crow;
                 unsigned int tsum;
                 for (crow = 0, tsum = 0; crow < crows; ++crow, tsum += ccols)
-                    garray[tsum + subcol[col]] = *(rowptr[crow] + addcol );
+                    garray[tsum + subcol[col]] = *(cgrayrow[crow] + addcol );
                 select489( garray, parray, numValues, median );
                 grayrow[col] = garray[parray[median]];
             }
         }
         pgm_writepgmrow( stdout, grayrow, cols, maxval, forceplain );
     }
-
-    {
-        unsigned int irow;
-        /* Write out remaining unchanged rows. */
-        for (irow = crowso2 + 1; irow < crows; ++irow)
-            pgm_writepgmrow(stdout, rowptr[irow], cols, maxval, forceplain);
-    }
     free(subcol);
     free(parray);
-    free(rowptr);
+    free(cgrayrow);
     pgm_freerow(garray);
 }
 
@@ -273,31 +305,40 @@ histogramSortMedian(FILE *       const ifP,
                     unsigned int const crows,
                     unsigned int const cols,
                     unsigned int const rows,
-                    unsigned int const median) {
+                    int          const format,
+                    gray         const maxval,
+                    unsigned int const median,
+                    unsigned int const firstRow) {
 
+    unsigned int const ccolso2 = ccols / 2;
+    unsigned int const crowso2 = crows / 2;
     unsigned int const histmax = maxval + 1;
 
     unsigned int * hist;
     unsigned int mdn, ltmdn;
     gray * leftCol;
     gray * rghtCol;
-    gray ** rowptr;
-
-    MALLOCARRAY(rowptr, crows);
+    gray ** cgrayrow;
+        /* The window of the image currently being convolved, with
+           cgrayrow[0] being the top row of the window.  Pointers into grays[]
+        */
+    unsigned int row;
+        /* Row number in input -- bottommost row in the window we're currently
+           convolving
+        */
+
+    MALLOCARRAY(cgrayrow, crows);
     MALLOCARRAY(hist, histmax);
 
-    if (rowptr == NULL || hist == NULL)
+    if (cgrayrow == NULL || hist == NULL)
         pm_error("Unable to allocate memory");
 
     leftCol = pgm_allocrow(crows);
     rghtCol = pgm_allocrow(crows);
 
     /* Apply median to main part of image. */
-    for ( ; row < rows; ++row) {
+    for (row = firstRow; row < rows; ++row) {
         unsigned int col;
-        unsigned int temprow;
-        unsigned int rownum;
-        unsigned int irow;
         unsigned int i;
         /* initialize hist[] */
         for (i = 0; i < histmax; ++i)
@@ -305,24 +346,18 @@ histogramSortMedian(FILE *       const ifP,
 
         pgm_readpgmrow(ifP, grays[row % crows], cols, maxval, format);
 
-        /* Rotate pointers to rows, so rows can be accessed in order. */
-        temprow = (row + 1) % crows;
-        rownum = 0;
-        for (irow = temprow; irow < crows; ++rownum, ++irow)
-            rowptr[rownum] = grays[irow];
-        for (irow = 0; irow < temprow; ++rownum, ++irow)
-            rowptr[rownum] = grays[irow];
+        setWindow(grays, crows, cgrayrow, row);
 
         for (col = 0; col < cols; ++col) {
             if (col < ccolso2 || col >= cols - ccolso2)
-                grayrow[col] = rowptr[crowso2][col];
+                grayrow[col] = cgrayrow[crowso2][col];
             else if (col == ccolso2) {
-                unsigned int crow;
                 unsigned int const leftcol = col - ccolso2;
+                unsigned int crow;
                 i = 0;
                 for (crow = 0; crow < crows; ++crow) {
                     unsigned int ccol;
-                    gray * const temprptr = rowptr[crow] + leftcol;
+                    gray * const temprptr = cgrayrow[crow] + leftcol;
                     for (ccol = 0; ccol < ccols; ++ccol) {
                         gray const g = *(temprptr + ccol);
                         ++hist[g];
@@ -338,12 +373,12 @@ histogramSortMedian(FILE *       const ifP,
 
                 grayrow[col] = mdn;
             } else {
-                unsigned int crow;
                 unsigned int const subcol = col - (ccolso2 + 1);
                 unsigned int const addcol = col + ccolso2;
+                unsigned int crow;
                 for (crow = 0; crow < crows; ++crow) {
-                    leftCol[crow] = *(rowptr[crow] + subcol);
-                    rghtCol[crow] = *(rowptr[crow] + addcol);
+                    leftCol[crow] = *(cgrayrow[crow] + subcol);
+                    rghtCol[crow] = *(cgrayrow[crow] + addcol);
                 }
                 for (crow = 0; crow < crows; ++crow) {
                     {
@@ -381,87 +416,127 @@ histogramSortMedian(FILE *       const ifP,
         }
         pgm_writepgmrow(stdout, grayrow, cols, maxval, forceplain);
     }
-
-    {
-        /* Write out remaining unchanged rows. */
-        unsigned int irow;
-        for (irow = crowso2 + 1; irow < crows; ++irow)
-            pgm_writepgmrow(stdout, rowptr[irow], cols, maxval, forceplain);
-    }
     pgm_freerow(leftCol);
     pgm_freerow(rghtCol);
     free(hist);
-    free(rowptr);
+    free(cgrayrow);
+}
+
+
+
+static void
+convolve(FILE *            const ifP,
+         unsigned int      const cols,
+         unsigned int      const rows,
+         gray              const maxval,
+         int               const format,
+         unsigned int      const ccols,
+         unsigned int      const crows,
+         enum MedianMethod const medianMethod,
+         unsigned int      const median) {
+
+    unsigned int const crowso2 = crows / 2;
+
+    unsigned int row;
+
+    /* An even-size convolution window is biased toward the top and left.  So
+       if it is 8 rows, the window covers 4 rows above the target row and 3
+       rows below it, plus the target row itself.  'crowso2' is the number of
+       the target row within the window.  There are always 'crowso2' rows
+       above it and either crowso2 or crowso2-1 rows below it.
+    */
+
+    /* Allocate space for number of rows in mask size. */
+    grays = pgm_allocarray(cols, crows);
+    grayrow = pgm_allocrow(cols);
+
+    /* Prime the convolution window -- fill it except the last row */
+    for (row = 0; row < crows - 1; ++row)
+        pgm_readpgmrow(ifP, grays[row], cols, maxval, format);
+
+    /* Copy the top half out verbatim, since convolution kernel for these rows
+       runs off the top of the image.
+    */
+    for (row = 0; row < crowso2; ++row)
+        pgm_writepgmrow(stdout, grays[row], cols, maxval, forceplain);
+
+    switch (medianMethod) {
+    case SELECT_MEDIAN:
+        selectMedian(ifP, ccols, crows, cols, rows, format, maxval,
+                     median, crows-1);
+        break;
+
+    case HISTOGRAM_SORT_MEDIAN:
+        histogramSortMedian(ifP, ccols, crows, cols, rows, format, maxval,
+                            median, crows-1);
+        break;
+    case MEDIAN_UNSPECIFIED:
+        pm_error("INTERNAL ERROR: median unspecified");
+    }
+
+    /* Copy the bottom half of the remaining convolution window verbatim,
+       since convolution kernel for these rows runs off the bottom of the
+       image.
+    */
+    assert(crows >= crowso2 + 1);
+
+    for (row = rows - (crows-crowso2-1); row < rows; ++row)
+        pgm_writepgmrow(stdout, grays[row % crows], cols, maxval,
+                        forceplain);
+
+    pgm_freearray(grays, crows);
+    pgm_freerow(grayrow);
 }
 
 
 
 int
-main(int    argc,
-     char * argv[]) {
+main(int          argc,
+     const char * argv[]) {
 
-    struct cmdlineInfo cmdline;
+    struct CmdlineInfo cmdline;
     FILE * ifP;
     int cols, rows;
-    int median;
-    enum medianMethod medianMethod;
+    int format;
+    gray maxval;
+    unsigned int ccols, crows;
+    unsigned int median;
+    enum MedianMethod medianMethod;
 
-    pgm_init(&argc, argv);
+    pm_proginit(&argc, argv);
 
     parseCommandLine(argc, argv, &cmdline);
 
     ifP = pm_openr(cmdline.inputFileName);
 
-    ccolso2 = cmdline.width / 2;
-    crowso2 = cmdline.height / 2;
+    assert(cmdline.height > 0 && cmdline.width > 0);
 
     pgm_readpgminit(ifP, &cols, &rows, &maxval, &format);
-    pgm_writepgminit(stdout, cols, rows, maxval, forceplain);
 
-    /* Allocate space for number of rows in mask size. */
-    grays = pgm_allocarray(cols, cmdline.height);
-    grayrow = pgm_allocrow(cols);
+    ccols = MIN(cmdline.width,  cols+1);
+    crows = MIN(cmdline.height, rows+1);
 
-    /* Read in and write out initial rows that won't get changed. */
-    for (row = 0; row < cmdline.height - 1; ++row) {
-        pgm_readpgmrow(ifP, grays[row], cols, maxval, format);
-        /* Write out the unchanged row. */
-        if (row < crowso2)
-            pgm_writepgmrow(stdout, grays[row], cols, maxval, forceplain);
-    }
+    pgm_writepgminit(stdout, cols, rows, maxval, forceplain);
 
-    median = (cmdline.height * cmdline.width) / 2;
+    median = (crows * ccols) / 2;
 
     /* Choose which sort to run. */
     if (cmdline.type == MEDIAN_UNSPECIFIED) {
-        if ((maxval / ((cmdline.width * cmdline.height) - 1)) < cmdline.cutoff)
+        if ((maxval / ((ccols * crows) - 1)) < cmdline.cutoff)
             medianMethod = HISTOGRAM_SORT_MEDIAN;
         else
             medianMethod = SELECT_MEDIAN;
     } else
         medianMethod = cmdline.type;
 
-    switch (medianMethod) {
-    case SELECT_MEDIAN:
-        selectMedian(ifP, cmdline.width, cmdline.height, cols, rows, median);
-        break;
 
-    case HISTOGRAM_SORT_MEDIAN:
-        histogramSortMedian(ifP, cmdline.width, cmdline.height,
-                            cols, rows, median);
-        break;
-    case MEDIAN_UNSPECIFIED:
-        pm_error("INTERNAL ERROR: median unspecified");
-    }
+    convolve(ifP, cols, rows, maxval, format, ccols, crows, medianMethod,
+             median);
 
     pm_close(ifP);
     pm_close(stdout);
 
-    pgm_freearray(grays, cmdline.height);
-    pgm_freerow(grayrow);
-
     return 0;
 }
 
 
-
diff --git a/editor/pnmalias.c b/editor/pnmalias.c
index 36b41ce4..51a71312 100644
--- a/editor/pnmalias.c
+++ b/editor/pnmalias.c
@@ -43,23 +43,23 @@ main(int argc, char * argv[] ) {
 
     while ( argn < argc && argv[argn][0] == '-' )
         {
-        if ( pm_keymatch( argv[argn], "-fgcolor", 3 ) ) 
+        if ( pm_keymatch( argv[argn], "-fgcolor", 3 ) )
         {
-        if ( ++argn >= argc ) 
+        if ( ++argn >= argc )
         pm_usage( usage );
-        else 
+        else
         fgcolorppm = ppm_parsecolor( argv[argn], PPM_MAXMAXVAL );
         }
-        else if ( pm_keymatch( argv[argn], "-bgcolor", 3 ) ) 
+        else if ( pm_keymatch( argv[argn], "-bgcolor", 3 ) )
         {
-        if ( ++argn >= argc ) 
+        if ( ++argn >= argc )
         pm_usage( usage );
-        else 
+        else
         bgcolorppm = ppm_parsecolor( argv[argn], PPM_MAXMAXVAL );
         }
-        else if ( pm_keymatch( argv[argn], "-weight", 2 ) ) 
+        else if ( pm_keymatch( argv[argn], "-weight", 2 ) )
         {
-        if ( ++argn >= argc ) 
+        if ( ++argn >= argc )
         pm_usage( usage );
         else if ( sscanf( argv[argn], "%lf", &weight ) != 1 )
             pm_usage( usage );
@@ -103,7 +103,7 @@ main(int argc, char * argv[] ) {
     fmask[5] = fmask[6] = fmask[7] = fmask[8] = ( 1.0 - weight ) / 8.0;
 
     pnm_readpnminit( ifp, &cols, &rows, &maxval, &format );
-   
+
     xelrow[0] = pnm_allocrow( cols );
     xelrow[1] = pnm_allocrow( cols );
     xelrow[2] = pnm_allocrow( cols );
@@ -120,29 +120,29 @@ main(int argc, char * argv[] ) {
     }
 
     /* Figure out foreground pixel value if none was given */
-    if (PPM_GETR(fgcolorppm) == 0 && PPM_GETG(fgcolorppm) == 0 && 
+    if (PPM_GETR(fgcolorppm) == 0 && PPM_GETG(fgcolorppm) == 0 &&
         PPM_GETB(fgcolorppm) == 0 ) {
         if ( PNM_FORMAT_TYPE(newformat) == PGM_TYPE )
             PNM_ASSIGN1( fgcolor, newmaxval );
-        else 
+        else
             PPM_ASSIGN( fgcolor, newmaxval, newmaxval, newmaxval );
     } else {
         if ( PNM_FORMAT_TYPE(newformat) == PGM_TYPE )
             PNM_ASSIGN1( fgcolor, PPM_GETR( fgcolorppm ) );
-        else 
+        else
             fgcolor = fgcolorppm;
     }
 
-    if (PPM_GETR(bgcolorppm) != 0 || PPM_GETG(bgcolorppm) != 0 || 
+    if (PPM_GETR(bgcolorppm) != 0 || PPM_GETG(bgcolorppm) != 0 ||
         PPM_GETB(bgcolorppm) != 0 ) {
         if ( PNM_FORMAT_TYPE(newformat) == PGM_TYPE )
             PNM_ASSIGN1( bgcolor, PPM_GETR( bgcolorppm) );
-        else 
+        else
             bgcolor = bgcolorppm;
     } else {
         if ( PNM_FORMAT_TYPE(newformat) == PGM_TYPE )
             PNM_ASSIGN1( bgcolor, 0 );
-        else 
+        else
             PPM_ASSIGN( bgcolor, 0, 0, 0 );
     }
 
@@ -158,9 +158,9 @@ main(int argc, char * argv[] ) {
 
         pnm_readpnmrow( ifp, xelrow[(row+1)%3], cols, newmaxval, format );
         newxelrow[0] = xelrow[row%3][0];
-        
+
         for ( col = 1, xpP = (xelrow[(row-1)%3] + 1), xP = (xelrow[row%3] + 1),
-                  xnP = (xelrow[(row+1)%3] + 1), nxP = (newxelrow+1); 
+                  xnP = (xelrow[(row+1)%3] + 1), nxP = (newxelrow+1);
               col < cols - 1; ++col, ++xpP, ++xP, ++xnP, ++nxP ) {
 
             int fgflag, bgflag;
@@ -168,28 +168,28 @@ main(int argc, char * argv[] ) {
             /* Reset flags if anti-aliasing is to be done on foreground
              * or background pixels only */
             if ( ( bgonly && PNM_EQUAL( *xP, fgcolor ) ) ||
-                 ( fgonly && PNM_EQUAL( *xP, bgcolor ) ) ) 
+                 ( fgonly && PNM_EQUAL( *xP, bgcolor ) ) )
                 bgflag = fgflag = 0;
             else {
                 /* Do anti-aliasing here: see if pixel is at the border of a
                  * background or foreground stepwise side */
-                bgflag = 
+                bgflag =
                     (PNM_EQUAL(*xpP,bgcolor) && PNM_EQUAL(*(xP+1),bgcolor)) ||
                     (PNM_EQUAL(*(xP+1),bgcolor) && PNM_EQUAL(*xnP,bgcolor)) ||
                     (PNM_EQUAL(*xnP,bgcolor) && PNM_EQUAL(*(xP-1),bgcolor)) ||
                     (PNM_EQUAL(*(xP-1),bgcolor) && PNM_EQUAL(*xpP,bgcolor));
-                fgflag = 
+                fgflag =
                     (PNM_EQUAL(*xpP,fgcolor) && PNM_EQUAL(*(xP+1),fgcolor)) ||
                     (PNM_EQUAL(*(xP+1),fgcolor) && PNM_EQUAL(*xnP,fgcolor)) ||
                     (PNM_EQUAL(*xnP,fgcolor) && PNM_EQUAL(*(xP-1),fgcolor)) ||
-                    (PNM_EQUAL(*(xP-1),fgcolor) && PNM_EQUAL(*xpP,fgcolor)); 
+                    (PNM_EQUAL(*(xP-1),fgcolor) && PNM_EQUAL(*xpP,fgcolor));
             }
-            if ( ( bgflag && bgalias ) || ( fgflag && fgalias ) || 
+            if ( ( bgflag && bgalias ) || ( fgflag && fgalias ) ||
                  ( bgflag && fgflag ) )
-                switch( PNM_FORMAT_TYPE( newformat ) ) {   
+                switch( PNM_FORMAT_TYPE( newformat ) ) {
                 case PGM_TYPE:
                     value = PNM_GET1(*(xpP-1)) * fmask[0] +
-                        PNM_GET1(*(xpP  )) * fmask[1] + 
+                        PNM_GET1(*(xpP  )) * fmask[1] +
                         PNM_GET1(*(xpP+1)) * fmask[2] +
                         PNM_GET1(*(xP -1)) * fmask[3] +
                         PNM_GET1(*(xP   )) * fmask[4] +
@@ -202,7 +202,7 @@ main(int argc, char * argv[] ) {
                     break;
                 default:
                     valuer= PPM_GETR(*(xpP-1)) * fmask[0] +
-                        PPM_GETR(*(xpP  )) * fmask[1] + 
+                        PPM_GETR(*(xpP  )) * fmask[1] +
                         PPM_GETR(*(xpP+1)) * fmask[2] +
                         PPM_GETR(*(xP -1)) * fmask[3] +
                         PPM_GETR(*(xP   )) * fmask[4] +
@@ -212,7 +212,7 @@ main(int argc, char * argv[] ) {
                         PPM_GETR(*(xnP+1)) * fmask[8] +
                         0.5;
                     valueg= PPM_GETG(*(xpP-1)) * fmask[0] +
-                        PPM_GETG(*(xpP  )) * fmask[1] + 
+                        PPM_GETG(*(xpP  )) * fmask[1] +
                         PPM_GETG(*(xpP+1)) * fmask[2] +
                         PPM_GETG(*(xP -1)) * fmask[3] +
                         PPM_GETG(*(xP   )) * fmask[4] +
@@ -222,7 +222,7 @@ main(int argc, char * argv[] ) {
                         PPM_GETG(*(xnP+1)) * fmask[8] +
                         0.5;
                     valueb= PPM_GETB(*(xpP-1)) * fmask[0] +
-                        PPM_GETB(*(xpP  )) * fmask[1] + 
+                        PPM_GETB(*(xpP  )) * fmask[1] +
                         PPM_GETB(*(xpP+1)) * fmask[2] +
                         PPM_GETB(*(xP -1)) * fmask[3] +
                         PPM_GETB(*(xP   )) * fmask[4] +
@@ -241,9 +241,9 @@ main(int argc, char * argv[] ) {
         newxelrow[cols-1] = xelrow[row%3][cols-1];
         pnm_writepnmrow( stdout, newxelrow, cols, newmaxval, newformat, 0 );
     }
-        
+
     pnm_writepnmrow( stdout, xelrow[row%3], cols, newmaxval, newformat, 0 );
-    
+
     pm_close( ifp );
     exit ( 0 );
 }
diff --git a/editor/pnmcat.c b/editor/pnmcat.c
deleted file mode 100644
index 565ecceb..00000000
--- a/editor/pnmcat.c
+++ /dev/null
@@ -1,874 +0,0 @@
-/* pnmcat.c - concatenate PNM images
-**
-** Copyright (C) 1989, 1991 by Jef Poskanzer.
-**
-** Permission to use, copy, modify, and distribute this software and its
-** documentation for any purpose and without fee is hereby granted, provided
-** that the above copyright notice appear in all copies and that both that
-** copyright notice and this permission notice appear in supporting
-** documentation.  This software is provided "as is" without express or
-** implied warranty.
-*/
-
-#include <assert.h>
-
-#include "pm_c_util.h"
-#include "mallocvar.h"
-#include "shhopt.h"
-#include "bitarith.h"
-#include "nstring.h"
-#include "pnm.h"
-
-#define LEFTBITS pm_byteLeftBits
-#define RIGHTBITS pm_byteRightBits
-
-enum backcolor {BACK_WHITE, BACK_BLACK, BACK_AUTO};
-
-enum orientation {TOPBOTTOM, LEFTRIGHT};
-
-enum justification {JUST_CENTER, JUST_MIN, JUST_MAX};
-
-struct imgInfo {
-    /* This obviously should be a struct pam.  We should convert this
-       to 'pamcat'.
-    */
-    FILE * ifP;
-    int    cols;
-    int    rows;
-    int    format;
-    xelval maxval;
-};
-
-
-
-struct cmdlineInfo {
-    /* All the information the user supplied in the command line,
-       in a form easy for the program to use.
-    */
-    const char ** inputFilespec;
-    unsigned int nfiles;
-    enum backcolor backcolor;
-    enum orientation orientation;
-    enum justification justification;
-};
-
-
-
-static void
-parseCommandLine(int argc, const char ** const argv,
-                 struct cmdlineInfo * const cmdlineP) {
-/*----------------------------------------------------------------------------
-   Note that the file spec array we return is stored in the storage that
-   was passed to us as the argv array.
------------------------------------------------------------------------------*/
-    optEntry * option_def;
-        /* Instructions to OptParseOptions3() on how to parse our options.
-         */
-    optStruct3 opt;
-
-    unsigned int option_def_index;
-
-    unsigned int leftright, topbottom, black, white, jtop, jbottom,
-        jleft, jright, jcenter;
-
-    MALLOCARRAY_NOFAIL(option_def, 100);
-
-    option_def_index = 0;   /* incremented by OPTENTRY */
-    OPTENT3(0, "leftright",  OPT_FLAG,   NULL, &leftright,   0);
-    OPTENT3(0, "lr",         OPT_FLAG,   NULL, &leftright,   0);
-    OPTENT3(0, "topbottom",  OPT_FLAG,   NULL, &topbottom,   0);
-    OPTENT3(0, "tb",         OPT_FLAG,   NULL, &topbottom,   0);
-    OPTENT3(0, "black",      OPT_FLAG,   NULL, &black,       0);
-    OPTENT3(0, "white",      OPT_FLAG,   NULL, &white,       0);
-    OPTENT3(0, "jtop",       OPT_FLAG,   NULL, &jtop,        0);
-    OPTENT3(0, "jbottom",    OPT_FLAG,   NULL, &jbottom,     0);
-    OPTENT3(0, "jleft",      OPT_FLAG,   NULL, &jleft,       0);
-    OPTENT3(0, "jright",     OPT_FLAG,   NULL, &jright,      0);
-    OPTENT3(0, "jcenter",    OPT_FLAG,   NULL, &jcenter,     0);
-
-    opt.opt_table = option_def;
-    opt.short_allowed = FALSE;  /* We have no short (old-fashioned) options */
-    opt.allowNegNum = FALSE;  /* We have no parms that are negative numbers */
-
-    pm_optParseOptions3(&argc, (char **)argv, opt, sizeof(opt), 0);
-        /* Uses and sets argc, argv, and some of *cmdlineP and others. */
-
-    free(option_def);
-
-    if (leftright + topbottom > 1)
-        pm_error("You may specify only one of -topbottom (-tb) and "
-                 "-leftright (-lr)");
-    else if (leftright)
-        cmdlineP->orientation = LEFTRIGHT;
-    else if (topbottom)
-        cmdlineP->orientation = TOPBOTTOM;
-    else
-        pm_error("You must specify either -leftright or -topbottom");
-
-    if (black + white > 1)
-        pm_error("You may specify only one of -black and -white");
-    else if (black)
-        cmdlineP->backcolor = BACK_BLACK;
-    else if (white)
-        cmdlineP->backcolor = BACK_WHITE;
-    else
-        cmdlineP->backcolor = BACK_AUTO;
-
-    if (jtop + jbottom + jleft + jright + jcenter > 1)
-        pm_error("You may specify onlyone of -jtop, -jbottom, "
-                 "-jleft, and -jright");
-    else {
-        switch (cmdlineP->orientation) {
-        case LEFTRIGHT:
-            if (jleft)
-                pm_error("-jleft is invalid with -leftright");
-            if (jright)
-                pm_error("-jright is invalid with -leftright");
-            if (jtop)
-                cmdlineP->justification = JUST_MIN;
-            else if (jbottom)
-                cmdlineP->justification = JUST_MAX;
-            else if (jcenter)
-                cmdlineP->justification = JUST_CENTER;
-            else
-                cmdlineP->justification = JUST_CENTER;
-            break;
-        case TOPBOTTOM:
-            if (jtop)
-                pm_error("-jtop is invalid with -topbottom");
-            if (jbottom)
-                pm_error("-jbottom is invalid with -topbottom");
-            if (jleft)
-                cmdlineP->justification = JUST_MIN;
-            else if (jright)
-                cmdlineP->justification = JUST_MAX;
-            else if (jcenter)
-                cmdlineP->justification = JUST_CENTER;
-            else
-                cmdlineP->justification = JUST_CENTER;
-            break;
-        }
-    }
-
-    if (argc-1 < 1) {
-        MALLOCARRAY_NOFAIL(cmdlineP->inputFilespec, 1);
-        cmdlineP->inputFilespec[0] = "-";
-        cmdlineP->nfiles = 1;
-    } else {
-        unsigned int i;
-        unsigned int stdinCt;
-            /* Number of input files user specified as Standard Input */
-
-        MALLOCARRAY_NOFAIL(cmdlineP->inputFilespec, argc-1);
-
-        for (i = 0, stdinCt = 0; i < argc-1; ++i) {
-            cmdlineP->inputFilespec[i] = argv[1+i];
-            if (streq(argv[1+i], "-"))
-                ++stdinCt;
-        }
-        cmdlineP->nfiles = argc-1;
-        if (stdinCt > 1)
-            pm_error("At most one input image can come from Standard Input.  "
-                     "You specified %u", stdinCt);
-    }
-}
-
-
-
-static void
-computeOutputParms(unsigned int     const nfiles,
-                   enum orientation const orientation,
-                   struct imgInfo   const img[],
-                   unsigned int *   const newcolsP,
-                   unsigned int *   const newrowsP,
-                   xelval *         const newmaxvalP,
-                   int *            const newformatP) {
-
-    double newcols, newrows;
-    int newformat;
-    xelval newmaxval;
-
-    unsigned int i;
-
-    newcols = 0;
-    newrows = 0;
-
-    for (i = 0; i < nfiles; ++i) {
-        const struct imgInfo * const imgP = &img[i];
-
-        if (i == 0) {
-            newmaxval = imgP->maxval;
-            newformat = imgP->format;
-        } else {
-            if (PNM_FORMAT_TYPE(imgP->format) > PNM_FORMAT_TYPE(newformat))
-                newformat = imgP->format;
-            if (imgP->maxval > newmaxval)
-                newmaxval = imgP->maxval;
-        }
-        switch (orientation) {
-        case LEFTRIGHT:
-            newcols += imgP->cols;
-            if (imgP->rows > newrows)
-                newrows = imgP->rows;
-            break;
-        case TOPBOTTOM:
-            newrows += imgP->rows;
-            if (imgP->cols > newcols)
-                newcols = imgP->cols;
-            break;
-        }
-    }
-
-    /* Note that while 'double' is not in general a precise numerical type,
-       in the case of a sum of integers which is less than INT_MAX, it
-       is exact, because double's precision is greater than int's.
-    */
-    if (newcols > INT_MAX)
-       pm_error("Output width too large: %.0f.", newcols);
-    if (newrows > INT_MAX)
-       pm_error("Output height too large: %.0f.", newrows);
-
-    *newrowsP   = (unsigned int)newrows;
-    *newcolsP   = (unsigned int)newcols;
-    *newmaxvalP = newmaxval;
-    *newformatP = newformat;
-}
-
-
-
-static void
-copyBitrow(const unsigned char * const source,
-           unsigned char *       const destBitrow,
-           unsigned int          const cols,
-           unsigned int          const offset) {
-/*----------------------------------------------------------------------------
-  Copy from source to destBitrow, without shifting.  Preserve
-  surrounding image data.
------------------------------------------------------------------------------*/
-    unsigned char * const dest = & destBitrow[ offset/8 ];
-        /* Copy destination, with leading full bytes ignored. */
-    unsigned int const rs = offset % 8;
-        /* The "little offset", as measured from start of dest.  Source
-           is already shifted by this value.
-        */
-    unsigned int const trs = (cols + rs) % 8;
-        /* The number of partial bits in the final char. */
-    unsigned int const colByteCnt = pbm_packed_bytes(cols + rs);
-        /* # bytes to process, including partial ones on both ends. */
-    unsigned int const last = colByteCnt - 1;
-
-    unsigned char const origHead = dest[0];
-    unsigned char const origEnd  = dest[last];
-
-    unsigned int i;
-
-    assert(colByteCnt >= 1);
-
-    for (i = 0; i < colByteCnt; ++i)
-        dest[i] = source[i];
-
-    if (rs > 0)
-        dest[0] = LEFTBITS(origHead, rs) | RIGHTBITS(dest[0], 8-rs);
-
-    if (trs > 0)
-        dest[last] = LEFTBITS(dest[last], trs) | RIGHTBITS(origEnd, 8-trs);
-}
-
-
-
-static void
-padFillBitrow(unsigned char * const destBitrow,
-              unsigned char   const padColor,
-              unsigned int    const cols,
-              unsigned int    const offset) {
-/*----------------------------------------------------------------------------
-   Fill destBitrow, starting at offset, with padColor.  padColor is a
-   byte -- 0x00 or 0xff -- not a single bit.
------------------------------------------------------------------------------*/
-    unsigned char * const dest = &destBitrow[offset/8];
-    unsigned int const rs = offset % 8;
-    unsigned int const trs = (cols + rs) % 8;
-    unsigned int const colByteCnt = pbm_packed_bytes(cols + rs);
-    unsigned int const last = colByteCnt - 1;
-
-    unsigned char const origHead = dest[0];
-    unsigned char const origEnd  = dest[last];
-
-    unsigned int i;
-
-    assert(colByteCnt > 0);
-
-    for (i = 0; i < colByteCnt; ++i)
-        dest[i] = padColor;
-
-    if (rs > 0)
-        dest[0] = LEFTBITS(origHead, rs) | RIGHTBITS(dest[0], 8-rs);
-
-    if (trs > 0)
-        dest[last] = LEFTBITS(dest[last], trs) | RIGHTBITS(origEnd, 8-trs);
-}
-
-
-
-/* concatenateLeftRightPBM() and concatenateLeftRightGen()
-   employ almost identical algorithms.
-   The difference is in the data types and functions.
-
-   Same for concatenateTopBottomPBM() and concatenateTopBottomGen().
-*/
-
-
-struct imgInfoPbm2 {
-    /* Information about one image */
-    unsigned char * proberow;
-        /* Top row of image, when background color is
-           auto-determined.
-        */
-    unsigned int offset;
-        /* start position of image, in bits, counting from left
-           edge
-        */
-    unsigned char background;
-        /* Background color.  0x00 means white; 0xff means black */
-    unsigned int padtop;
-        /* Top padding amount */
-};
-
-
-
-static void
-getPbmImageInfo(struct imgInfo        const img[],
-                unsigned int          const nfiles,
-                unsigned int          const newrows,
-                enum justification    const justification,
-                enum backcolor        const backcolor,
-                struct imgInfoPbm2 ** const img2P) {
-/*----------------------------------------------------------------------------
-   Read the first row of each image in img[] and return that and additional
-   information about images as *img2P.
------------------------------------------------------------------------------*/
-    struct imgInfoPbm2 * img2;
-    unsigned int i;
-
-    MALLOCARRAY_NOFAIL(img2, nfiles);
-
-    for (i = 0; i < nfiles; ++i) {
-        switch (justification) {
-        case JUST_MIN:    img2[i].padtop = 0;                           break;
-        case JUST_MAX:    img2[i].padtop = newrows - img[i].rows;       break;
-        case JUST_CENTER: img2[i].padtop = (newrows - img[i].rows) / 2; break;
-        }
-
-        img2[i].offset = (i == 0) ? 0 : img2[i-1].offset + img[i-1].cols;
-
-        if (img[i].rows == newrows)  /* no padding */
-            img2[i].proberow = NULL;
-        else {                   /* determine pad color for image i */
-            switch (backcolor) {
-            case BACK_AUTO: {
-                bit bgBit;
-                img2[i].proberow = pbm_allocrow_packed(img[i].cols+7);
-                pbm_readpbmrow_bitoffset(
-                    img[i].ifP, img2[i].proberow,
-                    img[i].cols, img[i].format, img2[i].offset % 8);
-
-                bgBit = pbm_backgroundbitrow(
-                    img2[i].proberow, img[i].cols, img2[i].offset % 8);
-
-                img2[i].background = bgBit == PBM_BLACK ? 0xff : 0x00;
-            } break;
-            case BACK_BLACK:
-                img2[i].proberow   = NULL;
-                img2[i].background = 0xff;
-                break;
-            case BACK_WHITE:
-                img2[i].proberow   = NULL;
-                img2[i].background = 0x00;
-                break;
-            }
-        }
-    }
-    *img2P = img2;
-}
-
-
-
-static void
-destroyPbmImg2(struct imgInfoPbm2 * const img2,
-               unsigned int         const nfiles) {
-
-    unsigned int i;
-
-    for (i = 0; i < nfiles; ++i) {
-        if (img2[i].proberow)
-            free(img2[i].proberow);
-    }
-    free(img2);
-}
-
-
-
-static void
-concatenateLeftRightPbm(FILE *             const ofP,
-                        unsigned int       const nfiles,
-                        unsigned int       const newcols,
-                        unsigned int       const newrows,
-                        enum justification const justification,
-                        struct imgInfo     const img[],
-                        enum backcolor     const backcolor) {
-
-    unsigned char * const outrow = pbm_allocrow_packed(newcols);
-        /* We use just one outrow.  All padding and image data (with the
-           exception of following img2.proberow) goes directly into this
-           packed PBM row.
-        */
-
-    struct imgInfoPbm2 * img2;
-        /* malloc'ed array, one element per image.  Shadows img[] */
-    unsigned int row;
-
-    getPbmImageInfo(img, nfiles, newrows, justification, backcolor, &img2);
-
-    outrow[pbm_packed_bytes(newcols)-1] = 0x00;
-
-    for (row = 0; row < newrows; ++row) {
-        unsigned int i;
-
-        for (i = 0; i < nfiles; ++i) {
-
-            if ((row == 0 && img2[i].padtop > 0) ||
-                row == img2[i].padtop + img[i].rows) {
-
-                /* This row begins a run of padding, either above or below
-                   file 'i', so set 'outrow' to padding.
-                */
-                padFillBitrow(outrow, img2[i].background, img[i].cols,
-                              img2[i].offset);
-            }
-
-            if (row == img2[i].padtop && img2[i].proberow != NULL) {
-                /* Top row has been read to proberow[] to determine
-                   background.  Copy it to outrow[].
-                */
-                copyBitrow(img2[i].proberow, outrow,
-                           img[i].cols, img2[i].offset);
-            } else if (row >= img2[i].padtop &&
-                       row < img2[i].padtop + img[i].rows) {
-                pbm_readpbmrow_bitoffset(
-                    img[i].ifP, outrow, img[i].cols, img[i].format,
-                    img2[i].offset);
-            } else {
-                /* It's a row of padding, so outrow[] is already set
-                   appropriately.
-                */
-            }
-        }
-        pbm_writepbmrow_packed(ofP, outrow, newcols, 0);
-    }
-
-    destroyPbmImg2(img2, nfiles);
-
-    pbm_freerow_packed(outrow);
-}
-
-
-
-static void
-concatenateTopBottomPbm(FILE *             const ofP,
-                        unsigned int       const nfiles,
-                        int                const newcols,
-                        int                const newrows,
-                        enum justification const justification,
-                        struct imgInfo     const img[],
-                        enum backcolor     const backcolor) {
-
-    unsigned char * const outrow = pbm_allocrow_packed(newcols);
-        /* Like the left-right PBM case, all padding and image data
-           goes directly into outrow.  There is no proberow.
-        */
-    unsigned char background, backgroundPrev;
-        /* 0x00 means white; 0xff means black */
-    unsigned int  padleft;
-    bool          backChange;
-        /* Background color is different from that of the previous
-           input image.
-        */
-
-    unsigned int i;
-    unsigned int row, startRow;
-
-    outrow[pbm_packed_bytes(newcols)-1] = 0x00;
-
-    switch (backcolor){
-    case BACK_AUTO:   /* do nothing */    break;
-    case BACK_BLACK:  background = 0xff;  break;
-    case BACK_WHITE:  background = 0x00;  break;
-    }
-
-    for (i = 0; i < nfiles; ++i) {
-        if (img[i].cols == newcols) {
-            /* No padding */
-            startRow = 0;
-            backChange = FALSE;
-            padleft = 0;
-            outrow[pbm_packed_bytes(newcols)-1] = 0x00;
-        } else {
-            /* Determine amount of padding and color */
-            switch (justification) {
-            case JUST_MIN:     padleft = 0;                           break;
-            case JUST_MAX:     padleft = newcols - img[i].cols;       break;
-            case JUST_CENTER:  padleft = (newcols - img[i].cols) / 2; break;
-            }
-
-            switch (backcolor) {
-            case BACK_AUTO: {
-                bit bgBit;
-
-                startRow = 1;
-
-                pbm_readpbmrow_bitoffset(img[i].ifP,
-                                         outrow, img[i].cols, img[i].format,
-                                         padleft);
-
-                bgBit = pbm_backgroundbitrow(outrow, img[i].cols, padleft);
-                background = bgBit == PBM_BLACK ? 0xff : 0x00;
-
-                backChange = (i == 0 || background != backgroundPrev);
-            } break;
-            case BACK_WHITE:
-            case BACK_BLACK:
-                startRow = 0;
-                backChange = (i==0);
-                break;
-            }
-
-            if (backChange || (i > 0 && img[i-1].cols > img[i].cols)) {
-                unsigned int const padright = newcols - padleft - img[i].cols;
-
-                if (padleft > 0)
-                    padFillBitrow(outrow, background, padleft, 0);
-
-                if (padright > 0)
-                    padFillBitrow(outrow, background, padright,
-                                  padleft + img[i].cols);
-
-            }
-        }
-
-        if (startRow == 1)
-            /* Top row already read for auto background color
-               determination.  Write it out.
-            */
-            pbm_writepbmrow_packed(ofP, outrow, newcols, 0);
-
-        for (row = startRow; row < img[i].rows; ++row) {
-            pbm_readpbmrow_bitoffset(img[i].ifP, outrow, img[i].cols,
-                                     img[i].format, padleft);
-            pbm_writepbmrow_packed(ofP, outrow, newcols, 0);
-        }
-
-        backgroundPrev = background;
-    }
-    pbm_freerow_packed(outrow);
-}
-
-
-
-struct imgGen2 {
-    xel * xelrow;
-    xel * inrow;
-    xel   background;
-    int   padtop;
-};
-
-
-
-static void
-getGenImgInfo(struct imgInfo     const img[],
-              unsigned int       const nfiles,
-              xel *              const newxelrow,
-              unsigned int       const newrows,
-              xelval             const newmaxval,
-              int                const newformat,
-              enum justification const justification,
-              enum backcolor     const backcolor,
-              struct imgGen2 **  const img2P) {
-
-    struct imgGen2 * img2;
-    unsigned int i;
-
-    MALLOCARRAY_NOFAIL(img2, nfiles);
-
-    for (i = 0; i < nfiles; ++i) {
-        switch (justification) {  /* Determine top padding */
-            case JUST_MIN:
-                img2[i].padtop = 0;
-                break;
-            case JUST_MAX:
-                img2[i].padtop = newrows - img[i].rows;
-                break;
-            case JUST_CENTER:
-                img2[i].padtop = (newrows - img[i].rows) / 2;
-                break;
-        }
-
-        img2[i].inrow =
-            (i == 0 ? &newxelrow[0] : img2[i-1].inrow + img[i-1].cols);
-
-        if (img[i].rows == newrows)  /* no padding */
-            img2[i].xelrow = NULL;
-        else {
-            /* Determine pad color */
-            switch (backcolor){
-            case BACK_AUTO:
-                img2[i].xelrow = pnm_allocrow(img[i].cols);
-                pnm_readpnmrow(img[i].ifP, img2[i].xelrow,
-                               img[i].cols, img[i].maxval, img[i].format);
-                pnm_promoteformatrow(img2[i].xelrow, img[i].cols,
-                                     img[i].maxval, img[i].format,
-                                     newmaxval, newformat);
-                img2[i].background = pnm_backgroundxelrow(
-                    img2[i].xelrow, img[i].cols, newmaxval, newformat);
-                break;
-            case BACK_BLACK:
-                img2[i].xelrow = NULL;
-                img2[i].background = pnm_blackxel(newmaxval, newformat);
-                break;
-            case BACK_WHITE:
-                img2[i].xelrow = NULL;
-                img2[i].background = pnm_whitexel(newmaxval, newformat);
-                break;
-            }
-        }
-    }
-    *img2P = img2;
-}
-
-
-
-static void
-concatenateLeftRightGen(FILE *             const ofP,
-                        unsigned int       const nfiles,
-                        unsigned int       const newcols,
-                        unsigned int       const newrows,
-                        xelval             const newmaxval,
-                        int                const newformat,
-                        enum justification const justification,
-                        struct imgInfo     const img[],
-                        enum backcolor     const backcolor) {
-
-    xel * const outrow = pnm_allocrow(newcols);
-    struct imgGen2 * img2;
-    unsigned int row;
-
-    getGenImgInfo(img, nfiles, outrow, newrows,
-                  newmaxval, newformat, justification, backcolor, &img2);
-
-    for (row = 0; row < newrows; ++row) {
-        unsigned int i;
-
-        for (i = 0; i < nfiles; ++i) {
-            if ((row == 0 && img2[i].padtop > 0) ||
-                row == img2[i].padtop + img[i].rows) {
-                /* This row begins a run of padding, either above or below
-                   file 'i', so set 'outrow' to padding.
-                */
-                unsigned int col;
-                for (col = 0; col < img[i].cols; ++col)
-                    img2[i].inrow[col] = img2[i].background;
-            }
-            if (row == img2[i].padtop && img2[i].xelrow) {
-                /* We're at the top row of file 'i', and that row
-                   has already been read to xelrow[] to determine
-                   background.  Copy it to 'outrow'.
-                */
-                unsigned int col;
-                for (col = 0; col < img[i].cols; ++col)
-                    img2[i].inrow[col] = img2[i].xelrow[col];
-
-                free(img2[i].xelrow);
-            } else if (row >= img2[i].padtop &&
-                       row < img2[i].padtop + img[i].rows) {
-                pnm_readpnmrow(
-                    img[i].ifP, img2[i].inrow, img[i].cols, img[i].maxval,
-                    img[i].format);
-                pnm_promoteformatrow(
-                    img2[i].inrow, img[i].cols, img[i].maxval,
-                    img[i].format, newmaxval, newformat);
-            } else {
-                /* It's a row of padding, so outrow[] is already set
-                   appropriately.
-                */
-            }
-        }
-        pnm_writepnmrow(ofP, outrow, newcols, newmaxval, newformat, 0);
-    }
-    pnm_freerow(outrow);
-}
-
-
-
-static void
-concatenateTopBottomGen(FILE *             const ofP,
-                        unsigned int       const nfiles,
-                        int                const newcols,
-                        int                const newrows,
-                        xelval             const newmaxval,
-                        int                const newformat,
-                        enum justification const justification,
-                        struct imgInfo     const img[],
-                        enum backcolor     const backcolor) {
-
-    xel * const newxelrow = pnm_allocrow(newcols);
-    xel * inrow;
-    unsigned int padleft;
-    unsigned int i;
-    unsigned int row, startRow;
-    xel background, backgroundPrev;
-    bool backChange;
-        /* The background color is different from that of the previous
-           input image.
-        */
-
-    switch (backcolor) {
-    case BACK_AUTO: /* do nothing now, determine at start of each image */
-                     break;
-    case BACK_BLACK: background = pnm_blackxel(newmaxval, newformat);
-                     break;
-    case BACK_WHITE: background = pnm_whitexel(newmaxval, newformat);
-                     break;
-    }
-
-    for ( i = 0; i < nfiles; ++i, backgroundPrev = background) {
-        if (img[i].cols == newcols) {
-            /* no padding */
-            startRow = 0;
-            backChange = FALSE;
-            inrow = newxelrow;
-        } else { /* Calculate left padding amount */
-            switch (justification) {
-            case JUST_MIN:    padleft = 0;                            break;
-            case JUST_MAX:    padleft = newcols - img[i].cols;        break;
-            case JUST_CENTER: padleft = (newcols - img[i].cols) / 2;  break;
-            }
-
-            if (backcolor == BACK_AUTO) {
-                /* Determine background color */
-
-                startRow = 1;
-                inrow = &newxelrow[padleft];
-
-                pnm_readpnmrow(img[i].ifP, inrow,
-                               img[i].cols, img[i].maxval, img[i].format);
-                pnm_promoteformatrow(inrow, img[i].cols, img[i].maxval,
-                                     img[i].format,
-                                     newmaxval, newformat);
-                background = pnm_backgroundxelrow(
-                    inrow, img[i].cols, newmaxval, newformat);
-
-                backChange = i==0 || !PNM_EQUAL(background, backgroundPrev);
-            } else {
-                /* background color is constant: black or white */
-                startRow = 0;
-                inrow = &newxelrow[padleft];
-                backChange = (i==0);
-            }
-
-            if (backChange || (i > 0 && img[i-1].cols > img[i].cols)) {
-                unsigned int col;
-
-                for (col = 0; col < padleft; ++col)
-                    newxelrow[col] = background;
-                for (col = padleft + img[i].cols; col < newcols; ++col)
-                    newxelrow[col] = background;
-            }
-        }
-
-        if (startRow == 1)
-            /* Top row already read for auto background
-               color determination.  Write it out. */
-            pnm_writepnmrow(ofP, newxelrow, newcols, newmaxval, newformat, 0);
-
-        for (row = startRow; row < img[i].rows; ++row) {
-            pnm_readpnmrow(img[i].ifP,
-                           inrow, img[i].cols, img[i].maxval, img[i].format);
-            pnm_promoteformatrow(
-                inrow, img[i].cols, img[i].maxval, img[i].format,
-                newmaxval, newformat);
-
-            pnm_writepnmrow(ofP, newxelrow, newcols, newmaxval, newformat, 0);
-        }
-    }
-    pnm_freerow(newxelrow);
-}
-
-
-
-int
-main(int           argc,
-     const char ** argv) {
-
-    struct cmdlineInfo cmdline;
-    struct imgInfo * img;  /* malloc'ed array */
-    xelval newmaxval;
-    int newformat;
-    unsigned int i;
-    unsigned int newrows, newcols;
-
-    pm_proginit(&argc, argv);
-
-    parseCommandLine(argc, argv, &cmdline);
-
-    MALLOCARRAY_NOFAIL(img, cmdline.nfiles);
-
-    for (i = 0; i < cmdline.nfiles; ++i) {
-        img[i].ifP = pm_openr(cmdline.inputFilespec[i]);
-        pnm_readpnminit(img[i].ifP, &img[i].cols, &img[i].rows,
-                        &img[i].maxval, &img[i].format);
-    }
-
-    computeOutputParms(cmdline.nfiles, cmdline.orientation, img,
-                       &newcols, &newrows, &newmaxval, &newformat);
-
-    pnm_writepnminit(stdout, newcols, newrows, newmaxval, newformat, 0);
-
-    if (PNM_FORMAT_TYPE(newformat) == PBM_TYPE) {
-        switch (cmdline.orientation) {
-        case LEFTRIGHT:
-            concatenateLeftRightPbm(stdout, cmdline.nfiles,
-                                    newcols, newrows, cmdline.justification,
-                                    img, cmdline.backcolor);
-            break;
-        case TOPBOTTOM:
-            concatenateTopBottomPbm(stdout, cmdline.nfiles,
-                                    newcols, newrows, cmdline.justification,
-                                    img, cmdline.backcolor);
-            break;
-        }
-    } else {
-        switch (cmdline.orientation) {
-        case LEFTRIGHT:
-            concatenateLeftRightGen(stdout, cmdline.nfiles,
-                                    newcols, newrows, newmaxval, newformat,
-                                    cmdline.justification, img,
-                                    cmdline.backcolor);
-            break;
-        case TOPBOTTOM:
-            concatenateTopBottomGen(stdout, cmdline.nfiles,
-                                    newcols, newrows, newmaxval, newformat,
-                                    cmdline.justification, img,
-                                    cmdline.backcolor);
-            break;
-        }
-    }
-    for (i = 0; i < cmdline.nfiles; ++i)
-        pm_close(img[i].ifP);
-    free(cmdline.inputFilespec);
-    free(img);
-    pm_close(stdout);
-
-    return 0;
-}
-
-
-
diff --git a/editor/pnmconvol.c b/editor/pnmconvol.c
index fcd52bea..981797c7 100644
--- a/editor/pnmconvol.c
+++ b/editor/pnmconvol.c
@@ -617,6 +617,64 @@ normalizeKernel(struct ConvKernel * const convKernelP) {
 
 
 static void
+readPseudoPnmKernel(FILE *       const fileP,
+                    struct pam * const pamP,
+                    tuple ***    const tuplesP) {
+/*----------------------------------------------------------------------------
+   Read in the pseudo-PNM that is the convolution matrix.
+
+   This is essentially pnm_readpam(), except that it can take sample values
+   that exceed the maxval, which is not legal in PNM.  That's why it's
+   psuedo-PNM and not true PNM.
+-----------------------------------------------------------------------------*/
+
+    /* pm_getuint() is supposed to be internal to libnetpbm, but since we're
+       doing this backward compatibility hack here, we use it anyway.
+    */
+
+    unsigned int
+    pm_getuint(FILE * const file);
+
+    tuple ** tuples;
+    unsigned int row;
+
+    pnm_readpaminit(fileP, pamP, PAM_STRUCT_SIZE(tuple_type));
+
+    tuples = pnm_allocpamarray(pamP);
+
+    for (row = 0; row < pamP->height; ++row) {
+        if (pamP->format == PGM_FORMAT || pamP->format == PPM_FORMAT) {
+            /* Plain format -- can't use pnm_readpnmrow() because it will
+               reject a sample > maxval
+            */
+            unsigned int col;
+            for (col = 0; col < pamP->width; ++col) {
+                switch (pamP->format) {
+                case PGM_FORMAT:
+                    tuples[row][col][0] = pm_getuint(fileP);
+                    break;
+                case PPM_FORMAT:
+                    tuples[row][col][PAM_RED_PLANE] = pm_getuint(fileP);
+                    tuples[row][col][PAM_GRN_PLANE] = pm_getuint(fileP);
+                    tuples[row][col][PAM_BLU_PLANE] = pm_getuint(fileP);
+                    break;
+                default:
+                    assert(false);
+                }
+            }
+        } else {
+            /* Raw or PBM format -- pnm_readpnmrow() won't do any maxval
+               checking
+            */
+            pnm_readpamrow(pamP, tuples[row]);
+        }
+    }
+    *tuplesP = tuples;
+}
+
+
+
+static void
 getKernelPnm(const char *         const fileName,
              unsigned int         const depth,
              bool                 const offset,
@@ -639,12 +697,14 @@ getKernelPnm(const char *         const fileName,
     cifP = pm_openr(fileName);
 
     /* Read in the convolution matrix. */
-    ctuples = pnm_readpam(cifP, &cpam, PAM_STRUCT_SIZE(tuple_type));
+    readPseudoPnmKernel(cifP, &cpam, &ctuples);
     pm_close(cifP);
 
     validateKernelDimensions(cpam.width, cpam.height);
 
     convKernelCreatePnm(&cpam, ctuples, depth, offset, convKernelPP);
+
+    pnm_freepamarray(ctuples, &cpam);
 }
 
 
diff --git a/editor/pnmflip b/editor/pnmflip
index 07d4ddb9..962198a2 100755
--- a/editor/pnmflip
+++ b/editor/pnmflip
@@ -46,6 +46,13 @@ exec perl -w -x -S -- "$0" "$@"
 use strict;
 use File::Basename;
 use Cwd 'abs_path';
+use IO::Handle;
+
+sub pm_message($) {
+    STDERR->print("pnmflip: $_[0]\n");
+}
+
+
 
 my $xformOpt;
 my @miscOptions;
@@ -78,8 +85,7 @@ foreach (@ARGV) {
     } else {
         # It's a parameter
         if (defined($infile)) {
-            print(STDERR
-                  "You may specify at most one non-option parameter.\n");
+            pm_message("You may specify at most one non-option parameter.");
             exit(10);
         } else {
             $infile = $_;
diff --git a/editor/pnmgamma.c b/editor/pnmgamma.c
index 1fdf20eb..9b8dcdac 100644
--- a/editor/pnmgamma.c
+++ b/editor/pnmgamma.c
@@ -80,13 +80,13 @@ interpretOldArguments(int                  const argc,
         cmdlineP->ggamma = atof(argv[2]);
         cmdlineP->bgamma = atof(argv[3]);
         cmdlineP->filespec = argv[4];
-    } else 
+    } else
         pm_error("Wrong number of arguments.  "
                  "You may have 0, 1, or 3 gamma values "
                  "plus zero or one filename");
-        
-    if (cmdlineP->rgamma <= 0.0 || 
-        cmdlineP->ggamma <= 0.0 || 
+
+    if (cmdlineP->rgamma <= 0.0 ||
+        cmdlineP->ggamma <= 0.0 ||
         cmdlineP->bgamma <= 0.0 )
         pm_error("Invalid gamma value.  Must be positive floating point "
                  "number.");
@@ -106,7 +106,7 @@ getGammaFromOpts(struct cmdlineInfo * const cmdlineP,
     if (gammaSpec)
         if (gammaOpt < 0.0)
             pm_error("Invalid gamma value %f.  Must be positive.", gammaOpt);
-    
+
     if (rgammaSpec) {
         if (cmdlineP->rgamma < 0.0)
             pm_error("Invalid red gamma value %f.  Must be positive.",
@@ -114,17 +114,17 @@ getGammaFromOpts(struct cmdlineInfo * const cmdlineP,
     } else {
         if (gammaSpec)
             cmdlineP->rgamma = gammaOpt;
-        else 
+        else
             cmdlineP->rgamma = defaultGamma;
     }
     if (ggammaSpec) {
-        if (cmdlineP->ggamma < 0.0) 
+        if (cmdlineP->ggamma < 0.0)
             pm_error("Invalid green gamma value %f.  Must be positive.",
                      cmdlineP->ggamma);
     } else {
         if (gammaSpec)
             cmdlineP->ggamma = gammaOpt;
-        else 
+        else
             cmdlineP->ggamma = defaultGamma;
     }
     if (bgammaSpec) {
@@ -142,7 +142,7 @@ getGammaFromOpts(struct cmdlineInfo * const cmdlineP,
 
 
 static void
-parseCommandLine(int argc, char ** argv, 
+parseCommandLine(int argc, char ** argv,
                  struct cmdlineInfo * const cmdlineP) {
 
     optEntry *option_def;
@@ -189,7 +189,7 @@ parseCommandLine(int argc, char ** argv,
 
     opt.opt_table = option_def;
     opt.short_allowed = FALSE;  /* We have no short (old-fashioned) options */
-    opt.allowNegNum = TRUE; 
+    opt.allowNegNum = TRUE;
 
     pm_optParseOptions3(&argc, argv, opt, sizeof(opt), 0);
         /* Uses and sets argc, argv, and some of *cmdline_p and others. */
@@ -295,7 +295,7 @@ buildPowGamma(xelval       table[],
               double const gamma) {
 /*----------------------------------------------------------------------------
    Build a gamma table of size maxval+1 for the given gamma value.
-  
+
    This function depends on pow(3m).  If you don't have it, you can
    simulate it with '#define pow(x,y) exp((y)*log(x))' provided that
    you have the exponential function exp(3m) and the natural logarithm
@@ -310,7 +310,7 @@ buildPowGamma(xelval       table[],
             /* Xel sample value normalized to 0..1 */
         double const v = pow(normalized, oneOverGamma);
 
-        table[i] = MIN((xelval)(v * newMaxval + 0.5), newMaxval);  
+        table[i] = MIN((xelval)(v * newMaxval + 0.5), newMaxval);
             /* denormalize, round and clip */
     }
 }
@@ -337,17 +337,17 @@ buildBt709Gamma(xelval       table[],
        unlike the popular pure exponential gamma transfer function.
     */
     xelval const linearCutoff = (xelval) (maxval * 0.018 + 0.5);
-    double const linearExpansion = 
+    double const linearExpansion =
         (1.099 * pow(0.018, oneOverGamma) - 0.099) / 0.018;
     double const maxvalScaler = (double)newMaxval/maxval;
 
-    for (i = 0; i <= linearCutoff; ++i) 
+    for (i = 0; i <= linearCutoff; ++i)
         table[i] = i * linearExpansion * maxvalScaler + 0.5;
     for (; i <= maxval; ++i) {
         double const normalized = ((double) i) / maxval;
             /* Xel sample value normalized to 0..1 */
         double const v = 1.099 * pow(normalized, oneOverGamma) - 0.099;
-        table[i] = MIN((xelval)(v * newMaxval + 0.5), newMaxval);  
+        table[i] = MIN((xelval)(v * newMaxval + 0.5), newMaxval);
             /* denormalize, round, and clip */
     }
 }
@@ -375,18 +375,18 @@ buildBt709GammaInverse(xelval       table[],
     */
 
     xelval const linearCutoff = (xelval) (maxval * 0.018 + 0.5);
-    double const linearCompression = 
+    double const linearCompression =
         0.018 / (1.099 * pow(0.018, oneOverGamma) - 0.099);
     double const maxvalScaler = (double)newMaxval/maxval;
 
-    for (i = 0; i <= linearCutoff / linearCompression; ++i) 
+    for (i = 0; i <= linearCutoff / linearCompression; ++i)
         table[i] = i * linearCompression * maxvalScaler + 0.5;
 
     for (; i <= maxval; ++i) {
         double const normalized = ((double) i) / maxval;
             /* Xel sample value normalized to 0..1 */
         double const v = pow((normalized + 0.099) / 1.099, gamma);
-        table[i] = MIN((xelval)(v * newMaxval + 0.5), newMaxval);  
+        table[i] = MIN((xelval)(v * newMaxval + 0.5), newMaxval);
             /* denormalize, round, and clip */
     }
 }
@@ -413,17 +413,17 @@ buildSrgbGamma(xelval       table[],
        unlike the popular pure exponential gamma transfer function.
     */
     xelval const linearCutoff = (xelval) maxval * 0.0031308 + 0.5;
-    double const linearExpansion = 
+    double const linearExpansion =
         (1.055 * pow(0.0031308, oneOverGamma) - 0.055) / 0.0031308;
     double const maxvalScaler = (double)newMaxval/maxval;
 
-    for (i = 0; i <= linearCutoff; ++i) 
+    for (i = 0; i <= linearCutoff; ++i)
         table[i] = i * linearExpansion * maxvalScaler + 0.5;
     for (; i <= maxval; ++i) {
         double const normalized = ((double) i) / maxval;
             /* Xel sample value normalized to 0..1 */
         double const v = 1.055 * pow(normalized, oneOverGamma) - 0.055;
-        table[i] = MIN((xelval)(v * newMaxval + 0.5), newMaxval);  
+        table[i] = MIN((xelval)(v * newMaxval + 0.5), newMaxval);
             /* denormalize, round, and clip */
     }
 }
@@ -450,17 +450,17 @@ buildSrgbGammaInverse(xelval       table[],
        unlike the popular pure exponential gamma transfer function.
     */
     xelval const linearCutoff = (xelval) maxval * 0.0031308 + 0.5;
-    double const linearCompression = 
+    double const linearCompression =
         0.0031308 / (1.055 * pow(0.0031308, oneOverGamma) - 0.055);
     double const maxvalScaler = (double)newMaxval/maxval;
 
-    for (i = 0; i <= linearCutoff / linearCompression; ++i) 
+    for (i = 0; i <= linearCutoff / linearCompression; ++i)
         table[i] = i * linearCompression * maxvalScaler + 0.5;
     for (; i <= maxval; ++i) {
         double const normalized = ((double) i) / maxval;
             /* Xel sample value normalized to 0..1 */
         double const v = pow((normalized + 0.055) / 1.055, gamma);
-        table[i] = MIN((xelval)(v * newMaxval + 0.5), newMaxval);  
+        table[i] = MIN((xelval)(v * newMaxval + 0.5), newMaxval);
             /* denormalize, round, and clip */
     }
 }
@@ -491,11 +491,11 @@ buildBt709ToSrgbGamma(xelval       table[],
     */
 
     xelval const linearCutoff709 = (xelval) (maxval * 0.018 + 0.5);
-    double const linearCompression709 = 
+    double const linearCompression709 =
         0.018 / (1.099 * pow(0.018, oneOverGamma709) - 0.099);
 
     double const linearCutoffSrgb = 0.0031308;
-    double const linearExpansionSrgb = 
+    double const linearExpansionSrgb =
         (1.055 * pow(0.0031308, oneOverGammaSrgb) - 0.055) / 0.0031308;
 
     xelval i;
@@ -516,7 +516,7 @@ buildBt709ToSrgbGamma(xelval       table[],
         if (radiance < linearCutoffSrgb * normalizer)
             srgb = radiance * linearExpansionSrgb;
         else
-            srgb = 1.055 * pow(normalized, oneOverGammaSrgb) - 0.055;
+            srgb = 1.055 * pow(radiance, oneOverGammaSrgb) - 0.055;
 
         assert(srgb <= 1.0);
 
@@ -549,11 +549,11 @@ buildSrgbToBt709Gamma(xelval       table[],
        unlike the popular pure exponential gamma transfer function.
     */
     xelval const linearCutoffSrgb = (xelval) maxval * 0.0031308 + 0.5;
-    double const linearCompressionSrgb = 
+    double const linearCompressionSrgb =
         0.0031308 / (1.055 * pow(0.0031308, oneOverGammaSrgb) - 0.055);
 
     xelval const linearCutoff709 = (xelval) (maxval * 0.018 + 0.5);
-    double const linearExpansion709 = 
+    double const linearExpansion709 =
         (1.099 * pow(0.018, oneOverGamma709) - 0.099) / 0.018;
 
     xelval i;
@@ -567,14 +567,14 @@ buildSrgbToBt709Gamma(xelval       table[],
         if (i < linearCutoffSrgb / linearCompressionSrgb)
             radiance = normalized * linearCompressionSrgb;
         else
-            radiance = pow((normalized + 0.099) / 1.099, gammaSrgb);
+            radiance = pow((normalized + 0.055) / 1.055, gammaSrgb);
 
         assert(radiance <= 1.0);
 
         if (radiance < linearCutoff709 * normalizer)
             bt709 = radiance * linearExpansion709;
         else
-            bt709 = 1.055 * pow(normalized, oneOverGamma709) - 0.055;
+            bt709 = 1.099 * pow(radiance, oneOverGamma709) - 0.099;
 
         assert(bt709 <= 1.0);
 
@@ -588,8 +588,8 @@ static void
 createGammaTables(enum transferFunction const transferFunction,
                   xelval                const maxval,
                   xelval                const newMaxval,
-                  double                const rgamma, 
-                  double                const ggamma, 
+                  double                const rgamma,
+                  double                const ggamma,
                   double                const bgamma,
                   xelval **             const rtableP,
                   xelval **             const gtableP,
@@ -677,7 +677,7 @@ convertRaster(FILE *   const ifP,
     for (row = 0; row < rows; ++row) {
         pnm_readpnmrow(ifP, xelrow, cols, maxval, format);
 
-        pnm_promoteformatrow(xelrow, cols, maxval, format, 
+        pnm_promoteformatrow(xelrow, cols, maxval, format,
                              maxval, outputFormat);
 
         switch (PNM_FORMAT_TYPE(outputFormat)) {
@@ -730,10 +730,10 @@ main(int argc, char *argv[]) {
 
     if (PNM_FORMAT_TYPE(format) == PPM_TYPE)
         outputFormat = PPM_TYPE;
-    else if (cmdline.rgamma != cmdline.ggamma 
-             || cmdline.ggamma != cmdline.bgamma) 
+    else if (cmdline.rgamma != cmdline.ggamma
+             || cmdline.ggamma != cmdline.bgamma)
         outputFormat = PPM_TYPE;
-    else 
+    else
         outputFormat = PGM_TYPE;
 
     if (PNM_FORMAT_TYPE(format) != outputFormat) {
diff --git a/editor/pnmhisteq.c b/editor/pnmhisteq.c
index a339f73f..c2e39089 100644
--- a/editor/pnmhisteq.c
+++ b/editor/pnmhisteq.c
@@ -1,15 +1,14 @@
-/*
-                 pnmhisteq.c
-
-           Equalize histogram for a PNM image
+/*=============================================================================
+                              pnmhisteq
+===============================================================================
+  Equalize histogram for a PNM image
 
   By Bryan Henderson 2005.09.10, based on ideas from the program of
   the same name by John Walker (kelvin@fourmilab.ch) -- March MVM.
   WWW home page: http://www.fourmilab.ch/ in 1995.
 
   This program is contributed to the public domain by its author.
-*/
-
+=============================================================================*/
 #include <string.h>
 
 #include "pm_c_util.h"
@@ -18,7 +17,7 @@
 #include "mallocvar.h"
 
 
-struct cmdlineInfo {
+struct CmdlineInfo {
     /* All the information the user supplied in the command line,
        in a form easy for the program to use.
     */
@@ -34,8 +33,8 @@ struct cmdlineInfo {
 
 
 static void
-parseCommandLine(int argc, char ** argv,
-                 struct cmdlineInfo * const cmdlineP) {
+parseCommandLine(int argc, const char ** argv,
+                 struct CmdlineInfo * const cmdlineP) {
 /*----------------------------------------------------------------------------
    Note that the file spec array we return is stored in the storage that
    was passed to us as the argv array.
@@ -68,7 +67,7 @@ parseCommandLine(int argc, char ** argv,
     opt.short_allowed = FALSE;  /* We have no short (old-fashioned) options */
     opt.allowNegNum = FALSE;  /* We may have parms that are negative numbers */
 
-    pm_optParseOptions3(&argc, argv, opt, sizeof(opt), 0);
+    pm_optParseOptions3(&argc, (char **)argv, opt, sizeof(opt), 0);
         /* Uses and sets argc, argv, and some of *cmdlineP and others. */
 
 
@@ -497,9 +496,9 @@ writeMap(const char * const wmapFileName,
 
 
 int
-main(int argc, char * argv[]) {
+main(int argc, const char ** const argv) {
 
-    struct cmdlineInfo cmdline;
+    struct CmdlineInfo cmdline;
     FILE * ifP;
     gray * lumamap;           /* Luminosity map */
     unsigned int * lumahist;  /* Histogram of luminosity values */
@@ -509,7 +508,7 @@ main(int argc, char * argv[]) {
     xel ** xels;              /* Pixel array */
     unsigned int pixelCount;
 
-    pnm_init(&argc, argv);
+    pm_proginit(&argc, argv);
 
     parseCommandLine(argc, argv, &cmdline);
 
diff --git a/editor/pnmindex.csh b/editor/pnmindex.csh
deleted file mode 100755
index c6f1e844..00000000
--- a/editor/pnmindex.csh
+++ /dev/null
@@ -1,189 +0,0 @@
-#!/bin/csh -f
-#
-# pnmindex - build a visual index of a bunch of anymaps
-#
-# Copyright (C) 1991 by Jef Poskanzer.
-#
-# Permission to use, copy, modify, and distribute this software and its
-# documentation for any purpose and without fee is hereby granted, provided
-# that the above copyright notice appear in all copies and that both that
-# copyright notice and this permission notice appear in supporting
-# documentation.  This software is provided "as is" without express or
-# implied warranty.
-
-# -title and -quant added by John Heidemann 13-Sep-00.
-
-set size=100		# make the images about this big
-set across=6		# show this many images per row
-set colors=256		# quantize results to this many colors
-set back="-white"	# default background color
-set doquant=true	# quantize or not
-set title=""		# default title (none)
-
-while ( 1 )
-    switch ( "$1" )
-
-	case -s*:
-	if ( $#argv < 2 ) goto usage
-	set size="$2"
-	shift
-	shift
-	breaksw
-
-	case -a*:
-	if ( $#argv < 2 ) goto usage
-	set across="$2"
-	shift
-	shift
-	breaksw
-
-	case -t*:
-	if ( $#argv < 2 ) goto usage
-	set title="$2"
-	shift
-	shift
-	breaksw
-
-	case -c*:
-	set colors="$2"
-	shift
-	shift
-	breaksw
-
-	case -noq*:
-	set doquant=false
-	shift
-	breaksw
-
-	case -q*:
-	set doquant=true
-	shift
-	breaksw
-
-	case -b*:
-	set back="-black"
-	shift
-	breaksw
-
-	case -w*:
-	set back="-white"
-	shift
-	breaksw
-
-	case -*:
-	goto usage
-	breaksw
-
-	default:
-	break
-	breaksw
-
-    endsw
-end
-
-if ( $#argv == 0 ) then
-    goto usage
-endif
-
-set tmpfile=/tmp/pi.tmp.$$
-rm -f $tmpfile
-set maxformat=PBM
-
-set rowfiles=()
-set imagefiles=()
-@ row = 1
-@ col = 1
-
-if ( "$title" != "" ) then
-    set rowfile=/tmp/pi.${row}.$$
-    rm -f $rowfile
-    pbmtext "$title" > $rowfile
-    set rowfiles=( $rowfiles $rowfile )
-    @ row += 1
-endif
-
-foreach i ( $argv )
-
-    set description=`pnmfile $i`
-    if ( $description[4] <= $size && $description[6] <= $size ) then
-	cat $i > $tmpfile
-    else
-	switch ( $description[2] )
-	    case PBM:
-	    pnmscale -quiet -xysize $size $size $i | pgmtopbm > $tmpfile
-	    breaksw
-
-	    case PGM:
-	    pnmscale -quiet -xysize $size $size $i > $tmpfile
-	    if ( $maxformat == PBM ) then
-		set maxformat=PGM
-	    endif
-	    breaksw
-
-	    default:
-	    if ( $doquant == false ) then
-	        pnmscale -quiet -xysize $size $size $i > $tmpfile
-	    else
-	        pnmscale -quiet -xysize $size $size $i | ppmquant -quiet $colors > $tmpfile
-	    endif
-	    set maxformat=PPM
-	    breaksw
-	endsw
-    endif
-    set imagefile=/tmp/pi.${row}.${col}.$$
-    rm -f $imagefile
-    if ( "$back" == "-white" ) then
-	pbmtext "$i" | pnmcat $back -tb $tmpfile - > $imagefile
-    else
-	pbmtext "$i" | pnminvert | pnmcat $back -tb $tmpfile - > $imagefile
-    endif
-    rm -f $tmpfile
-    set imagefiles=( $imagefiles $imagefile )
-
-    if ( $col >= $across ) then
-	set rowfile=/tmp/pi.${row}.$$
-	rm -f $rowfile
-	if ( $maxformat != PPM || $doquant == false ) then
-	    pnmcat $back -lr -jbottom $imagefiles > $rowfile
-	else
-	    pnmcat $back -lr -jbottom $imagefiles | ppmquant -quiet $colors > $rowfile
-	endif
-	rm -f $imagefiles
-	set imagefiles=()
-	set rowfiles=( $rowfiles $rowfile )
-	@ col = 1
-	@ row += 1
-    else
-	@ col += 1
-    endif
-
-end
-
-if ( $#imagefiles > 0 ) then
-    set rowfile=/tmp/pi.${row}.$$
-    rm -f $rowfile
-    if ( $maxformat != PPM || $doquant == false ) then
-	pnmcat $back -lr -jbottom $imagefiles > $rowfile
-    else
-	pnmcat $back -lr -jbottom $imagefiles | ppmquant -quiet $colors > $rowfile
-    endif
-    rm -f $imagefiles
-    set rowfiles=( $rowfiles $rowfile )
-endif
-
-if ( $#rowfiles == 1 ) then
-    cat $rowfiles
-else
-    if ( $maxformat != PPM || $doquant == false ) then
-	pnmcat $back -tb $rowfiles
-    else
-	pnmcat $back -tb $rowfiles | ppmquant -quiet $colors
-    endif
-endif
-rm -f $rowfiles
-
-exit 0
-
-usage:
-echo "usage: $0 [-size N] [-across N] [-colors N] [-black] pnmfile ..."
-exit 1
diff --git a/editor/pnmindex.sh b/editor/pnmindex.sh
deleted file mode 100755
index dfc5b82a..00000000
--- a/editor/pnmindex.sh
+++ /dev/null
@@ -1,214 +0,0 @@
-#!/bin/sh
-#
-# pnmindex - build a visual index of a bunch of PNM images
-#
-# Copyright (C) 1991 by Jef Poskanzer.
-#
-# Permission to use, copy, modify, and distribute this software and its
-# documentation for any purpose and without fee is hereby granted, provided
-# that the above copyright notice appear in all copies and that both that
-# copyright notice and this permission notice appear in supporting
-# documentation.  This software is provided "as is" without express or
-# implied warranty.
-
-size=100        # make the images about this big
-across=6        # show this many images per row
-colors=256      # quantize results to this many colors
-back="-white"   # default background color
-doquant=true    # quantize or not
-title=""        # default title (none)
-
-usage ()
-{
-  echo "usage: $0 [-size N] [-across N] [-colors N] [-black] pnmfile ..."
-  exit 1
-}
-
-while :; do
-    case "$1" in
-
-    -s*)
-        if [ $# -lt 2 ]; then usage; fi
-        size="$2"
-        shift
-        shift
-    ;;
-
-    -a*)
-        if [ $# -lt 2 ]; then usage; fi
-        across="$2"
-        shift
-        shift
-    ;;
-
-    -t*)
-        if [ $# -lt 2 ]; then usage; fi
-        title="$2"
-        shift
-        shift
-    ;;
-
-    -c*)
-        if [ $# -lt 2 ]; then usage; fi
-        colors="$2"
-        shift
-        shift
-    ;;
-
-    -b*)
-        back="-black"
-        shift
-    ;;
-
-    -w*)
-        back="-white"
-        shift
-    ;;
-
-    -noq*)
-        doquant=false
-        shift
-    ;;
-
-    -q*)
-        doquant=true
-        shift
-    ;;
-
-    -*)
-        usage
-    ;;
-
-    *)
-        break
-    ;;
-    esac
-done
-
-if [ $# -eq 0 ]; then
-    usage
-fi
-
-tempdir="${TMPDIR-/tmp}/pnmindex.$$"
-mkdir -m 0700 $tempdir || \
-  { echo "Could not create temporary file. Exiting."; exit 1;}
-trap 'rm -rf $tempdir' 0 1 3 15
-
-tmpfile=$tempdir/pi.tmp
-maxformat=PBM
-
-rowfiles=()
-imagefiles=()
-row=1
-col=1
-
-if [ "$title"x != ""x ] ; then
-#    rowfile=`tempfile -p pirow -m 600`
-    rowfile=$tempdir/pi.${row}
-    pbmtext "$title" > $rowfile
-    rowfiles=(${rowfiles[*]} $rowfile )
-    row=$(($row + 1))
-fi
-
-for i in "$@"; do
-
-    description=(`pnmfile $i`)
-
-    format=${description[1]}
-    width=${description[3]}
-    height=${description[5]}
-
-    if [ $? -ne 0 ]; then
-        echo pnmfile returned an error
-        exit $?
-    fi
-
-    if [ $width -le $size ] && \
-       [ $height -le $size ]; then
-        cat $i > $tmpfile
-    else
-        case $format in
-
-        PBM) 
-            pamscale -quiet -xysize $size $size $i | pgmtopbm > $tmpfile
-        ;;
-
-        PGM)
-            pamscale -quiet -xysize $size $size $i > $tmpfile
-            if [ $maxformat = PBM ]; then
-                maxformat=PGM
-            fi
-        ;;
-
-        *) 
-            if [ "$doquant" = "true" ] ; then
-                pamscale -quiet -xysize $size $size $i | \
-                pnmquant -quiet $colors > $tmpfile
-            else
-                pamscale -quiet -xysize $size $size $i > $tmpfile
-            fi
-            maxformat=PPM
-        ;;
-        esac
-    fi
-
-    imagefile=$tempdir/pi.${row}.${col}
-    rm -f $imagefile
-    if [ "$back" = "-white" ]; then
-        pbmtext "$i" | pnmcat $back -tb $tmpfile - > $imagefile
-    else
-        pbmtext "$i" | pnminvert | pnmcat $back -tb $tmpfile - > $imagefile
-    fi
-    imagefiles=( ${imagefiles[*]} $imagefile )
-
-    if [ $col -ge $across ]; then
-        rowfile=$tempdir/pi.${row}
-        rm -f $rowfile
-
-        if [ $maxformat != PPM -o "$doquant" = "false" ]; then
-            pnmcat $back -lr -jbottom ${imagefiles[*]} > $rowfile
-        else
-            pnmcat $back -lr -jbottom ${imagefiles[*]} | \
-            pnmquant -quiet $colors > $rowfile
-        fi
-
-        rm -f ${imagefiles[*]}
-        unset imagefiles
-        imagefiles=()
-        rowfiles=( ${rowfiles[*]} $rowfile )
-        col=1
-        row=$(($row + 1))
-    else
-        col=$(($col + 1))
-    fi
-done
-
-# All the full rows have been put in row files.  
-# Now put the final partial row in its row file.
-
-if [ ${#imagefiles[*]} -gt 0 ]; then
-    rowfile=$tempdir/pi.${row}
-    rm -f $rowfile
-    if [ $maxformat != PPM -o "$doquant" = "false" ]; then
-        pnmcat $back -lr -jbottom ${imagefiles[*]} > $rowfile
-    else
-        pnmcat $back -lr -jbottom ${imagefiles[*]} | \
-        pnmquant -quiet $colors > $rowfile
-    fi
-    rm -f ${imagefiles[*]}
-    rowfiles=( ${rowfiles[*]} $rowfile )
-fi
-
-if [ ${#rowfiles[*]} -eq 1 ]; then
-    cat $rowfiles
-else
-    if [ $maxformat != PPM -o "$doquant" = "false" ]; then
-        pnmcat $back -tb ${rowfiles[*]}
-    else
-        pnmcat $back -tb ${rowfiles[*]} | pnmquant -quiet $colors
-    fi
-fi
-rm -f ${rowfiles[*]}
-
-exit 0
-
diff --git a/editor/pnminvert.c b/editor/pnminvert.c
index d4aad503..208b8bfa 100644
--- a/editor/pnminvert.c
+++ b/editor/pnminvert.c
@@ -38,18 +38,18 @@ invertPbm(FILE * const ifP,
 -----------------------------------------------------------------------------*/
     int const colChars = pbm_packed_bytes(cols);
 
-    unsigned char * bitrow; 
+    unsigned char * bitrow;
     unsigned int row;
-    
+
     bitrow = pbm_allocrow_packed(cols);
-    
+
     for (row = 0; row < rows; ++row) {
         unsigned int colChar;
-        
+
         pbm_readpbmrow_packed(ifP, bitrow, cols, format);
         for (colChar = 0; colChar < colChars; ++colChar)
             bitrow[colChar] = ~ bitrow[colChar];
-        
+
         /* Clean off remainder of fractional last character and write */
         pbm_cleanrowend_packed(bitrow, cols);
         pbm_writepbmrow_packed(ofP, bitrow, cols, 0);
@@ -69,15 +69,15 @@ invertPnm(FILE * const ifP,
 
     xel * xelrow;
     unsigned int row;
-    
+
     xelrow = pnm_allocrow(cols);
-    
+
     for (row = 0; row < rows; ++row) {
         unsigned int col;
         pnm_readpnmrow(ifP, xelrow, cols, maxval, format);
         for (col = 0; col < cols; ++col)
             pnm_invertxel(&xelrow[col], maxval, format);
-        
+
         pnm_writepnmrow(ofP, xelrow, cols, maxval, format, 0);
     }
     pnm_freerow(xelrow);
@@ -103,7 +103,7 @@ main(int argc, char * argv[]) {
 
     pnm_readpnminit(ifP, &cols, &rows, &maxval, &format);
     pnm_writepnminit(stdout, cols, rows, maxval, format, 0);
-    
+
     if (PNM_FORMAT_TYPE(format) == PBM_TYPE)
         /* Take fast path */
         invertPbm(ifP, stdout, cols, rows, format);
@@ -113,7 +113,7 @@ main(int argc, char * argv[]) {
 
     pm_close(ifP);
     pm_close(stdout);
-    
+
     return 0;
 }
 
diff --git a/editor/pnmmargin b/editor/pnmmargin
index 1b5370be..6f82ddbe 100755
--- a/editor/pnmmargin
+++ b/editor/pnmmargin
@@ -11,15 +11,6 @@
 # documentation.  This software is provided "as is" without express or
 # implied warranty.
 
-tempdir=$(mktemp -d "${TMPDIR:-/tmp}/netpbm.XXXXXXXX") ||
-    { echo "Could not create temporary file. Exiting." 1>&2; exit 1; }
-trap 'rm -rf $tempdir' 0 1 3 15
-
-tmp1=$tempdir/pnmm1
-tmp2=$tempdir/pnmm2
-tmp3=$tempdir/pnmm3
-tmp4=$tempdir/pnmm4
-
 color="-gofigure"
 plainopt=""
 
@@ -67,42 +58,43 @@ fi
 size="$1"
 shift
 
+case $size in
+    ''|*[!0-9]*)
+        echo "Size argument '$size' is not a whole number"
+        exit 1
+        ;;
+esac
+
 if [ ${2-""} ] ; then
     echo "usage: $0 [-white|-black|-color <colorspec>] <size> [pnmfile]" 1>&2
     exit 1
 fi
 
-# Capture input file in a tmp file, in case it's a pipe.
 # TODO: This code does not consider the case when the input file is specified
 # and there is also input coming in from a pipe.
 
-cat $@ > $tmp1
-
 if [ $size -eq 0 ] ; then
     # Zero margin; just copy input to output
-    pamtopnm $plainopt $tmp1;
+    pamtopnm $plainopt $@;
 else
     # If -white or -black, write output with pnmpad and exit.
     # Otherwise construct spacer files.
 
     case "$color" in
         -gofigure )
-        pnmcut 0 0 1 1 $tmp1 | pnmtile $size 1 > $tmp2
+        pnmpad $plainopt -detect-background \
+            -left=$size -right=$size -top=$size -bottom=$size $@
+        exit
         ;;
         -white | -black )
         pnmpad $plainopt $color \
-            -left=$size -right=$size -top=$size -bottom=$size $tmp1
+            -left=$size -right=$size -top=$size -bottom=$size $@
         exit
         ;;
         * )
-        ppmmake $color $size 1 > $tmp2
+        pnmpad $plainopt -color $color \
+            -left=$size -right=$size -top=$size -bottom=$size $@
+        exit
         ;;
     esac
-    pamflip -rotate90 $tmp2 > $tmp3
-
-    # Cat things together.
-    pnmcat -lr $tmp2 $tmp1 $tmp2 > $tmp4
-    pnmcat -tb $plainopt $tmp3 $tmp4 $tmp3
 fi
-
-
diff --git a/editor/pnmmontage.c b/editor/pnmmontage.c
index 7bd00dbe..c6f03ead 100644
--- a/editor/pnmmontage.c
+++ b/editor/pnmmontage.c
@@ -42,7 +42,7 @@ parseCommandLine(int argc, const char ** argv,
                  struct CmdlineInfo * const cmdlineP) {
 /*----------------------------------------------------------------------------
    parse program command line described in Unix standard form by argc
-   and argv.  Return the information in the options as *cmdlineP.  
+   and argv.  Return the information in the options as *cmdlineP.
 
    If command line is internally inconsistent (invalid options, etc.),
    issue error message to stderr and abort program.
@@ -59,7 +59,7 @@ parseCommandLine(int argc, const char ** argv,
     unsigned int q[10];
 
     MALLOCARRAY_NOFAIL(option_def, 100);
-  
+
     option_def_index = 0;   /* incremented by OPTENTRY */
     OPTENT3( 0,  "data",    OPT_STRING, &cmdlineP->data, &dataSpec, 0);
     OPTENT3( 0,  "header",  OPT_STRING, &cmdlineP->header, &headerSpec, 0);
@@ -93,7 +93,7 @@ parseCommandLine(int argc, const char ** argv,
     if (!qualitySpec)
         cmdlineP->quality = 200;
 
-    
+
     /* cmdlineP->quality2 is the greatest number from the --1, --2, etc.
        options, or 5 if none of those are specified.
     */
@@ -150,7 +150,7 @@ lr(Rectangle const r) {
 
 
 
-static Factorset 
+static Factorset
 factor(unsigned int const arg) {
 /*----------------------------------------------------------------------------
    The prime factors of 'arg'.
@@ -177,7 +177,7 @@ factor(unsigned int const arg) {
 
 
 
-static int 
+static int
 gcf(unsigned int const n,
     unsigned int const m) {
 /*----------------------------------------------------------------------------
@@ -236,12 +236,12 @@ collides(Rectangle         const test,
 
 
 
-static void 
+static void
 recursefindpack(Rectangle *    const current,
                 Coord          const currentsz,
                 Coord *        const best,
                 unsigned int   const minarea,
-                unsigned int * const maxareaP, 
+                unsigned int * const maxareaP,
                 unsigned int   const depth,
                 unsigned int   const n,
                 unsigned int   const xinc,
@@ -295,7 +295,7 @@ recursefindpack(Rectangle *    const current,
 
 
 
-static void 
+static void
 findpack(struct pam * const imgs,
          unsigned int const imgCt,
          Coord **     const coordsP,
@@ -312,7 +312,7 @@ findpack(struct pam * const imgs,
     Coord c;
 
     MALLOCARRAY(coords, imgCt);
-  
+
     if (!coords)
         pm_error("Out of memory allocating %u-element coords array", imgCt);
 
@@ -356,12 +356,12 @@ findpack(struct pam * const imgs,
 
 
 
-static void 
+static void
 adjustDepth(tuple *            const tuplerow,
             const struct pam * const inpamP,
             const struct pam * const outpamP,
             Coord              const coord) {
-    
+
     if (inpamP->depth < outpamP->depth) {
         unsigned int i;
         for (i = coord.x; i < coord.x + inpamP->width; ++i) {
@@ -374,7 +374,7 @@ adjustDepth(tuple *            const tuplerow,
 
 
 
-static void 
+static void
 adjustMaxval(tuple *            const tuplerow,
              const struct pam * const inpamP,
              const struct pam * const outpamP,
@@ -420,14 +420,14 @@ writePam(struct pam *       const outpamP,
 -----------------------------------------------------------------------------*/
     tuple * tuplerow;
     unsigned int row;  /* Row number in the output image */
-  
+
     pnm_writepaminit(outpamP);
 
     tuplerow = pnm_allocpamrow(outpamP);
 
     for (row = 0; row < outpamP->height; ++row) {
         unsigned int imgIdx;
-        
+
         makeRowBlack(outpamP, tuplerow);  /* initial value */
 
         for (imgIdx = 0; imgIdx < imgCt; ++imgIdx) {
@@ -494,13 +494,13 @@ writeHeader(FILE * const headerFileP,
         struct pam const img = imgs[i];
 
         unsigned int j;
-        
+
         *strchr(buffer, '.') = 0;
         for (j = 0; buffer[j]; ++j) {
             if (ISLOWER(buffer[j]))
                 buffer[j] = TOUPPER(buffer[j]);
         }
-        fprintf(headerFileP, "#define %s%sX %u\n", 
+        fprintf(headerFileP, "#define %s%sX %u\n",
                 prefix, buffer, coord.x);
 
         fprintf(headerFileP, "#define %s%sY %u\n",
@@ -538,7 +538,7 @@ sortImagesByArea(unsigned int  const nfiles,
 
                 struct pam p;
                 const char * c;
-                
+
                 p = imgs[i]; imgs[i] = imgs[j]; imgs[j] = p;
                 c = names[i]; names[i] = names[j]; names[j] = c;
             }
@@ -600,7 +600,7 @@ computeOutputDimensions(int *              const widthP,
 
     widthGuess  = 0;  /* initial value */
     heightGuess = 0;  /* initial value */
-    
+
     for (i = 0; i < nfiles; ++i) {
         widthGuess  = MAX(widthGuess,  imgs[i].width  + coords[i].x);
         heightGuess = MAX(heightGuess, imgs[i].height + coords[i].y);
@@ -622,8 +622,8 @@ qfactorFromQuality(unsigned int const quality,
     case 0: case 1:
         qfactor = quality;
         break;
-    case 2: case 3: case 4: case 5: case 6: 
-        qfactor = 100 * (8 - quality2); 
+    case 2: case 3: case 4: case 5: case 6:
+        qfactor = 100 * (8 - quality2);
         break;
     case 7: qfactor = 150; break;
     case 8: qfactor = 125; break;
@@ -709,7 +709,7 @@ closeFiles(const struct pam * const imgPam,
 
 
 
-int 
+int
 main(int argc, const char **argv) {
 
     struct CmdlineInfo cmdline;
@@ -749,7 +749,7 @@ main(int argc, const char **argv) {
     pnm_setminallocationdepth(&outimg, outimg.depth);
     outimg.plainformat = false;
     outimg.file = stdout;
- 
+
     writePam(&outimg, fileCt, coords, imgPam);
 
     if (dataFileP)
diff --git a/editor/pnmnlfilt.c b/editor/pnmnlfilt.c
index bcb3680d..906ce460 100644
--- a/editor/pnmnlfilt.c
+++ b/editor/pnmnlfilt.c
@@ -990,7 +990,7 @@ main(int argc, char *argv[]) {
 
     FILE * ifP;
     struct cmdlineInfo cmdline;
-	int eof;  /* We've hit the end of the input stream */
+        int eof;  /* We've hit the end of the input stream */
     unsigned int imageSeq;  /* Sequence number of image, starting from 0 */
 
     pnm_init(&argc, argv);
diff --git a/editor/pnmpad.c b/editor/pnmpad.c
index 55cdcd6c..94ea0ed1 100644
--- a/editor/pnmpad.c
+++ b/editor/pnmpad.c
@@ -1,26 +1,71 @@
-/* pnmpad.c - add border to sides of a portable anymap
+/* pnmpad.c - add border to sides of a PNM
    ** AJCD 4/9/90
  */
 
+#include <stdbool.h>
 #include <assert.h>
 #include <string.h>
 #include <stdio.h>
 
 #include "pm_c_util.h"
 #include "mallocvar.h"
+#include <nstring.h>
 #include "shhopt.h"
 #include "pnm.h"
 
-#define MAX_WIDTHHEIGHT INT_MAX-10
+#define MAX_WIDTHHEIGHT ((INT_MAX)-10)
     /* The maximum width or height value we can handle without risking
        arithmetic overflow
     */
 
-struct cmdlineInfo {
+enum PadType {
+    /* PAD_COLOR means the specified padding is not black, white, or gray --
+       even regardless of whether user specified it with a -color option.
+       E.g. -color=black is PAD_BLACK.
+    */
+    PAD_BLACK,
+    PAD_WHITE,
+    PAD_GRAY,
+    PAD_COLOR,
+    PAD_DETECTED_BG,
+    PAD_EXTEND_EDGE
+};
+
+enum PromoteType {
+    PROMOTE_NONE,
+    PROMOTE_FORMAT,
+    PROMOTE_ALL
+};
+
+
+
+static enum PadType
+padTypeFmColorStr(const char * const colorStr) {
+
+    pixel const color = ppm_parsecolor(colorStr, PPM_OVERALLMAXVAL);
+
+    enum PadType retval;
+
+    if (PPM_ISGRAY(color)) {
+        if (PPM_GETR(color) == 0)
+            retval = PAD_BLACK;
+        else if  (PPM_GETR(color) == PPM_OVERALLMAXVAL)
+            retval = PAD_WHITE;
+        else
+            retval = PAD_GRAY;
+    } else
+        retval = PAD_COLOR;
+
+    return retval;
+}
+
+
+
+struct CmdlineInfo {
     /* All the information the user supplied in the command line,
        in a form easy for the program to use.
     */
-    const char * input_filespec;  /* Filespecs of input files */
+    const char * inputFileNm;  /* Names of input files */
     unsigned int xsize;
     unsigned int xsizeSpec;
     unsigned int ysize;
@@ -37,7 +82,9 @@ struct cmdlineInfo {
     float yalign;
     unsigned int mwidth;
     unsigned int mheight;
-    unsigned int white;     /* >0: pad white; 0: pad black */
+    enum PadType padType;
+    const char * color;
+    enum PromoteType promote;
     unsigned int reportonly;
     unsigned int verbose;
 };
@@ -45,8 +92,45 @@ struct cmdlineInfo {
 
 
 static void
+validateNoOldOptionSyntax( int const argc, const char ** const argv) {
+/*----------------------------------------------------------------------------
+  Reject obsolete command line syntax, e.g. "pnmpad -l50".
+
+  Starting in Netpbm 9.25 (February 2002), this resulted in a warning message
+  and was no longer documented.  Starting in Netpbm 11.05 (December 2023),
+  it is no longer accepted.
+
+  It was too hard to maintain.
+-----------------------------------------------------------------------------*/
+    bool isOld;
+
+    isOld = false;  /* initial assumption */
+
+    if (argc > 1 && argv[1][0] == '-') {
+        if (argv[1][1] == 't' || argv[1][1] == 'b'
+            || argv[1][1] == 'l' || argv[1][1] == 'r') {
+            if (argv[1][2] >= '0' && argv[1][2] <= '9')
+                isOld = true;
+        }
+    }
+    if (argc > 2 && argv[2][0] == '-') {
+        if (argv[2][1] == 't' || argv[2][1] == 'b'
+            || argv[2][1] == 'l' || argv[2][1] == 'r') {
+            if (argv[2][2] >= '0' && argv[2][2] <= '9')
+                isOld = true;
+        }
+    }
+    if (isOld)
+        pm_error("Old-style Unix options (e.g. \"-l50\") "
+                 "not accepted by current 'pnmpad'.  "
+                 "Use e.g. \"-l 50\" instead");
+}
+
+
+
+static void
 parseCommandLine(int argc, const char ** argv,
-                 struct cmdlineInfo * const cmdlineP) {
+                 struct CmdlineInfo * const cmdlineP) {
 /*----------------------------------------------------------------------------
    Note that the file spec array we return is stored in the storage that
    was passed to us as the argv array.
@@ -57,8 +141,12 @@ parseCommandLine(int argc, const char ** argv,
     optStruct3 opt;
 
     unsigned int option_def_index;
-    unsigned int blackOpt;
+    unsigned int black, white, extend_edge;
     unsigned int xalignSpec, yalignSpec, mwidthSpec, mheightSpec;
+    unsigned int colorSpec;
+    unsigned int detect_background;
+    unsigned int promoteSpec;
+    const char * promoteOpt;
 
     MALLOCARRAY_NOFAIL(option_def, 100);
 
@@ -88,28 +176,89 @@ parseCommandLine(int argc, const char ** argv,
     OPTENT3(0,   "valign",    OPT_FLOAT,   &cmdlineP->yalign,
             &yalignSpec,           0);
     OPTENT3(0,   "mwidth",    OPT_UINT,    &cmdlineP->mwidth,
-            &mwidthSpec,         0);
+            &mwidthSpec,           0);
     OPTENT3(0,   "mheight",   OPT_UINT,    &cmdlineP->mheight,
-            &mheightSpec,        0);
+            &mheightSpec,          0);
     OPTENT3(0,   "black",     OPT_FLAG,    NULL,
-            &blackOpt,           0);
+            &black,                0);
     OPTENT3(0,   "white",     OPT_FLAG,    NULL,
-            &cmdlineP->white,    0);
+            &white,                0);
+    OPTENT3(0,   "color",     OPT_STRING,  &cmdlineP->color,
+            &colorSpec,            0);
+    OPTENT3(0,   "extend-edge", OPT_FLAG,  NULL,
+            &extend_edge,          0);
+    OPTENT3(0,   "detect-background",  OPT_FLAG,  NULL,
+            &detect_background,    0);
+    OPTENT3(0,   "promote",     OPT_STRING, &promoteOpt,
+            &promoteSpec,          0);
     OPTENT3(0,   "reportonly", OPT_FLAG,   NULL,
-            &cmdlineP->reportonly,   0);
-    OPTENT3(0,   "verbose",   OPT_FLAG,    NULL,
-            &cmdlineP->verbose,  0);
+            &cmdlineP->reportonly, 0);
+    OPTENT3(0,   "verbose",    OPT_FLAG,   NULL,
+            &cmdlineP->verbose,    0);
 
     opt.opt_table = option_def;
-    opt.short_allowed = FALSE;  /* We have no short (old-fashioned) options */
-    opt.allowNegNum = FALSE;  /* We have no parms that are negative numbers */
+    opt.short_allowed = false;  /* We have no short (old-fashioned) options */
+    opt.allowNegNum = false;  /* We have no parms that are negative numbers */
 
     pm_optParseOptions3(&argc, (char **)argv, opt, sizeof opt, 0);
         /* Uses and sets argc, argv, and some of *cmdlineP and others. */
 
-    if (blackOpt && cmdlineP->white)
-        pm_error("You cannot specify both -black and -white");
+    if (!colorSpec)
+        cmdlineP->color = NULL;
+
+    if (black + white + colorSpec + detect_background + extend_edge > 1)
+        pm_error("You can specify only one one of -black, -white, "
+                 "-color -detect-background and -extend-edge");
+    else if (black)
+        cmdlineP->padType = PAD_BLACK;
+    else if (white)
+        cmdlineP->padType = PAD_WHITE;
+    else if (colorSpec)
+        cmdlineP->padType = padTypeFmColorStr(cmdlineP->color);
+    else if (extend_edge)
+        cmdlineP->padType = PAD_EXTEND_EDGE;
+    else if (detect_background)
+        cmdlineP->padType = PAD_DETECTED_BG;
+    else {
+        cmdlineP->padType = PAD_BLACK;
+        if (cmdlineP->verbose)
+            pm_message("No pad color specified.  Padding with black.");
+    }
 
+    if (promoteSpec) {
+        if (!colorSpec)
+            pm_error("-promote requires -color");
+        else {
+            switch (cmdlineP->padType) {
+            case PAD_COLOR:
+            case PAD_GRAY:
+                if (streq(promoteOpt, "none"))
+                    cmdlineP->promote = PROMOTE_NONE;
+                else if (streq(promoteOpt, "format"))
+                    cmdlineP->promote = PROMOTE_FORMAT;
+                else if (streq(promoteOpt, "all"))
+                    cmdlineP->promote = PROMOTE_ALL;
+                else
+                    pm_error("Invalid value for -promote.  "
+                             "Valid values are 'none', 'format', and 'all'");
+                break;
+            case PAD_BLACK:
+            case PAD_WHITE:
+                cmdlineP->promote = PROMOTE_NONE;
+                break;
+            case PAD_DETECTED_BG:
+            case PAD_EXTEND_EDGE:
+                assert(false);  /* Because we have -color */
+                break;
+            }
+        }
+    } else {
+        if (cmdlineP->padType == PAD_COLOR ||
+            cmdlineP->padType == PAD_GRAY) {
+            cmdlineP->promote = PROMOTE_ALL;
+        } else
+            cmdlineP->promote = PROMOTE_NONE;
+    }
     if (cmdlineP->topSpec > 1)
        pm_error("You can specify -top only once");
 
@@ -129,16 +278,16 @@ parseCommandLine(int argc, const char ** argv,
        pm_error("You can specify -height only once");
 
     if (xalignSpec && (cmdlineP->leftSpec || cmdlineP->rightSpec))
-        pm_error("You cannot specify both -xalign and -left or -right");
+        pm_error("You cannot specify both -halign and -left or -right");
 
     if (yalignSpec && (cmdlineP->topSpec || cmdlineP->bottomSpec))
-        pm_error("You cannot specify both -yalign and -top or -bottom");
+        pm_error("You cannot specify both -valign and -top or -bottom");
 
-    if (xalignSpec && !cmdlineP->xsizeSpec)
-        pm_error("-xalign is meaningless without -width");
+    if (xalignSpec && (!cmdlineP->xsizeSpec && !mwidthSpec) )
+        pm_error("-halign is meaningless without -width or -mwidth");
 
-    if (yalignSpec && !cmdlineP->ysizeSpec)
-        pm_error("-yalign is meaningless without -height");
+    if (yalignSpec && (!cmdlineP->ysizeSpec && !mheightSpec) )
+        pm_error("-valign is meaningless without -height or -mheight");
 
     if (xalignSpec) {
         if (cmdlineP->xalign < 0)
@@ -171,83 +320,15 @@ parseCommandLine(int argc, const char ** argv,
         pm_error("This program takes at most 1 parameter.  You specified %d",
                  argc-1);
     else if (argc-1 == 1)
-        cmdlineP->input_filespec = argv[1];
-    else
-        cmdlineP->input_filespec = "-";
-}
-
-
-
-static void
-parseCommandLineOld(int argc, const char ** argv,
-                    struct cmdlineInfo * const cmdlineP) {
-
-    /* This syntax was abandoned in February 2002. */
-    pm_message("Warning: old style options are deprecated!");
-
-    cmdlineP->xsize = cmdlineP->ysize = 0;
-    cmdlineP->left = cmdlineP->right = cmdlineP->top = cmdlineP->bottom = 0;
-    cmdlineP->xalign = cmdlineP->yalign = 0.5;
-    cmdlineP->white = cmdlineP->verbose = FALSE;
-
-    while (argc >= 2 && argv[1][0] == '-') {
-        if (strcmp(argv[1]+1,"black") == 0) cmdlineP->white = FALSE;
-        else if (strcmp(argv[1]+1,"white") == 0) cmdlineP->white = TRUE;
-        else switch (argv[1][1]) {
-        case 'l':
-            if (atoi(argv[1]+2) < 0)
-                pm_error("left border too small");
-            else if (atoi(argv[1]+2) > MAX_WIDTHHEIGHT)
-                pm_error("left border too large");
-            else
-                cmdlineP->left = atoi(argv[1]+2);
-            break;
-        case 'r':
-            if (atoi(argv[1]+2) < 0)
-                pm_error("right border too small");
-            else if (atoi(argv[1]+2) > MAX_WIDTHHEIGHT)
-                pm_error("right border too large");
-            else
-                cmdlineP->right = atoi(argv[1]+2);
-            break;
-        case 'b':
-            if (atoi(argv[1]+2) < 0)
-                pm_error("bottom border too small");
-            else if (atoi(argv[1]+2) > MAX_WIDTHHEIGHT)
-                pm_error("bottom border too large");
-            else
-                cmdlineP->bottom = atoi(argv[1]+2);
-            break;
-        case 't':
-            if (atoi(argv[1]+2) < 0)
-                pm_error("top border too small");
-            else if (atoi(argv[1]+2) > MAX_WIDTHHEIGHT)
-                pm_error("top border too large");
-            else
-                cmdlineP->top = atoi(argv[1]+2);
-            break;
-        default:
-            pm_usage("[-white|-black] [-l#] [-r#] [-t#] [-b#] [pnmfile]");
-        }
-        argc--, argv++;
-    }
-
-    cmdlineP->xsizeSpec = (cmdlineP->xsize > 0);
-    cmdlineP->ysizeSpec = (cmdlineP->ysize > 0);
-
-    if (argc > 2)
-        pm_usage("[-white|-black] [-l#] [-r#] [-t#] [-b#] [pnmfile]");
-
-    if (argc == 2)
-        cmdlineP->input_filespec = argv[1];
+        cmdlineP->inputFileNm = argv[1];
     else
-        cmdlineP->input_filespec = "-";
+        cmdlineP->inputFileNm = "-";
 }
 
 
 
 static void
-validateHorizontalSize(struct cmdlineInfo const cmdline,
+validateHorizontalSize(struct CmdlineInfo const cmdline,
                        unsigned int       const cols) {
 /*----------------------------------------------------------------------------
    Abort the program if the padding parameters in 'cmdline', applied to
@@ -268,14 +349,14 @@ validateHorizontalSize(struct cmdlineInfo const cmdline,
         pm_error("The right padding value you specified is too large.");
 
     if ((double) cols +
-        (double) lpad + 
+        (double) lpad +
         (double) rpad +
         (double) mwidthMaxPad > MAX_WIDTHHEIGHT)
         pm_error("Given padding parameters make output width too large "
                  "for this program to compute");
 
     if (cmdline.xsizeSpec &&
-        (double) cmdline.xsize + (double) mwidthMaxPad> MAX_WIDTHHEIGHT)
+        (double) cmdline.xsize + (double) mwidthMaxPad > MAX_WIDTHHEIGHT)
         pm_error("Given padding parameters make output width too large "
                  "for this program to compute");
 }
@@ -300,8 +381,8 @@ computePadSizeBeforeMult(unsigned int   const unpaddedSize,
 -----------------------------------------------------------------------------*/
     if (sizeSpec) {
         if (begPadSpec && endPadSpec) {
-            if (begPadReq + unpaddedSize + endPadReq < unpaddedSize) {
-                pm_error("Beginning adding (%u), and end "
+            if (begPadReq + unpaddedSize + endPadReq < sizeReq) {
+                pm_error("Beginning padding (%u), and end "
                          "padding (%u) are insufficient to bring the "
                          "image size of %u up to %u.",
                          begPadReq, endPadReq, unpaddedSize, sizeReq);
@@ -378,9 +459,9 @@ computePadSizesOneDim(unsigned int   const unpaddedSize,
         unsigned int const totalPadBeforeMult =
             begPadBeforeMult + endPadBeforeMult;
         double const begFrac =
-            totalPadBeforeMult > 0 ? 
+            totalPadBeforeMult > 0 ?
             (double)begPadBeforeMult / totalPadBeforeMult :
-            0.0;
+            align;
         unsigned int const addlMsizeBegPad = ROUNDU(morePadNeeded * begFrac);
             /* # of pixels we have to add to the beginning to satisfy
                user's desire for the final size to be a multiple of something
@@ -396,7 +477,7 @@ computePadSizesOneDim(unsigned int   const unpaddedSize,
 
 
 static void
-computeHorizontalPadSizes(struct cmdlineInfo const cmdline,
+computeHorizontalPadSizes(struct CmdlineInfo const cmdline,
                           unsigned int       const cols,
                           unsigned int *     const lpadP,
                           unsigned int *     const rpadP) {
@@ -415,7 +496,7 @@ computeHorizontalPadSizes(struct cmdlineInfo const cmdline,
 
 
 static void
-validateVerticalSize(struct cmdlineInfo const cmdline,
+validateVerticalSize(struct CmdlineInfo const cmdline,
                      unsigned int       const rows) {
 /*----------------------------------------------------------------------------
    Abort the program if the padding parameters in 'cmdline', applied to
@@ -453,7 +534,7 @@ validateVerticalSize(struct cmdlineInfo const cmdline,
 
 
 static void
-computeVerticalPadSizes(struct cmdlineInfo const cmdline,
+computeVerticalPadSizes(struct CmdlineInfo const cmdline,
                         int                const rows,
                         unsigned int *     const tpadP,
                         unsigned int *     const bpadP) {
@@ -472,7 +553,7 @@ computeVerticalPadSizes(struct cmdlineInfo const cmdline,
 
 
 static void
-computePadSizes(struct cmdlineInfo const cmdline,
+computePadSizes(struct CmdlineInfo const cmdline,
                 int                const cols,
                 int                const rows,
                 unsigned int *     const lpadP,
@@ -501,13 +582,212 @@ reportPadSizes(int          const inCols,
 
     unsigned int const outCols = inCols + lpad + rpad;
     unsigned int const outRows = inRows + tpad + bpad;
- 
+
     printf("%u %u %u %u %u %u\n", lpad, rpad, tpad, bpad, outCols, outRows);
 
 }
 
 
 
+static unsigned char
+bitPeek(const unsigned char * const bitrow,
+        unsigned int          const position) {
+/*----------------------------------------------------------------------------
+  Value of pixel (bit) of 'bitrow' at 'position'.
+-----------------------------------------------------------------------------*/
+    bool retval;
+
+    unsigned int const charPosition = position / 8;
+    unsigned int const bitPosition  = position % 8;
+
+    retval =  (bitrow[charPosition] >> (7 - bitPosition)) & 0x01;
+
+    return retval;
+}
+
+
+
+static void
+extendLeftPbm(unsigned char * const bitrow,
+              unsigned int    const lpad) {
+/*----------------------------------------------------------------------------
+  Add 'lpad' pixels of padding the the left side of PBM row 'bitrow' by
+  duplicating leftmost pixel.
+-----------------------------------------------------------------------------*/
+    unsigned int const padCharCt  = lpad / 8;
+    unsigned int const fractBitCt = lpad % 8;
+    unsigned int const color      = bitPeek(bitrow, lpad);
+
+    unsigned int colChar;
+
+    for (colChar = 0; colChar < padCharCt; ++colChar)
+        bitrow[colChar] = 0xff * color;
+
+    if (fractBitCt > 0) {
+        bitrow[colChar] = (unsigned char)
+            (0xff * color) << (8-fractBitCt) |
+            (bitrow[colChar] & (0xff >> fractBitCt));
+    }
+}
+
+
+
+static void
+extendRightPbm(unsigned char * const bitrow,
+               unsigned int    const lcols,
+               unsigned int    const rpad) {
+/*----------------------------------------------------------------------------
+  Add 'rpad' pixels of padding the the left side of PBM row 'bitrow',
+  which is 'lcols' columns wide, by duplicating leftmost pixel.
+-----------------------------------------------------------------------------*/
+    unsigned int  const rpad0       = (8 - lcols % 8) % 8;
+    unsigned int  const rpad1       = rpad - rpad0;
+    unsigned int  const rpad1CharCt =
+        rpad1 > 0 ? pbm_packed_bytes(rpad1) : 0;
+    unsigned int  const lastColChar = lcols / 8 - (rpad0 == 0 ? 1 : 0);
+    unsigned char const fillColor   = bitPeek(bitrow, lcols - 1);
+
+    unsigned int colChar;
+
+    if (rpad0 > 0) {
+        if (fillColor == 0x1) {
+            bitrow[lastColChar] =
+                bitrow[lastColChar] | (bitrow[lastColChar] - 1);
+        } else if (lcols % 8 > 0) {
+            /* This is essentially pbm_cleanrowend_packed(bitrow, lcols); */
+
+            unsigned int const last = pbm_packed_bytes(lcols) - 1;
+
+            bitrow[last] >>= 8 - lcols % 8;
+            bitrow[last] <<= 8 - lcols % 8;
+        }
+    }
+
+    for (colChar = 0; colChar < rpad1CharCt; ++colChar)
+        bitrow[lastColChar + colChar +1] = 0xff * fillColor;
+
+    if (fillColor == 0x1)
+        pbm_cleanrowend_packed(bitrow, lcols + rpad);
+}
+
+
+
+static void
+extendEdgePbm(FILE *       const ifP,
+              unsigned int const cols,
+              unsigned int const rows,
+              int          const format,
+              unsigned int const newcols,
+              unsigned int const lpad,
+              unsigned int const rpad,
+              unsigned int const tpad,
+              unsigned int const bpad,
+              FILE *       const ofP) {
+/*----------------------------------------------------------------------------
+  Fast extend-edge routine for PBM
+-----------------------------------------------------------------------------*/
+    unsigned char * const newbitrow = pbm_allocrow_packed(newcols);
+
+    unsigned int row;
+
+    pbm_writepbminit(stdout, newcols, rows + tpad + bpad, 0);
+
+    /* Write top row tpad + 1 times */
+    if (rpad > 0)
+        newbitrow[(cols + lpad) / 8] = 0x00;
+
+    pbm_readpbmrow_bitoffset(ifP, newbitrow, cols, format, lpad);
+
+    if (lpad > 0)
+        extendLeftPbm(newbitrow, lpad);
+    if (rpad > 0)
+        extendRightPbm(newbitrow, lpad + cols, rpad);
+
+    pbm_cleanrowend_packed(newbitrow, newcols);
+
+    for (row = 0; row < tpad + 1; ++row)
+        pbm_writepbmrow_packed(ofP, newbitrow, newcols, 0);
+
+    /* Read rows, shift and write with left and right margins added.
+
+       Alter left/right margin only when the color of leftmost/rightmost
+       pixel is different from that of the previous row.
+    */
+
+    for (row = 1;  row < rows; ++row) {
+        pbm_readpbmrow_bitoffset(ifP, newbitrow, cols, format, lpad);
+
+        if (lpad > 0 &&
+            (bitPeek(newbitrow, lpad - 1) != bitPeek(newbitrow, lpad)))
+            extendLeftPbm(newbitrow, lpad);
+        if (rpad > 0 &&
+            (bitPeek(newbitrow, lpad + cols -1) !=
+             bitPeek(newbitrow, lpad + cols)))
+            extendRightPbm(newbitrow, lpad + cols, rpad);
+        pbm_writepbmrow_packed(ofP, newbitrow, newcols, 0);
+    }
+
+    /* Write bottom margin */
+    for (row = 0; row < bpad; ++row)
+        pbm_writepbmrow_packed(ofP, newbitrow, newcols, 0);
+
+    pnm_freerow(newbitrow);
+}
+
+
+
+static void
+extendEdgeGeneral(FILE *       const ifP,
+                  unsigned int const cols,
+                  unsigned int const rows,
+                  xelval       const maxval,
+                  int          const format,
+                  unsigned int const newcols,
+                  unsigned int const lpad,
+                  unsigned int const rpad,
+                  unsigned int const tpad,
+                  unsigned int const bpad,
+                  FILE *       const ofP) {
+/*----------------------------------------------------------------------------
+  General extend-edge routine (logic works for PBM)
+-----------------------------------------------------------------------------*/
+    xel * const xelrow = pnm_allocrow(newcols);
+
+    unsigned int row, col;
+
+    pnm_writepnminit(ofP, newcols, rows + tpad + bpad, maxval, format, 0);
+
+    pnm_readpnmrow(ifP, &xelrow[lpad], cols, maxval, format);
+
+    for (col = 0; col < lpad; ++col)
+        xelrow[col] = xelrow[lpad];
+    for (col = lpad + cols; col < newcols; ++col)
+        xelrow[col] = xelrow[lpad + cols - 1];
+
+    for (row = 0; row < tpad + 1; ++row)
+        pnm_writepnmrow(ofP, xelrow, newcols, maxval, format, 0);
+
+    for (row = 1; row < rows; ++row) {
+        unsigned int col;
+
+        pnm_readpnmrow(ifP, &xelrow[lpad], cols, maxval, format);
+
+        for (col = 0; col < lpad; ++col)
+            xelrow[col] = xelrow[lpad];
+        for (col = lpad + cols; col < newcols; ++col)
+            xelrow[col] = xelrow[lpad + cols - 1];
+
+        pnm_writepnmrow(ofP, xelrow, newcols, maxval, format, 0);
+    }
+
+    for (row = 0; row < bpad; ++row)
+        pnm_writepnmrow(ofP, xelrow, newcols, maxval, format, 0);
+
+    pnm_freerow(xelrow);
+}
+
+
+
 static void
 padPbm(FILE *       const ifP,
        unsigned int const cols,
@@ -518,7 +798,8 @@ padPbm(FILE *       const ifP,
        unsigned int const rpad,
        unsigned int const tpad,
        unsigned int const bpad,
-       bool         const colorWhite) {
+       enum PadType const padType,
+       FILE *       const ofP) {
 /*----------------------------------------------------------------------------
   Fast padding routine for PBM
 -----------------------------------------------------------------------------*/
@@ -526,7 +807,7 @@ padPbm(FILE *       const ifP,
     unsigned char * const newrow = pbm_allocrow_packed(newcols);
 
     unsigned char const padChar =
-        0xff * (colorWhite ? PBM_WHITE : PBM_BLACK);
+        0xff * (padType == PAD_WHITE ? PBM_WHITE : PBM_BLACK);
 
     unsigned int const newColChars = pbm_packed_bytes(newcols);
 
@@ -542,70 +823,280 @@ padPbm(FILE *       const ifP,
         newrow[newColChars-1] <<= 8 - newcols % 8;
     }
 
-    pbm_writepbminit(stdout, newcols, rows + tpad + bpad, 0);
+    pbm_writepbminit(ofP, newcols, rows + tpad + bpad, 0);
 
     /* Write top margin */
     for (row = 0; row < tpad; ++row)
-        pbm_writepbmrow_packed(stdout, bgrow, newcols, 0);
-    
+        pbm_writepbmrow_packed(ofP, bgrow, newcols, 0);
+
     /* Read rows, shift and write with left and right margins added */
     for (row = 0; row < rows; ++row) {
         pbm_readpbmrow_bitoffset(ifP, newrow, cols, format, lpad);
-        pbm_writepbmrow_packed(stdout, newrow, newcols, 0);
+        pbm_writepbmrow_packed(ofP, newrow, newcols, 0);
     }
 
     pnm_freerow(newrow);
 
     /* Write bottom margin */
     for (row = 0; row < bpad; ++row)
-        pbm_writepbmrow_packed(stdout, bgrow, newcols, 0);
+        pbm_writepbmrow_packed(ofP, bgrow, newcols, 0);
 
     pnm_freerow(bgrow);
 }
 
 
+
+static xel
+regressColor(int  const format,
+             int  const maxval,
+             xel  const color) {
+
+    gray const grayval = (gray) ppm_luminosity(color);
+
+    xel retval;
+
+    switch (PNM_FORMAT_TYPE(format)) {
+    case PBM_TYPE:
+      {
+        gray const threshold = maxval / 2;
+
+        retval = grayval > threshold ?
+            pnm_whitexel(maxval, format) : pnm_blackxel(maxval, format);
+      }
+        break;
+    case PGM_TYPE:
+        retval.b = grayval;
+        retval.r = retval.g = 0;
+        break;
+    case PPM_TYPE:
+        retval = color;
+        break;
+    default:
+        pm_error("internal error -- impossible value of PNM format "
+                 "type in regressColor");
+    }
+    return retval;
+}
+
+
+
+static void
+computeOutputFormatAndBackground(int              const format,
+                                 int              const maxval,
+                                 enum PadType     const padType,
+                                 const char *     const colorStr,
+                                 enum PromoteType const promoteType,
+                                 int *            const newformatP,
+                                 pixval *         const newmaxvalP,
+                                 xel *            const backgroundP) {
+
+    int    newformat;
+    xelval newmaxval;
+    xel    background;
+
+    switch (promoteType) {
+    case PROMOTE_NONE:
+        newformat = format;
+        newmaxval = maxval;
+
+        switch (padType) {
+        case PAD_BLACK:
+            background = pnm_blackxel(newmaxval, newformat);
+            break;
+        case PAD_WHITE:
+            background = pnm_whitexel(newmaxval, newformat);
+            break;
+        case PAD_GRAY:
+        case PAD_COLOR:
+            background = regressColor(format, maxval,
+                                      ppm_parsecolor(colorStr, newmaxval));
+            break;
+        case PAD_DETECTED_BG:
+        case PAD_EXTEND_EDGE:
+            pm_error("internal error -- impossible value of 'promoteType' "
+                     "in computeOutputFormatAndBackground");
+        } break;
+
+    case PROMOTE_FORMAT:
+    case PROMOTE_ALL: {
+        newmaxval = promoteType == PROMOTE_ALL ? MAX(255, maxval) : maxval;
+
+        switch (padType) {
+        case PAD_BLACK:
+            newformat = format;
+            background = pnm_blackxel(newmaxval, newformat);
+            break;
+        case PAD_WHITE:
+            newformat = format;
+            background = pnm_whitexel(newmaxval, newformat);
+            break;
+        case PAD_GRAY:
+            newformat =
+                PNM_FORMAT_TYPE(format) == PBM_TYPE ? PGM_TYPE : format;
+            background = ppm_parsecolor(colorStr, newmaxval);
+            break;
+        case PAD_COLOR:
+            newformat = PPM_TYPE;
+            background = ppm_parsecolor(colorStr, newmaxval);
+            break;
+        case PAD_DETECTED_BG:
+        case PAD_EXTEND_EDGE:
+            pm_error("internal error -- impossible value of 'promoteType' "
+                     "in computeOutputFormatAndBackground");
+        } break;
+    }
+    }
+
+    *newformatP  = newformat;
+    *newmaxvalP  = newmaxval;
+    *backgroundP = background;
+}
+
+
+
 static void
-padGeneral(FILE *       const ifP,
-           unsigned int const cols,
-           unsigned int const rows,
-           xelval       const maxval,
-           int          const format,
-           unsigned int const newcols,
-           unsigned int const lpad,
-           unsigned int const rpad,
-           unsigned int const tpad,
-           unsigned int const bpad,
-           bool         const colorWhite) {
+padDetectedBg(FILE *       const ifP,
+              unsigned int const cols,
+              unsigned int const rows,
+              xelval       const maxval,
+              int          const format,
+              unsigned int const newcols,
+              unsigned int const lpad,
+              unsigned int const rpad,
+              unsigned int const tpad,
+              unsigned int const bpad,
+              FILE *       const ofP) {
 /*----------------------------------------------------------------------------
-  General padding routine (logic works for PBM)
+  Pad using top left pixel as background color.
+
+  (There is no special PBM routine for this case)
 -----------------------------------------------------------------------------*/
     xel * const bgrow  = pnm_allocrow(newcols);
+        /* A row of background color (for top and bottom padding) */
     xel * const xelrow = pnm_allocrow(newcols);
-    xel background;
+        /* A row of padded output image.  Left and right padding is
+           constant; middle varies from row to row.
+        */
+    xel * const window = &xelrow[lpad];
+        /* The foreground part of the current row */
+
+    unsigned int row;;
+
+    pnm_writepnminit(ofP, newcols, rows + tpad + bpad, maxval, format, 0);
+
+    pnm_readpnmrow(ifP, window, cols, maxval, format);
+
+    {
+        /* Set 'bgrow' and constant parts of 'xelrow' */
+        xel const background = window[0];
+
+        unsigned int col;
+
+        for (col = 0; col < newcols; ++col)
+            bgrow[col] = background;
+
+        for (col = 0; col < lpad; ++col)
+            xelrow[col] = background;
+
+        for (col = lpad + cols; col < newcols; ++col)
+            xelrow[col] = background;
+    }
+
+    /* Write top padding */
+    for (row = 0; row < tpad; ++row)
+        pnm_writepnmrow(ofP, bgrow, newcols, maxval, format, 0);
+
+    /* Write body of image */
+    pnm_writepnmrow(ofP, xelrow, newcols, maxval, format, 0);
+
+    for (row = 1; row < rows; ++row) {
+        pnm_readpnmrow(ifP, window, cols, maxval, format);
+        pnm_writepnmrow(ofP, xelrow, newcols, maxval, format, 0);
+    }
+    pnm_freerow(xelrow);
+
+    /* Write bottom padding */
+    for (row = 0; row < bpad; ++row)
+        pnm_writepnmrow(ofP, bgrow, newcols, maxval, format, 0);
+
+    pnm_freerow(bgrow);
+}
+
+
+
+static void
+padGeneral(FILE *           const ifP,
+           unsigned int     const cols,
+           unsigned int     const rows,
+           xelval           const maxval,
+           int              const format,
+           unsigned int     const newcols,
+           unsigned int     const lpad,
+           unsigned int     const rpad,
+           unsigned int     const tpad,
+           unsigned int     const bpad,
+           enum PadType     const padType,
+           const char *     const colorStr,
+           enum PromoteType const promoteType,
+           FILE *           const ofP) {
+/*----------------------------------------------------------------------------
+  General padding routine (logic works for PBM)
+-----------------------------------------------------------------------------*/
+    xel * const bgrow = pnm_allocrow(newcols);
+        /* A row of background color (for top and bottom padding) */
+
+    int    newformat;
+    pixval newmaxval;
+    xel    background;
+
     unsigned int row, col;
 
-    if (colorWhite)
-        background = pnm_whitexel(maxval, format);
-    else
-        background = pnm_blackxel(maxval, format);
+    computeOutputFormatAndBackground(
+        format, maxval, padType, colorStr, promoteType,
+        &newformat, &newmaxval, &background);
+
+    if (newformat != format)
+        pm_message("Promoting to %s", pnm_formattypenm(newformat));
 
     for (col = 0; col < newcols; ++col)
-        xelrow[col] = bgrow[col] = background;
+        bgrow[col] = background;
+
+    pnm_writepnminit(ofP, newcols, rows + tpad + bpad,
+                     newmaxval, newformat, 0);
 
-    pnm_writepnminit(stdout, newcols, rows + tpad + bpad, maxval, format, 0);
+    /* Write top padding */
 
     for (row = 0; row < tpad; ++row)
-        pnm_writepnmrow(stdout, bgrow, newcols, maxval, format, 0);
+        pnm_writepnmrow(ofP, bgrow, newcols, newmaxval, newformat, 0);
 
-    for (row = 0; row < rows; ++row) {
-        pnm_readpnmrow(ifP, &xelrow[lpad], cols, maxval, format);
-        pnm_writepnmrow(stdout, xelrow, newcols, maxval, format, 0);
+    /* Write body of image */
+    {
+        xel * const xelrow = pnm_allocrow(newcols);
+            /* A row of padded output image.  Left and right padding is
+               constant; middle varies from row to row.
+            */
+        xel * const window = &xelrow[lpad];
+            /* The foreground part of the current row */
+
+        /* Initial value for 'xelrow': all background */
+        for (col = 0; col < newcols; ++col)
+            xelrow[col] = bgrow[col] = background;
+
+        for (row = 0; row < rows; ++row) {
+            pnm_readpnmrow(ifP, window, cols, maxval, format);
+            if (maxval != newmaxval || format != newformat) {
+                pnm_promoteformatrow(window, cols, maxval, format,
+                                     newmaxval, newformat);
+            }
+            pnm_writepnmrow(ofP, xelrow, newcols, newmaxval, newformat, 0);
+        }
+        pnm_freerow(xelrow);
     }
 
+    /* Write bottom padding */
     for (row = 0; row < bpad; ++row)
-        pnm_writepnmrow(stdout, bgrow, newcols, maxval, format, 0);
+        pnm_writepnmrow(ofP, bgrow, newcols, newmaxval, newformat, 0);
 
-    pnm_freerow(xelrow);
     pnm_freerow(bgrow);
 }
 
@@ -614,43 +1105,25 @@ padGeneral(FILE *       const ifP,
 int
 main(int argc, const char ** argv) {
 
-    struct cmdlineInfo cmdline;
+    struct CmdlineInfo cmdline;
     FILE * ifP;
 
     xelval maxval;
     int rows, cols, newcols, format;
-    bool depr_cmd; /* use deprecated commandline interface */
     unsigned int lpad, rpad, tpad, bpad;
 
     pm_proginit(&argc, argv);
 
-    /* detect deprecated options */
-    depr_cmd = FALSE;  /* initial assumption */
-    if (argc > 1 && argv[1][0] == '-') {
-        if (argv[1][1] == 't' || argv[1][1] == 'b'
-            || argv[1][1] == 'l' || argv[1][1] == 'r') {
-            if (argv[1][2] >= '0' && argv[1][2] <= '9')
-                depr_cmd = TRUE;
-        }
-    }
-    if (argc > 2 && argv[2][0] == '-') {
-        if (argv[2][1] == 't' || argv[2][1] == 'b'
-            || argv[2][1] == 'l' || argv[2][1] == 'r') {
-            if (argv[2][2] >= '0' && argv[2][2] <= '9')
-                depr_cmd = TRUE;
-        }
-    }
+    validateNoOldOptionSyntax(argc, argv);
 
-    if (depr_cmd)
-        parseCommandLineOld(argc, argv, &cmdline);
-    else
-        parseCommandLine(argc, argv, &cmdline);
+    parseCommandLine(argc, argv, &cmdline);
 
-    ifP = pm_openr(cmdline.input_filespec);
+    ifP = pm_openr(cmdline.inputFileNm);
 
     pnm_readpnminit(ifP, &cols, &rows, &maxval, &format);
 
-    if (cmdline.verbose) pm_message("image WxH = %dx%d", cols, rows);
+    if (cmdline.verbose)
+        pm_message("image WxH = %dx%d", cols, rows);
 
     computePadSizes(cmdline, cols, rows, &lpad, &rpad, &tpad, &bpad);
 
@@ -659,15 +1132,40 @@ main(int argc, const char ** argv) {
     if (cmdline.reportonly)
         reportPadSizes(cols, rows, lpad, rpad, tpad, bpad);
     else {
-        if (PNM_FORMAT_TYPE(format) == PBM_TYPE)
-            padPbm(ifP, cols, rows, format, newcols, lpad, rpad, tpad, bpad,
-                   !!cmdline.white);
-        else
-            padGeneral(ifP, cols, rows, maxval, format,
-                       newcols, lpad, rpad, tpad, bpad, !!cmdline.white);
+        switch (cmdline.padType) {
+        case PAD_EXTEND_EDGE:
+            if (PNM_FORMAT_TYPE(format) == PBM_TYPE)
+                extendEdgePbm(ifP, cols, rows, format,
+                              newcols, lpad, rpad, tpad, bpad, stdout);
+            else
+                extendEdgeGeneral(ifP, cols, rows, maxval, format,
+                                  newcols, lpad, rpad, tpad, bpad, stdout);
+            break;
+        case PAD_DETECTED_BG:
+            padDetectedBg(ifP, cols, rows, maxval, format,
+                          newcols, lpad, rpad, tpad, bpad, stdout);
+            break;
+        case PAD_BLACK:
+        case PAD_WHITE:
+        case PAD_GRAY:
+        case PAD_COLOR:
+            if (PNM_FORMAT_TYPE(format) == PBM_TYPE &&
+                (cmdline.padType == PAD_WHITE || cmdline.padType == PAD_BLACK))
+                padPbm(ifP, cols, rows, format,
+                       newcols, lpad, rpad, tpad, bpad, cmdline.padType,
+                       stdout);
+            else
+                padGeneral(ifP, cols, rows, maxval, format,
+                           newcols, lpad, rpad, tpad, bpad, cmdline.padType,
+                           cmdline.color, cmdline.promote, stdout);
+            break;
+        }
     }
 
     pm_close(ifP);
 
     return 0;
 }
+
+
+
diff --git a/editor/pnmquant b/editor/pnmquant
index f7af9e7a..4dd133f1 100755
--- a/editor/pnmquant
+++ b/editor/pnmquant
@@ -37,9 +37,16 @@ use Getopt::Long;
 use File::Spec;
 #use Fcntl ":seek";  # not available in Perl 5.00503
 use Fcntl;  # gets open flags
+use IO::Handle;
 
 my ($TRUE, $FALSE) = (1,0);
 
+sub pm_message($) {
+    STDERR->print("pnmquant: $_[0]\n");
+}
+
+
+
 my ($SEEK_SET, $SEEK_CUR, $SEEK_END) = (0, 1, 2);
 
 
@@ -59,16 +66,17 @@ sub doVersionHack($) {
 
 sub tempFile($) {
 
+    my ($suffix) = @_;
+
     # We trust Perl's File::Temp to do a better job of creating the temp
     # file, but it doesn't exist before Perl 5.6.1.
 
     if (eval { require File::Temp; 1 }) {
         return File::Temp::tempfile("pnmquant_XXXX", 
-                                    SUFFIX=>".pnm", 
+                                    SUFFIX=>$suffix, 
                                     DIR=>File::Spec->tmpdir(),
                                     UNLINK=>$TRUE);
     } else {
-        my ($suffix) = @_;
         my $fileName;
         local *file;  # For some inexplicable reason, must be local, not my
         my $i;
@@ -102,17 +110,16 @@ sub parseCommandLine(@) {
                                   "plain");
 
     if (!$optsAreValid) {
-        print(STDERR "Invalid option syntax.\n");
+        pm_message("Invalid option syntax");
         exit(1);
     }
     if (@ARGV > 2) {
-        print(STDERR "This program takes at most 2 arguments.  You specified ",
-              scalar(@ARGV), "\n");
+        pm_message("This program takes at most 2 arguments.  You specified " .
+                   scalar(@ARGV));
         exit(1);
     } 
     elsif (@ARGV < 1) {
-        print(STDERR 
-              "You must specify the number of colors as an argument.\n");
+        pm_message("You must specify the number of colors as an argument.");
         exit(1);
     }
     my $infile;
@@ -120,9 +127,8 @@ sub parseCommandLine(@) {
     
     if (!($cmdline{ncolors} =~ m{ ^[[:digit:]]+$ }x ) || 
         $cmdline{ncolors} == 0) {
-        print(STDERR 
-              "Number of colors argument '$cmdline{ncolors}' " .
-              "is not a positive integer.\n");
+        pm_message("Number of colors argument '$cmdline{ncolors}' " .
+                   "is not a positive integer.");
         exit(1);
     }
 
@@ -210,8 +216,8 @@ sub makeColormap($$$$$$$) {
     my ($mapfileFh, $mapfileSpec) = tempFile(".pnm");
 
     if (!defined($mapfileFh)) {
-        print(STDERR "Unable to create temporary file for colormap.  " .
-              "errno = $ERRNO\n");
+        pm_message("Unable to create temporary file for colormap.  " .
+                   "errno = $ERRNO");
         exit(1);
     }
        
@@ -223,8 +229,8 @@ sub makeColormap($$$$$$$) {
         (defined($opt_center)    ? 1 : 0);
 
     if ($colorSummaryOptCt > 1) {
-        print(STDERR "You can specify only one of " .
-              "-meanpixel, -meancolor, and -center\n");
+        pm_message("You can specify only one of " .
+                   "-meanpixel, -meancolor, and -center");
         exit(1);
     }
     if (defined($opt_meanpixel)) {
@@ -240,8 +246,8 @@ sub makeColormap($$$$$$$) {
         (defined($opt_spreadbrightness) ? 1 : 0);
 
     if ($spreadOptCt > 1) {
-        print(STDERR "You can specify only one of " .
-              "-spreadluminosity and -spreadbrightness\n");
+        pm_message("You can specify only one of " .
+                   "-spreadluminosity and -spreadbrightness");
         exit(1);
     }
 
@@ -263,7 +269,7 @@ sub makeColormap($$$$$$$) {
     my $maprc = system("pnmcolormap", $ncolors, @options);
 
     if ($maprc != 0) {
-        print(STDERR "pnmcolormap failed, rc=$maprc\n");
+        pm_message("pnmcolormap failed, rc=$maprc");
         exit(1);
     } 
     return $mapfileSpec;
@@ -287,15 +293,15 @@ sub remap($$$$$$) {
     }
     if ($opt_norandom) {
         if (defined($opt_randomseed)) {
-             print(STDERR "You cannot specify -randomseed with -norandom\n");
+             pm_message("You cannot specify -randomseed with -norandom");
              exit(1);
         }
         push(@options, "-norandom");
     }
     if (defined($opt_randomseed)) {
         if ($opt_randomseed < 0) {
-             print(STDERR "-randomseed value must not be negative.  " .
-                   "You specified $opt_randomseed\n");
+             pm_message("-randomseed value must not be negative.  " .
+                        "You specified $opt_randomseed");
              exit(10);
         }
         push(@options, "-randomseed=$opt_randomseed");
@@ -310,7 +316,7 @@ sub remap($$$$$$) {
     my $remaprc = system("pnmremap", "-mapfile=$mapfileSpec", @options);
     
     if ($remaprc != 0) {
-        print(STDERR "pnmremap failed, rc=$remaprc\n");
+        pm_message("pnmremap failed, rc=$remaprc");
         exit(1);
     }
 }
diff --git a/editor/pnmquantall b/editor/pnmquantall
index aea6cc84..594e8f7b 100755
--- a/editor/pnmquantall
+++ b/editor/pnmquantall
@@ -57,11 +57,18 @@ use warnings;
 use English;
 use Fcntl;  # gets open flags
 use File::Copy;
+use IO::Handle;
 
 my $TRUE=1; my $FALSE = 0;
 
 
 
+sub pm_message($) {
+    STDERR->print("pnmquantall: $_[0]\n");
+}
+
+
+
 sub doVersionHack($) {
     my ($argvR) = @_;
 
@@ -84,7 +91,7 @@ sub parseArgs($$$$) {
 
     if (@argv > 0 && $argv[0] eq "-ext") {
         if (@argv < 2) {
-            print STDERR ("-ext requires a value\n");
+            pm_message("-ext requires a value");
         exit(100);
         } else {
             $$extR = $argv[1];
@@ -96,8 +103,8 @@ sub parseArgs($$$$) {
     }
 
     if (@argv < $firstArgPos + 2) {
-        print STDERR ("Not enough arguments.  You need at least the number " .
-                      "of colors and one file name\n");
+        pm_message("Not enough arguments.  You need at least the number " .
+                      "of colors and one file name");
         exit(100);
     }
     
@@ -110,16 +117,17 @@ sub parseArgs($$$$) {
 
 sub tempFile($) {
 
+    my ($suffix) = @_;
+
     # We trust Perl's File::Temp to do a better job of creating the temp
     # file, but it doesn't exist before Perl 5.6.1.
 
     if (eval { require File::Temp; 1 }) {
         return File::Temp::tempfile("pnmquant_XXXX", 
-                                    SUFFIX=>".pnm", 
+                                    SUFFIX=>$suffix, 
                                     DIR=>File::Spec->tmpdir(),
                                     UNLINK=>$TRUE);
     } else {
-        my ($suffix) = @_;
         my $fileName;
         local *file;  # For some inexplicable reason, must be local, not my
         my $i;
@@ -137,11 +145,11 @@ sub tempFile($) {
 sub makeColorMap($$$$) {
     my ($fileNamesR, $newColorCt, $colorMapFileName, $errorR) = @_;
 
-    my $pnmcatCmd = "pnmcat -topbottom -white -jleft @{$fileNamesR}";
+    my $pamcatCmd = "pamcat -topbottom -white -jleft @{$fileNamesR}";
 
     my $pnmcolormapCmd = "pnmcolormap $newColorCt";
 
-    my $makeMapCmd = "$pnmcatCmd | $pnmcolormapCmd >$colorMapFileName";
+    my $makeMapCmd = "$pamcatCmd | $pnmcolormapCmd >$colorMapFileName";
 
     my $termStatus = system($makeMapCmd);
 
@@ -212,7 +220,7 @@ if (!$progError) {
 my $exitStatus;
 
 if ($progError) {
-    print STDERR ("Failed.  $progError\n");
+    pm_message("Failed.  $progError");
     $exitStatus = 1;
 } else {
     $exitStatus = 0;
diff --git a/editor/pnmremap.c b/editor/pnmremap.c
index 0c0096ba..38e203f7 100644
--- a/editor/pnmremap.c
+++ b/editor/pnmremap.c
@@ -28,6 +28,7 @@
 #include "pm_c_util.h"
 #include "mallocvar.h"
 #include "nstring.h"
+#include "rand.h"
 #include "shhopt.h"
 #include "pam.h"
 #include "ppm.h"
@@ -399,20 +400,21 @@ randomizeError(long **       const err,
    Set a random error in the range [-1 .. 1] (normalized via FS_SCALE)
    in the error array err[][].
 -----------------------------------------------------------------------------*/
-    unsigned int const seed = (random.init == RANDOM_WITHSEED) ?
-        random.seed : pm_randseed();
-
     unsigned int col;
+    struct pm_randSt randSt;
 
     assert(random.init != RANDOM_NONE);
 
-    srand(seed);
+    pm_randinit(&randSt);
+    pm_srand2(&randSt, random.init == RANDOM_WITHSEED, random.seed);
 
     for (col = 0; col < width; ++col) {
         unsigned int plane;
         for (plane = 0; plane < depth; ++plane)
-            err[plane][col] = rand() % (FS_SCALE * 2) - FS_SCALE;
+            err[plane][col] = pm_rand(&randSt) % (FS_SCALE * 2) - FS_SCALE;
     }
+
+    pm_randterm(&randSt);
 }
 
 
@@ -466,7 +468,7 @@ fserr_init(struct pam *   const pamP,
 -----------------------------------------------------------------------------*/
     unsigned int plane;
 
-    unsigned int const fserrSize = pamP->width + 2;
+    unsigned int const fserrSz = pamP->width + 2;
 
     fserrP->width = pamP->width;
 
@@ -480,20 +482,20 @@ fserr_init(struct pam *   const pamP,
                  "for depth %u", pamP->depth);
 
     for (plane = 0; plane < pamP->depth; ++plane) {
-        MALLOCARRAY(fserrP->thiserr[plane], fserrSize);
+        MALLOCARRAY(fserrP->thiserr[plane], fserrSz);
         if (fserrP->thiserr[plane] == NULL)
             pm_error("Out of memory allocating Floyd-Steinberg structures "
-                     "for Plane %u, size %u", plane, fserrSize);
-        MALLOCARRAY(fserrP->nexterr[plane], fserrSize);
+                     "for Plane %u, size %u", plane, fserrSz);
+        MALLOCARRAY(fserrP->nexterr[plane], fserrSz);
         if (fserrP->nexterr[plane] == NULL)
             pm_error("Out of memory allocating Floyd-Steinberg structures "
-                     "for Plane %u, size %u", plane, fserrSize);
+                     "for Plane %u, size %u", plane, fserrSz);
     }
 
     if (random.init != RANDOM_NONE)
-        randomizeError(fserrP->thiserr, fserrSize, pamP->depth, random);
+        randomizeError(fserrP->thiserr, fserrSz, pamP->depth, random);
     else
-        zeroError(fserrP->thiserr, fserrSize, pamP->depth);
+        zeroError(fserrP->thiserr, fserrSz, pamP->depth);
 
     fserr_setForward(fserrP);
 }
@@ -1012,7 +1014,7 @@ static void
 copyRaster(struct pam *   const inpamP,
            struct pam *   const outpamP,
            tupletable     const colormap,
-           unsigned int   const colormapSize,
+           unsigned int   const colormapSz,
            bool           const floyd,
            struct Random  const random,
            tuple          const defaultColor,
@@ -1047,7 +1049,7 @@ copyRaster(struct pam *   const inpamP,
 
     usehash = TRUE;
 
-    createColormapFinder(outpamP, colormap, colormapSize, &colorFinderP);
+    createColormapFinder(outpamP, colormap, colormapSz, &colorFinderP);
 
     if (floyd)
         fserr_init(inpamP, &fserr, random);
@@ -1080,13 +1082,13 @@ static void
 remap(FILE *             const ifP,
       const struct pam * const outpamCommonP,
       tupletable         const colormap,
-      unsigned int       const colormapSize,
+      unsigned int       const colormapSz,
       bool               const floyd,
       struct Random      const random,
       tuple              const defaultColor,
       bool               const verbose) {
 /*----------------------------------------------------------------------------
-   Remap the pixels from the raster on *ifP to the 'colormapSize' colors in
+   Remap the pixels from the raster on *ifP to the 'colormapSz' colors in
    'colormap'.
 
    Where the input pixel's color is in the map, just use that for the output.
@@ -1127,7 +1129,7 @@ remap(FILE *             const ifP,
         */
         pnm_setminallocationdepth(&inpam, outpam.depth);
 
-        copyRaster(&inpam, &outpam, colormap, colormapSize, floyd,
+        copyRaster(&inpam, &outpam, colormap, colormapSz, floyd,
                    random, defaultColor, &missingCount);
 
         if (verbose)
@@ -1140,15 +1142,15 @@ remap(FILE *             const ifP,
 
 
 static void
-processMapFile(const char *   const mapFileName,
+processMapFile(const char *   const mapFileNm,
                struct pam *   const outpamCommonP,
                tupletable *   const colormapP,
-               unsigned int * const colormapSizeP,
+               unsigned int * const colormapSzP,
                tuple *        const firstColorP) {
 /*----------------------------------------------------------------------------
-   Read a color map from the file named 'mapFileName'.  It's a map that
+   Read a color map from the file named 'mapFileNm'.  It's a map that
    associates each color in that file with a unique whole number.  Return the
-   map as *colormapP, with the number of entries in it as *colormapSizeP.
+   map as *colormapP, with the number of entries in it as *colormapSzP.
 
    Also determine the first color (top left) in the map file and return that
    as *firstColorP.
@@ -1158,11 +1160,11 @@ processMapFile(const char *   const mapFileName,
     tuple ** maptuples;
     tuple firstColor;
 
-    mapfile = pm_openr(mapFileName);
+    mapfile = pm_openr(mapFileNm);
     maptuples = pnm_readpam(mapfile, &mappam, PAM_STRUCT_SIZE(tuple_type));
     pm_close(mapfile);
 
-    computeColorMapFromMap(&mappam, maptuples, colormapP, colormapSizeP);
+    computeColorMapFromMap(&mappam, maptuples, colormapP, colormapSzP);
 
     firstColor = pnm_allocpamtuple(&mappam);
     pnm_assigntuple(&mappam, firstColor, maptuples[0][0]);
@@ -1178,15 +1180,15 @@ processMapFile(const char *   const mapFileName,
 
 static void
 getSpecifiedMissingColor(struct pam * const pamP,
-                         const char * const colorName,
+                         const char * const colorNm,
                          tuple *      const specColorP) {
 
     tuple specColor;
 
     specColor = pnm_allocpamtuple(pamP);
 
-    if (colorName) {
-        pixel const color = ppm_parsecolor(colorName, pamP->maxval);
+    if (colorNm) {
+        pixel const color = ppm_parsecolor(colorNm, pamP->maxval);
         if (pamP->depth == 3) {
             specColor[PAM_RED_PLANE] = PPM_GETR(color);
             specColor[PAM_GRN_PLANE] = PPM_GETG(color);
@@ -1216,7 +1218,7 @@ main(int argc, const char * argv[] ) {
            across all output images.
         */
     tupletable colormap;
-    unsigned int colormapSize;
+    unsigned int colormapSz;
     tuple specColor;
         /* A tuple of the color the user specified to use for input colors
            that are not in the colormap.  Arbitrary tuple if he didn't
@@ -1237,7 +1239,7 @@ main(int argc, const char * argv[] ) {
     ifP = pm_openr(cmdline.inputFilespec);
 
     processMapFile(cmdline.mapFilespec, &outpamCommon,
-                   &colormap, &colormapSize, &firstColor);
+                   &colormap, &colormapSz, &firstColor);
 
     getSpecifiedMissingColor(&outpamCommon, cmdline.missingcolor, &specColor);
 
@@ -1253,7 +1255,7 @@ main(int argc, const char * argv[] ) {
         break;
     }
 
-    remap(ifP, &outpamCommon, colormap, colormapSize,
+    remap(ifP, &outpamCommon, colormap, colormapSz,
           cmdline.floyd, cmdline.random, defaultColor,
           cmdline.verbose);
 
diff --git a/editor/pnmrotate.c b/editor/pnmrotate.c
index 44952a59..b034d395 100644
--- a/editor/pnmrotate.c
+++ b/editor/pnmrotate.c
@@ -40,7 +40,7 @@ struct cmdlineInfo {
 enum rotationDirection {CLOCKWISE, COUNTERCLOCKWISE};
 
 struct shearParm {
-    /* These numbers tell how to shear a pixel, but I haven't figured out 
+    /* These numbers tell how to shear a pixel, but I haven't figured out
        yet exactly what each means.
     */
     long fracnew0;
@@ -67,13 +67,13 @@ parseCommandLine(int argc, char ** const argv,
     unsigned int option_def_index;
 
     option_def_index = 0;   /* incremented by OPTENTRY */
-    OPTENT3(0, "background",  OPT_STRING, &cmdlineP->background, 
+    OPTENT3(0, "background",  OPT_STRING, &cmdlineP->background,
             &backgroundSpec,        0);
-    OPTENT3(0, "noantialias", OPT_FLAG,   NULL, 
+    OPTENT3(0, "noantialias", OPT_FLAG,   NULL,
             &cmdlineP->noantialias, 0);
-    OPTENT3(0, "keeptemp",    OPT_FLAG,   NULL, 
+    OPTENT3(0, "keeptemp",    OPT_FLAG,   NULL,
             &cmdlineP->keeptemp,    0);
-    OPTENT3(0, "verbose",     OPT_FLAG,   NULL, 
+    OPTENT3(0, "verbose",     OPT_FLAG,   NULL,
             &cmdlineP->verbose,     0);
 
     opt.opt_table = option_def;
@@ -110,7 +110,7 @@ parseCommandLine(int argc, char ** const argv,
                 cmdlineP->inputFilespec = "-";
             else {
                 cmdlineP->inputFilespec = argv[2];
-                
+
                 if (argc-1 > 2)
                     pm_error("Program takes at most two arguments "
                              "(angle and filename).  You specified %d",
@@ -139,10 +139,10 @@ storeImage(const char * const fileName,
     pm_close(ofP);
 }
 
-  
+
 
 static void
-computeNewFormat(bool     const antialias, 
+computeNewFormat(bool     const antialias,
                  int      const format,
                  xelval   const maxval,
                  int *    const newformatP,
@@ -172,7 +172,7 @@ backgroundColor(const char * const backgroundColorName,
 
     if (backgroundColorName) {
         retval = pnm_parsecolorxel(backgroundColorName, maxval, format);
-    } else 
+    } else
         retval = pnm_backgroundxelrow(topRow, cols, maxval, format);
 
     return retval;
@@ -190,9 +190,9 @@ reportBackground(xel const bgColor) {
 
 
 static void
-shearX(xel * const inRow, 
-       xel * const outRow, 
-       int   const cols, 
+shearX(xel * const inRow,
+       xel * const outRow,
+       int   const cols,
        int   const format,
        xel   const bgxel,
        bool  const antialias,
@@ -210,9 +210,9 @@ shearX(xel * const inRow,
    We shift the row on a background of color 'bgxel'.
 
    The output row has the same format and maxval as the input.
-   
+
    'shiftAmount' may not be negative.
-   
+
    'shiftAmount' can be fractional, so we either just go by the
    nearest integer value or mix pixels to achieve the shift, depending
    on 'antialias'.
@@ -230,7 +230,7 @@ shearX(xel * const inRow,
 
         for (col = 0; col < newcols; ++col)
             outRow[col] = bgxel;
-            
+
         prevxel = bgxel;
         for (col = 0, nxP = &(outRow[shiftWhole]);
              col < cols; ++col, ++nxP) {
@@ -240,21 +240,21 @@ shearX(xel * const inRow,
             switch (PNM_FORMAT_TYPE(format)) {
             case PPM_TYPE:
                 PPM_ASSIGN(*nxP,
-                           (fracShift * PPM_GETR(prevxel) 
-                            + omfracShift * PPM_GETR(p) 
+                           (fracShift * PPM_GETR(prevxel)
+                            + omfracShift * PPM_GETR(p)
                             + HALFSCALE) / SCALE,
-                           (fracShift * PPM_GETG(prevxel) 
-                            + omfracShift * PPM_GETG(p) 
+                           (fracShift * PPM_GETG(prevxel)
+                            + omfracShift * PPM_GETG(p)
                             + HALFSCALE) / SCALE,
-                           (fracShift * PPM_GETB(prevxel) 
-                            + omfracShift * PPM_GETB(p) 
+                           (fracShift * PPM_GETB(prevxel)
+                            + omfracShift * PPM_GETB(p)
                             + HALFSCALE) / SCALE );
                 break;
-                
+
             default:
                 PNM_ASSIGN1(*nxP,
-                            (fracShift * PNM_GET1(prevxel) 
-                             + omfracShift * PNM_GET1(p) 
+                            (fracShift * PNM_GET1(prevxel)
+                             + omfracShift * PNM_GET1(p)
                              + HALFSCALE) / SCALE );
                 break;
             }
@@ -264,21 +264,21 @@ shearX(xel * const inRow,
             switch (PNM_FORMAT_TYPE(format)) {
             case PPM_TYPE:
                 PPM_ASSIGN(*nxP,
-                           (fracShift * PPM_GETR(prevxel) 
-                            + omfracShift * PPM_GETR(bgxel) 
+                           (fracShift * PPM_GETR(prevxel)
+                            + omfracShift * PPM_GETR(bgxel)
                             + HALFSCALE) / SCALE,
-                           (fracShift * PPM_GETG(prevxel) 
-                            + omfracShift * PPM_GETG(bgxel) 
+                           (fracShift * PPM_GETG(prevxel)
+                            + omfracShift * PPM_GETG(bgxel)
                             + HALFSCALE) / SCALE,
-                           (fracShift * PPM_GETB(prevxel) 
-                            + omfracShift * PPM_GETB(bgxel) 
+                           (fracShift * PPM_GETB(prevxel)
+                            + omfracShift * PPM_GETB(bgxel)
                             + HALFSCALE) / SCALE );
                 break;
-                    
+
             default:
                 PNM_ASSIGN1(*nxP,
-                            (fracShift * PNM_GET1(prevxel) 
-                             + omfracShift * PNM_GET1(bgxel) 
+                            (fracShift * PNM_GET1(prevxel)
+                             + omfracShift * PNM_GET1(bgxel)
                              + HALFSCALE) / SCALE );
                 break;
             }
@@ -289,14 +289,14 @@ shearX(xel * const inRow,
         unsigned int outcol;
 
         outcol = 0;  /* initial value */
-        
+
         for (col = 0; col < shiftCols; ++col)
             outRow[outcol++] = bgxel;
         for (col = 0; col < cols; ++col)
             outRow[outcol++] = inRow[col];
         for (col = shiftCols + cols; col < newcols; ++col)
             outRow[outcol++] = bgxel;
-        
+
         assert(outcol == newcols);
     }
 }
@@ -332,7 +332,7 @@ shearXFromInputFile(FILE *                 const ifP,
 -----------------------------------------------------------------------------*/
     unsigned int const maxShear = (rows - 0.5) * xshearfac + 0.5;
     unsigned int const newcols = cols + maxShear;
-    
+
     xel ** shearedXels;
     xel * xelrow;
     xel bgColor;
@@ -348,13 +348,13 @@ shearXFromInputFile(FILE *                 const ifP,
            the right pixel.  We use the distance of the center of this
            pixel from the relevant edge to compute shift amount:
         */
-        float const xDistance = 
+        float const xDistance =
             (direction == COUNTERCLOCKWISE ? row + 0.5 : (rows-0.5 - row));
         float const shiftAmount = xshearfac * xDistance;
 
         pnm_readpnmrow(ifP, xelrow, cols, maxval, format);
 
-        pnm_promoteformatrow(xelrow, cols, maxval, format, 
+        pnm_promoteformatrow(xelrow, cols, maxval, format,
                              newmaxval, newformat);
 
         if (row == 0)
@@ -375,7 +375,7 @@ shearXFromInputFile(FILE *                 const ifP,
 
 
 
-static void 
+static void
 shearYNoAntialias(xel **           const inxels,
                   xel **           const outxels,
                   int              const cols,
@@ -421,7 +421,7 @@ shearYNoAntialias(xel **           const inxels,
 
 
 static void
-shearYColAntialias(xel ** const inxels, 
+shearYColAntialias(xel ** const inxels,
                    xel ** const outxels,
                    int    const col,
                    int    const inrows,
@@ -435,12 +435,12 @@ shearYColAntialias(xel ** const inxels,
     long const fracnew0   = shearParm[col].fracnew0;
     long const omfracnew0 = shearParm[col].omfracnew0;
     int  const shiftWhole = shearParm[col].shiftWhole;
-        
+
     int outrow;
 
     xel prevxel;
     int inrow;
-        
+
     /* Initialize everything to background color */
     for (outrow = 0; outrow < outrows; ++outrow)
         outxels[outrow][col] = bgxel;
@@ -455,21 +455,21 @@ shearYColAntialias(xel ** const inxels,
             switch ( PNM_FORMAT_TYPE(format) ) {
             case PPM_TYPE:
                 PPM_ASSIGN(*nxP,
-                           (fracnew0 * PPM_GETR(prevxel) 
-                            + omfracnew0 * PPM_GETR(x) 
+                           (fracnew0 * PPM_GETR(prevxel)
+                            + omfracnew0 * PPM_GETR(x)
                             + HALFSCALE) / SCALE,
-                           (fracnew0 * PPM_GETG(prevxel) 
-                            + omfracnew0 * PPM_GETG(x) 
+                           (fracnew0 * PPM_GETG(prevxel)
+                            + omfracnew0 * PPM_GETG(x)
                             + HALFSCALE) / SCALE,
-                           (fracnew0 * PPM_GETB(prevxel) 
-                            + omfracnew0 * PPM_GETB(x) 
+                           (fracnew0 * PPM_GETB(prevxel)
+                            + omfracnew0 * PPM_GETB(x)
                             + HALFSCALE) / SCALE );
                 break;
-                        
+
             default:
                 PNM_ASSIGN1(*nxP,
-                            (fracnew0 * PNM_GET1(prevxel) 
-                             + omfracnew0 * PNM_GET1(x) 
+                            (fracnew0 * PNM_GET1(prevxel)
+                             + omfracnew0 * PNM_GET1(x)
                              + HALFSCALE) / SCALE );
                 break;
             }
@@ -481,26 +481,26 @@ shearYColAntialias(xel ** const inxels,
         switch (PNM_FORMAT_TYPE(format)) {
         case PPM_TYPE:
             PPM_ASSIGN(*nxP,
-                       (fracnew0 * PPM_GETR(prevxel) 
-                        + omfracnew0 * PPM_GETR(bgxel) 
+                       (fracnew0 * PPM_GETR(prevxel)
+                        + omfracnew0 * PPM_GETR(bgxel)
                         + HALFSCALE) / SCALE,
-                       (fracnew0 * PPM_GETG(prevxel) 
-                        + omfracnew0 * PPM_GETG(bgxel) 
+                       (fracnew0 * PPM_GETG(prevxel)
+                        + omfracnew0 * PPM_GETG(bgxel)
                         + HALFSCALE) / SCALE,
-                       (fracnew0 * PPM_GETB(prevxel) 
-                        + omfracnew0 * PPM_GETB(bgxel) 
+                       (fracnew0 * PPM_GETB(prevxel)
+                        + omfracnew0 * PPM_GETB(bgxel)
                         + HALFSCALE) / SCALE);
             break;
-                
+
         default:
             PNM_ASSIGN1(*nxP,
-                        (fracnew0 * PNM_GET1(prevxel) 
-                         + omfracnew0 * PNM_GET1(bgxel) 
+                        (fracnew0 * PNM_GET1(prevxel)
+                         + omfracnew0 * PNM_GET1(bgxel)
                          + HALFSCALE) / SCALE);
             break;
         }
     }
-} 
+}
 
 
 
@@ -516,14 +516,14 @@ shearImageY(xel **                 const inxels,
             int                    const yshearjunk,
             xel ***                const outxelsP,
             unsigned int *         const outrowsP) {
-    
+
     unsigned int const maxShear = (cols - 0.5) * yshearfac + 0.5;
     unsigned int const outrows = inrows + maxShear - 2 * yshearjunk;
 
     struct shearParm * shearParm;  /* malloc'ed */
     int col;
     xel ** outxels;
-    
+
     outxels = pnm_allocarray(cols, outrows);
 
     MALLOCARRAY(shearParm, cols);
@@ -536,7 +536,7 @@ shearImageY(xel **                 const inxels,
            the bottom pixel.  We use the distance of the center of this
            pixel from the relevant edge to compute shift amount:
         */
-        float const yDistance = 
+        float const yDistance =
             (direction == CLOCKWISE ? col + 0.5 : (cols-0.5 - col));
         float const shiftAmount = yshearfac * yDistance;
 
@@ -552,12 +552,12 @@ shearImageY(xel **                 const inxels,
         /* TODO: do this row-by-row, same as for noantialias, to save
            real memory.
         */
-        for (col = 0; col < cols; ++col) 
-            shearYColAntialias(inxels, outxels, col, inrows, outrows, format, 
+        for (col = 0; col < cols; ++col)
+            shearYColAntialias(inxels, outxels, col, inrows, outrows, format,
                                bgxel, shearParm);
     }
     free(shearParm);
-    
+
     *outxelsP = outxels;
     *outrowsP = outrows;
 }
@@ -565,9 +565,9 @@ shearImageY(xel **                 const inxels,
 
 
 static void
-shearFinal(xel * const inRow, 
-           xel * const outRow, 
-           int   const incols, 
+shearFinal(xel * const inRow,
+           xel * const outRow,
+           int   const incols,
            int   const outcols,
            int   const format,
            xel   const bgxel,
@@ -585,8 +585,8 @@ shearFinal(xel * const inRow,
     }
 
     if (antialias) {
-        long const fracnew0   = (shiftAmount - (int) shiftAmount) * SCALE; 
-        long const omfracnew0 = SCALE - fracnew0; 
+        long const fracnew0   = (shiftAmount - (int) shiftAmount) * SCALE;
+        long const omfracnew0 = SCALE - fracnew0;
         unsigned int const shiftWhole = (int)shiftAmount - x2shearjunk;
 
         xel prevxel;
@@ -601,21 +601,21 @@ shearFinal(xel * const inRow,
                 switch (PNM_FORMAT_TYPE(format)) {
                 case PPM_TYPE:
                     PPM_ASSIGN(*nxP,
-                               (fracnew0 * PPM_GETR(prevxel) 
-                                + omfracnew0 * PPM_GETR(x) 
+                               (fracnew0 * PPM_GETR(prevxel)
+                                + omfracnew0 * PPM_GETR(x)
                                 + HALFSCALE) / SCALE,
-                               (fracnew0 * PPM_GETG(prevxel) 
-                                + omfracnew0 * PPM_GETG(x) 
+                               (fracnew0 * PPM_GETG(prevxel)
+                                + omfracnew0 * PPM_GETG(x)
                                 + HALFSCALE) / SCALE,
-                               (fracnew0 * PPM_GETB(prevxel) 
-                                + omfracnew0 * PPM_GETB(x) 
+                               (fracnew0 * PPM_GETB(prevxel)
+                                + omfracnew0 * PPM_GETB(x)
                                 + HALFSCALE) / SCALE);
                     break;
-                    
+
                 default:
                     PNM_ASSIGN1(*nxP,
-                                (fracnew0 * PNM_GET1(prevxel) 
-                                 + omfracnew0 * PNM_GET1(x) 
+                                (fracnew0 * PNM_GET1(prevxel)
+                                 + omfracnew0 * PNM_GET1(x)
                                  + HALFSCALE) / SCALE );
                     break;
                 }
@@ -627,21 +627,21 @@ shearFinal(xel * const inRow,
             switch (PNM_FORMAT_TYPE(format)) {
             case PPM_TYPE:
                 PPM_ASSIGN(*nxP,
-                           (fracnew0 * PPM_GETR(prevxel) 
-                            + omfracnew0 * PPM_GETR(bgxel) 
+                           (fracnew0 * PPM_GETR(prevxel)
+                            + omfracnew0 * PPM_GETR(bgxel)
                             + HALFSCALE) / SCALE,
-                           (fracnew0 * PPM_GETG(prevxel) 
-                            + omfracnew0 * PPM_GETG(bgxel) 
+                           (fracnew0 * PPM_GETG(prevxel)
+                            + omfracnew0 * PPM_GETG(bgxel)
                             + HALFSCALE) / SCALE,
-                           (fracnew0 * PPM_GETB(prevxel) 
-                            + omfracnew0 * PPM_GETB(bgxel) 
+                           (fracnew0 * PPM_GETB(prevxel)
+                            + omfracnew0 * PPM_GETB(bgxel)
                             + HALFSCALE) / SCALE);
                 break;
-                
+
             default:
                 PNM_ASSIGN1(*nxP,
-                            (fracnew0 * PNM_GET1(prevxel) 
-                             + omfracnew0 * PNM_GET1(bgxel) 
+                            (fracnew0 * PNM_GET1(prevxel)
+                             + omfracnew0 * PNM_GET1(bgxel)
                              + HALFSCALE) / SCALE );
                 break;
             }
@@ -664,7 +664,7 @@ shearFinal(xel * const inRow,
 static void
 shearXToOutputFile(FILE *                 const ofP,
                    xel **                 const xels,
-                   unsigned int           const cols, 
+                   unsigned int           const cols,
                    unsigned int           const rows,
                    xelval                 const maxval,
                    int                    const format,
@@ -688,7 +688,7 @@ shearXToOutputFile(FILE *                 const ofP,
 
     unsigned int row;
     xel * xelrow;
-    
+
     pnm_writepnminit(ofP, newcols, rows, maxval, format, 0);
 
     xelrow = pnm_allocrow(newcols);
@@ -699,11 +699,11 @@ shearXToOutputFile(FILE *                 const ofP,
            the right pixel.  We use the distance of the center of this
            pixel from the relevant edge to compute shift amount:
         */
-        float const xDistance = 
+        float const xDistance =
             (direction == COUNTERCLOCKWISE ? row + 0.5 : (rows-0.5 - row));
         float const shiftAmount = xshearfac * xDistance;
 
-        shearFinal(xels[row], xelrow, cols, newcols, format, 
+        shearFinal(xels[row], xelrow, cols, newcols, format,
                    bgColor, antialias, shiftAmount, x2shearjunk);
 
         pnm_writepnmrow(ofP, xelrow, newcols, maxval, format, 0);
@@ -714,7 +714,7 @@ shearXToOutputFile(FILE *                 const ofP,
 
 
 int
-main(int argc, char *argv[]) { 
+main(int argc, char *argv[]) {
 
     struct cmdlineInfo cmdline;
     FILE * ifP;
@@ -738,8 +738,8 @@ main(int argc, char *argv[]) {
     ifP = pm_openr(cmdline.inputFilespec);
 
     pnm_readpnminit(ifP, &cols, &rows, &maxval, &format);
-    
-    computeNewFormat(!cmdline.noantialias, format, maxval, 
+
+    computeNewFormat(!cmdline.noantialias, format, maxval,
                      &newformat, &newmaxval);
 
     xshearfac = fabs(tan(cmdline.angle / 2.0));
@@ -755,7 +755,7 @@ main(int argc, char *argv[]) {
                         newmaxval, newformat,
                         !cmdline.noantialias, cmdline.background,
                         &shear1xels, &shear1Cols, &bgColor);
-    
+
     pm_close(ifP);
 
     if (cmdline.verbose)
@@ -777,16 +777,16 @@ main(int argc, char *argv[]) {
     pnm_freearray(shear1xels, rows);
 
     if (cmdline.keeptemp)
-        storeImage("pnmrotate_stage2.pnm", shear2xels, shear1Cols, newrows, 
+        storeImage("pnmrotate_stage2.pnm", shear2xels, shear1Cols, newrows,
                    newmaxval, newformat);
 
     shearXToOutputFile(stdout, shear2xels, shear1Cols, newrows,
                        newmaxval, newformat,
-                       direction, xshearfac, x2shearjunk, 
+                       direction, xshearfac, x2shearjunk,
                        bgColor, !cmdline.noantialias);
 
     pnm_freearray(shear2xels, newrows);
     pm_close(stdout);
-    
+
     return 0;
 }
diff --git a/editor/pnmscalefixed.c b/editor/pnmscalefixed.c
index 884ca315..1a89a2e5 100644
--- a/editor/pnmscalefixed.c
+++ b/editor/pnmscalefixed.c
@@ -15,10 +15,11 @@
 **               - added -reduce N to allow scaling by integer value
 **                 in this case, scale_comp becomes 1/N and x/yscale
 **                 get set as they should
-**    
+**
 **
 */
- 
+
+#include <limits.h>
 #include <math.h>
 
 #include "pm_c_util.h"
@@ -27,12 +28,12 @@
 #include "pnm.h"
 
 /* The pnm library allows us to code this program without branching cases
-   for PGM and PPM, but we do the branch anyway to speed up processing of 
+   for PGM and PPM, but we do the branch anyway to speed up processing of
    PGM images.
 */
 
 /* We do all our arithmetic in integers.  In order not to get killed by the
-   rounding, we scale every number up by the factor SCALE, do the 
+   rounding, we scale every number up by the factor SCALE, do the
    arithmetic, then scale it back down.
    */
 #define SCALE 4096
@@ -118,16 +119,16 @@ parse_command_line(int argc, char ** argv,
         pm_error("Cannot specify both -xsize/width and -xscale.");
     if (ysize != -1 && yscale != -1)
         pm_error("Cannot specify both -ysize/height and -yscale.");
-    
-    if (xysize && 
-        (xsize != -1 || xscale != -1 || ysize != -1 || yscale != -1 || 
+
+    if (xysize &&
+        (xsize != -1 || xscale != -1 || ysize != -1 || yscale != -1 ||
          reduce != -1 || pixels != -1) )
         pm_error("Cannot specify -xysize with other dimension options.");
-    if (pixels != -1 && 
+    if (pixels != -1 &&
         (xsize != -1 || xscale != -1 || ysize != -1 || yscale != -1 ||
          reduce != -1) )
         pm_error("Cannot specify -pixels with other dimension options.");
-    if (reduce != -1 && 
+    if (reduce != -1 &&
         (xsize != -1 || xscale != -1 || ysize != -1 || yscale != -1) )
         pm_error("Cannot specify -reduce with other dimension options.");
 
@@ -148,7 +149,7 @@ parse_command_line(int argc, char ** argv,
         else {
             cmdline_p->xbox = atoi(argv[1]);
             cmdline_p->ybox = atoi(argv[2]);
-            
+
             if (argc-1 < 3)
                 cmdline_p->input_filespec = "-";
             else
@@ -157,7 +158,7 @@ parse_command_line(int argc, char ** argv,
     } else {
         cmdline_p->xbox = 0;
         cmdline_p->ybox = 0;
-        
+
         if (xsize == -1 && xscale == -1 && ysize == -1 && yscale == -1
             && pixels == -1 && reduce == -1) {
             /* parameters are scale factor and optional filespec */
@@ -187,7 +188,7 @@ parse_command_line(int argc, char ** argv,
 
             if (reduce != -1) {
                 scale_parm = ((double) 1.0) / ((double) reduce);
-                pm_message("reducing by %d gives scale factor of %f.", 
+                pm_message("reducing by %d gives scale factor of %f.",
                            reduce, scale_parm);
             } else
                 scale_parm = 0.0;
@@ -210,12 +211,12 @@ parse_command_line(int argc, char ** argv,
 
 
 static void
-compute_output_dimensions(const struct cmdline_info cmdline, 
+compute_output_dimensions(const struct cmdline_info cmdline,
                           const int rows, const int cols,
                           int * newrowsP, int * newcolsP) {
 
     if (cmdline.pixels) {
-        if (rows * cols <= cmdline.pixels) {
+        if (rows <= cmdline.pixels / cols) {
             *newrowsP = rows;
             *newcolsP = cols;
         } else {
@@ -226,9 +227,9 @@ compute_output_dimensions(const struct cmdline_info cmdline,
         }
     } else if (cmdline.xbox) {
         const double aspect_ratio = (float) cols / (float) rows;
-        const double box_aspect_ratio = 
+        const double box_aspect_ratio =
             (float) cmdline.xbox / (float) cmdline.ybox;
-        
+
         if (box_aspect_ratio > aspect_ratio) {
             *newrowsP = cmdline.ybox;
             *newcolsP = *newrowsP * aspect_ratio + 0.5;
@@ -254,24 +255,24 @@ compute_output_dimensions(const struct cmdline_info cmdline,
             *newrowsP = rows * ((float) cmdline.xsize/cols) +.5;
         else
             *newrowsP = rows;
-    }    
+    }
 
-    /* If the calculations above yielded (because of rounding) a zero 
+    /* If the calculations above yielded (because of rounding) a zero
        dimension, we fudge it up to 1.  We do this rather than considering
-       it a specification error (and dying) because it's friendlier to 
+       it a specification error (and dying) because it's friendlier to
        automated processes that work on arbitrary input.  It saves them
        having to check their numbers to avoid catastrophe.
     */
 
     if (*newcolsP < 1) *newcolsP = 1;
     if (*newrowsP < 1) *newrowsP = 1;
-}        
+}
 
 
 
 static void
-horizontal_scale(const xel inputxelrow[], xel newxelrow[], 
-                 const int cols, const int newcols, const long sxscale, 
+horizontal_scale(const xel inputxelrow[], xel newxelrow[],
+                 const int cols, const int newcols, const long sxscale,
                  const int format, const xelval maxval,
                  int * stretchP) {
 /*----------------------------------------------------------------------------
@@ -282,14 +283,14 @@ horizontal_scale(const xel inputxelrow[], xel newxelrow[],
    'format' and 'maxval' describe the Netpbm format of the both input and
    output rows.
 
-   *stretchP is the number of columns (could be fractional) on the right 
+   *stretchP is the number of columns (could be fractional) on the right
    that we had to fill by stretching because of rounding problems.
 -----------------------------------------------------------------------------*/
     long r, g, b;
     long fraccoltofill, fraccolleft;
     unsigned int col;
     unsigned int newcol;
-    
+
     newcol = 0;
     fraccoltofill = SCALE;  /* Output column is "empty" now */
     r = g = b = 0;          /* initial value */
@@ -302,7 +303,7 @@ horizontal_scale(const xel inputxelrow[], xel newxelrow[],
         */
         while (fraccolleft >= fraccoltofill) {
             /* Generate one output pixel in 'newxelrow'.  It will consist
-               of anything accumulated from prior input pixels in 'r','g', 
+               of anything accumulated from prior input pixels in 'r','g',
                and 'b', plus a fraction of the current input pixel.
             */
             switch (PNM_FORMAT_TYPE(format)) {
@@ -332,7 +333,7 @@ horizontal_scale(const xel inputxelrow[], xel newxelrow[],
             fraccoltofill = SCALE;
             r = g = b = 0;
         }
-        /* There's not enough left in the current input pixel to fill up 
+        /* There's not enough left in the current input pixel to fill up
            a whole output column, so just accumulate the remainder of the
            pixel into the current output column.
         */
@@ -343,7 +344,7 @@ horizontal_scale(const xel inputxelrow[], xel newxelrow[],
                 g += fraccolleft * PPM_GETG(inputxelrow[col]);
                 b += fraccolleft * PPM_GETB(inputxelrow[col]);
                 break;
-                    
+
             default:
                 g += fraccolleft * PNM_GET1(inputxelrow[col]);
                 break;
@@ -356,7 +357,7 @@ horizontal_scale(const xel inputxelrow[], xel newxelrow[],
     while (newcol < newcols) {
         /* We ran out of input columns before we filled up the output
            columns.  This would be because of rounding down.  For small
-           images, we're probably missing only a tiny fraction of a column, 
+           images, we're probably missing only a tiny fraction of a column,
            but for large images, it could be multiple columns.
 
            So we fake the remaining output columns by copying the rightmost
@@ -382,7 +383,7 @@ horizontal_scale(const xel inputxelrow[], xel newxelrow[],
             if ( b > maxval ) b = maxval;
             PPM_ASSIGN(newxelrow[newcol], r, g, b );
             break;
-                
+
         default:
             g += fraccoltofill * PNM_GET1(inputxelrow[cols-1]);
             g += HALFSCALE;  /* for rounding */
@@ -416,7 +417,7 @@ main(int argc, char **argv ) {
     long* gs;
     long* bs;
     int vertical_stretch;
-        /* The number of rows we had to fill by stretching because of 
+        /* The number of rows we had to fill by stretching because of
            rounding error, which made us run out of input rows before we
            had filled up the output rows.
            */
@@ -434,7 +435,7 @@ main(int argc, char **argv ) {
         newformat = PGM_TYPE;
         newmaxval = PGM_MAXMAXVAL;
         pm_message( "promoting from PBM to PGM" );
-	}  else {
+        }  else {
         newformat = format;
         newmaxval = maxval;
     }
@@ -446,18 +447,22 @@ main(int argc, char **argv ) {
        unfilled.  We can address that by stretching, whereas the other
        case would require throwing away some of the input.
     */
+    if (newcols > INT_MAX / SCALE)
+        pm_error("New image width (%d) is uncomputably large", newcols);
+    if (newrows > INT_MAX / SCALE)
+        pm_error("New image height (%d) is uncomputably large", newrows);
     sxscale = SCALE * newcols / cols;
     syscale = SCALE * newrows / rows;
 
     if (cmdline.verbose) {
-        pm_message("Scaling by %ld/%d = %f horizontally to %d columns.", 
+        pm_message("Scaling by %ld/%d = %f horizontally to %d columns.",
                    sxscale, SCALE, (float) sxscale/SCALE, newcols );
-        pm_message("Scaling by %ld/%d = %f vertically to %d rows.", 
+        pm_message("Scaling by %ld/%d = %f vertically to %d rows.",
                    syscale, SCALE, (float) syscale/SCALE, newrows);
     }
 
     xelrow = pnm_allocrow(cols);
-    if (newrows == rows)	/* shortcut Y scaling if possible */
+    if (newrows == rows)        /* shortcut Y scaling if possible */
         tempxelrow = xelrow;
     else
         tempxelrow = pnm_allocrow( cols );
@@ -468,18 +473,18 @@ main(int argc, char **argv ) {
     fracrowleft = syscale;
     needtoreadrow = 1;
     for ( col = 0; col < cols; ++col )
-	rs[col] = gs[col] = bs[col] = HALFSCALE;
+        rs[col] = gs[col] = bs[col] = HALFSCALE;
     fracrowtofill = SCALE;
     vertical_stretch = 0;
-    
+
     pnm_writepnminit( stdout, newcols, newrows, newmaxval, newformat, 0 );
     newxelrow = pnm_allocrow( newcols );
-    
+
     for ( row = 0; row < newrows; ++row ) {
         /* First scale vertically from xelrow into tempxelrow. */
         if ( newrows == rows ) { /* shortcut vertical scaling if possible */
             pnm_readpnmrow( ifp, xelrow, cols, newmaxval, format );
-	    } else {
+            } else {
             while ( fracrowleft < fracrowtofill ) {
                 if ( needtoreadrow )
                     if ( rowsread < rows ) {
@@ -513,8 +518,8 @@ main(int argc, char **argv ) {
                 } else {
                     /* We need another input row to fill up this output row,
                        but there aren't any more.  That's because of rounding
-                       down on our scaling arithmetic.  So we go ahead with 
-                       the data from the last row we read, which amounts to 
+                       down on our scaling arithmetic.  So we go ahead with
+                       the data from the last row we read, which amounts to
                        stretching out the last output row.
                     */
                     vertical_stretch += fracrowtofill;
@@ -544,7 +549,7 @@ main(int argc, char **argv ) {
                 for ( col = 0, xP = xelrow, nxP = tempxelrow;
                       col < cols; ++col, ++xP, ++nxP ) {
                     register long g;
-                    
+
                     g = gs[col] + fracrowtofill * PNM_GET1( *xP );
                     g /= SCALE;
                     if ( g > newmaxval ) g = newmaxval;
@@ -559,37 +564,37 @@ main(int argc, char **argv ) {
                 needtoreadrow = 1;
             }
             fracrowtofill = SCALE;
-	    }
+            }
 
         /* Now scale tempxelrow horizontally into newxelrow & write it out. */
 
-        if (newcols == cols)	/* shortcut X scaling if possible */
-            pnm_writepnmrow(stdout, tempxelrow, newcols, 
+        if (newcols == cols)    /* shortcut X scaling if possible */
+            pnm_writepnmrow(stdout, tempxelrow, newcols,
                             newmaxval, newformat, 0);
         else {
             int stretch;
 
-            horizontal_scale(tempxelrow, newxelrow, cols, newcols, sxscale, 
+            horizontal_scale(tempxelrow, newxelrow, cols, newcols, sxscale,
                              format, newmaxval, &stretch);
-            
+
             if (cmdline.verbose && row == 0 && stretch != 0)
                 pm_message("%d/%d = %f right columns filled by stretching "
-                           "because of arithmetic imprecision", 
+                           "because of arithmetic imprecision",
                            stretch, SCALE, (float) stretch/SCALE);
-            
-            pnm_writepnmrow(stdout, newxelrow, newcols, 
+
+            pnm_writepnmrow(stdout, newxelrow, newcols,
                             newmaxval, newformat, 0 );
         }
-	}
+        }
 
     if (cmdline.verbose && vertical_stretch != 0)
         pm_message("%d/%d = %f bottom rows filled by stretching due to "
-                   "arithmetic imprecision", 
-                   vertical_stretch, SCALE, 
+                   "arithmetic imprecision",
+                   vertical_stretch, SCALE,
                    (float) vertical_stretch/SCALE);
-    
+
     pm_close( ifp );
     pm_close( stdout );
-    
+
     exit( 0 );
 }
diff --git a/editor/pnmsmooth.c b/editor/pnmsmooth.c
index a76bd42b..b4dc1b9a 100644
--- a/editor/pnmsmooth.c
+++ b/editor/pnmsmooth.c
@@ -1,4 +1,4 @@
-/* pnmsmooth.c - smooth out an image by replacing each pixel with the 
+/* pnmsmooth.c - smooth out an image by replacing each pixel with the
 **               average of its width x height neighbors.
 **
 ** Version 2.0   December 5, 1994
@@ -51,7 +51,7 @@ parseCommandLine (int argc, const char ** argv,
                   struct cmdlineInfo *cmdlineP) {
 /*----------------------------------------------------------------------------
    parse program command line described in Unix standard form by argc
-   and argv.  Return the information in the options as *cmdlineP.  
+   and argv.  Return the information in the options as *cmdlineP.
 
    If command line is internally inconsistent (invalid options, etc.),
    issue error message to stderr and abort program.
@@ -69,9 +69,9 @@ parseCommandLine (int argc, const char ** argv,
     unsigned int widthSpec, heightSpec, sizeSpec;
 
     MALLOCARRAY_NOFAIL(option_def, 100);
-    
+
     option_def_index = 0;   /* incremented by OPTENT3 */
-    OPTENT3(0,   "dump",          OPT_FLAG,   
+    OPTENT3(0,   "dump",          OPT_FLAG,
             NULL,                       &cmdlineP->dump, 0);
     OPTENT3(0,   "width",         OPT_UINT,
             &cmdlineP->width,           &widthSpec, 0);
@@ -117,7 +117,7 @@ parseCommandLine (int argc, const char ** argv,
         else {
             cmdlineP->width  = atoi(argv[1]);
             cmdlineP->height = atoi(argv[2]);
-            
+
             if (argc-1 < 3)
                 cmdlineP->inputFilespec = "-";
             else
@@ -179,7 +179,7 @@ makeConvolutionKernel(unsigned int const cols,
     else {
         unsigned int row;
         unsigned int cursor;
-     
+
         for (row = 0, cursor = 0; row < rows; ++row) {
             unsigned int col;
 
diff --git a/editor/pnmstitch.c b/editor/pnmstitch.c
index b27445b0..ab21021c 100644
--- a/editor/pnmstitch.c
+++ b/editor/pnmstitch.c
@@ -152,7 +152,7 @@ typedef struct stitcher {
     bool      (* Match)(struct stitcher *me, Image * Left, Image * Right);
         /* Determine the transformation parameters for the stitching.
            I.e. determine the parameters that affect future invocations
-           of the transformation methods below.  You must execute a 
+           of the transformation methods below.  You must execute a
            'Match' before executing any of the transformation methods.
         */
     /*-----------------------------------------------------------------------
@@ -162,7 +162,7 @@ typedef struct stitcher {
 
       If there is no pixel in the left image that contributes to the output
       pixel in question, the methods return column or row numbers outside
-      the bounds of the left image (possibly negative).  Likewise for the 
+      the bounds of the left image (possibly negative).  Likewise for the
       right image.
     */
     float     (* XLeft)(struct stitcher *me, int x, int y);
@@ -225,7 +225,7 @@ parseCommandLine ( int argc, char ** argv,
 {
 /*----------------------------------------------------------------------------
    parse program command line described in Unix standard form by argc
-   and argv.  Return the information in the options as *cmdlineP.  
+   and argv.  Return the information in the options as *cmdlineP.
 
    If command line is internally inconsistent (invalid options, etc.),
    issue error message to stderr and abort program.
@@ -241,25 +241,25 @@ parseCommandLine ( int argc, char ** argv,
     unsigned int option_def_index;
 
     char *outputOpt;
-    unsigned int widthSpec, heightSpec, outputSpec, 
+    unsigned int widthSpec, heightSpec, outputSpec,
         xrightposSpec, yrightposSpec, stitcherSpec, filterSpec;
 
     option_def_index = 0;   /* incremented by OPTENT3 */
-    OPTENT3(0, "width",       OPT_UINT,   &cmdlineP->width, 
+    OPTENT3(0, "width",       OPT_UINT,   &cmdlineP->width,
             &widthSpec,         0);
-    OPTENT3(0, "height",      OPT_UINT,   &cmdlineP->height, 
+    OPTENT3(0, "height",      OPT_UINT,   &cmdlineP->height,
             &heightSpec,        0);
-    OPTENT3(0, "verbose",     OPT_FLAG,   NULL,                  
+    OPTENT3(0, "verbose",     OPT_FLAG,   NULL,
             &cmdlineP->verbose, 0 );
-    OPTENT3(0, "output",      OPT_STRING, &outputOpt, 
+    OPTENT3(0, "output",      OPT_STRING, &outputOpt,
             &outputSpec,        0);
-    OPTENT3(0, "xrightpos",   OPT_UINT,   &cmdlineP->xrightpos, 
+    OPTENT3(0, "xrightpos",   OPT_UINT,   &cmdlineP->xrightpos,
             &xrightposSpec,     0);
-    OPTENT3(0, "yrightpos",   OPT_UINT,   &cmdlineP->yrightpos, 
+    OPTENT3(0, "yrightpos",   OPT_UINT,   &cmdlineP->yrightpos,
             &yrightposSpec,     0);
-    OPTENT3(0, "stitcher",    OPT_STRING, &cmdlineP->stitcher, 
+    OPTENT3(0, "stitcher",    OPT_STRING, &cmdlineP->stitcher,
             &stitcherSpec,      0);
-    OPTENT3(0, "filter",      OPT_STRING, &cmdlineP->filter, 
+    OPTENT3(0, "filter",      OPT_STRING, &cmdlineP->filter,
             &filterSpec,        0);
 
     opt.opt_table = option_def;
@@ -333,14 +333,14 @@ main (int argc, char **argv)
 
     verbose = cmdline.verbose;
 
-    return pnmstitch (cmdline.leftFilespec, 
-                      cmdline.rightFilespec, 
-                      cmdline.outputFilespec, 
-                      cmdline.xrightpos, 
-                      cmdline.yrightpos, 
-                      cmdline.width, 
-                      cmdline.height, 
-                      cmdline.stitcher, 
+    return pnmstitch (cmdline.leftFilespec,
+                      cmdline.rightFilespec,
+                      cmdline.outputFilespec,
+                      cmdline.xrightpos,
+                      cmdline.yrightpos,
+                      cmdline.width,
+                      cmdline.height,
+                      cmdline.stitcher,
                       cmdline.filter);
 } /* main() - end */
 
@@ -353,10 +353,10 @@ static Image *
 allocate_image(void)
 {
     Image * retVal;
-    
+
     MALLOCVAR(retVal);
 
-    if (retVal != NULL) 
+    if (retVal != NULL)
         memset (retVal, 0, (unsigned)sizeof(Image));
 
     return retVal;
@@ -372,11 +372,11 @@ free_image(Image * image)
 {
     if (image->name) {
         pm_strfree(image->name);
-        image->name = NULL;     
+        image->name = NULL;
     }
     if (image->tuple) {
         pnm_freepamarray(image->tuple, &image->pam);
-        image->tuple = NULL; 
+        image->tuple = NULL;
     }
     if (image->pam.file) {
         fclose (image->pam.file);
@@ -393,8 +393,8 @@ openWithPossibleExtension(const char *  const baseName,
                           const char ** const filenameP) {
 
     /* list of possible extensions for input file */
-    const char * const extlist[] = { 
-        "", ".pnm", ".pam", ".pgm", ".pbm", ".ppm" 
+    const char * const extlist[] = {
+        "", ".pnm", ".pam", ".pgm", ".pbm", ".ppm"
     };
 
     FILE * ifP;
@@ -403,23 +403,23 @@ openWithPossibleExtension(const char *  const baseName,
     ifP = NULL;   /* initial value -- no file opened yet */
 
     for (extIndex = 0; extIndex < ARRAY_SIZE(extlist) && !ifP; ++extIndex) {
-        
+
         const char * trialName;
-        
+
         pm_asprintf(&trialName, "%s%s", baseName, extlist[extIndex]);
-        
+
         ifP = fopen(trialName, "rb");
-        
+
         if (ifP)
             *filenameP = trialName;
         else
             pm_strfree(trialName);
     }
-    if (!ifP) 
+    if (!ifP)
         pm_error ("Failed to open input file named '%s' "
-                  "or '%s' with one of various common extensions.", 
+                  "or '%s' with one of various common extensions.",
                   baseName, baseName);
-    
+
     *ifPP = ifP;
 }
 
@@ -435,7 +435,7 @@ readinit(const char * const name)
     Image * const image = allocate_image();
     Image * retVal;
 
-    if (image == NULL) 
+    if (image == NULL)
         retVal = NULL;
     else {
         FILE * ifP;
@@ -446,7 +446,7 @@ readinit(const char * const name)
         } else {
             openWithPossibleExtension(name, &ifP, &image->name);
         }
-        image->tuple = pnm_readpam(ifP, &(image->pam), 
+        image->tuple = pnm_readpam(ifP, &(image->pam),
                                    PAM_STRUCT_SIZE(tuple_type));
         fclose (ifP);
         image->pam.file = NULL;
@@ -507,7 +507,7 @@ regionDifference(Image * left,
 {
     unsigned long total;
     unsigned      row;
-    
+
     total = 0;  /* initial value */
 
     for (row = 0; row < height; ++row) {
@@ -830,7 +830,7 @@ stitchOnePixel(Image *    const Left,
                int        const right_column,
                unsigned * const firstRightP,
                tuple      const outPixel) {
-               
+
     unsigned plane;
 
     for (plane = 0; plane < outpam.depth; ++plane) {
@@ -848,7 +848,7 @@ stitchOnePixel(Image *    const Left,
         rightPixel = 0;
         if (right_column >= 0) {
             rightPixel = Right->tuple[right_row][right_column][plane];
-            if ((rightPixel > 0) && (*firstRightP == 0)) 
+            if ((rightPixel > 0) && (*firstRightP == 0))
                 *firstRightP = column;
         }
         if (leftPixel == 0) {
@@ -869,7 +869,7 @@ stitchOnePixel(Image *    const Left,
             } else {
                 int const v = w * 4;
                 leftPixel = (sample)(
-                    ((leftPixel 
+                    ((leftPixel
                       * (unsigned long)(Left->pam.width - column))
                      + (rightPixel
                         * (unsigned long)(column - Left->pam.width + v)))
@@ -929,22 +929,22 @@ stitchOneRow(Image *    const Left,
                 right_column = -1;
                 right_row    = -1;
             }
-        } else 
+        } else
             right_column = -1;
 
         /* Create the pixel at column 'column' of row 'row' of the
            output 'Out': Row[column].
         */
-        stitchOnePixel(Left, Right, Out->image->pam, row, column, y, 
+        stitchOnePixel(Left, Right, Out->image->pam, row, column, y,
                        right_row, right_column, &firstRight, Row[column]);
     }
 }
 
 
 
-static void 
-stitchit(Image *      const Left, 
-         Image *      const Right, 
+static void
+stitchit(Image *      const Left,
+         Image *      const Right,
          const char * const outfilename,
          const char * const filter,
          Stitcher *   const Stitch,
@@ -954,8 +954,8 @@ stitchit(Image *      const Left,
                                     sizeof(OutputMethods[0]));
     unsigned   row;
     int        xp[8], yp[8], x, y, width, height;
-    
-    if ((Out == (Output *)NULL) || (Out->Name == (char *)NULL)) 
+
+    if ((Out == (Output *)NULL) || (Out->Name == (char *)NULL))
         *retvalP = -2;
     else {
         if (verbose)
@@ -966,13 +966,13 @@ stitchit(Image *      const Left,
         determineMaskCorners(Stitch, Left, Right, xp, yp);
 
         /* Output the combined images */
-                
+
         /* Calculate generic x,y left top corner, and the width and height */
         calculateXyWidthHeight(xp, yp, &x, &y, &width, &height);
-                
-        if (verbose) 
+
+        if (verbose)
             printPlan(xp, yp, Left, Right);
-    
+
         if (!(*(Out->Alloc))(Out, outfilename, width, height, &Left->pam))
             *retvalP = -9;
         else {
@@ -989,7 +989,7 @@ stitchit(Image *      const Left,
             }
             (*(Out->FlushImage))(Out);
             (*(Out->DeAlloc))(Out);
-        
+
             *retvalP = 0;
         }
     }
@@ -1014,10 +1014,10 @@ pnmstitch(const char * const leftfilename,
     Image    * Right;
     int        retval;
 
-    if ((Stitch == (Stitcher *)NULL) || (Stitch->Name == (char *)NULL)) 
+    if ((Stitch == (Stitcher *)NULL) || (Stitch->Name == (char *)NULL))
         retval = -1;
     else {
-        if (verbose) 
+        if (verbose)
             fprintf (stderr, "Selected %s stitcher algorithm\n",
                      Stitch->Name);
 
@@ -1034,7 +1034,7 @@ pnmstitch(const char * const leftfilename,
                 if (Left->pam.depth != Right->pam.depth) {
                     fprintf(stderr, "Images should have matching depth.  "
                             "The left image has depth %d, "
-                            "while the right has depth %d.", 
+                            "while the right has depth %d.",
                             Left->pam.depth, Right->pam.depth);
                     retval = -5;
                 } else if (Left->pam.maxval != Right->pam.maxval) {
@@ -1042,19 +1042,19 @@ pnmstitch(const char * const leftfilename,
                              "Images should have matching maxval.  "
                              "The left image has maxval %u, "
                              "while the right has maxval %u.",
-                             (unsigned)Left->pam.maxval, 
+                             (unsigned)Left->pam.maxval,
                              (unsigned)Right->pam.maxval);
                     retval = -6;
-                } else if ((*(Stitch->Alloc))(Stitch) == FALSE) 
+                } else if ((*(Stitch->Alloc))(Stitch) == FALSE)
                     retval = -7;
                 else {
-                    (*(Stitch->Constrain))(Stitch, reqx, reqy, 
+                    (*(Stitch->Constrain))(Stitch, reqx, reqy,
                                            reqWidth, reqHeight);
 
-                    if ((*(Stitch->Match))(Stitch, Left, Right) == FALSE) 
+                    if ((*(Stitch->Match))(Stitch, Left, Right) == FALSE)
                         retval = -8;
-                    else 
-                        stitchit(Left, Right, outfilename, filter, Stitch, 
+                    else
+                        stitchit(Left, Right, outfilename, filter, Stitch,
                                  &retval);
                 }
                 free_image(Right);
@@ -1356,7 +1356,7 @@ LinearAlloc(Stitcher * me)
     bool retval;
 
     MALLOCARRAY(me->parms, 8);
-    if (me->parms == NULL) 
+    if (me->parms == NULL)
         retval = FALSE;
     else {
         /* Constraints unset */
@@ -1478,7 +1478,7 @@ LinearConstrain(Stitcher * me, int x, int y, int width, int height)
 /* Following global variables are for use by SliverMatch() */
 static unsigned long starPeriod;
     /* The number of events between printing of a "*" progress
-       indicator.  
+       indicator.
     */
 static unsigned long starCount;
     /* The number of events until the next * progress indicator needs to be
@@ -1487,7 +1487,7 @@ static unsigned long starCount;
 
 static void
 starEvent() {
-    
+
     if (--starCount == 0) {
         starCount = starPeriod;
         fprintf (stderr, "*");
@@ -1521,7 +1521,7 @@ findBestMatches(Image *  const Left,
                 unsigned const Xmax,
                 int      const Ymin,
                 int      const Ymax,
-                Best           best[NUM_BEST]) { 
+                Best           best[NUM_BEST]) {
 /*----------------------------------------------------------------------------
   Compare the rectangle 'width' columns by 'height' rows with upper
   left corner at Column 'x', Row y+offY in image 'Right' to a bunch of
@@ -1562,8 +1562,8 @@ allocate_best_array(Best *** const bestP, unsigned const bestSize) {
     MALLOCARRAY(best, bestSize);
     if (best == NULL)
         pm_error("No memory for Best array");
-    
-    for (i = 0; i < bestSize; ++i) 
+
+    for (i = 0; i < bestSize; ++i)
         best[i] = allocate_best();
     *bestP = best;
 }
@@ -1577,7 +1577,7 @@ static void determineXYRange(Stitcher * const me,
                              unsigned * const XmaxP,
                              int *      const YminP,
                              int *      const YmaxP) {
-    
+
     if (me->x == INT_MAX) {
         *XmaxP = Left->pam.width - me->width;
         /* I can't bring myself to go half way */
@@ -1594,7 +1594,7 @@ static void determineXYRange(Stitcher * const me,
         *YminP = me->y;
         *YmaxP = me->y + 1;
     }
-    if (verbose) 
+    if (verbose)
         pm_message("Test %d<x<%d %d<y<%d", *XminP, *XmaxP, *YminP, *YmaxP);
 }
 
@@ -1609,7 +1609,7 @@ SliverMatch(Stitcher * me, Image * Left, Image * Right,
             unsigned image_portion, unsigned skip_sliver)
 {
     /* up/down 3/10, make sure has an odd number of members */
-    unsigned const bestSize = 
+    unsigned const bestSize =
         1 + 2 * ((image_portion * 3) / (10 * skip_sliver));
     Best       ** best; /* malloc'ed array of Best * */
     float         sumydotx, sumx, sumydot, sum;
@@ -1681,8 +1681,8 @@ SliverMatch(Stitcher * me, Image * Left, Image * Right,
             }
             for (X = x; X < (x + me->width); ++X) {
                 for (Y = y + offY; Y < (y + offY + me->height); ++Y) {
-                    for (plane = 0; 
-                         plane < MIN(Right->pam.depth,3); 
+                    for (plane = 0;
+                         plane < MIN(Right->pam.depth,3);
                          ++plane) {
                         sample point = Right->tuple[Y][X][plane];
                         SUM[plane]   += point;
@@ -1693,7 +1693,7 @@ SliverMatch(Stitcher * me, Image * Left, Image * Right,
             /* How many features */
             features[in] = 0.0;
             for (plane = 0; plane < MIN(Right->pam.depth,3); ++plane) {
-                features[in] += SUMSQ[plane] - 
+                features[in] += SUMSQ[plane] -
                     (SUM[plane]*SUM[plane]/(float)(me->width*me->height));
             }
             if ((minf == 0.0) || (features[in] < minf)) {
@@ -1733,12 +1733,12 @@ SliverMatch(Stitcher * me, Image * Left, Image * Right,
             }
             if ((verbose == 1) || (verbose == 2))
                 for (X = Xmin; X < Xmax; ++X) {
-                    for (Y = Ymin; Y < Ymax; ++Y) 
+                    for (Y = Ymin; Y < Ymax; ++Y)
                         starEvent();
                 }
             continue;
         }
-        findBestMatches(Left, Right, x, y, me->width, me->height, 
+        findBestMatches(Left, Right, x, y, me->width, me->height,
                         offY, Xmin, Xmax, Ymin, Ymax,
                         best[in]);
         /* slop (noise in NUM_BEST) */
@@ -1980,7 +1980,7 @@ SliverMatch(Stitcher * me, Image * Left, Image * Right,
 static bool
 LinearMatch(Stitcher * me, Image * Left, Image * Right)
 {
-    if (SliverMatch(me, Left, Right, IMAGE_PORTION, SKIP_SLIVER * 8) 
+    if (SliverMatch(me, Left, Right, IMAGE_PORTION, SKIP_SLIVER * 8)
         == FALSE) {
         return FALSE;
     }
@@ -1989,7 +1989,7 @@ LinearMatch(Stitcher * me, Image * Left, Image * Right)
     me->y = - (me->parms[Sliver_yp] + me->parms[Sliver_ypp]
           + (1 - Left->pam.height)) / 2;
 
-    if (verbose) 
+    if (verbose)
         pm_message("LinearMatch translation parameters are (%d,%d)",
                    me->x, me->y);
 
diff --git a/editor/pnmtile.c b/editor/pnmtile.c
index 5ec53415..ca542c43 100644
--- a/editor/pnmtile.c
+++ b/editor/pnmtile.c
@@ -70,7 +70,7 @@ parseCommandLine(int argc, const char ** argv,
                 pm_error("There are at most three arguments: "
                          "width, height, file name.  You specified %u",
                          argc-1);
-        } else 
+        } else
             cmdlineP->inputFileName = "-";
     }
 }
diff --git a/editor/ppmchange.c b/editor/ppmchange.c
index cfc34769..16f4390e 100644
--- a/editor/ppmchange.c
+++ b/editor/ppmchange.c
@@ -33,8 +33,8 @@ struct CmdlineInfo {
         /* colors user wants replaced */
     const char * newcolorname[TCOLS];
         /* colors with which he wants them replaced */
-    float closeness;    
-    const char * remainder_colorname;  
+    float closeness;
+    const char * remainder_colorname;
       /* Color user specified for -remainder.  Null pointer if he didn't
          specify -remainder.
       */
@@ -87,8 +87,8 @@ parseCommandLine(int argc, const char ** const argv,
     if (cmdlineP->closeness > 100)
         pm_error("-closeness value %f is more than 100%%",
                  cmdlineP->closeness);
-    
-    if ((argc-1) % 2 == 0) 
+
+    if ((argc-1) % 2 == 0)
         cmdlineP->input_filespec = "-";
     else
         cmdlineP->input_filespec = argv[argc-1];
@@ -96,8 +96,8 @@ parseCommandLine(int argc, const char ** const argv,
     {
         int argn;
         cmdlineP->ncolors = 0;  /* initial value */
-        for (argn = 1; 
-             argn+1 < argc && cmdlineP->ncolors < TCOLS; 
+        for (argn = 1;
+             argn+1 < argc && cmdlineP->ncolors < TCOLS;
              argn += 2) {
             cmdlineP->oldcolorname[cmdlineP->ncolors] = argv[argn];
             cmdlineP->newcolorname[cmdlineP->ncolors] = argv[argn+1];
@@ -109,8 +109,8 @@ parseCommandLine(int argc, const char ** const argv,
 
 
 static bool
-colorMatches(pixel        const comparand, 
-             pixel        const comparator, 
+colorMatches(pixel        const comparand,
+             pixel        const comparator,
              unsigned int const allowableDiff) {
 /*----------------------------------------------------------------------------
    The colors 'comparand' and 'comparator' are within 'allowableDiff'
@@ -126,21 +126,21 @@ colorMatches(pixel        const comparand,
 
 
 static void
-changeRow(const pixel * const inrow, 
-          pixel *       const outrow, 
+changeRow(const pixel * const inrow,
+          pixel *       const outrow,
           int           const cols,
-          int           const ncolors, 
-          const pixel         colorfrom[], 
+          int           const ncolors,
+          const pixel         colorfrom[],
           const pixel         colorto[],
-          bool          const remainder_specified, 
-          pixel         const remainder_color, 
+          bool          const remainder_specified,
+          pixel         const remainder_color,
           unsigned int  const allowableDiff) {
 /*----------------------------------------------------------------------------
-   Replace the colors in a single row.  There are 'ncolors' colors to 
+   Replace the colors in a single row.  There are 'ncolors' colors to
    replace.  The to-replace colors are in the array colorfrom[], and the
    replace-with colors are in corresponding elements of colorto[].
    Iff 'remainder_specified' is true, replace all colors not mentioned
-   in colorfrom[] with 'remainder_color'.  
+   in colorfrom[] with 'remainder_color'.
 
    Consider the color in inrow[] to match a color in colorfrom[] if it is
    within 'allowableDiff' color levels of it, in cartesian distance (e.g.
@@ -155,7 +155,7 @@ changeRow(const pixel * const inrow,
     for (col = 0; col < cols; ++col) {
         unsigned int i;
         bool haveMatch; /* logical: It's a color user said to change */
-        pixel newcolor;  
+        pixel newcolor;
         /* Color to which we must change current pixel.  Undefined unless
            'haveMatch' is true.
         */
@@ -205,7 +205,7 @@ main(int argc, const char ** const argv) {
     pm_proginit(&argc, argv);
 
     parseCommandLine(argc, argv, &cmdline);
-    
+
     ifP = pm_openr(cmdline.input_filespec);
 
     ppm_readppminit(ifP, &cols, &rows, &maxval, &format);
@@ -213,7 +213,7 @@ main(int argc, const char ** const argv) {
     if (cmdline.remainder_colorname)
         remainder_color = ppm_parsecolor2(cmdline.remainder_colorname, maxval,
                                           cmdline.closeok);
-    { 
+    {
         int i;
         for (i = 0; i < cmdline.ncolors; ++i) {
             oldcolor[i] = ppm_parsecolor2(cmdline.oldcolorname[i], maxval,
@@ -223,7 +223,7 @@ main(int argc, const char ** const argv) {
         }
     }
     allowableDiff = ROUNDU(sqrt3 * maxval * cmdline.closeness/100);
-    
+
     ppm_writeppminit( stdout, cols, rows, maxval, 0 );
     inrow = ppm_allocrow(cols);
     outrow = ppm_allocrow(cols);
diff --git a/editor/ppmdim.c b/editor/ppmdim.c
index 4e64965a..0bcc8ebb 100644
--- a/editor/ppmdim.c
+++ b/editor/ppmdim.c
@@ -1,4 +1,3 @@
-
 /*********************************************************************/
 /* ppmdim -  dim a picture down to total blackness                   */
 /* Frank Neumann, October 1993                                       */
@@ -29,84 +28,84 @@ int main(argc, argv)
 int argc;
 char *argv[];
 {
-	FILE* ifp;
-	int argn, rows, cols, format, i = 0, j = 0;
-	pixel *srcrow, *destrow;
-	pixel *pP = NULL, *pP2 = NULL;
-	pixval maxval;
-	double dimfactor;
-	long longfactor;
-	const char * const usage = "dimfactor [ppmfile]\n        dimfactor: 0.0 = total blackness, 1.0 = original picture\n";
-
-	/* parse in 'default' parameters */
-	ppm_init(&argc, argv);
-
-	argn = 1;
-
-	/* parse in dim factor */
-	if (argn == argc)
-		pm_usage(usage);
-	if (sscanf(argv[argn], "%lf", &dimfactor) != 1)
-		pm_usage(usage);
-	if (dimfactor < 0.0 || dimfactor > 1.0)
-		pm_error("dim factor must be in the range from 0.0 to 1.0 ");
-	++argn;
-
-	/* parse in filename (if present, stdin otherwise) */
-	if (argn != argc)
-	{
-		ifp = pm_openr(argv[argn]);
-		++argn;
-	}
-	else
-		ifp = stdin;
-
-	if (argn != argc)
-		pm_usage(usage);
-
-	/* read first data from file */
-	ppm_readppminit(ifp, &cols, &rows, &maxval, &format);
-
-	/* no error checking required here, ppmlib does it all for us */
-	srcrow = ppm_allocrow(cols);
-
-	longfactor = (long)(dimfactor * 65536);
-
-	/* allocate a row of pixel data for the new pixels */
-	destrow = ppm_allocrow(cols);
-
-	ppm_writeppminit(stdout, cols, rows, maxval, 0);
-
-	/** now do the dim'ing **/
-	/* the 'float' parameter for dimming is sort of faked - in fact, we */
-	/* convert it to a range from 0 to 65536 for integer math. Shouldn't */
-	/* be something you'll have to worry about, though. */
-
-	for (i = 0; i < rows; i++)
-	{
-		ppm_readppmrow(ifp, srcrow, cols, maxval, format);
-
-		pP = srcrow;
-		pP2 = destrow;
-
-		for (j = 0; j < cols; j++)
-		{
-			PPM_ASSIGN(*pP2, (PPM_GETR(*pP) * longfactor) >> 16,
-							 (PPM_GETG(*pP) * longfactor) >> 16,
-							 (PPM_GETB(*pP) * longfactor) >> 16);
-
-			pP++;
-			pP2++;
-		}
-
-		/* write out one line of graphic data */
-		ppm_writeppmrow(stdout, destrow, cols, maxval, 0);
-	}
-
-	pm_close(ifp);
-	ppm_freerow(srcrow);
-	ppm_freerow(destrow);
-
-	exit(0);
+        FILE* ifp;
+        int argn, rows, cols, format, i = 0, j = 0;
+        pixel *srcrow, *destrow;
+        pixel *pP = NULL, *pP2 = NULL;
+        pixval maxval;
+        double dimfactor;
+        long longfactor;
+        const char * const usage = "dimfactor [ppmfile]\n        dimfactor: 0.0 = total blackness, 1.0 = original picture\n";
+
+        /* parse in 'default' parameters */
+        ppm_init(&argc, argv);
+
+        argn = 1;
+
+        /* parse in dim factor */
+        if (argn == argc)
+                pm_usage(usage);
+        if (sscanf(argv[argn], "%lf", &dimfactor) != 1)
+                pm_usage(usage);
+        if (dimfactor < 0.0 || dimfactor > 1.0)
+                pm_error("dim factor must be in the range from 0.0 to 1.0 ");
+        ++argn;
+
+        /* parse in filename (if present, stdin otherwise) */
+        if (argn != argc)
+        {
+                ifp = pm_openr(argv[argn]);
+                ++argn;
+        }
+        else
+                ifp = stdin;
+
+        if (argn != argc)
+                pm_usage(usage);
+
+        /* read first data from file */
+        ppm_readppminit(ifp, &cols, &rows, &maxval, &format);
+
+        /* no error checking required here, ppmlib does it all for us */
+        srcrow = ppm_allocrow(cols);
+
+        longfactor = (long)(dimfactor * 65536);
+
+        /* allocate a row of pixel data for the new pixels */
+        destrow = ppm_allocrow(cols);
+
+        ppm_writeppminit(stdout, cols, rows, maxval, 0);
+
+        /** now do the dim'ing **/
+        /* the 'float' parameter for dimming is sort of faked - in fact, we */
+        /* convert it to a range from 0 to 65536 for integer math. Shouldn't */
+        /* be something you'll have to worry about, though. */
+
+        for (i = 0; i < rows; i++)
+        {
+                ppm_readppmrow(ifp, srcrow, cols, maxval, format);
+
+                pP = srcrow;
+                pP2 = destrow;
+
+                for (j = 0; j < cols; j++)
+                {
+                        PPM_ASSIGN(*pP2, (PPM_GETR(*pP) * longfactor) >> 16,
+                                                         (PPM_GETG(*pP) * longfactor) >> 16,
+                                                         (PPM_GETB(*pP) * longfactor) >> 16);
+
+                        pP++;
+                        pP2++;
+                }
+
+                /* write out one line of graphic data */
+                ppm_writeppmrow(stdout, destrow, cols, maxval, 0);
+        }
+
+        pm_close(ifp);
+        ppm_freerow(srcrow);
+        ppm_freerow(destrow);
+
+        exit(0);
 }
 
diff --git a/editor/ppmdither.c b/editor/ppmdither.c
index ec1b9771..2619c8b7 100644
--- a/editor/ppmdither.c
+++ b/editor/ppmdither.c
@@ -1,5 +1,5 @@
 /*=============================================================================
-                                 pamdither
+                                 ppmdither
 ===============================================================================
   By Bryan Henderson, July 2006.
 
@@ -23,7 +23,7 @@
 #define MAX_DITH_POWER (((unsigned)sizeof(unsigned int)*8 - 1) / 2)
 
 
-struct colorResolution {
+struct ColorResolution {
     unsigned int c[3];
         /* comp[PAM_RED_PLANE] is number of distinct red levels, etc. */
 };
@@ -32,13 +32,13 @@ struct colorResolution {
 #define GRN PAM_GRN_PLANE
 #define BLU PAM_BLU_PLANE
 
-struct cmdlineInfo {
+struct CmdlineInfo {
     /* All the information the user supplied in the command line,
        in a form easy for the program to use.
     */
     const char * inputFileName;  /* File name of input file */
     unsigned int dim;
-    struct colorResolution colorRes;
+    struct ColorResolution colorRes;
     unsigned int verbose;
 };
 
@@ -46,10 +46,10 @@ struct cmdlineInfo {
 
 static void
 parseCommandLine(int argc, const char ** const argv,
-                 struct cmdlineInfo * const cmdlineP) {
+                 struct CmdlineInfo * const cmdlineP) {
 /*----------------------------------------------------------------------------
    parse program command line described in Unix standard form by argc
-   and argv.  Return the information in the options as *cmdlineP.  
+   and argv.  Return the information in the options as *cmdlineP.
 
    If command line is internally inconsistent (invalid options, etc.),
    issue error message to stderr and abort program.
@@ -67,13 +67,13 @@ parseCommandLine(int argc, const char ** const argv,
     unsigned int dimSpec, redSpec, greenSpec, blueSpec;
 
     MALLOCARRAY_NOFAIL(option_def, 100);
-    
+
     option_def_index = 0;   /* incremented by OPTENT3 */
-    OPTENT3(0, "dim",          OPT_UINT, 
+    OPTENT3(0, "dim",          OPT_UINT,
             &cmdlineP->dim,            &dimSpec,                  0);
-    OPTENT3(0, "red",          OPT_UINT, 
+    OPTENT3(0, "red",          OPT_UINT,
             &cmdlineP->colorRes.c[RED],   &redSpec,       0);
-    OPTENT3(0, "green",        OPT_UINT, 
+    OPTENT3(0, "green",        OPT_UINT,
             &cmdlineP->colorRes.c[GRN],   &greenSpec,     0);
     OPTENT3(0, "blue",         OPT_UINT,
             &cmdlineP->colorRes.c[BLU],   &blueSpec,      0);
@@ -94,7 +94,7 @@ parseCommandLine(int argc, const char ** const argv,
         pm_error("Dithering matrix power %u (-dim) is too large.  "
                  "Must be <= %u",
                  cmdlineP->dim, MAX_DITH_POWER);
-        
+
     if (redSpec) {
         if (cmdlineP->colorRes.c[RED] < 2)
             pm_error("-red must be at least 2.  You specified %u",
@@ -139,7 +139,7 @@ typedef struct {
    0-3, and blue value of 0-1 to a tuple with maxval 255.  So you can
    ask it to scale (1,1,1) and it responds with (85, 85, 255).
 -----------------------------------------------------------------------------*/
-    struct colorResolution colorRes;
+    struct ColorResolution colorRes;
         /* Number of values of each color component possible, i.e. maxval
            plus 1
         */
@@ -148,7 +148,7 @@ typedef struct {
            certain function (see scaler_scale()) of the input red, green, and
            blue values.
         */
-} scaler;    
+} Scaler;
 
 
 
@@ -156,7 +156,7 @@ static tuple *
 allocScalerMap(unsigned int const size) {
     /* The tuple row data structure starts with 'size' pointers to
        the tuples, immediately followed by the 'size' tuples
-       themselves.  Each tuple consists of 3 samples.  
+       themselves.  Each tuple consists of 3 samples.
     */
 
     unsigned int const depth = 3;
@@ -165,14 +165,14 @@ allocScalerMap(unsigned int const size) {
     tuple * map;
 
     map = malloc(size * (sizeof(tuple *) + bytesPerTuple));
-                      
+
     if (map != NULL) {
         /* Now we initialize the pointers to the individual tuples
-           to make this a regulation C two dimensional array.  
+           to make this a regulation C two dimensional array.
         */
         char * p;
         unsigned int i;
-        
+
         p = (char*) (map + size);  /* location of Tuple 0 */
         for (i = 0; i < size; ++i) {
             map[i] = (tuple) p;
@@ -186,12 +186,12 @@ allocScalerMap(unsigned int const size) {
 
 static void
 scaler_create(sample                 const outputMaxval,
-              struct colorResolution const colorRes,
-              scaler **              const scalerPP) {
+              struct ColorResolution const colorRes,
+              Scaler **              const scalerPP) {
 
-    scaler * scalerP;
+    Scaler * scalerP;
     unsigned int mapSize;
-    
+
     if (UINT_MAX / colorRes.c[RED] / colorRes.c[GRN] / colorRes.c[BLU] < 1)
         pm_error("red/green/blue dimensions %u/%u/%u is uncomputably large",
                  colorRes.c[RED], colorRes.c[GRN], colorRes.c[BLU]);
@@ -223,10 +223,10 @@ scaler_create(sample                 const outputMaxval,
                         (r * colorRes.c[GRN] + g)
                         * colorRes.c[BLU] + b;
                     tuple const t = scalerP->out[index];
-                         
+
                     t[PAM_RED_PLANE] =
                         r * outputMaxval / (colorRes.c[RED] - 1);
-                    t[PAM_GRN_PLANE] = 
+                    t[PAM_GRN_PLANE] =
                         g * outputMaxval / (colorRes.c[GRN] - 1);
                     t[PAM_BLU_PLANE] =
                         b * outputMaxval / (colorRes.c[BLU] - 1);
@@ -240,7 +240,7 @@ scaler_create(sample                 const outputMaxval,
 
 
 static void
-scaler_destroy(scaler * const scalerP) {
+scaler_destroy(Scaler * const scalerP) {
 
     free(scalerP->out);
 
@@ -250,7 +250,7 @@ scaler_destroy(scaler * const scalerP) {
 
 
 static tuple
-scaler_scale(const scaler * const scalerP,
+scaler_scale(const Scaler * const scalerP,
              unsigned int   const red,
              unsigned int   const grn,
              unsigned int   const blu) {
@@ -275,7 +275,7 @@ dither(sample       const p,
        unsigned int const ditheredMaxval,
        unsigned int const ditherMatrixArea) {
 /*----------------------------------------------------------------------------
-  Return the dithered brightness for a component of a pixel whose real 
+  Return the dithered brightness for a component of a pixel whose real
   brightness for that component is 'p' based on a maxval of 'maxval'.
   The returned brightness is based on a maxval of ditheredMaxval.
 
@@ -292,7 +292,7 @@ dither(sample       const p,
         /* This is the input intensity P expressed with a maxval of
            'ditherSquareMaxval'
         */
-    
+
     /* Now we scale the intensity back down to the 'ditheredMaxval', and
        as that will involve rounding, we round up or down based on the position
        in the dithered square, as determined by 'd'
@@ -306,7 +306,7 @@ dither(sample       const p,
 static unsigned int
 dithValue(unsigned int const yArg,
           unsigned int const xArg,
-          unsigned int const dithPower) { 
+          unsigned int const dithPower) {
 /*----------------------------------------------------------------------------
   Return the value of a dither matrix which is 2 ** dithPower elements
   square at Row x, Column y.
@@ -336,45 +336,37 @@ dithValue(unsigned int const yArg,
 
 
 static unsigned int **
-dithMatrix(unsigned int const dithPower) {
+newDithMatrix(unsigned int const dithPower) {
 /*----------------------------------------------------------------------------
    Create the dithering matrix for dimension 'dithDim'.
 
    Return it in newly malloc'ed storage.
 
-   Note that we assume 'dithPower' is small enough that the 'dithMatSize'
-   computed within fits in an int.  Otherwise, results are undefined.
+   Note that we assume 'dithPower' is not greater than the number of bits in
+   an unsigned int.
 -----------------------------------------------------------------------------*/
     unsigned int const dithDim = 1 << dithPower;
 
     unsigned int ** dithMat;
+    unsigned int y;
 
     assert(dithPower < sizeof(unsigned int) * 8);
 
-    {
-        unsigned int const dithMatSize = 
-            (dithDim * sizeof(*dithMat)) + /* pointers */
-            (dithDim * dithDim * sizeof(**dithMat)); /* data */
-        
-        dithMat = malloc(dithMatSize);
-        
-        if (dithMat == NULL) 
-            pm_error("Out of memory.  "
-                     "Cannot allocate %u bytes for dithering matrix.",
-                     dithMatSize);
-    }
-    {
-        unsigned int * const rowStorage = (unsigned int *)&dithMat[dithDim];
-        unsigned int y;
-        for (y = 0; y < dithDim; ++y)
-            dithMat[y] = &rowStorage[y * dithDim];
-    }
-    {
-        unsigned int y;
+    MALLOCARRAY(dithMat, dithDim);
+    if (!dithMat)
+        pm_error("Cannot allocate %u-row dithering matrix index", dithDim);
+    else {
         for (y = 0; y < dithDim; ++y) {
-            unsigned int x;
-            for (x = 0; x < dithDim; ++x)
-                dithMat[y][x] = dithValue(y, x, dithPower);
+            MALLOCARRAY(dithMat[y], dithDim);
+            if (!dithMat[y])
+                pm_error("Failed to allocate %uth row of "
+                         "%ux%u dithering matrix", y, dithDim, dithDim);
+            else {
+                unsigned int x;
+
+                for (x = 0; x < dithDim; ++x)
+                    dithMat[y][x] = dithValue(y, x, dithPower);
+            }
         }
     }
     return dithMat;
@@ -383,9 +375,25 @@ dithMatrix(unsigned int const dithPower) {
 
 
 static void
+freeDithMatrix(unsigned int ** const dithMat,
+               unsigned int    const dithPower) {
+
+    unsigned int const dithDim = 1 << dithPower;
+
+    unsigned int y;
+
+    for (y = 0; y < dithDim; ++y)
+        free(dithMat[y]);
+
+    free(dithMat);
+}
+
+
+
+static void
 validateNoDitherOverflow(unsigned int           const ditherMatrixArea,
                          struct pam *           const inpamP,
-                         struct colorResolution const colorRes) {
+                         struct ColorResolution const colorRes) {
 /*----------------------------------------------------------------------------
    Validate that we'll be able to do the dithering calculations based on
    the parameters above without busting out of an integer.
@@ -409,10 +417,10 @@ validateNoDitherOverflow(unsigned int           const ditherMatrixArea,
 static void
 ditherRow(struct pam *           const inpamP,
           const tuple *          const inrow,
-          const scaler *         const scalerP,
+          const Scaler *         const scalerP,
           unsigned int **        const ditherMatrix,
           unsigned int           const ditherMatrixArea,
-          struct colorResolution const colorRes,
+          struct ColorResolution const colorRes,
           unsigned int           const row,
           unsigned int           const modMask,
           struct pam *           const outpamP,
@@ -447,9 +455,9 @@ ditherRow(struct pam *           const inpamP,
 
 static void
 ditherImage(struct pam *           const inpamP,
-            const scaler *         const scalerP,
+            const Scaler *         const scalerP,
             unsigned int           const dithPower,
-            struct colorResolution const colorRes,
+            struct ColorResolution const colorRes,
             struct pam *           const outpamP,
             tuple ***              const outTuplesP) {
 
@@ -460,17 +468,17 @@ ditherImage(struct pam *           const inpamP,
        /* And this into N to compute N % dithDim cheaply, since we
           know (though the compiler doesn't) that dithDim is a power of 2
        */
-    unsigned int ** const ditherMatrix = dithMatrix(dithPower);
+    unsigned int ** const ditherMatrix = newDithMatrix(dithPower);
 
     tuple * inrow;
     tuple ** outTuples;
-    unsigned int row; 
+    unsigned int row;
     struct pam ditherPam;
         /* Describes the tuples that ditherRow() sees */
 
     assert(dithPower < sizeof(unsigned int) * 8);
     assert(UINT_MAX / dithDim >= dithDim);
-    
+
     validateNoDitherOverflow(ditherMatrixArea, inpamP, colorRes);
 
     inrow = pnm_allocpamrow(inpamP);
@@ -490,7 +498,7 @@ ditherImage(struct pam *           const inpamP,
                   colorRes, row, modMask,
                   outpamP, outTuples[row]);
     }
-    free(ditherMatrix);
+    freeDithMatrix(ditherMatrix, dithPower);
     pnm_freepamrow(inrow);
     *outTuplesP = outTuples;
 }
@@ -501,10 +509,10 @@ int
 main(int           argc,
      const char ** argv) {
 
-    struct cmdlineInfo cmdline;
+    struct CmdlineInfo cmdline;
     FILE * ifP;
     tuple ** outTuples;        /* Output image */
-    scaler * scalerP;
+    Scaler * scalerP;
     struct pam inpam;
     struct pam outpam;
 
@@ -517,7 +525,7 @@ main(int           argc,
     pnm_readpaminit(ifP, &inpam, PAM_STRUCT_SIZE(allocation_depth));
 
     pnm_setminallocationdepth(&inpam, 3);
-    
+
     outpam.size               = sizeof(outpam);
     outpam.len                = PAM_STRUCT_SIZE(tuple_type);
     outpam.file               = stdout;
@@ -549,3 +557,5 @@ main(int           argc,
 
     return 0;
 }
+
+
diff --git a/editor/ppmfade b/editor/ppmfade
index dcd7bf26..4e2c8367 100755
--- a/editor/ppmfade
+++ b/editor/ppmfade
@@ -35,12 +35,22 @@ exec perl -w -x -S -- "$0" "$@"
 #
 #  Inspired by the program Pbmfade by Wesley C. Barris of AHPCRC,
 #  Minnesota Supercomputer Center, Inc. January 7, 1994.  Pbmfade does
-#  much the same thing, but handles non-Netpbm formats too, and is 
+#  much the same thing, but handles non-Netpbm formats too, and is
 #  implemented in a more primitive language.
 #
 ##############################################################################
 use strict;
 
+use File::Temp;
+
+#
+#  Define a couple linear ramps.
+#
+# We don't use element 0 of these arrays.
+my @spline10 = (0, 0, 0.11, 0.22, 0.33, 0.44, 0.55, 0.66, 0.77, 0.88, 1.0);
+my @spline20 = (0, 0, 0.05, 0.11, 0.16, 0.21, 0.26, 0.32, 0.37, 0.42, 0.47,
+                0.53, 0.58, 0.63, 0.69, 0.74, 0.79, 0.84, 0.89, 0.95, 1.0);
+
 sub doVersionHack($) {
     my ($argvR) = @_;
 
@@ -52,280 +62,411 @@ sub doVersionHack($) {
     }
 }
 
+my $tmpdir;
 
+$tmpdir = File::Temp::tempdir("ppmfade.XXXXXX", CLEANUP => 1);
 
-my $SPREAD =  1;
-my $SHIFT =   2;
-my $RELIEF =  3;
-my $OIL =     4;
-my $EDGE =    5;
-my $BENTLEY = 6;
-my $BLOCK =   7;
-my $MIX =     8;
-#
-#  Set some defaults.
-#
-my $nframes = 30;			# total number of files created (1 sec)
-my $first_file = "undefined";
-my $last_file = "undefined";
-my $base_name = "fade";		# default base name of output files
-my $image = "ppm";		# default output storage format
-my $mode = $SPREAD;		# default fading mode
+sub commandLineArgs() {
 
-doVersionHack(\@ARGV);
+    my ($firstFileNm, $lastFileNm, $mode, $baseNm);
 
-my $n;  # argument number
+    for (my $i = 0; $i < @ARGV; ++$i) {
+        my $arg = $ARGV[$i];
 
-for ($n = 0; $n < @ARGV; $n++) {
-    if ("$ARGV[$n]" eq "-f") {
-        $n++;
-        $first_file = $ARGV[$n];
-        if (-e $first_file) {
+        if (0) {
+        } elsif ($arg eq "-f") {
+            ++$i;
+            $firstFileNm = $ARGV[$i];
+        } elsif ($arg eq "-l") {
+            ++$i;
+            $lastFileNm = $ARGV[$i];
+        } elsif ($arg eq "-base") {
+            ++$i;
+            $baseNm = $ARGV[$i];
+        } elsif ($arg eq "-spread") {
+            $mode = 'SPREAD';
+        } elsif ($arg eq "-shift") {
+            $mode = 'SHIFT';
+        } elsif ($arg eq "-relief") {
+            $mode = 'RELIEF';
+        } elsif ($arg eq "-oil") {
+            $mode = 'OIL';
+        } elsif ($arg eq "-edge") {
+            $mode = 'EDGE';
+        } elsif ($arg eq "-bentley") {
+            $mode ='BENTLEY';
+        } elsif ($arg eq "-block") {
+            $mode = 'BLOCK';
+        } elsif ($arg eq "-mix") {
+            $mode = 'MIX';
         } else {
-            print "I can't find first file '$first_file'\n";
-            exit 20;
+            if (substr($arg, 0, 1) eq '-') {
+                   print STDERR ("Unknown option '$arg'.  " .
+                                 "We understand -f, -l, -base, " .
+                                 "-spread, -shift, -relief, -oil, -edge, " .
+                                 "-bentley, -block, and -mix\n");
+            } else {
+                print STDERR ("There are no non-option arguments possible.  " .
+                              "You specified '$arg'\n");
+            }
+            exit 100;
         }
-    } elsif ($ARGV[$n] eq "-l") {
-        $n++;
-        $last_file = $ARGV[$n];
-        if (-e $last_file) {
+    }
+
+    if (!defined($firstFileNm) && !defined($lastFileNm)) {
+        print STDERR ("You must specify -f or -l (or both)\n");
+        exit 90;
+    }
+
+    if (!defined($mode)) {
+        $mode = 'SPREAD';
+    }
+
+    if (!defined($baseNm)) {
+        $baseNm = 'fade';
+    }
+
+    return $mode, $firstFileNm, $lastFileNm, $baseNm;
+}
+
+
+
+sub imageDimensions($$) {
+    my ($firstFileNm, $lastFileNm) = @_;
+
+    my ($width, $height);
+
+    if (defined($firstFileNm)) {
+        if ((`pnmfile $firstFileNm` =~ m{\b(\d+)\sby\s(\d+)} )) {
+            $width = $1; $height = $2;
         } else {
-            print "I can't find last file '$last_file'\n";
-            exit 20;
+            print STDERR
+                ("Unrecognized results from pnmfile on $firstFileNm.\n");
+            exit(50);
         }
-    } elsif ($ARGV[$n] eq "-base") {
-        $n++;
-        $base_name = $ARGV[$n];
-    } elsif ($ARGV[$n] eq "-spread") {
-        $mode = $SPREAD;
-    } elsif ($ARGV[$n] eq "-shift") {
-        $mode = $SHIFT;
-    } elsif ($ARGV[$n] eq "-relief") {
-        $mode = $RELIEF;
-    } elsif ($ARGV[$n] eq "-oil") {
-        $mode = $OIL;
-    } elsif ("$ARGV[$n]" eq "-edge") {
-        $mode = $EDGE;
-    } elsif ("$ARGV[$n]" eq "-bentley") {
-        $mode = $BENTLEY;
-    } elsif ("$ARGV[$n]" eq "-block") {
-        $mode = $BLOCK;
-    } elsif ("$ARGV[$n]" eq "-mix") {
-        $mode = $MIX;
     } else {
-        print "Unknown argument: $ARGV[$n]\n";
-        exit 100;
-    } 
+        # $lastFileNm is defined
+        if ((`pnmfile $lastFileNm` =~ m{\b(\d+)\sby\s(\d+)} )) {
+            $width = $1; $height = $2;
+        } else {
+            print STDERR
+                ("Unrecognized results from pnmfile on $firstFileNm.\n");
+            exit(50);
+        }
+    }
+    return $width, $height;
 }
-#
-#  Define a couple linear ramps.
-#
-# We don't use element 0 of these arrays.
-my @spline10 = (0, 0, 0.11, 0.22, 0.33, 0.44, 0.55, 0.66, 0.77, 0.88, 1.0);
-my @spline20 = (0, 0, 0.05, 0.11, 0.16, 0.21, 0.26, 0.32, 0.37, 0.42, 0.47, 
-                0.53, 0.58, 0.63, 0.69, 0.74, 0.79, 0.84, 0.89, 0.95, 1.0);
-#
-#  Just what are we supposed to do?
-#
-my ($height, $width);    # width and height of our frames
-if ($first_file ne "undefined") {
-    if ((`pnmfile $first_file` =~ m{\b(\d+)\sby\s(\d+)} )) { 
-        $width = $1; $height = $2;
+
+
+
+sub spreadOne($) {
+    my ($frameNum) = @_;
+
+    if ($frameNum <= 10) {
+        my $n = $spline20[$frameNum] * 100;
+        system("ppmspread $n $tmpdir/first.ppm >$tmpdir/this.ppm");
+    } elsif ($frameNum <= 20) {
+        my $n;
+        $n = $spline20[$frameNum] * 100;
+        system("ppmspread $n $tmpdir/first.ppm >$tmpdir/junk1a.ppm");
+        $n = (1-$spline20[$frameNum-10]) * 100;
+        system("ppmspread $n $tmpdir/last.ppm >$tmpdir/junk2a.ppm");
+        $n = $spline10[$frameNum-10];
+        system("ppmmix $n $tmpdir/junk1a.ppm $tmpdir/junk2a.ppm " .
+               ">$tmpdir/this.ppm");
     } else {
-        print("Unrecognized results from pnmfile on $first_file.\n");
-        exit(50);
+        my $n = (1-$spline20[$frameNum-10])*100;
+        system("ppmspread $n $tmpdir/last.ppm >$tmpdir/this.ppm");
     }
-} elsif ($last_file ne "undefined") {
-    if ((`pnmfile $last_file` =~ m{\b(\d+)\sby\s(\d+)} )) { 
-        $width = $1; $height = $2;
+}
+
+
+
+sub shiftOne($) {
+    my ($frameNum) = @_;
+
+    if ($frameNum <= 10) {
+        my $n = $spline20[$frameNum] * 100;
+        system("ppmshift $n $tmpdir/first.ppm >$tmpdir/this.ppm");
+    } elsif ($frameNum <= 20) {
+        my $n;
+        $n = $spline20[$frameNum] * 100;
+        system("ppmshift $n $tmpdir/first.ppm >$tmpdir/junk1a.ppm");
+        $n = (1-$spline20[$frameNum-10])*100;
+        system("ppmshift $n $tmpdir/last.ppm >$tmpdir/junk2a.ppm");
+        $n = $spline10[$frameNum-10];
+        system("ppmmix $n $tmpdir/junk1a.ppm $tmpdir/junk2a.ppm " .
+               ">$tmpdir/this.ppm");
     } else {
-        print("Unrecognized results from pnmfile on $first_file.\n");
-        exit(50);
+        my $n = (1-$spline20[$frameNum-10]) * 100;
+        system("ppmshift $n $tmpdir/last.ppm >$tmpdir/this.ppm");
     }
-} else {
-    print("ppmfade:  You must specify -f or -l (or both)\n");
-    exit(90);
 }
 
-print("Frames are " . $width . "W x " . $height . "H\n");
 
-if ($first_file eq "undefined") {
-    print "Fading from black to ";
-    system("ppmmake \\#000 $width $height >junk1$$.ppm");
-} else {
-    print "Fading from $first_file to ";
-    system("cp", $first_file, "junk1$$.ppm");
+
+sub reliefOne($) {
+    my ($frameNum) = @_;
+
+    if ($frameNum == 1) {
+        system("ppmrelief $tmpdir/first.ppm >$tmpdir/junk1r.ppm");
+    }
+    if ($frameNum <= 10) {
+        my $n = $spline10[$frameNum];
+        system("ppmmix $n $tmpdir/first.ppm $tmpdir/junk1r.ppm " .
+               ">$tmpdir/this.ppm");
+    } elsif ($frameNum <= 20) {
+        my $n = $spline10[$frameNum-10];
+        system("ppmmix $n $tmpdir/junk1r.ppm $tmpdir/junk2r.ppm " .
+               ">$tmpdir/this.ppm");
+    } else {
+        my $n = $spline10[$frameNum-20];
+        system("ppmmix $n $tmpdir/junk2r.ppm $tmpdir/last.ppm " .
+               ">$tmpdir/this.ppm");
+    }
+    if ($frameNum == 10) {
+        system("ppmrelief $tmpdir/last.ppm >$tmpdir/junk2r.ppm");
+    }
 }
 
-if ($last_file eq "undefined") {
-    print "black.\n";
-    system("ppmmake \\#000 $width $height >junk2$$.ppm");
-} else {
-    print "$last_file\n";
-    system("cp", $last_file, "junk2$$.ppm");
+
+
+sub oilOne($) {
+    my ($frameNum) = @_;
+
+    if ($frameNum == 1) {
+        system("ppmtopgm $tmpdir/first.ppm | pgmoil >$tmpdir/junko.ppm");
+        system("rgb3toppm " .
+               "$tmpdir/junko.ppm $tmpdir/junko.ppm $tmpdir/junko.ppm " .
+               ">$tmpdir/junk1o.ppm");
+    }
+    if ($frameNum <= 10) {
+        my $n = $spline10[$frameNum];
+        system("ppmmix $n $tmpdir/first.ppm $tmpdir/junk1o.ppm " .
+               ">$tmpdir/this.ppm");
+    } elsif ($frameNum <= 20) {
+        my $n = $spline10[$frameNum-10];
+        system("ppmmix $n $tmpdir/junk1o.ppm $tmpdir/junk2o.ppm " .
+               ">$tmpdir/this.ppm");
+    } else {
+        my $n = $spline10[$frameNum-20];
+        system("ppmmix $n $tmpdir/junk2o.ppm $tmpdir/last.ppm " .
+               ">$tmpdir/this.ppm");
+    }
+    if ($frameNum == 10) {
+        system("ppmtopgm $tmpdir/last.ppm | pgmoil >$tmpdir/junko.ppm");
+        system("rgb3toppm " .
+               "$tmpdir/junko.ppm $tmpdir/junko.ppm $tmpdir/junko.ppm " .
+               ">$tmpdir/junk2o.ppm");
+    }
 }
 
-#
-#  Perform the fade.
-#
 
-# Here's what our temporary files are:
-#   junk1$$.ppm: The original (fade-from) image
-#   junk2$$.ppm: The target (fade-from) image
-#   junk3$$.ppm: The frame of the fade for the current iteration of the 
-#                the for loop.
-#   junk1a$$.ppm: If the fade involves a ppmmix sequence from one intermediate
-#                 image to another, this is the first frame of that 
-#                 sequence.
-#   junk2a$$.ppm: This is the last frame of the above-mentioned ppmmix sequence
-
-my $i;    # Frame number
-for ($i = 1; $i <= $nframes; $i++) {
-    print("Creating $i of $nframes...\n");
-    if ($mode eq $SPREAD) {
-        if ($i <= 10) {
-            my $n = $spline20[$i] * 100;
-            system("ppmspread $n junk1$$.ppm >junk3$$.ppm");
-        } elsif ($i <= 20) {
-            my $n;
-            $n = $spline20[$i] * 100;
-            system("ppmspread $n junk1$$.ppm >junk1a$$.ppm");
-            $n = (1-$spline20[$i-10]) * 100;
-            system("ppmspread $n junk2$$.ppm >junk2a$$.ppm");
-            $n = $spline10[$i-10];
-            system("ppmmix $n junk1a$$.ppm junk2a$$.ppm >junk3$$.ppm");
-        } else {
-            my $n = (1-$spline20[$i-10])*100;
-            system("ppmspread $n junk2$$.ppm >junk3$$.ppm");
-        }
-    } elsif ($mode eq $SHIFT) {
-        if ($i <= 10) {
-            my $n = $spline20[$i] * 100;
-            system("ppmshift $n junk1$$.ppm >junk3$$.ppm");
-        } elsif ($i <= 20) {
-            my $n;
-            $n = $spline20[$i] * 100;
-            system("ppmshift $n junk1$$.ppm >junk1a$$.ppm");
-            $n = (1-$spline20[$i-10])*100;
-            system("ppmshift $n junk2$$.ppm >junk2a$$.ppm");
-            $n = $spline10[$i-10];
-            system("ppmmix $n junk1a$$.ppm junk2a$$.ppm >junk3$$.ppm");
-        } else {
-            my $n = (1-$spline20[$i-10]) * 100;
-            system("ppmshift $n junk2$$.ppm >junk3$$.ppm");
-        }
-    } elsif ($mode eq $RELIEF) {
-        if ($i == 1) {
-            system("ppmrelief junk1$$.ppm >junk1r$$.ppm");
-        }
-        if ($i <= 10) {
-            my $n = $spline10[$i];
-            system("ppmmix $n junk1$$.ppm junk1r$$.ppm >junk3$$.ppm");
-        } elsif ($i <= 20) {
-            my $n = $spline10[$i-10];
-            system("ppmmix $n junk1r$$.ppm junk2r$$.ppm >junk3$$.ppm");
-        } else {
-            my $n = $spline10[$i-20];
-            system("ppmmix $n junk2r$$.ppm junk2$$.ppm >junk3$$.ppm");
-        }
-        if ($i == 10) {
-            system("ppmrelief junk2$$.ppm >junk2r$$.ppm");
-        }
-    } elsif ($mode eq $OIL) {
-        if ($i == 1) {
-            system("ppmtopgm junk1$$.ppm | pgmoil >junko$$.ppm");
-            system("rgb3toppm junko$$.ppm junko$$.ppm junko$$.ppm " .
-                   ">junk1o$$.ppm");
-        }
-        if ($i <= 10) {
-            my $n = $spline10[$i];
-            system("ppmmix $n junk1$$.ppm junk1o$$.ppm >junk3$$.ppm");
-        } elsif ($i <= 20) {
-            my $n = $spline10[$i-10];
-            system("ppmmix $n junk1o$$.ppm junk2o$$.ppm >junk3$$.ppm");
-        } else {
-            my $n = $spline10[$i-20];
-            system("ppmmix $n junk2o$$.ppm junk2$$.ppm >junk3$$.ppm");
-        }
-        if ($i == 10) {
-            system("ppmtopgm junk2$$.ppm | pgmoil >junko$$.ppm");
-            system("rgb3toppm junko$$.ppm junko$$.ppm junko$$.ppm " .
-                   ">junk2o$$.ppm");
-        }
-    } elsif ($mode eq $EDGE) {
-        if ($i == 1) {
-            system("ppmtopgm junk1$$.ppm | pgmedge >junko$$.ppm");
-            system("rgb3toppm junko$$.ppm junko$$.ppm junko$$.ppm " .
-                   ">junk1o$$.ppm");
-        }
-        if ($i <= 10) {
-            my $n = $spline10[$i];
-            system("ppmmix $n junk1$$.ppm junk1o$$.ppm >junk3$$.ppm");
-        } elsif ($i <= 20) {
-            my $n = $spline10[$i-10];
-            system("ppmmix $n junk1o$$.ppm junk2o$$.ppm >junk3$$.ppm");
-        } else {
-            my $n = $spline10[$i-20];
-            system("ppmmix $n junk2o$$.ppm junk2$$.ppm >junk3$$.ppm");
-        }
-        if ($i == 10) {
-            system("ppmtopgm junk2$$.ppm | pgmedge >junko$$.ppm");
-            system("rgb3toppm junko$$.ppm junko$$.ppm junko$$.ppm " .
-                   ">junk2o$$.ppm");
-        } 
-    } elsif ($mode eq $BENTLEY) {
-        if ($i == 1) {
-            system("ppmtopgm junk1$$.ppm | pgmbentley >junko$$.ppm");
-            system("rgb3toppm junko$$.ppm junko$$.ppm junko$$.ppm " .
-                   ">junk1o$$.ppm");
-        }
-        if ($i <= 10) {
-            my $n = $spline10[$i];
-            system("ppmmix $n junk1$$.ppm junk1o$$.ppm >junk3$$.ppm");
-        } elsif ($i <= 20) {
-            my $n = $spline10[$i-10];
-            system("ppmmix $n junk1o$$.ppm junk2o$$.ppm >junk3$$.ppm");
-        } else {
-            my $n = $spline10[$i-20];
-            system("ppmmix $n junk2o$$.ppm junk2$$.ppm >junk3$$.ppm");
-        }
-        if ($i == 10) {
-            system("ppmtopgm junk2$$.ppm | pgmbentley >junko$$.ppm");
-            system("rgb3toppm junko$$.ppm junko$$.ppm junko$$.ppm " .
-                   ">junk2o$$.ppm");
-        }
-    } elsif ($mode eq $BLOCK) {
-        if ($i <= 10) {
-            my $n = 1 - 1.9*$spline20[$i];
-            system("pamscale $n junk1$$.ppm | " .
-                   "pamscale -width $width -height $height >junk3$$.ppm");
-        } elsif ($i <= 20) {
-            my $n = $spline10[$i-10];
-            system("ppmmix $n junk1a$$.ppm junk2a$$.ppm >junk3$$.ppm");
-        } else {
-            my $n = 1 - 1.9*$spline20[31-$i];
-            system("pamscale $n junk2$$.ppm | " .
-                   "pamscale -width $width -height $height >junk3$$.ppm");
+
+sub edgeOne($) {
+    my ($frameNum) = @_;
+
+    if ($frameNum == 1) {
+        system("ppmtopgm $tmpdir/first.ppm | pgmedge >$tmpdir/junko.ppm");
+        system("rgb3toppm " .
+               "$tmpdir/junko.ppm $tmpdir/junko.ppm $tmpdir/junko.ppm " .
+               ">$tmpdir/junk1o.ppm");
+    }
+    if ($frameNum <= 10) {
+        my $n = $spline10[$frameNum];
+        system("ppmmix $n $tmpdir/first.ppm $tmpdir/junk1o.ppm " .
+               ">$tmpdir/this.ppm");
+    } elsif ($frameNum <= 20) {
+        my $n = $spline10[$frameNum-10];
+        system("ppmmix $n $tmpdir/junk1o.ppm $tmpdir/junk2o.ppm " .
+               ">$tmpdir/this.ppm");
+    } else {
+        my $n = $spline10[$frameNum-20];
+        system("ppmmix $n $tmpdir/junk2o.ppm $tmpdir/last.ppm " .
+               ">$tmpdir/this.ppm");
+    }
+    if ($frameNum == 10) {
+        system("ppmtopgm $tmpdir/last.ppm | pgmedge >$tmpdir/junko.ppm");
+        system("rgb3toppm " .
+               "$tmpdir/junko.ppm $tmpdir/junko.ppm $tmpdir/junko.ppm " .
+               ">$tmpdir/junk2o.ppm");
+    }
+}
+
+
+
+sub bentleyOne($) {
+    my ($frameNum) = @_;
+
+    if ($frameNum == 1) {
+        system("ppmtopgm $tmpdir/first.ppm | pgmbentley >$tmpdir/junko.ppm");
+        system("rgb3toppm " .
+               "$tmpdir/junko.ppm $tmpdir/junko.ppm $tmpdir/junko.ppm " .
+               ">$tmpdir/junk1o.ppm");
+    }
+    if ($frameNum <= 10) {
+        my $n = $spline10[$frameNum];
+        system("ppmmix $n $tmpdir/first.ppm $tmpdir/junk1o.ppm " .
+               ">$tmpdir/this.ppm");
+    } elsif ($frameNum <= 20) {
+        my $n = $spline10[$frameNum-10];
+        system("ppmmix $n $tmpdir/junk1o.ppm $tmpdir/junk2o.ppm " .
+               ">$tmpdir/this.ppm");
+    } else {
+        my $n = $spline10[$frameNum-20];
+        system("ppmmix $n $tmpdir/junk2o.ppm $tmpdir/last.ppm " .
+               ">$tmpdir/this.ppm");
+    }
+    if ($frameNum == 10) {
+        system("ppmtopgm $tmpdir/last.ppm | pgmbentley " .
+               ">$tmpdir/junko.ppm");
+        system("rgb3toppm $tmpdir/junko.ppm $tmpdir/junko.ppm " .
+               "$tmpdir/junko.ppm " .
+               ">$tmpdir/junk2o.ppm");
+    }
+}
+
+
+
+sub blockOne($$$) {
+    my ($frameNum, $width, $height) = @_;
+
+    if ($frameNum <= 10) {
+        my $n = 1 - 1.9*$spline20[$frameNum];
+        system("pamscale $n $tmpdir/first.ppm | " .
+               "pamscale -width $width -height $height " .
+               ">$tmpdir/this.ppm");
+        if ($frameNum == 10) {
+            system("cp", "$tmpdir/this.ppm", "$tmpdir/junk1a.ppm");
+            system("pamscale $n $tmpdir/last.ppm | " .
+                   "pamscale -width $width -height $height " .
+                   ">$tmpdir/junk2a.ppm");
         }
-        if ($i == 10) {
-            system("cp", "junk3$$.ppm", "junk1a$$.ppm");
-            system("pamscale $n junk2$$.ppm | " .
-                   "pamscale -width $width -height $height >junk2a$$.ppm");
-        }    
-    } elsif ($mode eq $MIX) {
-        my $fade_factor = sqrt(1/($nframes-$i+1));
-        system("ppmmix $fade_factor junk1$$.ppm junk2$$.ppm >junk3$$.ppm");
+    } elsif ($frameNum <= 20) {
+        my $n = $spline10[$frameNum-10];
+        system("ppmmix $n $tmpdir/junk1a.ppm $tmpdir/junk2a.ppm " .
+               ">$tmpdir/this.ppm");
     } else {
-        print("Internal error: impossible mode value '$mode'\n");
+        my $n = 1 - 1.9*$spline20[31-$frameNum];
+        system("pamscale $n $tmpdir/last.ppm | " .
+               "pamscale -width $width -height $height " .
+               ">$tmpdir/this.ppm");
     }
+}
+
+
+
+sub mixOne($$) {
+    my ($frameNum, $nFrame) = @_;
 
-    my $outfile = sprintf("%s.%04d.ppm", $base_name, $i);
-    system("cp", "junk3$$.ppm", $outfile);
+    my $fadeFactor = sqrt(1/($nFrame - $frameNum + 1));
+
+    system("ppmmix $fadeFactor $tmpdir/first.ppm $tmpdir/last.ppm " .
+           ">$tmpdir/this.ppm");
 }
 
+
+
+sub fade($$$$$) {
+    my ($nFrame, $mode, $width, $height, $baseNm) = @_;
+#-----------------------------------------------------------------------------
+#  Do the fade starting, from image "first.ppm" in the temporary direct
+#  $tmpdir and ending up at "last.ppm", creating $nFrame frames, including
+#  the first and last.
 #
-#  Clean up shop.
+#  Make the outputs $width by $height.
 #
-system("rm junk*$$.ppm");
+#  Name the result files $baseNm.NNNN.ppm.
+#-----------------------------------------------------------------------------
+
+    # Here's what our temporary files are:
+    #   first.ppm: The original (fade-from) image
+    #   last.ppm: The target (fade-from) image
+    #   this.ppm: The frame of the fade for the current iteration of the
+    #             the for loop.
+    #   junk1a.ppm: If the fade involves a ppmmix sequence from one
+    #               intermediate image to another, this is the first frame
+    #               of that sequence.
+    #   junk2a.ppm: This is the last frame of the above-mentioned
+    #               ppmmix sequence
+
+    my $frameNum;    # Frame number
+    for ($frameNum = 1; $frameNum <= $nFrame; ++$frameNum) {
+
+        print("Creating Frame $frameNum of $nFrame...\n");
+
+        if ($mode eq 'SPREAD') {
+            spreadOne($frameNum);
+        } elsif ($mode eq 'SHIFT') {
+            shiftOne($frameNum);
+        } elsif ($mode eq 'RELIEF') {
+            reliefOne($frameNum);
+        } elsif ($mode eq 'OIL') {
+            oilOne($frameNum);
+        } elsif ($mode eq 'EDGE') {
+            edgeOne($frameNum);
+        } elsif ($mode eq 'BENTLEY') {
+            bentleyOne($frameNum);
+        } elsif ($mode eq 'BLOCK') {
+            blockOne($frameNum, $width, $height);
+        } elsif ($mode eq 'MIX') {
+            mixOne($frameNum, $nFrame);
+        } else {
+            print("INTERNAL ERROR: impossible mode value '$mode'\n");
+        }
+
+        my $outFileNm = sprintf("%s.%04d.ppm", $baseNm, $frameNum);
+        system("cp", "$tmpdir/this.ppm", $outFileNm);
+    }
+}
+
+
+
+#-----------------------------------------------------------------------------
+#  MAINLINE
+#-----------------------------------------------------------------------------
+
+my $nFrame = 30;
+    # Number of images in created sequence, including the fade-from and
+    # fade-to images.  In standard video, 30 frames is one second.
+
+doVersionHack(\@ARGV);
+
+my ($mode, $firstFileNm, $lastFileNm, $baseNm) = commandLineArgs();
+
+if (defined($firstFileNm) && !-e($firstFileNm)) {
+    print STDERR ("First file '$firstFileNm' does not exist\n");
+    exit 20;
+}
+
+if (defined($lastFileNm) && !-e($lastFileNm)) {
+    print STDERR ("Last file '$lastFileNm' does not exist\n");
+    exit 20;
+}
+
+my ($width, $height) = imageDimensions($firstFileNm, $lastFileNm);
+
+    # width and height of our frames in pixels
+
+print("Frames are " . $width . "W x " . $height . "H\n");
+
+my $fromDesc = defined($firstFileNm) ? "'$firstFileNm'" : "black";
+my $toDesc   = defined($lastFileNm)  ? "'$lastFileNm'"  : "black";
+
+if (!defined($firstFileNm)) {
+    system("ppmmake \\#000 $width $height >$tmpdir/first.ppm");
+} else {
+    system("cp", $firstFileNm, "$tmpdir/first.ppm");
+}
+
+if (!defined($lastFileNm)) {
+    system("ppmmake \\#000 $width $height >$tmpdir/last.ppm");
+} else {
+    system("cp", $lastFileNm, "$tmpdir/last.ppm");
+}
+
+print("Fading from $fromDesc to $toDesc\n");
+
+fade($nFrame, $mode, $width, $height, $baseNm);
 
 exit(0);
diff --git a/editor/ppmflash.c b/editor/ppmflash.c
index d1d048df..c8335890 100644
--- a/editor/ppmflash.c
+++ b/editor/ppmflash.c
@@ -1,4 +1,3 @@
-
 /*********************************************************************/
 /* ppmflash -  brighten a picture up to total whiteout               */
 /* Frank Neumann, August 1993                                        */
@@ -89,12 +88,12 @@ int main(argc, argv)
         pP2 = destrow;
 
         for (j = 0; j < cols; j++) {
-            PPM_ASSIGN(*pP2, 
-                       PPM_GETR(*pP) + 
+            PPM_ASSIGN(*pP2,
+                       PPM_GETR(*pP) +
                        (((maxval - PPM_GETR(*pP)) * longfactor) >> 16),
-                       PPM_GETG(*pP) + 
+                       PPM_GETG(*pP) +
                        (((maxval - PPM_GETG(*pP)) * longfactor) >> 16),
-                       PPM_GETB(*pP) + 
+                       PPM_GETB(*pP) +
                        (((maxval - PPM_GETB(*pP)) * longfactor) >> 16));
 
             pP++;
diff --git a/editor/ppmlabel.c b/editor/ppmlabel.c
index 389ab59e..21e7d84c 100644
--- a/editor/ppmlabel.c
+++ b/editor/ppmlabel.c
@@ -26,7 +26,7 @@ static pixel rgbcolor, backcolor;
 /*  DRAWTEXT  --  Draw text at current location and advance to
           start of next line.  */
 
-static void 
+static void
 drawtext(const char * const text) {
 
     if (!transparent && strlen(text) > 0) {
@@ -38,10 +38,10 @@ drawtext(const char * const text) {
         double sina, cosa;
 
         handle = ppmd_fill_create();
-        
+
         ppmd_text_box(size, 0, text, &left, &top, &right, &bottom);
 
-        /* Displacement vector */ 
+        /* Displacement vector */
 
         lx = right;
         ly = -(top - bottom);
diff --git a/editor/ppmshadow b/editor/ppmshadow
index c07c03b0..438d4fa9 100755
--- a/editor/ppmshadow
+++ b/editor/ppmshadow
@@ -198,7 +198,7 @@ if ($keeptemp) {
     mkdir($ourtmp, 0777) or
         die("Unable to create directory for temporary files '$ourtmp");
 } else {
-    $ourtmp = File::Temp::tempdir("$tmpdir/ppmshadowXXXX", UNLINK=>1);
+    $ourtmp = File::Temp::tempdir("$tmpdir/ppmshadowXXXX", CLEANUP=>1);
 }
 
 #   Apply defaults for arguments not specified
diff --git a/editor/specialty/pamdeinterlace.c b/editor/specialty/pamdeinterlace.c
index d6f6aee1..a21484a9 100644
--- a/editor/specialty/pamdeinterlace.c
+++ b/editor/specialty/pamdeinterlace.c
@@ -2,12 +2,14 @@
                              pamdeinterlace
 *******************************************************************************
   De-interlace an image, i.e. select every 2nd row.
-   
+
   By Bryan Henderson, San Jose, CA 2001.11.11.
 
   Contributed to the public domain.
 ******************************************************************************/
 
+#include <stdbool.h>
+
 #include "pm_c_util.h"
 #include "pam.h"
 #include "shhopt.h"
@@ -15,7 +17,7 @@
 
 enum evenodd {EVEN, ODD};
 
-struct cmdlineInfo {
+struct CmdlineInfo {
     /* All the information the user supplied in the command line,
        in a form easy for the program to use.
     */
@@ -24,9 +26,10 @@ struct cmdlineInfo {
 };
 
 
+
 static void
-parseCommandLine(int argc, char ** argv,
-                 struct cmdlineInfo *cmdlineP) {
+parseCommandLine(int argc, const char ** argv,
+                 struct CmdlineInfo * const cmdlineP) {
 /*----------------------------------------------------------------------------
    Note that the file spec array we return is stored in the storage that
    was passed to us as the argv array.
@@ -44,10 +47,10 @@ parseCommandLine(int argc, char ** argv,
     OPTENT3(0,   "takeodd",  OPT_FLAG, NULL, &takeodd,  0);
 
     opt.opt_table = option_def;
-    opt.short_allowed = FALSE;  /* We have no short (old-fashioned) options */
-    opt.allowNegNum = FALSE;  /* We have no parms that are negative numbers */
+    opt.short_allowed = false;  /* We have no short (old-fashioned) options */
+    opt.allowNegNum = false;  /* We have no parms that are negative numbers */
 
-    pm_optParseOptions3(&argc, argv, opt, sizeof(opt), 0);
+    pm_optParseOptions3(&argc, (char **)argv, opt, sizeof(opt), 0);
         /* Uses and sets argc, argv, and some of *cmdlineP and others. */
 
     free(option_def);
@@ -65,31 +68,29 @@ parseCommandLine(int argc, char ** argv,
     else if (argc-1 == 1)
         cmdlineP->inputFilespec = argv[1];
     else
-        pm_error("You specified too many arguments (%d).  The only "
-                 "argument is the optional input file specification.",
+        pm_error("You specified too many arguments (%u).  The only "
+                 "possible argument is the optional input file specification.",
                  argc-1);
 }
 
 
 
-
-
 int
-main(int argc, char *argv[]) {
+main(int argc, const char ** argv) {
 
     FILE * ifP;
     tuple * tuplerow;   /* Row from input image */
     unsigned int row;
-    struct cmdlineInfo cmdline;
-    struct pam inpam;  
+    struct CmdlineInfo cmdline;
+    struct pam inpam;
     struct pam outpam;
 
-    pnm_init( &argc, argv );
+    pm_proginit(&argc, argv);
 
     parseCommandLine(argc, argv, &cmdline);
 
     ifP = pm_openr(cmdline.inputFilespec);
-    
+
     pnm_readpaminit(ifP, &inpam, PAM_STRUCT_SIZE(tuple_type));
 
     if (inpam.height < 2 && cmdline.rowsToTake == ODD)
@@ -133,7 +134,7 @@ main(int argc, char *argv[]) {
     pnm_freepamrow(tuplerow);
     pm_close(inpam.file);
     pm_close(outpam.file);
-    
+
     return 0;
 }
 
diff --git a/editor/specialty/pamoil.c b/editor/specialty/pamoil.c
index 6cb8d3ac..d7b76e85 100644
--- a/editor/specialty/pamoil.c
+++ b/editor/specialty/pamoil.c
@@ -1,4 +1,4 @@
-/* pgmoil.c - read a portable pixmap and turn into an oil painting
+/* pgmoil.c - read a PPM image and turn into an oil painting
 **
 ** Copyright (C) 1990 by Wilson Bent (whb@hoh-2.att.com)
 ** Shamelessly butchered into a color version by Chris Sheppard
@@ -12,60 +12,153 @@
 ** implied warranty.
 */
 
+#include <stdbool.h>
 #include <stdio.h>
 #include <stdlib.h>
 #include <unistd.h>
-#include "pam.h"
+
 #include "mallocvar.h"
+#include "shhopt.h"
+#include "pam.h"
+
+
+
+struct CmdlineInfo {
+    /* All the information the user supplied in the command line,
+       in a form easy for the program to use.
+    */
+    const char * inputFileNm;
+    unsigned int n;
+};
+
+
+
+static void
+parseCommandLine(int argc, const char ** argv,
+                 struct CmdlineInfo * const cmdlineP) {
+/*----------------------------------------------------------------------------
+   Note that the file spec array we return is stored in the storage that
+   was passed to us as the argv array.
+-----------------------------------------------------------------------------*/
+    optStruct3 opt;  /* set by OPTENT3 */
+    optEntry * option_def;
+    unsigned int option_def_index;
+
+    unsigned int nSpec;
+
+    MALLOCARRAY_NOFAIL(option_def, 100);
+
+    option_def_index = 0;   /* incremented by OPTENT3 */
+    OPTENT3(0,   "n", OPT_UINT, &cmdlineP->n, &nSpec, 0);
 
-static void 
-convertRow(struct pam const inpam, tuple ** const tuples,
-           tuple * const tuplerow, int const row, int const smearFactor,
-           int * const hist) {
+    opt.opt_table = option_def;
+    opt.short_allowed = false;  /* We have no short (old-fashioned) options */
+    opt.allowNegNum = false;  /* We have no parms that are negative numbers */
+
+    pm_optParseOptions3(&argc, (char **)argv, opt, sizeof(opt), 0);
+        /* Uses and sets argc, argv, and some of *cmdlineP and others. */
+
+    free(option_def);
+
+    if (!nSpec)
+        cmdlineP->n = 3;
+
+    if (argc-1 < 1)
+        cmdlineP->inputFileNm = "-";
+    else if (argc-1 == 1)
+        cmdlineP->inputFileNm = argv[1];
+    else
+        pm_error("You specified too many arguments (%u).  The only "
+                 "possible argument is the optional input file specification.",
+                 argc-1);
+}
+
+
+
+static void
+computeRowHist(struct pam   const inpam,
+               tuple **     const tuples,
+               unsigned int const smearFactor,
+               unsigned int const plane,
+               unsigned int const row,
+               unsigned int const col,
+               sample *     const hist) {
+/*----------------------------------------------------------------------------
+  Compute hist[] - frequencies, in the neighborhood of row 'row', column
+  'col', in plane 'plane', of each sample value
+-----------------------------------------------------------------------------*/
+    sample i;
+    int drow;
+
+    for (i = 0; i <= inpam.maxval; ++i)
+        hist[i] = 0;
+
+    for (drow = row - smearFactor; drow <= row + smearFactor; ++drow) {
+        if (drow >= 0 && drow < inpam.height) {
+            int dcol;
+
+            for (dcol = col - smearFactor;
+                 dcol <= col + smearFactor;
+                 ++dcol) {
+                if (dcol >= 0 && dcol < inpam.width)
+                    ++hist[tuples[drow][dcol][plane]];
+            }
+        }
+    }
+}
+
+
+
+static sample
+modalValue(sample * const hist,
+           sample   const maxval) {
+/*----------------------------------------------------------------------------
+  The sample value that occurs most often according to histogram hist[].
+-----------------------------------------------------------------------------*/
+    sample modalval;
+    unsigned int maxfreq;
+    sample sampleval;
+
+    for (sampleval = 0, maxfreq = 0, modalval = 0;
+         sampleval <= maxval;
+         ++sampleval) {
+
+        if (hist[sampleval] > maxfreq) {
+            maxfreq = hist[sampleval];
+            modalval = sampleval;
+        }
+    }
+    return modalval;
+}
+
+
+
+static void
+convertRow(struct pam     const inpam,
+           tuple **       const tuples,
+           tuple *        const tuplerow,
+           unsigned int   const row,
+           unsigned int   const smearFactor,
+           sample *       const hist) {
+/*----------------------------------------------------------------------------
+   'hist' is a working buffer inpam.width wide.
+-----------------------------------------------------------------------------*/
+    unsigned int plane;
+
+    for (plane = 0; plane < inpam.depth; plane++) {
+        unsigned int col;
 
-    int sample;
-    for (sample = 0; sample < inpam.depth; sample++) {
-        int col;
         for (col = 0; col < inpam.width; ++col)  {
-            int i;
-            int drow;
-            int modalval;
+            sample modalval;
                 /* The sample value that occurs most often in the neighborhood
-                   of the pixel being examined
+                   of column 'col' of row 'row', in plane 'plane'.
                 */
 
-            /* Compute hist[] - frequencies, in the neighborhood, of each 
-               sample value
-            */
-            for (i = 0; i <= inpam.maxval; ++i) hist[i] = 0;
-
-            for (drow = row - smearFactor; drow <= row + smearFactor; ++drow) {
-                if (drow >= 0 && drow < inpam.height) {
-                    int dcol;
-                    for (dcol = col - smearFactor; 
-                         dcol <= col + smearFactor; 
-                         ++dcol) {
-                        if ( dcol >= 0 && dcol < inpam.width )
-                            ++hist[tuples[drow][dcol][sample]];
-                    }
-                }
-            }
-            {
-                /* Compute modalval */
-                int sampleval;
-                int maxfreq;
-
-                maxfreq = 0;
-                modalval = 0;
-
-                for (sampleval = 0; sampleval <= inpam.maxval; ++sampleval) {
-                    if (hist[sampleval] > maxfreq) {
-                        maxfreq = hist[sampleval];
-                        modalval = sampleval;
-                    }
-                }
-            }
-            tuplerow[col][sample] = modalval;
+            computeRowHist(inpam, tuples, smearFactor, plane, row, col, hist);
+
+            modalval = modalValue(hist, inpam.maxval);
+
+            tuplerow[col][plane] = modalval;
         }
     }
 }
@@ -73,44 +166,24 @@ convertRow(struct pam const inpam, tuple ** const tuples,
 
 
 int
-main(int argc, char *argv[] ) {
+main(int argc, const char ** argv) {
+
     struct pam inpam, outpam;
-    FILE* ifp;
-    tuple ** tuples;
-    tuple * tuplerow;
-    int * hist;
+    FILE * ifP;
+    tuple ** tuples;  /* malloc'ed */
+    tuple * tuplerow;  /* malloc'ed */
+    sample * hist;  /* malloc'ed */
         /* A buffer for the convertRow subroutine to use */
-    int argn;
     int row;
-    int smearFactor;
-    const char* const usage = "[-n <n>] [ppmfile]";
-
-    ppm_init( &argc, argv );
-
-    argn = 1;
-    smearFactor = 3;       /* DEFAULT VALUE */
-
-    /* Check for options. */
-    if ( argn < argc && argv[argn][0] == '-' ) {
-        if ( argv[argn][1] == 'n' ) {
-            ++argn;
-            if ( argn == argc || sscanf(argv[argn], "%d", &smearFactor) != 1 )
-                pm_usage( usage );
-        } else
-            pm_usage( usage );
-        ++argn;
-    }
-    if ( argn < argc ) {
-        ifp = pm_openr( argv[argn] );
-        ++argn;
-    } else
-        ifp = stdin;
+    struct CmdlineInfo cmdline;
+
+    pm_proginit(&argc, argv);
 
-    if ( argn != argc )
-        pm_usage( usage );
+    parseCommandLine(argc, argv, &cmdline);
 
-    tuples = pnm_readpam(ifp, &inpam, PAM_STRUCT_SIZE(tuple_type));
-    pm_close(ifp);
+    ifP = pm_openr(cmdline.inputFileNm);
+
+    tuples = pnm_readpam(ifP, &inpam, PAM_STRUCT_SIZE(tuple_type));
 
     MALLOCARRAY(hist, inpam.maxval + 1);
     if (hist == NULL)
@@ -123,7 +196,7 @@ main(int argc, char *argv[] ) {
     tuplerow = pnm_allocpamrow(&inpam);
 
     for (row = 0; row < inpam.height; ++row) {
-        convertRow(inpam, tuples, tuplerow, row, smearFactor, hist);
+        convertRow(inpam, tuples, tuplerow, row, cmdline.n, hist);
         pnm_writepamrow(&outpam, tuplerow);
     }
 
@@ -131,7 +204,9 @@ main(int argc, char *argv[] ) {
     free(hist);
     pnm_freepamarray(tuples, &inpam);
 
+    pm_close(ifP);
     pm_close(stdout);
-    exit(0);
+    return 0;
 }
 
+
diff --git a/editor/specialty/pampaintspill.c b/editor/specialty/pampaintspill.c
index c7994723..7490fcef 100644
--- a/editor/specialty/pampaintspill.c
+++ b/editor/specialty/pampaintspill.c
@@ -6,7 +6,7 @@
  *
  * ----------------------------------------------------------------------
  *
- * Copyright (C) 2010 Scott Pakin <scott+pbm@pakin.org>
+ * Copyright (C) 2010-2021 Scott Pakin <scott+pbm@pakin.org>
  *
  * This program is free software: you can redistribute it and/or modify
  * it under the terms of the GNU General Public License as published by
@@ -45,11 +45,11 @@
 
 #include "mallocvar.h"
 #include "nstring.h"
+#include "rand.h"
 #include "shhopt.h"
 #include "pam.h"
 #include "pammap.h"
 
-
 static time_t const timeUpdateDelta = 30;
     /* Seconds between progress updates */
 static int const    minUpdates = 4;
@@ -67,6 +67,10 @@ struct cmdlineInfo {
     unsigned int all;
     float        power;
     unsigned int downsample;
+    unsigned int randomseedSpec;
+    unsigned int randomseed;
+    unsigned int nearSpec;
+    unsigned int near;
 };
 
 struct coords {
@@ -98,16 +102,20 @@ parseCommandLine(int argc, const char ** const argv,
     MALLOCARRAY_NOFAIL(option_def, 100);
     option_def_index = 0;          /* Incremented by OPTENTRY */
 
-    OPTENT3(0, "bgcolor",    OPT_STRING, &cmdlineP->bgcolor,    
+    OPTENT3(0, "bgcolor",    OPT_STRING, &cmdlineP->bgcolor,
             &bgcolorSpec, 0);
     OPTENT3(0, "wrap",       OPT_FLAG,   NULL,
             &cmdlineP->wrap,       0);
     OPTENT3(0, "all",        OPT_FLAG,   NULL,
             &cmdlineP->all,        0);
-    OPTENT3(0, "power",      OPT_FLOAT,  &cmdlineP->power,      
+    OPTENT3(0, "power",      OPT_FLOAT,  &cmdlineP->power,
             &powerSpec, 0);
-    OPTENT3(0, "downsample", OPT_UINT,   &cmdlineP->downsample, 
+    OPTENT3(0, "downsample", OPT_UINT,   &cmdlineP->downsample,
             &downsampleSpec, 0);
+    OPTENT3(0, "randomseed", OPT_UINT,   &cmdlineP->randomseed,
+            &cmdlineP->randomseedSpec, 0);
+    OPTENT3(0, "near",       OPT_UINT,   &cmdlineP->near,
+            &cmdlineP->nearSpec, 0);
 
     opt.opt_table = option_def;
     opt.short_allowed = 0;
@@ -124,6 +132,11 @@ parseCommandLine(int argc, const char ** const argv,
     if (!downsampleSpec)
         cmdlineP->downsample = 0;
 
+    if (cmdlineP->nearSpec) {
+        if (cmdlineP->near == 0)
+            pm_error("The -near option requires a positive argument");
+    }
+
     if (argc-1 < 1)
         cmdlineP->inputFilename = "-";
     else {
@@ -223,7 +236,9 @@ locatePaintSources(struct pam *            const pamP,
                    tuple **                const tuples,
                    tuple                   const bgColor,
                    unsigned int            const downsample,
-                   struct paintSourceSet * const paintSourcesP) {
+                   struct paintSourceSet * const paintSourcesP,
+                   bool                    const randomseedSpec,
+                   unsigned int            const randomseed) {
 /*--------------------------------------------------------------------
   Construct a list of all pixel coordinates in the input image that
   represent a non-background color.
@@ -248,21 +263,24 @@ locatePaintSources(struct pam *            const pamP,
     pm_message("Image contains %u background + %u non-background pixels",
                pamP->width * pamP->height - paintSources.size,
                paintSources.size);
-    
+
     /* Reduce the number of paint sources to reduce execution time. */
     if (downsample > 0 && downsample < paintSources.size) {
+        struct pm_randSt randSt;
         unsigned int i;
 
-        srand(pm_randseed());
+        pm_randinit(&randSt);
+        pm_srand2(&randSt, randomseedSpec, randomseed);
 
         for (i = 0; i < downsample; ++i) {
             unsigned int const swapIdx =
-                i + rand() % (paintSources.size - i);
+                i + pm_rand(&randSt) % (paintSources.size - i);
             struct coords const swapVal = paintSources.list[i];
 
             paintSources.list[i] = paintSources.list[swapIdx];
             paintSources.list[swapIdx] = swapVal;
         }
+        pm_randterm(&randSt);
         paintSources.size = downsample;
     }
 
@@ -356,6 +374,70 @@ reportProgress(unsigned int const rowsComplete,
 
 
 
+struct distanceList {
+    struct coords * sources;  /* malloc'ed */
+        /* The list of places in the image from which paint comes */
+    double * distSqrs;        /* malloc'ed */
+        /* The list of squared distances from the current point */
+    unsigned int size;
+        /* Number of entries in sources[] */
+};
+
+
+
+static void
+computeDistances(struct pam *           const pamP,
+                 struct coords          const target,
+                 struct paintSourceSet  const paintSources,
+                 distFunc_t *           const distFunc,
+                 bool                   const nearOnly,
+                 unsigned int           const numNear,
+                 struct distanceList *  const distancesP) {
+
+    unsigned int ps;
+
+    /* Acquire a list of all distances. */
+    distancesP->size = 0;
+    for (ps = 0; ps < paintSources.size; ++ps) {
+        struct coords const source = paintSources.list[ps];
+        double const distSqr =
+            (*distFunc)(&target, &source,
+                        pamP->width, pamP->height);
+        distancesP->sources[distancesP->size]  = source;
+        distancesP->distSqrs[distancesP->size] = distSqr;
+        ++distancesP->size;
+    }
+
+    /* If requested, truncate the list to the smallest numNear distances. */
+    if (nearOnly && numNear < distancesP->size) {
+        unsigned int i;
+
+        /* Perform a partial sort -- just enough to identify the numNear
+           smallest distances.  For performance reasons we assume that
+           numNear is much less than paintSources.size (say, less than
+           log2(paintSources.size)).
+        */
+        for (i = 0; i < numNear; ++i) {
+            unsigned int j;
+            for (j = i + 1; j < distancesP->size; ++j) {
+                if (distancesP->distSqrs[i] > distancesP->distSqrs[j]) {
+                    /* Swap elements i and j. */
+                    struct coords const src   = distancesP->sources[i];;
+                    double        const dist2 = distancesP->distSqrs[i];
+
+                    distancesP->sources[i]  = distancesP->sources[j];
+                    distancesP->distSqrs[i] = distancesP->distSqrs[j];
+                    distancesP->sources[j]  = src;
+                    distancesP->distSqrs[j] = dist2;
+                }
+            }
+        }
+        distancesP->size = numNear;
+    }
+}
+
+
+
 static void
 spillOnePixel(struct pam *          const pamP,
               struct coords         const target,
@@ -363,37 +445,38 @@ spillOnePixel(struct pam *          const pamP,
               distFunc_t *          const distFunc,
               double                const distPower,
               tuple                 const outTuple,
-              double *              const newColor) {
+              double *              const newColor,
+              bool                  const nearOnly,
+              unsigned int          const numNear,
+              struct distanceList * const distancesP) {
 
     unsigned int plane;
-    unsigned int ps;
+    unsigned int d;
     double       totalWeight;
 
     for (plane = 0; plane < pamP->depth; ++plane)
         newColor[plane] = 0.0;
+    computeDistances(pamP, target, paintSources, distFunc,
+                     nearOnly, numNear, distancesP);
     totalWeight = 0.0;
-    for (ps = 0; ps < paintSources.size; ++ps) {
-        struct coords const source = paintSources.list[ps];
-        double const distSqr =
-            (*distFunc)(&target, &source,
-                        pamP->width, pamP->height);
+    for (d = 0; d < distancesP->size; ++d) {
+        double        const distSqr = distancesP->distSqrs[d];
+        struct coords const source  = distancesP->sources[d];
 
-        if (distSqr > 0.0) {
-            /* We do special cases for some common cases with code
-               that is much faster than pow().
-            */
-            double const weight =
-                distPower == -2.0 ? 1.0 / distSqr :
-                distPower == -1.0 ? 1.0 / sqrt(distSqr):
-                pow(distSqr, distPower/2);
+        /* We do special cases for some common cases with code
+           that is much faster than pow().
+        */
+        double const weight =
+            distPower == -2.0 ? 1.0 / distSqr :
+            distPower == -1.0 ? 1.0 / sqrt(distSqr):
+            pow(distSqr, distPower/2);
 
-            unsigned int plane;
+        unsigned int plane;
 
-            for (plane = 0; plane < pamP->depth; ++plane)
-                newColor[plane] += weight * source.color[plane];
+        for (plane = 0; plane < pamP->depth; ++plane)
+            newColor[plane] += weight * source.color[plane];
 
-            totalWeight += weight;
-        }
+        totalWeight += weight;
     }
     for (plane = 0; plane < pamP->depth; ++plane)
         outTuple[plane] = (sample) (newColor[plane] / totalWeight);
@@ -409,6 +492,8 @@ produceOutputImage(struct pam *          const pamP,
                    distFunc_t *          const distFunc,
                    double                const distPower,
                    bool                  const all,
+                   bool                  const nearOnly,
+                   unsigned int          const numNear,
                    tuple ***             const outtuplesP) {
 /*--------------------------------------------------------------------
   Color each background pixel (or, if allPixels is 1, all pixels)
@@ -424,10 +509,14 @@ produceOutputImage(struct pam *          const pamP,
     rowsComplete = 0;
     #pragma omp parallel for
     for (row = 0; row < pamP->height; ++row) {
-        struct coords   target;
-        double        * newColor;
-        
+        struct coords         target;
+        double *              newColor;   /* malloc'ed */
+        struct distanceList * distancesP; /* malloc'ed */
+
         MALLOCARRAY(newColor, pamP->depth);
+        MALLOCVAR_NOFAIL(distancesP);
+        MALLOCARRAY_NOFAIL(distancesP->sources,  paintSources.size);
+        MALLOCARRAY_NOFAIL(distancesP->distSqrs, paintSources.size);
 
         target.y = row;
         for (target.x = 0; target.x < pamP->width; ++target.x) {
@@ -436,13 +525,17 @@ produceOutputImage(struct pam *          const pamP,
 
             if (all || tupleEqualColor(pamP, targetTuple, bgColor))
                 spillOnePixel(pamP, target, paintSources, distFunc, distPower,
-                              outputTuple, newColor);
+                              outputTuple, newColor, nearOnly, numNear,
+                              distancesP);
             else
                 pnm_assigntuple(pamP,  outputTuple, targetTuple);
         }
         #pragma omp critical (rowTally)
         reportProgress(++rowsComplete, pamP->height);
 
+        free(distancesP->distSqrs);
+        free(distancesP->sources);
+        free(distancesP);
         free(newColor);
     }
     *outtuplesP = outtuples;
@@ -484,10 +577,12 @@ main(int argc, const char *argv[]) {
                pnm_colorname(&inPam, bgColor, PAM_COLORNAME_HEXOK));
 
     locatePaintSources(&inPam, inTuples, bgColor, cmdline.downsample,
-                       &paintSources);
+                       &paintSources,
+                       cmdline.randomseedSpec, cmdline.randomseed);
 
     produceOutputImage(&inPam, inTuples, bgColor, paintSources, distFunc,
-                       cmdline.power, cmdline.all, &outTuples);
+                       cmdline.power, cmdline.all,
+                       cmdline.nearSpec, cmdline.near, &outTuples);
 
     outPam = inPam;
     outPam.file = stdout;
@@ -498,3 +593,6 @@ main(int argc, const char *argv[]) {
 
     return 0;
 }
+
+
+
diff --git a/editor/specialty/pampop9.c b/editor/specialty/pampop9.c
index b92c7d6b..7211c5eb 100644
--- a/editor/specialty/pampop9.c
+++ b/editor/specialty/pampop9.c
@@ -1,4 +1,4 @@
-/* 
+/*
  *
  * (c) Robert Tinsley, 2003 (http://www.thepoacher.net/contact)
  *
@@ -53,7 +53,7 @@ int main(int argc, char *argv[])
     ydelta = atoi(argv[5]);
 
     if (filename == NULL || *filename == '\0'
-        || xtiles <= 0 || ytiles <= 0 || xdelta < 0 || ydelta < 0) 
+        || xtiles <= 0 || ytiles <= 0 || xdelta < 0 || ydelta < 0)
         pm_error("invalid argument");
 
     /* read src pam */
diff --git a/editor/specialty/pbmlife.c b/editor/specialty/pbmlife.c
index be34cc69..03735d58 100644
--- a/editor/specialty/pbmlife.c
+++ b/editor/specialty/pbmlife.c
@@ -31,12 +31,12 @@ char* argv[];
     pbm_init( &argc, argv );
 
     if ( argc > 2 )
-	pm_usage( "[pbmfile]" );
+        pm_usage( "[pbmfile]" );
 
     if ( argc == 2 )
-	ifp = pm_openr( argv[1] );
+        ifp = pm_openr( argv[1] );
     else
-	ifp = stdin;
+        ifp = stdin;
 
     pbm_readpbminit( ifp, &cols, &rows, &format );
     prevrow = pbm_allocrow( cols );
@@ -49,63 +49,63 @@ char* argv[];
     pbm_readpbmrow( ifp, nextrow, cols, format );
 
     for ( row = 0; row < rows; ++row )
-	{
-	temprow = prevrow;
-	prevrow = thisrow;
-	thisrow = nextrow;
-	nextrow = temprow;
-	if ( row < rows - 1 )
-	    pbm_readpbmrow( ifp, nextrow, cols, format );
+        {
+        temprow = prevrow;
+        prevrow = thisrow;
+        thisrow = nextrow;
+        nextrow = temprow;
+        if ( row < rows - 1 )
+            pbm_readpbmrow( ifp, nextrow, cols, format );
 
         for ( col = 0; col < cols; ++col )
-	    {
-	    /* Check the neighborhood, with an unrolled double loop. */
-	    count = 0;
-	    if ( row > 0 )
-		{
-		/* upper left */
-		if ( col > 0 && prevrow[col - 1] == PBM_WHITE )
-		    ++count;
-		/* upper center */
-		if ( prevrow[col] == PBM_WHITE )
-		    ++count;
-		/* upper right */
-		if ( col < cols - 1 && prevrow[col + 1] == PBM_WHITE )
-		    ++count;
-		}
-	    /* left */
-	    if ( col > 0 && thisrow[col - 1] == PBM_WHITE )
-		++count;
-	    /* right */
-	    if ( col < cols - 1 && thisrow[col + 1] == PBM_WHITE )
-		++count;
-	    if ( row < rows - 1 )
-		{
-		/* lower left */
-		if ( col > 0 && nextrow[col - 1] == PBM_WHITE )
-		    ++count;
-		/* lower center */
-		if ( nextrow[col] == PBM_WHITE )
-		    ++count;
-		/* lower right */
-		if ( col < cols - 1 && nextrow[col + 1] == PBM_WHITE )
-		    ++count;
-		}
+            {
+            /* Check the neighborhood, with an unrolled double loop. */
+            count = 0;
+            if ( row > 0 )
+                {
+                /* upper left */
+                if ( col > 0 && prevrow[col - 1] == PBM_WHITE )
+                    ++count;
+                /* upper center */
+                if ( prevrow[col] == PBM_WHITE )
+                    ++count;
+                /* upper right */
+                if ( col < cols - 1 && prevrow[col + 1] == PBM_WHITE )
+                    ++count;
+                }
+            /* left */
+            if ( col > 0 && thisrow[col - 1] == PBM_WHITE )
+                ++count;
+            /* right */
+            if ( col < cols - 1 && thisrow[col + 1] == PBM_WHITE )
+                ++count;
+            if ( row < rows - 1 )
+                {
+                /* lower left */
+                if ( col > 0 && nextrow[col - 1] == PBM_WHITE )
+                    ++count;
+                /* lower center */
+                if ( nextrow[col] == PBM_WHITE )
+                    ++count;
+                /* lower right */
+                if ( col < cols - 1 && nextrow[col + 1] == PBM_WHITE )
+                    ++count;
+                }
 
-	    /* And compute the new value. */
-	    if ( thisrow[col] == PBM_WHITE )
-		if ( count == 2 || count == 3 )
-		    newrow[col] = PBM_WHITE;
-		else
-		    newrow[col] = PBM_BLACK;
-	    else
-		if ( count == 3 )
-		    newrow[col] = PBM_WHITE;
-		else
-		    newrow[col] = PBM_BLACK;
-	    }
-	pbm_writepbmrow( stdout, newrow, cols, 0 );
-	}
+            /* And compute the new value. */
+            if ( thisrow[col] == PBM_WHITE )
+                if ( count == 2 || count == 3 )
+                    newrow[col] = PBM_WHITE;
+                else
+                    newrow[col] = PBM_BLACK;
+            else
+                if ( count == 3 )
+                    newrow[col] = PBM_WHITE;
+                else
+                    newrow[col] = PBM_BLACK;
+            }
+        pbm_writepbmrow( stdout, newrow, cols, 0 );
+        }
 
     pm_close( ifp );
     pm_close( stdout );
diff --git a/editor/specialty/pgmabel.c b/editor/specialty/pgmabel.c
index aa748f88..3e05be5e 100644
--- a/editor/specialty/pgmabel.c
+++ b/editor/specialty/pgmabel.c
@@ -100,25 +100,24 @@ abel ( float *y, int N, double *adl)
 {
     register int n;
     double *rho, *rhop;       /* results and new index                       */
-    float  *yp;               /* new indizes for the y-array                 */
 
     MALLOCARRAY(rho, N);
     if( !rho )
         pm_error( "out of memory" );
+    for (n=0 ; n<N ; n++)
+        rho[n] = 0;
+
     rhop = rho;
-    yp  = y;
 
     for (n=0 ; n<N ; n++)
     {
-        *(rhop++) = ((*yp++) - Sum(n,rho,N,adl))/(adl[n*N+n]);
-/*    *(rhop++) = ((*yp++) - Sum(n,rho,N))/(dr(n,n+0.5,N));  old version */
-        if ( *rhop < 0.0 ) *rhop = 0.0;         /*  error correction !       */
-/*   if (n > 2) rhop[n-1] = (rho[n-2]+rho[n-1]+rho[n])/3.0;  stabilization*/
+        rhop[n] = MAX(0, (y[n] - Sum(n,rho,N,adl))/(adl[n*N+n]));
+            /* Clip to 0 for error correction !  */
     }
     for (n=0 ; n<N ; n++)
         {
             if (( n>=1 )&&( n<N-1 ))
-	       (*y++) = ((rho[n-1]*0.5+rho[n]+rho[n+1]*0.5)/2.0);/*1D median filter*/
+               (*y++) = ((rho[n-1]*0.5+rho[n]+rho[n+1]*0.5)/2.0);/*1D median filter*/
             else (*y++) = rho[n];
         }
     free(rho);
diff --git a/editor/specialty/pgmbentley.c b/editor/specialty/pgmbentley.c
index aed92074..87778a62 100644
--- a/editor/specialty/pgmbentley.c
+++ b/editor/specialty/pgmbentley.c
@@ -41,7 +41,7 @@ main(int argc, const char * argv[]) {
             pm_error("There are no options and only one argument.  "
                      "You specified %u", argc-1);
     }
-	ifP = pm_openr(inputFileName);
+        ifP = pm_openr(inputFileName);
 
     gin = pgm_readpgm(ifP, &cols, &rows, &maxval);
 
@@ -62,9 +62,9 @@ main(int argc, const char * argv[]) {
             unsigned int const brow = MIN(rows-1, row + gin[row][col] / N);
 
             gout[brow][col] = gin[row][col];
-	    }
+            }
     }
-     
+
     pgm_writepgm(stdout, gout, cols, rows, maxval, 0);
 
     pm_close(stdout);
diff --git a/editor/specialty/pgmmorphconv.c b/editor/specialty/pgmmorphconv.c
index 2ba2d62d..40ce5d76 100644
--- a/editor/specialty/pgmmorphconv.c
+++ b/editor/specialty/pgmmorphconv.c
@@ -1,9 +1,9 @@
-/* pgmmorphconv.c - morphological convolutions on a graymap: dilation and 
+/* pgmmorphconv.c - morphological convolutions on a graymap: dilation and
 ** erosion
 **
 ** Copyright (C) 2000 by Luuk van Dijk/Mind over Matter
 **
-** Based on 
+** Based on
 ** pnmconvol.c - general MxN convolution on a portable anymap
 **
 ** Copyright (C) 1989, 1991 by Jef Poskanzer.
@@ -95,7 +95,7 @@ parseCommandLine(int argc, const char ** const argv,
             cmdlineP->inputFileName = "-";
         else {
             cmdlineP->inputFileName = argv[2];
-            
+
             if (argc-1 > 2)
                 pm_error("Too many arguments: %u.  "
                          "The only possible arguments "
@@ -146,7 +146,7 @@ setAllPixel(gray **      const image,
     for (col = 0; col < cols; ++col) {
         unsigned int row;
         for (row = 0; row < rows; ++row)
-            image[row][col] = value; 
+            image[row][col] = value;
     }
 }
 
@@ -155,9 +155,9 @@ setAllPixel(gray **      const image,
 static void
 dilate(bit **         const template,
        int            const trowso2,
-       int            const tcolso2, 
+       int            const tcolso2,
        gray **        const inImage,
-       gray **        const outImage, 
+       gray **        const outImage,
        unsigned int   const rows,
        unsigned int   const cols,
        unsigned int * const templateCountP) {
@@ -198,9 +198,9 @@ dilate(bit **         const template,
 static void
 erode(bit **         const template,
       int            const trowso2,
-      int            const tcolso2, 
+      int            const tcolso2,
       gray **        const inImage,
-      gray **        const outImage, 
+      gray **        const outImage,
       unsigned int   const rows,
       unsigned int   const cols,
       unsigned int * const templateCountP) {
@@ -227,10 +227,10 @@ erode(bit **         const template,
                     for (c = ((tc > 0) ? 0 : -tc);
                          c < ((tc > 0) ? (cols-tc) : cols);
                          ++c) {
-                        
+
                         gray const source = inImage[r+tr][c+tc];
                         outImage[r][c] = MIN(source, outImage[r][c]);
-      
+
                     }
                 }
             }
@@ -244,9 +244,9 @@ erode(bit **         const template,
 static void
 openMorph(bit **         const template,
           int            const trowso2,
-          int            const tcolso2, 
+          int            const tcolso2,
           gray **        const inputImage,
-          gray **        const outputImage, 
+          gray **        const outputImage,
           unsigned int   const rows,
           unsigned int   const cols,
           unsigned int * const templateCountP) {
@@ -255,11 +255,11 @@ openMorph(bit **         const template,
     unsigned int erodedTemplateCount;
 
     erodedImage = pgm_allocarray(cols, rows);
-    
-    erode(template, trowso2, tcolso2, 
+
+    erode(template, trowso2, tcolso2,
           inputImage, erodedImage, rows, cols, &erodedTemplateCount);
 
-    dilate(template, trowso2, tcolso2, 
+    dilate(template, trowso2, tcolso2,
            erodedImage, outputImage, rows, cols, templateCountP);
 
     pgm_freearray(erodedImage, rows);
@@ -270,9 +270,9 @@ openMorph(bit **         const template,
 static void
 closeMorph(bit **         const template,
            int            const trowso2,
-           int            const tcolso2, 
+           int            const tcolso2,
            gray **        const inputImage,
-           gray **        const outputImage, 
+           gray **        const outputImage,
            unsigned int   const rows,
            unsigned int   const cols,
            unsigned int * const templateCountP) {
@@ -282,10 +282,10 @@ closeMorph(bit **         const template,
 
     dilatedImage = pgm_allocarray(cols, rows);
 
-    dilate(template, trowso2, tcolso2, 
+    dilate(template, trowso2, tcolso2,
            inputImage, dilatedImage, rows, cols, &dilatedTemplateCount);
 
-    erode(template, trowso2, tcolso2, 
+    erode(template, trowso2, tcolso2,
           dilatedImage, outputImage, rows, cols, templateCountP);
 
     pgm_freearray(dilatedImage, rows);
@@ -296,7 +296,7 @@ closeMorph(bit **         const template,
 static void
 subtract(gray **      const subtrahendImage,
          gray **      const subtractorImage,
-         gray **      const outImage, 
+         gray **      const outImage,
          unsigned int const rows,
          unsigned int const cols ) {
 
@@ -318,9 +318,9 @@ subtract(gray **      const subtrahendImage,
 static void
 gradient(bit **         const template,
          int            const trowso2,
-         int            const tcolso2, 
+         int            const tcolso2,
          gray **        const inputImage,
-         gray **        const outputImage, 
+         gray **        const outputImage,
          unsigned int   const rows,
          unsigned int   const cols,
          unsigned int * const templateCountP) {
@@ -328,14 +328,14 @@ gradient(bit **         const template,
     gray ** dilatedImage;
     gray ** erodedImage;
     unsigned int dilatedTemplateCount;
-    
+
     dilatedImage = pgm_allocarray(cols, rows);
     erodedImage = pgm_allocarray(cols, rows);
 
-    dilate(template, trowso2, tcolso2, 
+    dilate(template, trowso2, tcolso2,
            inputImage, dilatedImage, rows, cols, &dilatedTemplateCount);
 
-    erode(template, trowso2, tcolso2, 
+    erode(template, trowso2, tcolso2,
           inputImage, erodedImage, rows, cols, templateCountP);
 
     subtract(dilatedImage, erodedImage, outputImage, rows, cols);
@@ -369,14 +369,14 @@ main(int argc, const char ** argv) {
                        &template, &templateRows, &templateCols);
 
     /* Template coords run from -templateCols/2 .. 0 .. + templateCols/2 */
-  
+
     inputImage = pgm_readpgm(ifP, &cols, &rows, &maxval);
 
     if (cols < templateCols || rows < templateRows)
         pm_error("the image is smaller than the convolution matrix" );
-  
+
     outputImage = pgm_allocarray(cols, rows);
-  
+
     switch (cmdline.operation) {
     case DILATE:
         dilate(template, templateRows/2, templateCols/2,
diff --git a/editor/specialty/pnmindex.c b/editor/specialty/pnmindex.c
index 0a8e35cc..0214ee8b 100644
--- a/editor/specialty/pnmindex.c
+++ b/editor/specialty/pnmindex.c
@@ -1,8 +1,8 @@
 /*============================================================================
-                              pnmindex   
+                                pnmindex
 ==============================================================================
 
-  build a visual index of a bunch of PNM images
+  Build a visual index of a bunch of PNM images.
 
   This used to be a C shell program, and then a BASH program.  Neither
   were portable enough, and the program is too complex for either of
@@ -15,12 +15,14 @@
 ============================================================================*/
 
 #define _DEFAULT_SOURCE /* New name for SVID & BSD source defines */
+#define _C99_SOURCE  /* Make sure snprintf() is in stdio.h */
 #define _XOPEN_SOURCE 500  /* Make sure strdup() is in string.h */
 #define _BSD_SOURCE   /* Make sure strdup is in string.h */
 
 #include <assert.h>
 #include <unistd.h>
 #include <stdarg.h>
+#include <stdio.h>
 #include <errno.h>
 #include <sys/stat.h>
 
@@ -30,9 +32,10 @@
 #include "shhopt.h"
 #include "mallocvar.h"
 #include "nstring.h"
+#include "pm_system.h"
 #include "pnm.h"
 
-struct cmdlineInfo {
+struct CmdlineInfo {
     /* All the information the user supplied in the command line,
        in a form easy for the program to use.
     */
@@ -51,60 +54,74 @@ static bool verbose;
 
 
 
-static void PM_GNU_PRINTF_ATTR(1,2)
-systemf(const char * const fmt,
-        ...) {
+static const char *
+shellQuote(const char * const arg) {
+/*----------------------------------------------------------------------------
+   A string that in a Bourne shell command forms a single token whose value
+   understood by the shell is 'arg'.
 
-    va_list varargs;
-    
-    size_t dryRunLen;
-    
-    va_start(varargs, fmt);
-    
-    pm_vsnprintf(NULL, 0, fmt, varargs, &dryRunLen);
+   For example,
 
-    va_end(varargs);
+     'arg'           result
+     --------------  --------------
 
-    if (dryRunLen + 1 < dryRunLen)
-        /* arithmetic overflow */
-        pm_error("Command way too long");
-    else {
-        size_t const allocSize = dryRunLen + 1;
-        char * shellCommand;
-        shellCommand = malloc(allocSize);
-        if (shellCommand == NULL)
-            pm_error("Can't get storage for %u-character command",
-                     (unsigned)allocSize);
-        else {
-            va_list varargs;
-            size_t realLen;
-            int rc;
-
-            va_start(varargs, fmt);
-
-            pm_vsnprintf(shellCommand, allocSize, fmt, varargs, &realLen);
-                
-            assert(realLen == dryRunLen);
-            va_end(varargs);
-
-            if (verbose)
-                pm_message("shell cmd: %s", shellCommand);
-
-            rc = system(shellCommand);
-            if (rc != 0)
-                pm_error("shell command '%s' failed.  rc %d",
-                         shellCommand, rc);
-            
-            pm_strfree(shellCommand);
+     hello           'hello'
+     two words       'two words'
+     'Bryan's'       \''Bryan'\''s'\'
+
+   Note that in the last example the result is a concatenation of two
+   single-quoted strings and 3 esaped single quotes outside of those quoted
+   strings.
+
+   You can use this safely to insert an arbitrary string from an untrusted
+   source into a shell command without worrying about it changing the nature
+   of the shell command.
+
+   In newly malloced storage.
+-----------------------------------------------------------------------------*/
+    unsigned int const worstCaseResultLen = 3 * strlen(arg) + 1;
+
+    char * buffer;
+    unsigned int i;
+    unsigned int cursor;
+    bool inquotes;
+
+    MALLOCARRAY_NOFAIL(buffer, worstCaseResultLen);
+
+    for (i = 0, cursor=0, inquotes=false; i < strlen(arg); ++i) {
+        if (arg[i] == '\'') {
+            if (inquotes) {
+                buffer[cursor++] = '\'';  /* Close the quotation */
+                inquotes = false;
+            }
+            assert(!inquotes);
+            buffer[cursor++] = '\\';  /* Add escaped */
+            buffer[cursor++] = '\'';  /*    single quote */
+        } else {
+            if (!inquotes) {
+                buffer[cursor++] = '\'';
+                inquotes = true;
+            }
+            assert(inquotes);
+            buffer[cursor++] = arg[i];
         }
     }
+    if (inquotes)
+        buffer[cursor++] = '\'';   /* Close the final quotation */
+
+    buffer[cursor++] = '\0';  /* Terminate string */
+
+    assert(cursor <= worstCaseResultLen);
+
+    return buffer;
 }
-        
+
+
 
 
 static void
-parseCommandLine(int argc, char ** argv, 
-                 struct cmdlineInfo * const cmdlineP) {
+parseCommandLine(int argc, const char ** argv,
+                 struct CmdlineInfo * const cmdlineP) {
 
     unsigned int option_def_index;
     optEntry *option_def;
@@ -118,13 +135,13 @@ parseCommandLine(int argc, char ** argv,
     MALLOCARRAY_NOFAIL(option_def, 100);
 
     option_def_index = 0;   /* incremented by OPTENT3 */
-    OPTENT3(0, "black",       OPT_FLAG,   NULL,                  
+    OPTENT3(0, "black",       OPT_FLAG,   NULL,
             &cmdlineP->black,         0);
-    OPTENT3(0, "noquant",     OPT_FLAG,   NULL,                  
+    OPTENT3(0, "noquant",     OPT_FLAG,   NULL,
             &cmdlineP->noquant,       0);
-    OPTENT3(0, "quant",       OPT_FLAG,   NULL,                  
+    OPTENT3(0, "quant",       OPT_FLAG,   NULL,
             &quant,                   0);
-    OPTENT3(0, "verbose",     OPT_FLAG,   NULL,                  
+    OPTENT3(0, "verbose",     OPT_FLAG,   NULL,
             &cmdlineP->verbose,       0);
     OPTENT3(0, "size",        OPT_UINT,   &cmdlineP->size,
             &sizeSpec,                0);
@@ -137,21 +154,30 @@ parseCommandLine(int argc, char ** argv,
 
     opt.opt_table = option_def;
     opt.short_allowed = FALSE;  /* We have no short (old-fashioned) options */
-    opt.allowNegNum = FALSE; 
+    opt.allowNegNum = FALSE;
 
-    pm_optParseOptions3(&argc, argv, opt, sizeof(opt), 0);
+    pm_optParseOptions3(&argc, (char **)argv, opt, sizeof(opt), 0);
         /* Uses and sets argc, argv, and some of *cmdline_p and others. */
 
     if (quant && cmdlineP->noquant)
-        pm_error("You can't specify both -quant and -noquat");
+        pm_error("You can't specify both -quant and -noquant");
 
-    if (!colorsSpec)
+    if (colorsSpec) {
+        if (cmdlineP->colors == 0)
+            pm_error("-colors value must be positive");
+    } else
         cmdlineP->colors = 256;
-    
-    if (!sizeSpec)
+
+    if (sizeSpec) {
+        if (cmdlineP->size == 0)
+            pm_error("-size value must be positive");
+    } else
         cmdlineP->size = 100;
 
-    if (!acrossSpec)
+    if (acrossSpec) {
+        if (cmdlineP->across == 0)
+            pm_error("-across value must be positive");
+    } else
         cmdlineP->across = 6;
 
     if (!titleSpec)
@@ -181,7 +207,7 @@ parseCommandLine(int argc, char ** argv,
 
 
 static void
-freeCmdline(struct cmdlineInfo const cmdline) {
+freeCmdline(struct CmdlineInfo const cmdline) {
 
     unsigned int i;
 
@@ -195,10 +221,38 @@ freeCmdline(struct cmdlineInfo const cmdline) {
 
 
 static void
+validateTmpdir(const char * const dirNm) {
+/*----------------------------------------------------------------------------
+   Abort program if 'dirNm' contains special characters that would cause
+   trouble if included in a shell command.
+
+   The cleanest thing to do would be to allow any characters in the directory
+   name and just quote and escape the properly every time we include the name
+   of a temporary file in a shell command, but we're too lazy for that.
+-----------------------------------------------------------------------------*/
+    if (
+        strchr(dirNm, '\\') ||
+        strchr(dirNm, '\'') ||
+        strchr(dirNm, ' ') ||
+        strchr(dirNm, '"') ||
+        strchr(dirNm, '$') ||
+        strchr(dirNm, '`') ||
+        strchr(dirNm, '!')
+        ) {
+        pm_error("TMPDIR environment variable contains a shell special "
+                 "character; this program cannot use that.");
+    }
+}
+
+
+
+static void
 makeTempDir(const char ** const tempDirP) {
 
     const char * const tmpdir = getenv("TMPDIR") ? getenv("TMPDIR") : "/tmp";
 
+    validateTmpdir(tmpdir);
+
     const char * mytmpdir;
     int rc;
 
@@ -233,9 +287,9 @@ rowFileName(const char * const dirName,
             unsigned int const row) {
 
     const char * fileName;
-    
+
     pm_asprintf(&fileName, "%s/pi.%u", dirName, row);
-    
+
     return fileName;
 }
 
@@ -245,76 +299,116 @@ static void
 makeTitle(const char * const title,
           unsigned int const rowNumber,
           bool         const blackBackground,
-          const char * const tempDir) {
+          const char * const dirNm) {
+/*----------------------------------------------------------------------------
+   Create a PBM file containing the text 'title'.
+
+   If 'blackBackground' is true, make it white on black; otherwise, black
+   on white.
 
+   Name the file like a thumbnail row file for row number 'rowNumber',
+   in directory named 'dirNm'.
+-----------------------------------------------------------------------------*/
     const char * const invertStage = blackBackground ? "| pnminvert " : "";
 
     const char * fileName;
+    FILE * outFP;
+    struct bufferDesc titleBuf;
+    const char * shellCommand;
+    int termStatus;
 
-    fileName = rowFileName(tempDir, rowNumber);
-
-    /* This quoting is not adequate.  We really should do this without
-       a shell at all.
-    */
-    systemf("pbmtext \"%s\" "
-            "%s"
-            "> %s", 
-            title, invertStage, fileName);
+    titleBuf.size              = strlen(title);
+    titleBuf.buffer            = (unsigned char *)title;
+    titleBuf.bytesTransferredP = NULL;
 
+    fileName = rowFileName(dirNm, rowNumber);
+    outFP = pm_openw(fileName);
     pm_strfree(fileName);
+
+    pm_asprintf(&shellCommand, "pbmtext %s", invertStage);
+
+    pm_system2(&pm_feed_from_memory, &titleBuf,
+               &pm_accept_to_filestream, outFP,
+               shellCommand, &termStatus);
+
+    pm_strfree(shellCommand);
+
+    if (termStatus != 0)
+        pm_error("Failed to generate title image");
+
+    pm_close(outFP);
 }
 
 
 
 static void
-copyImage(const char * const inputFileName,
-          const char * const outputFileName) {
+copyImage(const char * const inputFileNm,
+          const char * const outputFileNm) {
+
+    int termStatus;
 
-    systemf("cat %s > %s", inputFileName, outputFileName);
-} 
+    pm_system2_lp("cat",
+                  &pm_feed_from_file, (void*)inputFileNm,
+                  &pm_accept_to_file, (void*)outputFileNm,
+                  &termStatus,
+                  "cat", NULL);
+
+    if (termStatus != 0)
+        pm_error("'cat' to copy image '%s' to '%s' failed, "
+                 "termination status = %d",
+                 inputFileNm, outputFileNm, termStatus);
+}
 
 
 
 static void
-copyScaleQuantImage(const char * const inputFileName,
-                    const char * const outputFileName,
+copyScaleQuantImage(const char * const inputFileNm,
+                    const char * const outputFileNm,
                     int          const format,
                     unsigned int const size,
                     unsigned int const quant,
-                    unsigned int const colors) {
+                    unsigned int const colorCt) {
 
     const char * scaleCommand;
+    int termStatus;
 
     switch (PNM_FORMAT_TYPE(format)) {
     case PBM_TYPE:
-        pm_asprintf(&scaleCommand, 
-                    "pamscale -quiet -xysize %u %u %s "
-                    "| pgmtopbm > %s",
-                    size, size, inputFileName, outputFileName);
+        pm_asprintf(&scaleCommand,
+                    "pamscale -quiet -xysize %u %u "
+                    "| pamditherbw",
+                    size, size);
         break;
-        
+
     case PGM_TYPE:
-        pm_asprintf(&scaleCommand, 
-                    "pamscale -quiet -xysize %u %u %s >%s",
-                    size, size, inputFileName, outputFileName);
+        pm_asprintf(&scaleCommand,
+                    "pamscale -quiet -xysize %u %u",
+                    size, size);
         break;
-        
+
     case PPM_TYPE:
         if (quant)
-            pm_asprintf(&scaleCommand, 
-                        "pamscale -quiet -xysize %u %u %s "
-                        "| pnmquant -quiet %u > %s",
-                        size, size, inputFileName, colors, outputFileName);
+            pm_asprintf(&scaleCommand,
+                        "pamscale -quiet -xysize %u %u "
+                        "| pnmquant -quiet %u ",
+                        size, size, colorCt);
         else
-            pm_asprintf(&scaleCommand, 
-                        "pamscale -quiet -xysize %u %u %s >%s",
-                        size, size, inputFileName, outputFileName);
+            pm_asprintf(&scaleCommand,
+                        "pamscale -quiet -xysize %u %u ",
+                        size, size);
         break;
     default:
         pm_error("Unrecognized Netpbm format: %d", format);
     }
 
-    systemf("%s", scaleCommand);
+    pm_system2(pm_feed_from_file, (void*)inputFileNm,
+               pm_accept_to_file, (void*)outputFileNm,
+               scaleCommand,
+               &termStatus);
+
+    if (termStatus != 0)
+        pm_message("Shell command '%s' failed.  Termination status=%d",
+                   scaleCommand, termStatus);
 
     pm_strfree(scaleCommand);
 }
@@ -326,7 +420,7 @@ formatTypeMax(int const typeA,
               int const typeB) {
 
     if (typeA == PPM_TYPE || typeB == PPM_TYPE)
-        return PPM_TYPE; 
+        return PPM_TYPE;
     else if (typeA == PGM_TYPE || typeB == PGM_TYPE)
         return PGM_TYPE;
     else
@@ -341,9 +435,9 @@ thumbnailFileName(const char * const dirName,
                   unsigned int const col) {
 
     const char * fileName;
-    
+
     pm_asprintf(&fileName, "%s/pi.%u.%u", dirName, row, col);
-    
+
     return fileName;
 }
 
@@ -364,7 +458,7 @@ thumbnailFileList(const char * const dirName,
         pm_error("Unable to allocate %u bytes for file list", maxListSize);
 
     list[0] = '\0';
-    
+
     for (col = 0; col < cols; ++col) {
         const char * const fileName = thumbnailFileName(dirName, row, col);
 
@@ -383,21 +477,51 @@ thumbnailFileList(const char * const dirName,
 
 
 static void
-makeImageFile(const char * const thumbnailFileName,
-              const char * const inputFileName,
+makeImageFile(const char * const thumbnailFileNm,
+              const char * const inputFileNm,
               bool         const blackBackground,
-              const char * const outputFileName) {
+              const char * const outputFileNm) {
+/*----------------------------------------------------------------------------
+   Create one thumbnail image.  It consists of the image in the file named
+   'thumbnailFileName' with text of that name appended to the bottom.
 
-    const char * const blackWhiteOpt = blackBackground ? "-black" : "-white";
-    const char * const invertStage = blackBackground ? "| pnminvert " : "";
+   Write the result to the file named 'outputFileName'.
 
-    systemf("pbmtext \"%s\" "
-            "%s"
-            "| pnmcat %s -topbottom %s - "
-            "> %s",
-            inputFileName, invertStage, blackWhiteOpt, 
-            thumbnailFileName, outputFileName);
-}    
+   'blackBackground' means give the image a black background where padding
+   is necessary and make the text white on black.  If false, give the image
+   a white background instead.
+-----------------------------------------------------------------------------*/
+    const char * const blackWhiteOpt = blackBackground ? "-black" : "-white";
+    const char * const invertStage   = blackBackground ? "| pnminvert " : "";
+    const char * const thumbnailFileNmToken = shellQuote(thumbnailFileNm);
+
+    struct bufferDesc fileNmBuf;
+    const char * shellCommand;
+    int termStatus;
+
+    fileNmBuf.size              = strlen(inputFileNm);
+    fileNmBuf.buffer            = (unsigned char *)inputFileNm;
+    fileNmBuf.bytesTransferredP = NULL;
+
+    pm_asprintf(&shellCommand,
+                "pbmtext "
+                "%s"
+                "| pamcat %s -topbottom %s - ",
+                invertStage, blackWhiteOpt, thumbnailFileNmToken);
+
+    pm_system2(&pm_feed_from_memory, &fileNmBuf,
+               &pm_accept_to_file, (void*)outputFileNm,
+               shellCommand,
+               &termStatus);
+
+    if (termStatus != 0)
+        pm_error("Shell command '%s' to add file name to thumbnail image "
+                 "of file '%s' failed, termination Status = %d",
+                 shellCommand, inputFileNm, termStatus);
+
+    pm_strfree(thumbnailFileNmToken);
+    pm_strfree(shellCommand);
+}
 
 
 
@@ -406,32 +530,31 @@ makeThumbnail(const char *  const inputFileName,
               unsigned int  const size,
               bool          const black,
               bool          const quant,
-              unsigned int  const colors,
+              unsigned int  const colorCt,
               const char *  const tempDir,
               unsigned int  const row,
               unsigned int  const col,
               int *         const formatP) {
 
+    const char * const fileName = thumbnailFileName(tempDir, row, col);
+
     FILE * ifP;
     int imageCols, imageRows, format;
     xelval maxval;
     const char * tmpfile;
-    const char * fileName;
-        
+
     ifP = pm_openr(inputFileName);
     pnm_readpnminit(ifP, &imageCols, &imageRows, &maxval, &format);
     pm_close(ifP);
-    
+
     pm_asprintf(&tmpfile, "%s/pi.tmp", tempDir);
 
     if (imageCols < size && imageRows < size)
         copyImage(inputFileName, tmpfile);
     else
-        copyScaleQuantImage(inputFileName, tmpfile, format, 
-                            size, quant, colors);
+        copyScaleQuantImage(inputFileName, tmpfile, format,
+                            size, quant, colorCt);
 
-    fileName = thumbnailFileName(tempDir, row, col);
-        
     makeImageFile(tmpfile, inputFileName, black, fileName);
 
     unlink(tmpfile);
@@ -441,7 +564,7 @@ makeThumbnail(const char *  const inputFileName,
 
     *formatP = format;
 }
-        
+
 
 
 static void
@@ -450,7 +573,7 @@ unlinkThumbnailFiles(const char * const dirName,
                      unsigned int const cols) {
 
     unsigned int col;
-    
+
     for (col = 0; col < cols; ++col) {
         const char * const fileName = thumbnailFileName(dirName, row, col);
 
@@ -467,7 +590,7 @@ unlinkRowFiles(const char * const dirName,
                unsigned int const rows) {
 
     unsigned int row;
-    
+
     for (row = 0; row < rows; ++row) {
         const char * const fileName = rowFileName(dirName, row);
 
@@ -481,40 +604,66 @@ unlinkRowFiles(const char * const dirName,
 
 static void
 combineIntoRowAndDelete(unsigned int const row,
-                        unsigned int const cols,
+                        unsigned int const colCt,
                         int          const maxFormatType,
                         bool         const blackBackground,
                         bool         const quant,
-                        unsigned int const colors,
+                        unsigned int const colorCt,
                         const char * const tempDir) {
+/*----------------------------------------------------------------------------
+   Combine the 'colCt' thumbnails for row 'row' into a PNM file in directory
+   'tempDir'.
+
+   Each thumbnail is from a specially named file in 'tempDir' whose name
+   indicates its position in the row, and the output is also specially named
+   with a name indicating it is row 'row'.
+
+   Where the thumnails are different heights, pad with black if
+   'blackBackground' is true; white otherwise.
 
+   If 'quant', color-quantize the result to have no more than 'colorCt'
+   colors, choosing the colors that best represent all the pixels in the
+   result.
+
+   'maxFormatType' is the most expressive format of all the thumbnail files;
+   results are undefined if it is not.
+-----------------------------------------------------------------------------*/
     const char * const blackWhiteOpt = blackBackground ? "-black" : "-white";
+    const char * const fileNm        = rowFileName(tempDir, row);
 
-    const char * fileName;
     const char * quantStage;
     const char * fileList;
-    
-    fileName = rowFileName(tempDir, row);
+    const char * shellCommand;
+    int termStatus;
 
-    unlink(fileName);
+    unlink(fileNm);
 
     if (maxFormatType == PPM_TYPE && quant)
-        pm_asprintf(&quantStage, "| pnmquant -quiet %u ", colors);
+        pm_asprintf(&quantStage, "| pnmquant -quiet %u ", colorCt);
     else
         quantStage = strdup("");
 
-    fileList = thumbnailFileList(tempDir, row, cols);
+    fileList = thumbnailFileList(tempDir, row, colCt);
+
+    pm_asprintf(&shellCommand, "pamcat %s -leftright -jbottom %s "
+                "%s",
+                blackWhiteOpt, fileList, quantStage);
 
-    systemf("pnmcat %s -leftright -jbottom %s "
-            "%s"
-            ">%s",
-            blackWhiteOpt, fileList, quantStage, fileName);
+    pm_system2(&pm_feed_null, NULL,
+               &pm_accept_to_file, (void*)fileNm,
+               shellCommand,
+               &termStatus);
+
+    if (termStatus != 0)
+        pm_error("Shell command '%s' to create row of thumbnails failed.  "
+                 "Termination status = %d", shellCommand, termStatus);
 
     pm_strfree(fileList);
     pm_strfree(quantStage);
-    pm_strfree(fileName);
+    pm_strfree(fileNm);
+    pm_strfree(shellCommand);
 
-    unlinkThumbnailFiles(tempDir, row, cols);
+    unlinkThumbnailFiles(tempDir, row, colCt);
 }
 
 
@@ -539,7 +688,7 @@ rowFileList(const char * const dirName,
 
         if (strlen(list) + strlen(fileName) + 1 > maxListSize - 1)
             pm_error("File name list too long for this program to handle.");
-        
+
         else {
             strcat(list, " ");
             strcat(list, fileName);
@@ -553,66 +702,99 @@ rowFileList(const char * const dirName,
 
 
 static void
-writeRowsAndDelete(unsigned int const rows,
+writeRowsAndDelete(unsigned int const rowCt,
                    int          const maxFormatType,
                    bool         const blackBackground,
                    bool         const quant,
-                   unsigned int const colors,
+                   unsigned int const colorCt,
                    const char * const tempDir) {
+/*----------------------------------------------------------------------------
+   Write the PNM image containing the 'rowCt' rows of thumbnails to Standard
+   Output.  Take each row of thumbnails from a specially named PNM file in
+   directory 'tempDir', and unlink it from that directory.
+
+   Where the rows are different widths, pad with black if 'blackBackground'
+   is true; white otherwise.
 
+   If 'quant', color-quantize the result to have no more than 'colorCt'
+   colors, choosing the colors that best represent all the pixels in the
+   result.
+
+   'maxFormatType' is the most expressive format of all the row files; results
+   are undefined if it is not.
+-----------------------------------------------------------------------------*/
     const char * const blackWhiteOpt = blackBackground ? "-black" : "-white";
+    const char * const plainOpt      = pm_plain_output ? "-plain" : "";
 
     const char * quantStage;
     const char * fileList;
-    
+    const char * shellCommand;
+    int termStatus;
+
     if (maxFormatType == PPM_TYPE && quant)
-        pm_asprintf(&quantStage, "| pnmquant -quiet %u ", colors);
+        pm_asprintf(&quantStage, "| pnmquant -quiet %u ", colorCt);
     else
         quantStage = strdup("");
 
-    fileList = rowFileList(tempDir, rows);
+    fileList = rowFileList(tempDir, rowCt);
 
-    systemf("pnmcat %s -topbottom %s %s",
-            blackWhiteOpt, fileList, quantStage);
+    pm_asprintf(&shellCommand, "pamcat %s %s -topbottom %s %s",
+                plainOpt, blackWhiteOpt, fileList, quantStage);
 
+    /* Do pamcat/pnmquant command with no Standard Input and writing to
+       our Standard Output
+    */
+    pm_system2(&pm_feed_null, NULL,
+               NULL, NULL,
+               shellCommand,
+               &termStatus);
+
+    if (termStatus != 0)
+        pm_error("Shell command '%s' to assemble %u rows of thumbnails and "
+                 "write them out failed; termination status = %d",
+                 shellCommand, rowCt, termStatus);
+
+    pm_strfree(shellCommand);
     pm_strfree(fileList);
     pm_strfree(quantStage);
 
-    unlinkRowFiles(tempDir, rows);
+    unlinkRowFiles(tempDir, rowCt);
 }
 
 
 
 int
-main(int argc, char *argv[]) {
-    struct cmdlineInfo cmdline;
+main(int argc, const char ** argv) {
+
+    struct CmdlineInfo cmdline;
     const char * tempDir;
     int maxFormatType;
     unsigned int colsInRow;
     unsigned int rowsDone;
     unsigned int i;
 
-    pnm_init(&argc, argv);
+    pm_proginit(&argc, argv);
 
     parseCommandLine(argc, argv, &cmdline);
 
     verbose = cmdline.verbose;
-    
+
     makeTempDir(&tempDir);
 
-    maxFormatType = PBM_TYPE;
-    colsInRow = 0;
-    rowsDone = 0;
+    rowsDone = 0;  /* initial value */
 
     if (cmdline.title)
         makeTitle(cmdline.title, rowsDone++, cmdline.black, tempDir);
 
-    for (i = 0; i < cmdline.inputFileCount; ++i) {
+    for (i = 0, colsInRow = 0, maxFormatType = PBM_TYPE;
+         i < cmdline.inputFileCount;
+         ++i) {
+
         const char * const inputFileName = cmdline.inputFileName[i];
 
         int format;
 
-        makeThumbnail(inputFileName, cmdline.size, cmdline.black, 
+        makeThumbnail(inputFileName, cmdline.size, cmdline.black,
                       !cmdline.noquant, cmdline.colors, tempDir,
                       rowsDone, colsInRow, &format);
 
@@ -640,3 +822,5 @@ main(int argc, char *argv[]) {
 
     return 0;
 }
+
+
diff --git a/editor/specialty/pnmmercator.c b/editor/specialty/pnmmercator.c
index 81f7f148..0c5c790f 100644
--- a/editor/specialty/pnmmercator.c
+++ b/editor/specialty/pnmmercator.c
@@ -27,16 +27,16 @@
 
 /* The pnm library allows us to code this program without branching cases for
    PGM and PPM, but we do the branch anyway to speed up processing of PGM
-   images. 
+   images.
 */
 
 
 
-struct cmdlineInfo 
+struct cmdlineInfo
 {
     /*
     All the information the user supplied in the command line,
-    in a form easy for the program to use. 
+    in a form easy for the program to use.
     */
 
     const char * input_filespec;  /* Filespecs of input files */
@@ -50,14 +50,14 @@ struct cmdlineInfo
 
 
 static void
-parseCommandLine(int                        argc, 
+parseCommandLine(int                        argc,
                  const char **              argv,
                  struct cmdlineInfo * const cmdlineP ) {
 
     optEntry * option_def;
     optStruct3 opt;
         /* Instructions to pm_optParseOptions3 on how to parse our options. */
-    
+
     unsigned int option_def_index;
 
     MALLOCARRAY_NOFAIL(option_def, 100);
@@ -85,9 +85,9 @@ parseCommandLine(int                        argc,
 
 
 static void
-computeOutputDimensions(const struct cmdlineInfo cmdline, 
+computeOutputDimensions(const struct cmdlineInfo cmdline,
                         const int rows, const int cols,
-                        int * newrowsP, int * newcolsP) 
+                        int * newrowsP, int * newcolsP)
 {
     *newcolsP = cols;
     if (!cmdline.inverse)
@@ -106,7 +106,7 @@ computeOutputDimensions(const struct cmdlineInfo cmdline,
             pm_message("Creating Degrees map, new size is %dx%d",
                        *newcolsP, *newrowsP);
     }
-}        
+}
 
 
 
@@ -117,15 +117,15 @@ transformWithMixing(FILE * const ifP,
                     int const newcols, int const newrows,
                     xelval const newmaxval, int const newformat,
                     bool const inverse,
-                    bool const verbose, bool const vverbose) 
+                    bool const verbose, bool const vverbose)
 {
-    /* 
-    Transform the map image on input file 'ifP' (which is described by 
+    /*
+    Transform the map image on input file 'ifP' (which is described by
     'cols', 'rows', 'format', and 'maxval') to a Mercator projection
-    and write the result to standard output as format 'newformat' and 
+    and write the result to standard output as format 'newformat' and
     with maxval 'newmaxval'.
 
-    We'll blend colors from subsequent rows in the output pixels. 
+    We'll blend colors from subsequent rows in the output pixels.
     */
 
     xel* oddxelrow;  /* an input row */
@@ -142,14 +142,14 @@ transformWithMixing(FILE * const ifP,
     double fLatRad;
     double fLatMerc;
 
-    oddxelrow = pnm_allocrow(cols); 
-    evenxelrow = pnm_allocrow(cols); 
+    oddxelrow = pnm_allocrow(cols);
+    evenxelrow = pnm_allocrow(cols);
     rowInXelrow = 0;
 
     newxelrow = pnm_allocrow(newcols);
 
     for (row = 0; row < newrows; ++row) {
-        
+
         fRow = (double)row + 0.5; /* center on half the pixel */
         if (!inverse) {
             /* the result is mercator, calculate back to degrees */
@@ -207,7 +207,7 @@ transformWithMixing(FILE * const ifP,
             }
         }
 
-        while ((rowInXelrow <= inputRow + 1) && 
+        while ((rowInXelrow <= inputRow + 1) &&
                (rowInXelrow < rows)) {
             /* we need to read one row ahead */
             if (rowInXelrow % 2 == 0) {
@@ -268,16 +268,16 @@ transformNoneMixing(FILE * const ifP,
                    int const newcols, int const newrows,
                    xelval const newmaxval, int const newformat,
                    bool const inverse,
-                   bool const verbose, bool const vverbose) 
+                   bool const verbose, bool const vverbose)
 {
     /*
-    Transform the map image on input file 'ifP' (which is described by 
+    Transform the map image on input file 'ifP' (which is described by
     'cols', 'rows', 'format', and 'maxval') to a Mercator projection and
-    write the result to standard output as format 'newformat' and with 
+    write the result to standard output as format 'newformat' and with
     maxval 'newmaxval'.
 
     Don't mix colors from different input pixels together in the output
-    pixels.  Each output pixel is an exact copy of some corresponding 
+    pixels.  Each output pixel is an exact copy of some corresponding
     input pixel.
     */
 
@@ -293,13 +293,13 @@ transformNoneMixing(FILE * const ifP,
     double fLatRad;
     double fLatMerc;
 
-    xelrow = pnm_allocrow(cols); 
+    xelrow = pnm_allocrow(cols);
     rowInXelrow = 0;
 
     newxelrow = pnm_allocrow(newcols);
 
     for (row = 0; row < newrows; ++row) {
-        
+
         fRow = (double)row + 0.5; /* center on half the pixel */
         if (!inverse) {
             /* the result is mercator, calculate back to degrees */
@@ -377,7 +377,7 @@ transformNoneMixing(FILE * const ifP,
 
 
 int
-main(int argc, const char ** argv ) 
+main(int argc, const char ** argv )
 {
     struct cmdlineInfo cmdline;
     FILE* ifP;
@@ -413,18 +413,18 @@ main(int argc, const char ** argv )
         if (verbose)
             pm_message("Transforming map without mixing/blending colors");
         transformNoneMixing(ifP, cols, rows, maxval, format,
-                            newcols, newrows, newmaxval, newformat, 
+                            newcols, newrows, newmaxval, newformat,
                             cmdline.inverse, verbose, cmdline.vverbose);
     } else {
         if (verbose)
             pm_message("Transforming map while using intermediate colors");
         transformWithMixing(ifP, cols, rows, maxval, format,
-                            newcols, newrows, newmaxval, newformat, 
+                            newcols, newrows, newmaxval, newformat,
                             cmdline.inverse, verbose, cmdline.vverbose);
     }
 
     pm_close(ifP);
     pm_close(stdout);
-    
+
     return 0;
 }
diff --git a/editor/specialty/ppm3d.c b/editor/specialty/ppm3d.c
index a6faa341..bb7cd1af 100644
--- a/editor/specialty/ppm3d.c
+++ b/editor/specialty/ppm3d.c
@@ -33,7 +33,7 @@ parseCommandLine(int argc, char ** argv,
                  struct cmdlineInfo * const cmdlineP) {
 /*----------------------------------------------------------------------------
    parse program command line described in Unix standard form by argc
-   and argv.  Return the information in the options as *cmdlineP.  
+   and argv.  Return the information in the options as *cmdlineP.
 
    If command line is internally inconsistent (invalid options, etc.),
    issue error message to stderr and abort program.
@@ -64,7 +64,7 @@ parseCommandLine(int argc, char ** argv,
 
     pm_optParseOptions3( &argc, argv, opt, sizeof(opt), 0);
         /* Uses and sets argc, argv, and some of *cmdlineP and others. */
-    
+
     if (argc-1 < 2)
         pm_error("You must specify at least two arguments: left and right "
                  "input file names.  You specified %u", argc-1);
@@ -122,7 +122,7 @@ compute3dRowMono(gray *       const lGrayrow,
                  pixel *      const pixelrow,
                  unsigned int const cols,
                  int          const offset) {
-    
+
     unsigned int col;
     gray *  lgP;
     gray *  rgP;
@@ -133,7 +133,7 @@ compute3dRowMono(gray *       const lGrayrow,
     for (col = 0, pP = pixelrow, lgP = lGrayrow, rgP = rGrayrow;
          col < cols + offset;
          ++col) {
-            
+
         if ((int)col < offset/2)
             ++lgP;
         else if ((int)col < offset) {
@@ -154,7 +154,7 @@ compute3dRowMono(gray *       const lGrayrow,
             ++rgP;
         }
     }
-}    
+}
 
 
 
@@ -164,7 +164,7 @@ compute3dRowColor(pixel *      const lPixelrow,
                   pixel *      const pixelrow,
                   unsigned int const cols,
                   unsigned int const offset) {
-    
+
     unsigned int col;
     pixel * lP;
     pixel * rP;
@@ -175,7 +175,7 @@ compute3dRowColor(pixel *      const lPixelrow,
     for (col = 0, pP = pixelrow, lP = lPixelrow, rP = rPixelrow;
          col < cols + offset;
          ++col) {
-            
+
         if ((int)col < offset/2)
             ++lP;
         else if ((int)col < offset) {
@@ -196,7 +196,7 @@ compute3dRowColor(pixel *      const lPixelrow,
             ++rP;
         }
     }
-}    
+}
 
 
 
@@ -265,11 +265,11 @@ main(int argc, char *argv[]) {
     int lRows, lCols;
     int lFormat;
     pixval lMaxval;
-   
+
     int rRows, rCols;
     int rFormat;
     pixval rMaxval;
-   
+
     ppm_init(&argc, argv);
 
     parseCommandLine(argc, argv, &cmdline);
@@ -279,12 +279,12 @@ main(int argc, char *argv[]) {
 
     ppm_readppminit(lIfP, &lCols, &lRows, &lMaxval, &lFormat);
     ppm_readppminit(rIfP, &rCols, &rRows, &rMaxval, &rFormat);
-    
-    if ((lCols != rCols) || (lRows != rRows) || 
-        (lMaxval != rMaxval) || 
+
+    if ((lCols != rCols) || (lRows != rRows) ||
+        (lMaxval != rMaxval) ||
         (PPM_FORMAT_TYPE(lFormat) != PPM_FORMAT_TYPE(rFormat)))
         pm_error ("Pictures are not of same size and format");
-    
+
     cols   = lCols;
     rows   = lRows;
     maxval = lMaxval;
@@ -293,7 +293,7 @@ main(int argc, char *argv[]) {
         pm_error("Magnitude of -offset (%u columns) is not less than "
                  "width of images "
                  "(%u columns)", abs(cmdline.offset), cols);
-   
+
     ppm_writeppminit(stdout, cols, rows, maxval, 0);
 
     write3dRaster(stdout, lIfP, rIfP, cols, rows, maxval,
diff --git a/editor/specialty/ppmglobe.c b/editor/specialty/ppmglobe.c
index bb043cc6..1ddaabc3 100644
--- a/editor/specialty/ppmglobe.c
+++ b/editor/specialty/ppmglobe.c
@@ -53,7 +53,7 @@ parseCommandLine(int argc, char ** argv,
     MALLOCARRAY_NOFAIL(option_def, 100);
 
     option_def_index = 0;   /* incremented by OPTENT3 */
-    OPTENT3(0, "background",     OPT_STRING, &cmdlineP->background, 
+    OPTENT3(0, "background",     OPT_STRING, &cmdlineP->background,
             &backgroundSpec, 0);
     OPTENT3(0, "closeok",        OPT_FLAG, NULL,
             &cmdlineP->closeok, 0);
@@ -68,21 +68,21 @@ parseCommandLine(int argc, char ** argv,
     if (!backgroundSpec)
         cmdlineP->background = NULL;
 
-    if (argc - 1 < 1) 
+    if (argc - 1 < 1)
         pm_error("You must specify at least one argument:  the strip count");
     else {
         int const stripcount = atoi(argv[1]);
         if (stripcount <= 0)
             pm_error("The strip count must be positive.  You specified %d",
                      stripcount);
-            
+
         cmdlineP->stripcount = stripcount;
 
         if (argc-1 < 2)
             cmdlineP->inputFileName = "-";
         else
             cmdlineP->inputFileName = argv[2];
-    
+
         if (argc - 1 > 2)
             pm_error("There are at most two arguments: strip count "
                      "and input file name.  "
@@ -113,9 +113,9 @@ main(int argc, char *argv[]) {
     ppm_init(&argc, argv);
 
     parseCommandLine(argc, argv, &cmdline);
-    
+
     ifP = pm_openr(cmdline.inputFileName);
-    
+
     srcPixels = ppm_readppm(ifP, &srcCols, &srcRows, &srcMaxval);
 
     pm_close(ifP);
@@ -139,7 +139,7 @@ main(int argc, char *argv[]) {
                                  &backgroundColor);
 
     dstPixels = ppm_allocarray(dstCols, dstRows);
-    
+
     for (row = 0; row < dstRows; ++row) {
         double const factor = sin(M_PI * row / dstRows);
             /* Amount by which we squeeze the foreground image of each
diff --git a/editor/specialty/ppmntsc.c b/editor/specialty/ppmntsc.c
index 08fbc835..24edc3bd 100644
--- a/editor/specialty/ppmntsc.c
+++ b/editor/specialty/ppmntsc.c
@@ -6,21 +6,21 @@
    The derivation was done by Bryan Henderson on 2000.04.21 to convert
    it from operating on the RLE format to operating on the PPM format
    and to rewrite it in a cleaner style, taking advantage of modern C
-   compiler technology.  
+   compiler technology.
 */
 
 
 /*
  * This software is copyrighted as noted below.  It may be freely copied,
- * modified, and redistributed, provided that the copyright notice is 
+ * modified, and redistributed, provided that the copyright notice is
  * preserved on all copies.
- * 
+ *
  * There is no warranty or other guarantee of fitness for this software,
  * it is provided solely "as is".  Bug reports or fixes may be sent
  * to the author, who may or may not act on them as he desires.
  *
  * You may not include this software in a program or other software product
- * without supplying the source, or without informing the end-user that the 
+ * without supplying the source, or without informing the end-user that the
  * source is available for no extra charge.
  *
  * If you modify this software, you should include a notice giving the
@@ -28,12 +28,12 @@
  * and the reason for such modification.
  */
 
-/* 
+/*
  * rlelegal.c - Make RGB colors legal in the YIQ or YUV color systems.
- * 
- * Author:	Wes Barris
- * 		Minnesota Supercomputer Center, Inc.
- * Date:	Fri Oct 15, 1993
+ *
+ * Author:      Wes Barris
+ *              Minnesota Supercomputer Center, Inc.
+ * Date:        Fri Oct 15, 1993
  * @Copyright, Research Equipment Inc., d/b/a Minnesota Supercomputer
  * Center, Inc., 1993
 
@@ -104,32 +104,32 @@ parseCommandLine(int argc, const char ** argv,
         cmdlineP->inputFilename = "-";  /* he wants stdin */
     else if (argc - 1 == 1)
         cmdlineP->inputFilename = argv[1];
-    else 
+    else
         pm_error("Too many arguments.  The only arguments accepted "
                  "are the mask color and optional input file specification");
 
     if (legalonly + illegalonly + correctedonly > 1)
         pm_error("--legalonly, --illegalonly, and --correctedonly are "
                  "conflicting options.  Specify at most one of these.");
-        
-    if (legalonly) 
+
+    if (legalonly)
         cmdlineP->output = LEGAL_ONLY;
-    else if (illegalonly) 
+    else if (illegalonly)
         cmdlineP->output = ILLEGAL_ONLY;
-    else if (correctedonly) 
+    else if (correctedonly)
         cmdlineP->output = CORRECTED_ONLY;
-    else 
+    else
         cmdlineP->output = ALL;
 }
 
 
 
-static void 
-rgbtoyiq(const int r, const int g, const int b, 
-         double * const y_p, 
-         double * const i_p, 
+static void
+rgbtoyiq(const int r, const int g, const int b,
+         double * const y_p,
+         double * const i_p,
          double * const q_p) {
-    
+
     *y_p = .299*(r/255.0) + .587*(g/255.0) + .114*(b/255.0);
     *i_p = .596*(r/255.0) - .274*(g/255.0) - .322*(b/255.0);
     *q_p = .211*(r/255.0) - .523*(g/255.0) + .312*(b/255.0);
@@ -137,8 +137,8 @@ rgbtoyiq(const int r, const int g, const int b,
 
 
 
-static void 
-yiqtorgb(const double y, const double i, const double q, 
+static void
+yiqtorgb(const double y, const double i, const double q,
          int * const r_p, int * const g_p, int * const b_p) {
     *r_p = 255.0*(1.00*y + .9562*i + .6214*q);
     *g_p = 255.0*(1.00*y - .2727*i - .6468*q);
@@ -147,10 +147,10 @@ yiqtorgb(const double y, const double i, const double q,
 
 
 
-static void 
-rgbtoyuv(const int r, const int g, const int b, 
-         double * const y_p, 
-         double * const u_p, 
+static void
+rgbtoyuv(const int r, const int g, const int b,
+         double * const y_p,
+         double * const u_p,
          double * const v_p) {
     *y_p =  .299*(r/255.0) + .587*(g/255.0) + .114*(b/255.0);
     *u_p = -.147*(r/255.0) - .289*(g/255.0) + .437*(b/255.0);
@@ -159,10 +159,10 @@ rgbtoyuv(const int r, const int g, const int b,
 
 
 
-static void 
-yuvtorgb(const double y, const double u, const double v, 
+static void
+yuvtorgb(const double y, const double u, const double v,
          int * const r_p, int * const g_p, int * const b_p) {
-    
+
     *r_p = 255.0*(1.00*y + .0000*u +1.1398*v);
     *g_p = 255.0*(1.00*y - .3938*u - .5805*v);
     *b_p = 255.0*(1.00*y +2.0279*u + .0000*v);
@@ -173,12 +173,12 @@ yuvtorgb(const double y, const double u, const double v,
 static void
 makeLegalYiq(double          const y,
              double          const i,
-             double          const q, 
-             double *        const yNewP, 
-             double *        const iNewP, 
+             double          const q,
+             double *        const yNewP,
+             double *        const iNewP,
              double *        const qNewP,
              enum legalize * const actionP) {
-    
+
     double satOld, satNew;
     /*
      * I and Q are legs of a right triangle.  Saturation is the hypotenuse.
@@ -209,13 +209,13 @@ makeLegalYiq(double          const y,
 
 
 static void
-make_legal_yuv(const double y, const double u, const double v, 
-               double * const y_new_p, 
-               double * const u_new_p, 
+make_legal_yuv(const double y, const double u, const double v,
+               double * const y_new_p,
+               double * const u_new_p,
                double * const v_new_p,
                enum legalize * const action_p
     ) {
-    
+
     double sat_old, sat_new;
     /*
      * U and V are legs of a right triangle.  Saturation is the hypotenuse.
@@ -246,13 +246,13 @@ make_legal_yuv(const double y, const double u, const double v,
 
 
 static void
-make_legal_yiq_i(const int r_in, const int g_in, const int b_in, 
-                 int * const r_out_p, 
-                 int * const g_out_p, 
+make_legal_yiq_i(const int r_in, const int g_in, const int b_in,
+                 int * const r_out_p,
+                 int * const g_out_p,
                  int * const b_out_p,
                  enum legalize * const action_p
     ) {
-    
+
     double y, i, q;
     double y_new, i_new, q_new;
     /*
@@ -276,15 +276,15 @@ make_legal_yiq_i(const int r_in, const int g_in, const int b_in,
 
 
 static void
-make_legal_yuv_i(const int r_in, const int g_in, const int b_in, 
-                 int * const r_out_p, 
-                 int * const g_out_p, 
+make_legal_yuv_i(const int r_in, const int g_in, const int b_in,
+                 int * const r_out_p,
+                 int * const g_out_p,
                  int * const b_out_p,
                  enum legalize * const action_p
     ){
-    
+
     double y, u, v;
-    double y_new, u_new, v_new;  
+    double y_new, u_new, v_new;
     /*
      * Convert to YUV and compute the new saturation.
      */
@@ -305,7 +305,7 @@ make_legal_yuv_i(const int r_in, const int g_in, const int b_in,
 
 
 
-static void 
+static void
 make_legal_yiq_b(const pixel input,
                  pixel * const output_p,
                  enum legalize * const action_p) {
@@ -313,7 +313,7 @@ make_legal_yiq_b(const pixel input,
 
     int ir_in, ig_in, ib_in;
     int ir_out, ig_out, ib_out;
-    
+
     ir_in = (int)PPM_GETR(input);
     ig_in = (int)PPM_GETG(input);
     ib_in = (int)PPM_GETB(input);
@@ -327,14 +327,14 @@ make_legal_yiq_b(const pixel input,
 
 
 
-static void 
+static void
 make_legal_yuv_b(const pixel input,
                  pixel * const output_p,
                  enum legalize * const action_p) {
 
     int ir_in, ig_in, ib_in;
     int ir_out, ig_out, ib_out;
-    
+
     ir_in = (int)PPM_GETR(input);
     ig_in = (int)PPM_GETG(input);
     ib_in = (int)PPM_GETB(input);
@@ -347,7 +347,7 @@ make_legal_yuv_b(const pixel input,
 
 
 
-static void 
+static void
 reportMapping(pixel const oldPixel,
               pixel const newPixel) {
 /*----------------------------------------------------------------------------
@@ -358,7 +358,7 @@ reportMapping(pixel const oldPixel,
     static pixel lastChangedPixel;
     static bool firstTime = true;
 
-    if (!PPM_EQUAL(oldPixel, newPixel) && 
+    if (!PPM_EQUAL(oldPixel, newPixel) &&
         (firstTime || PPM_EQUAL(oldPixel, lastChangedPixel))) {
         pm_message("Mapping %u %u %u -> %u %u %u\n",
                    PPM_GETR(oldPixel),
@@ -371,14 +371,14 @@ reportMapping(pixel const oldPixel,
 
         lastChangedPixel = oldPixel;
         firstTime = false;
-    }    
+    }
 }
 
 
 
 static void
 convertOneImage(FILE *             const ifP,
-                struct cmdlineInfo const cmdline, 
+                struct cmdlineInfo const cmdline,
                 unsigned int *     const hiCountP,
                 unsigned int *     const loCountP) {
 
@@ -419,8 +419,8 @@ convertOneImage(FILE *             const ifP,
                         make_legal_yiq_b(inputRow[col],
                                          &corrected,
                                          &action);
-                        
-                    if (action == LOWER_SAT) 
+
+                    if (action == LOWER_SAT)
                         ++*hiCountP;
                     if (action == RAISE_SAT)
                         ++*loCountP;
@@ -456,7 +456,7 @@ convertOneImage(FILE *             const ifP,
 
 int
 main(int argc, const char **argv) {
-    
+
     struct cmdlineInfo cmdline;
     FILE * ifP;
     unsigned int totalHiCount, totalLoCount;
@@ -469,7 +469,7 @@ main(int argc, const char **argv) {
     parseCommandLine(argc, argv, &cmdline);
 
     ifP = pm_openr(cmdline.inputFilename);
-    
+
     imageCount = 0;    /* initial value */
     totalHiCount = 0;  /* initial value */
     totalLoCount = 0;  /* initial value */
@@ -488,14 +488,14 @@ main(int argc, const char **argv) {
     }
 
 
-	if (cmdline.verbose) {
+        if (cmdline.verbose) {
         pm_message("%u images processed.", imageCount);
-        pm_message("%u pixels were above the saturation limit.", 
+        pm_message("%u pixels were above the saturation limit.",
                    totalHiCount);
-        pm_message("%u pixels were below the saturation limit.", 
+        pm_message("%u pixels were below the saturation limit.",
                    totalLoCount);
     }
-    
+
     pm_close(ifP);
 
     return 0;
diff --git a/editor/specialty/ppmrelief.c b/editor/specialty/ppmrelief.c
index 14a6d0a8..94453bdd 100644
--- a/editor/specialty/ppmrelief.c
+++ b/editor/specialty/ppmrelief.c
@@ -85,7 +85,7 @@ main(int argc, const char * argv[]) {
         for (col = 0; col < cols - 2; ++col) {
             pixel const inputA = inputbuf[rowa][col];
             pixel const inputB = inputbuf[rowb][col + 2];
-            
+
             pixval const r =
                 clip(PPM_GETR(inputA) + (mv2 - PPM_GETR(inputB)), maxval);
             pixval const g =
diff --git a/editor/specialty/ppmshift.c b/editor/specialty/ppmshift.c
index cdb0f173..37ed3785 100644
--- a/editor/specialty/ppmshift.c
+++ b/editor/specialty/ppmshift.c
@@ -1,4 +1,3 @@
-
 /*********************************************************************/
 /* ppmshift -  shift lines of a picture left or right by x pixels    */
 /* Frank Neumann, October 1993                                       */
@@ -12,11 +11,11 @@
 #include <stdbool.h>
 
 #include "mallocvar.h"
+#include "rand.h"
 #include "shhopt.h"
 #include "ppm.h"
 
 
-
 struct CmdlineInfo {
     /* All the information the user supplied in the command line,
        in a form easy for the program to use.
@@ -24,6 +23,7 @@ struct CmdlineInfo {
     const char * inputFileName;
 
     unsigned int shift;
+    unsigned int seedSpec;
     unsigned int seed;
 };
 
@@ -42,8 +42,6 @@ parseCommandLine(int argc, const char ** const argv,
 
     unsigned int option_def_index;
 
-    unsigned int seedSpec;
-
     MALLOCARRAY(option_def, 100);
 
     opt.opt_table = option_def;
@@ -52,14 +50,11 @@ parseCommandLine(int argc, const char ** const argv,
 
     option_def_index = 0;   /* incremented by OPTENT3 */
     OPTENT3(0,   "seed",            OPT_UINT,     &cmdlineP->seed,
-            &seedSpec,         0);
+            &cmdlineP->seedSpec,         0);
 
     pm_optParseOptions3(&argc, (char **)argv, opt, sizeof(opt), 0);
         /* Uses and sets argc, argv, and some of *cmdlineP and others. */
 
-    if (!seedSpec)
-        cmdlineP->seed = pm_randseed();
-
     if (argc-1 < 1)
         pm_error("You must specify the shift factor as an argument");
     else {
@@ -84,6 +79,62 @@ parseCommandLine(int argc, const char ** const argv,
 
 
 
+static void
+shiftRow(pixel *            const srcrow,
+         unsigned int       const cols,
+         unsigned int       const shift,
+         pixel *            const destrow,
+         struct pm_randSt * const randStP) {
+
+    /* the range by which a line is shifted lays in the range from */
+    /* -shift/2 .. +shift/2 pixels; however, within this range it is */
+    /* randomly chosen */
+
+    pixel * pP;
+    pixel * pP2;
+    int nowshift;
+
+    if (shift != 0)
+        nowshift = (pm_rand(randStP) % (shift+1)) - ((shift+1) / 2);
+    else
+        nowshift = 0;
+
+    pP  = &srcrow[0];
+    pP2 = &destrow[0];
+
+    /* if the shift value is less than zero, we take the original
+       pixel line and copy it into the destination line translated
+       to the left by x pixels. The empty pixels on the right end
+       of the destination line are filled up with the pixel that
+       is the right-most in the original pixel line.
+    */
+    if (nowshift < 0) {
+        unsigned int col;
+        pP += abs(nowshift);
+        for (col = 0; col < cols; ++col) {
+            PPM_ASSIGN(*pP2, PPM_GETR(*pP), PPM_GETG(*pP), PPM_GETB(*pP));
+            ++pP2;
+            if (col < (cols + nowshift) - 1)
+                ++pP;
+        }
+    } else {
+        unsigned int col;
+        /* The shift value is 0 or positive, so fill the first
+           <nowshift> pixels of the destination line with the
+           first pixel from the source line, and copy the rest of
+           the source line to the dest line
+        */
+        for (col = 0; col < cols; ++col) {
+            PPM_ASSIGN(*pP2, PPM_GETR(*pP), PPM_GETG(*pP), PPM_GETB(*pP));
+            ++pP2;
+            if (col >= nowshift)
+                ++pP;
+        }
+    }
+}
+
+
+
 int
 main(int argc, const char ** argv) {
 
@@ -95,13 +146,15 @@ main(int argc, const char ** argv) {
     pixel * destrow;
     unsigned int row;
     unsigned int shift;
+    struct pm_randSt randSt;
 
     /* parse in 'default' parameters */
     pm_proginit(&argc, argv);
 
     parseCommandLine(argc, argv, &cmdline);
 
-    srand(cmdline.seed);
+    pm_randinit(&randSt);
+    pm_srand2(&randSt, cmdline.seedSpec, cmdline.seed);
 
     ifP = pm_openr(cmdline.inputFileName);
 
@@ -115,67 +168,23 @@ main(int argc, const char ** argv) {
     } else
         shift = cmdline.shift;
 
-    srcrow = ppm_allocrow(cols);
-
+    srcrow  = ppm_allocrow(cols);
     destrow = ppm_allocrow(cols);
 
     ppm_writeppminit(stdout, cols, rows, maxval, 0);
 
-    /** now do the shifting **/
-    /* the range by which a line is shifted lays in the range from */
-    /* -shift/2 .. +shift/2 pixels; however, within this range it is */
-    /* randomly chosen */
     for (row = 0; row < rows; ++row) {
-        pixel * pP;
-        pixel * pP2;
-        unsigned int nowshift;
-
-        if (shift != 0)
-            nowshift = (rand() % (shift+1)) - ((shift+1) / 2);
-        else
-            nowshift = 0;
-
         ppm_readppmrow(ifP, srcrow, cols, maxval, format);
 
-        pP  = &srcrow[0];
-        pP2 = &destrow[0];
-
-        /* if the shift value is less than zero, we take the original
-           pixel line and copy it into the destination line translated
-           to the left by x pixels. The empty pixels on the right end
-           of the destination line are filled up with the pixel that
-           is the right-most in the original pixel line.
-        */
-        if (nowshift < 0) {
-            unsigned int col;
-            pP += abs(nowshift);
-            for (col = 0; col < cols; ++col) {
-                PPM_ASSIGN(*pP2, PPM_GETR(*pP), PPM_GETG(*pP), PPM_GETB(*pP));
-                ++pP2;
-                if (col < (cols + nowshift) - 1)
-                    ++pP;
-            }
-        } else {
-            unsigned int col;
-            /* The shift value is 0 or positive, so fill the first
-               <nowshift> pixels of the destination line with the
-               first pixel from the source line, and copy the rest of
-               the source line to the dest line
-            */
-            for (col = 0; col < cols; ++col) {
-                PPM_ASSIGN(*pP2, PPM_GETR(*pP), PPM_GETG(*pP), PPM_GETB(*pP));
-                ++pP2;
-                if (col >= nowshift)
-                    ++pP;
-            }
-        }
+        shiftRow(srcrow, cols, shift, destrow, &randSt);
 
         ppm_writeppmrow(stdout, destrow, cols, maxval, 0);
     }
 
-    pm_close(ifP);
-    ppm_freerow(srcrow);
     ppm_freerow(destrow);
+    ppm_freerow(srcrow);
+    pm_close(ifP);
+    pm_randterm(&randSt);
 
     return 0;
 }
diff --git a/editor/specialty/ppmspread.c b/editor/specialty/ppmspread.c
index 6753f4fe..7b9558e3 100644
--- a/editor/specialty/ppmspread.c
+++ b/editor/specialty/ppmspread.c
@@ -10,102 +10,158 @@
 
 #include <string.h>
 
+#include "nstring.h"
+#include "rand.h"
+#include "shhopt.h"
 #include "ppm.h"
 
 
+struct CmdlineInfo {
+    /* This structure represents all of the information the user
+       supplied in the command line but in a form that's easy for the
+       program to use.
+    */
+    const char * inputFilename;  /* '-' if stdin */
+    unsigned int spread;
+    unsigned int randomseedSpec;
+    unsigned int randomseed;
+};
+
+
+
+static void
+parseCommandLine(int argc, const char ** const argv,
+                 struct CmdlineInfo * const cmdlineP ) {
+
+    optEntry     * option_def;
+        /* Instructions to OptParseOptions3 on how to parse our options */
+    optStruct3     opt;
+    unsigned int   option_def_index;
+
+    MALLOCARRAY_NOFAIL(option_def, 100);
+    option_def_index = 0;          /* Incremented by OPTENTRY */
+
+    OPTENT3(0, "randomseed", OPT_UINT,   &cmdlineP->randomseed,
+            &cmdlineP->randomseedSpec, 0);
+
+    opt.opt_table = option_def;
+    opt.short_allowed = 0;
+    opt.allowNegNum = 1;
+
+    pm_optParseOptions3( &argc, (char **)argv, opt, sizeof(opt), 0 );
+
+    if (argc-1 < 1)
+        pm_error("You must specify the spread factor as an argument");
+    else {
+        const char * error;
+        pm_string_to_uint(argv[1], &cmdlineP->spread, &error);
+
+        if (error)
+            pm_error("Spread factor '%s' is not an unsigned integer.  %s",
+                     argv[1], error);
+
+        if (argc-1 < 2)
+            cmdlineP->inputFilename = "-";
+        else {
+            cmdlineP->inputFilename = argv[2];
+            if (argc-1 >2)
+                pm_error("Too many arguments: %u.  "
+                         "The only possible arguments are "
+                         "the spread factor and the optional input file name",
+                         argc-1);
+        }
+    }
+}
+
+
+
+static void
+spreadRow(pixel **           const srcarray,
+          unsigned int       const cols,
+          unsigned int       const rows,
+          unsigned int       const spread,
+          unsigned int       const row,
+          pixel **           const destarray,
+          struct pm_randSt * const randStP) {
+
+    unsigned int col;
+
+    for (col = 0; col < cols; ++col) {
+        pixel const p = srcarray[row][col];
+
+        int const xdis = (pm_rand(randStP) % (spread + 1) )
+            - ((spread + 1) / 2);
+        int const ydis = (pm_rand(randStP) % (spread + 1))
+            - ((spread + 1) / 2);
+
+        int const xnew = col + xdis;
+        int const ynew = row + ydis;
+
+        /* only set the displaced pixel if it's within the bounds
+           of the image
+        */
+        if (xnew >= 0 && xnew < cols && ynew >= 0 && ynew < rows) {
+            /* Displacing a pixel is accomplished by swapping it
+               with another pixel in its vicinity.
+            */
+            pixel const p2 = srcarray[ynew][xnew];
+                /* Original value of second pixel */
+
+            /* Set second pixel to new value */
+            PPM_ASSIGN(destarray[ynew][xnew],
+                       PPM_GETR(p), PPM_GETG(p), PPM_GETB(p));
+
+            /* Set first pixel to (old) value of second */
+            PPM_ASSIGN(destarray[row][col],
+                       PPM_GETR(p2), PPM_GETG(p2), PPM_GETB(p2));
+        } else {
+            /* Displaced pixel is out of bounds; leave the old pixel there.
+            */
+            PPM_ASSIGN(destarray[row][col],
+                       PPM_GETR(p), PPM_GETG(p), PPM_GETB(p));
+        }
+    }
+}
+
+
 
 int
-main(int    argc,
-     char * argv[]) {
+main(int          argc,
+     const char * argv[]) {
 
+    struct CmdlineInfo cmdline;
     FILE * ifP;
-    int argn, rows, cols;
+    int rows, cols;
     unsigned int row;
-    pixel ** destarray, ** srcarray;
-    pixel * pP;
-    pixel * pP2;
+    pixel ** destarray;
+    pixel ** srcarray;
     pixval maxval;
-    pixval r1, g1, b1;
-    int amount;
-    const char * const usage = "amount [ppmfile]\n        amount: # of pixels to displace a pixel by at most\n";
-
-    /* parse in 'default' parameters */
-    ppm_init(&argc, argv);
-
-    argn = 1;
-
-    /* parse in amount & seed */
-    if (argn == argc)
-        pm_usage(usage);
-    if (sscanf(argv[argn], "%d", &amount) != 1)
-        pm_usage(usage);
-    if (amount < 0)
-        pm_error("amount should be a positive number");
-    ++argn;
-
-    /* parse in filename (if present, stdin otherwise) */
-    if (argn != argc)
-    {
-        ifP = pm_openr(argv[argn]);
-        ++argn;
-    }
-    else
-        ifP = stdin;
+    struct pm_randSt randSt;
 
-    if (argn != argc)
-        pm_usage(usage);
+    pm_proginit(&argc, argv);
+
+    parseCommandLine(argc, argv, &cmdline);
+
+    ifP = pm_openr(cmdline.inputFilename);
 
     srcarray = ppm_readppm(ifP, &cols, &rows, &maxval);
 
     destarray = ppm_allocarray(cols, rows);
 
+    pm_randinit(&randSt);
+    pm_srand2(&randSt, cmdline.randomseedSpec, cmdline.randomseed);
+
     /* clear out the buffer */
     for (row = 0; row < rows; ++row)
         memset(destarray[row], 0, cols * sizeof(pixel));
 
-    srand(pm_randseed());
-
-    /* start displacing pixels */
+    /* Displace pixels */
     for (row = 0; row < rows; ++row) {
-        unsigned int col;
-        pP = &srcarray[row][0];
-
-        for (col = 0; col < cols; ++col) {
-            int const xdis = (rand() % (amount+1)) - ((amount+1) / 2);
-            int const ydis = (rand() % (amount+1)) - ((amount+1) / 2);
+        spreadRow(srcarray, cols, rows, cmdline.spread, row,
+                  destarray, &randSt);
 
-            int const xnew = col + xdis;
-            int const ynew = row + ydis;
-
-            /* only set the displaced pixel if it's within the bounds
-               of the image
-            */
-            if (xnew >= 0 && xnew < cols && ynew >= 0 && ynew < rows) {
-                /* displacing a pixel is accomplished by swapping it
-                   with another pixel in its vicinity - so, first
-                   store other pixel's RGB
-                */
-                pP2 = &srcarray[ynew][xnew];
-                r1 = PPM_GETR(*pP2);
-                g1 = PPM_GETG(*pP2);
-                b1 = PPM_GETB(*pP2);
-                /* set second pixel to new value */
-                pP2 = &destarray[ynew][xnew];
-                PPM_ASSIGN(*pP2, PPM_GETR(*pP), PPM_GETG(*pP), PPM_GETB(*pP));
-                
-                /* now, set first pixel to (old) value of second */
-                pP2 = &destarray[row][col];
-                PPM_ASSIGN(*pP2, r1, g1, b1);
-            } else {
-                /* displaced pixel is out of bounds; leave the old
-                   pixel there
-                */
-                pP2 = &destarray[row][col];
-                PPM_ASSIGN(*pP2, PPM_GETR(*pP), PPM_GETG(*pP), PPM_GETB(*pP));
-            }
-            ++pP;
-        }
     }
+    pm_randterm(&randSt);
 
     ppm_writeppm(stdout, destarray, cols, rows, maxval, 0);
 
@@ -115,3 +171,5 @@ main(int    argc,
 
     return 0;
 }
+
+
diff --git a/editor/specialty/ppmtv.c b/editor/specialty/ppmtv.c
index da25102a..7e540e34 100644
--- a/editor/specialty/ppmtv.c
+++ b/editor/specialty/ppmtv.c
@@ -1,4 +1,3 @@
-
 /*********************************************************************/
 /* ppmtv -  make a 'look-alike ntsc' picture from a PPM file       */
 /* Frank Neumann, October 1993                                       */
@@ -18,88 +17,88 @@ int main(argc, argv)
 int argc;
 char *argv[];
 {
-	FILE* ifp;
-	int argn, rows, cols, format, i = 0, j = 0;
-	pixel *srcrow, *destrow;
-	pixel *pP = NULL, *pP2 = NULL;
-	pixval maxval;
-	double dimfactor;
-	long longfactor;
-	const char * const usage = "dimfactor [ppmfile]\n        dimfactor: 0.0 = total blackness, 1.0 = original picture\n";
-
-	/* parse in 'default' parameters */
-	ppm_init(&argc, argv);
-
-	argn = 1;
-
-	/* parse in dim factor */
-	if (argn == argc)
-		pm_usage(usage);
-	if (sscanf(argv[argn], "%lf", &dimfactor) != 1)
-		pm_usage(usage);
-	if (dimfactor < 0.0 || dimfactor > 1.0)
-		pm_error("dim factor must be in the range from 0.0 to 1.0 ");
-	++argn;
-
-	/* parse in filename (if present, stdin otherwise) */
-	if (argn != argc)
-	{
-		ifp = pm_openr(argv[argn]);
-		++argn;
-	}
-	else
-		ifp = stdin;
-
-	if (argn != argc)
-		pm_usage(usage);
-
-	/* read first data from file */
-	ppm_readppminit(ifp, &cols, &rows, &maxval, &format);
-
-	/* no error checking required here, ppmlib does it all for us */
-	srcrow = ppm_allocrow(cols);
-
-	longfactor = (long)(dimfactor * 65536);
-
-	/* allocate a row of pixel data for the new pixels */
-	destrow = ppm_allocrow(cols);
-
-	ppm_writeppminit(stdout, cols, rows, maxval, 0);
-
-	/** now do the ntsc'ing (actually very similar to ppmdim) **/
-	for (i = 0; i < rows; i++)
-	{
-		ppm_readppmrow(ifp, srcrow, cols, maxval, format);
-
-		pP = srcrow;
-		pP2 = destrow;
-
-		for (j = 0; j < cols; j++)
-		{
-			/* every alternating row is left in unchanged condition */
-			if (i & 1)
-			{
-				PPM_ASSIGN(*pP2, PPM_GETR(*pP), PPM_GETG(*pP), PPM_GETB(*pP));
-			}
-			/* and the other lines are dimmed to the specified factor */
-			else
-			{
-				PPM_ASSIGN(*pP2, (PPM_GETR(*pP) * longfactor) >> 16,
-								 (PPM_GETG(*pP) * longfactor) >> 16,
-								 (PPM_GETB(*pP) * longfactor) >> 16);
-			}
-			pP++;
-			pP2++;
-		}
-
-		/* write out one line of graphic data */
-		ppm_writeppmrow(stdout, destrow, cols, maxval, 0);
-	}
-
-	pm_close(ifp);
-	ppm_freerow(srcrow);
-	ppm_freerow(destrow);
-
-	exit(0);
+        FILE* ifp;
+        int argn, rows, cols, format, i = 0, j = 0;
+        pixel *srcrow, *destrow;
+        pixel *pP = NULL, *pP2 = NULL;
+        pixval maxval;
+        double dimfactor;
+        long longfactor;
+        const char * const usage = "dimfactor [ppmfile]\n        dimfactor: 0.0 = total blackness, 1.0 = original picture\n";
+
+        /* parse in 'default' parameters */
+        ppm_init(&argc, argv);
+
+        argn = 1;
+
+        /* parse in dim factor */
+        if (argn == argc)
+                pm_usage(usage);
+        if (sscanf(argv[argn], "%lf", &dimfactor) != 1)
+                pm_usage(usage);
+        if (dimfactor < 0.0 || dimfactor > 1.0)
+                pm_error("dim factor must be in the range from 0.0 to 1.0 ");
+        ++argn;
+
+        /* parse in filename (if present, stdin otherwise) */
+        if (argn != argc)
+        {
+                ifp = pm_openr(argv[argn]);
+                ++argn;
+        }
+        else
+                ifp = stdin;
+
+        if (argn != argc)
+                pm_usage(usage);
+
+        /* read first data from file */
+        ppm_readppminit(ifp, &cols, &rows, &maxval, &format);
+
+        /* no error checking required here, ppmlib does it all for us */
+        srcrow = ppm_allocrow(cols);
+
+        longfactor = (long)(dimfactor * 65536);
+
+        /* allocate a row of pixel data for the new pixels */
+        destrow = ppm_allocrow(cols);
+
+        ppm_writeppminit(stdout, cols, rows, maxval, 0);
+
+        /** now do the ntsc'ing (actually very similar to ppmdim) **/
+        for (i = 0; i < rows; i++)
+        {
+                ppm_readppmrow(ifp, srcrow, cols, maxval, format);
+
+                pP = srcrow;
+                pP2 = destrow;
+
+                for (j = 0; j < cols; j++)
+                {
+                        /* every alternating row is left in unchanged condition */
+                        if (i & 1)
+                        {
+                                PPM_ASSIGN(*pP2, PPM_GETR(*pP), PPM_GETG(*pP), PPM_GETB(*pP));
+                        }
+                        /* and the other lines are dimmed to the specified factor */
+                        else
+                        {
+                                PPM_ASSIGN(*pP2, (PPM_GETR(*pP) * longfactor) >> 16,
+                                                                 (PPM_GETG(*pP) * longfactor) >> 16,
+                                                                 (PPM_GETB(*pP) * longfactor) >> 16);
+                        }
+                        pP++;
+                        pP2++;
+                }
+
+                /* write out one line of graphic data */
+                ppm_writeppmrow(stdout, destrow, cols, maxval, 0);
+        }
+
+        pm_close(ifp);
+        ppm_freerow(srcrow);
+        ppm_freerow(destrow);
+
+        exit(0);
 }
 
diff --git a/generator/Makefile b/generator/Makefile
index d54a6cc5..761181bd 100644
--- a/generator/Makefile
+++ b/generator/Makefile
@@ -18,7 +18,7 @@ SUBDIRS = pamtris
 
 PORTBINARIES = pamcrater pamgauss pamgradient \
 	       pamseq pamshadedrelief pamstereogram \
-	       pbmpage pbmmake pbmtext pbmupc \
+	       pbmpage pbmmake pbmnoise pbmtext pbmupc \
 	       pgmkernel pgmmake pgmnoise pgmramp \
 	       ppmcie ppmcolors ppmforge ppmmake ppmpat ppmrough ppmwheel \
 
diff --git a/generator/pamcrater.c b/generator/pamcrater.c
index 43c27dbc..8f0e422d 100644
--- a/generator/pamcrater.c
+++ b/generator/pamcrater.c
@@ -48,6 +48,7 @@
 
 #include "pm_c_util.h"
 #include "mallocvar.h"
+#include "rand.h"
 #include "shhopt.h"
 #include "nstring.h"
 #include "pam.h"
@@ -162,18 +163,18 @@ parseCommandLine(int argc, const char ** const argv,
 
 
 
-static double const arand       = 32767.0;  /* Random number parameters */
 static double const CdepthPower = 1.5;      /* Crater depth power factor */
 static double const DepthBias2  = 0.5;      /* Square of depth bias */
 
 
 
 static double const
-cast(double const high) {
+cast(double             const high,
+     struct pm_randSt * const randStP) {
 /*----------------------------------------------------------------------------
    A random number in the range [0, 'high'].
 -----------------------------------------------------------------------------*/
-    return high * ((rand() & 0x7FFF) / arand);
+  return high * ((double) pm_rand(randStP) / randStP->max);
 }
 
 
@@ -220,7 +221,6 @@ terrainModP(struct pam * const pamP,
 
 
 
-
 static sample
 terrainMod(struct pam * const pamP,
            tuple **     const terrain,
@@ -252,11 +252,12 @@ setElev(struct pam * const pamP,
 
 
 static void
-smallCrater(struct pam * const pamP,
-            tuple **     const terrain,
-            int          const cx,
-            int          const cy,
-            double       const radius) {
+smallCrater(struct pam *       const pamP,
+            tuple **           const terrain,
+            int                const cx,
+            int                const cy,
+            double             const radius,
+            struct pm_randSt * const randStP) {
 /*----------------------------------------------------------------------------
    Generate a crater with a special method for tiny craters.
 
@@ -283,10 +284,10 @@ smallCrater(struct pam * const pamP,
             /* The mean elevation of the Moore neighborhood (9 pixels
                centered on the crater location).
             */
-        
+
         /* Perturb the mean elevation by a small random factor. */
 
-        int const x = radius >= 1 ? ((rand() >> 8) & 0x3) - 1 : 0;
+        int const x = radius >= 1 ? ((pm_rand(randStP) >> 8) & 0x3) - 1 : 0;
 
         assert(axelev > 0);
 
@@ -374,7 +375,7 @@ normalCrater(struct pam * const pamP,
                 av = (axelev + cz) * (1 - roll) +
                     (terrainMod(pamP, terrain, x, y) + cz) * roll;
                 av = MAX(1000, MIN(64000, av));
-                
+
                 setElev(pamP, terrain, x, y, av);
             }
         }
@@ -388,19 +389,20 @@ normalCrater(struct pam * const pamP,
 
 
 static void
-plopCrater(struct pam * const pamP,
-           tuple **     const terrain,
-           int          const cx,
-           int          const cy,
-           double       const radius,
-           bool         const verbose) {
+plopCrater(struct pam *       const pamP,
+           tuple **           const terrain,
+           int                const cx,
+           int                const cy,
+           double             const radius,
+           bool               const verbose,
+           struct pm_randSt * const randStP) {
 
     if (verbose && pm_have_float_format())
         pm_message("Plopping crater at (%4d, %4d) with radius %g",
                    cx, cy, radius);
 
     if (radius < 3)
-        smallCrater (pamP, terrain, cx, cy, radius);
+        smallCrater (pamP, terrain, cx, cy, radius, randStP);
     else
         normalCrater(pamP, terrain, cx, cy, radius);
 }
@@ -448,6 +450,7 @@ genCraters(struct CmdlineInfo const cmdline) {
 -----------------------------------------------------------------------------*/
     tuple ** terrain;    /* elevation array */
     struct pam pam;
+    struct pm_randSt randSt;
 
     /* Allocate the elevation array and initialize it to mean surface
        elevation.
@@ -455,18 +458,22 @@ genCraters(struct CmdlineInfo const cmdline) {
 
     initCanvas(cmdline.width, cmdline.height, &pam, &terrain);
 
+    pm_randinit(&randSt);
+    pm_srand2(&randSt, cmdline.randomseedSpec, cmdline.randomseed);
+
     if (cmdline.test)
         plopCrater(&pam, terrain,
                    pam.width/2 + cmdline.offset,
                    pam.height/2 + cmdline.offset,
-                   (double) cmdline.radius, cmdline.verbose);
+                   (double) cmdline.radius, cmdline.verbose,
+                   &randSt);
     else {
         unsigned int const ncraters = cmdline.number; /* num of craters */
         unsigned int l;
 
         for (l = 0; l < ncraters; ++l) {
-            int const cx = cast((double) pam.width  - 1);
-            int const cy = cast((double) pam.height - 1);
+            int const cx = cast((double) pam.width  - 1, &randSt);
+            int const cy = cast((double) pam.height - 1, &randSt);
 
             /* Thanks, Rudy, for this equation that maps the uniformly
                distributed numbers from cast() into an area-law distribution
@@ -475,9 +482,11 @@ genCraters(struct CmdlineInfo const cmdline) {
                Produces values within the interval:
                0.56419 <= radius <= 56.419
             */
-            double const radius = sqrt(1 / (M_PI * (1 - cast(0.9999))));
+            double const radius =
+                sqrt(1 / (M_PI * (1 - cast(0.9999, &randSt))));
 
-            plopCrater(&pam, terrain, cx, cy, radius, cmdline.verbose);
+            plopCrater(&pam, terrain, cx, cy, radius,
+                       cmdline.verbose, &randSt);
 
             if (((l + 1) % 100000) == 0)
                 pm_message("%u craters generated of %u (%u%% done)",
@@ -485,6 +494,8 @@ genCraters(struct CmdlineInfo const cmdline) {
         }
     }
 
+    pm_randterm(&randSt);
+
     pnm_writepam(&pam, terrain);
 
     pnm_freepamarray(terrain, &pam);
@@ -503,8 +514,6 @@ main(int argc, const char ** argv) {
 
     parseCommandLine(argc, argv, &cmdline);
 
-    srand(cmdline.randomseedSpec ? cmdline.randomseed : pm_randseed());
-
     genCraters(cmdline);
 
     return 0;
diff --git a/generator/pamgauss.c b/generator/pamgauss.c
index 9656708b..5553e757 100644
--- a/generator/pamgauss.c
+++ b/generator/pamgauss.c
@@ -31,11 +31,11 @@ static void
 parseCommandLine(int argc, const char ** argv,
                  struct CmdlineInfo * const cmdlineP) {
 /*----------------------------------------------------------------------------
-  Convert program invocation arguments (argc,argv) into a format the 
+  Convert program invocation arguments (argc,argv) into a format the
   program can use easily, struct cmdlineInfo.  Validate arguments along
   the way and exit program with message if invalid.
 
-  Note that some string information we return as *cmdlineP is in the storage 
+  Note that some string information we return as *cmdlineP is in the storage
   argv[] points to.
 -----------------------------------------------------------------------------*/
     optEntry * option_def;
@@ -49,11 +49,11 @@ parseCommandLine(int argc, const char ** argv,
     MALLOCARRAY_NOFAIL(option_def, 100);
 
     option_def_index = 0;   /* incremented by OPTENTRY */
-    OPTENT3(0,   "tupletype",  OPT_STRING, &cmdlineP->tupletype, 
+    OPTENT3(0,   "tupletype",  OPT_STRING, &cmdlineP->tupletype,
             &tupletypeSpec,      0);
-    OPTENT3(0,   "maxval",     OPT_UINT,   &cmdlineP->maxval, 
+    OPTENT3(0,   "maxval",     OPT_UINT,   &cmdlineP->maxval,
             &maxvalSpec,         0);
-    OPTENT3(0,   "sigma",      OPT_FLOAT,  &cmdlineP->sigma, 
+    OPTENT3(0,   "sigma",      OPT_FLOAT,  &cmdlineP->sigma,
             &sigmaSpec,          0);
     OPTENT3(0,   "maximize",   OPT_FLAG,   NULL,
             &cmdlineP->maximize, 0);
@@ -75,12 +75,12 @@ parseCommandLine(int argc, const char ** argv,
             pm_error("The tuple type you specified is too long.  "
                      "Maximum %u characters.",
                      (unsigned)sizeof(pam.tuple_type)-1);
-    }        
+    }
 
     if (!sigmaSpec)
         pm_error("You must specify the -sigma option.");
     else if (cmdlineP->sigma <= 0.0)
-        pm_error("-sigma must be positive.  You specified %f", 
+        pm_error("-sigma must be positive.  You specified %f",
                  cmdlineP->sigma);
 
     if (!maxvalSpec)
@@ -91,7 +91,7 @@ parseCommandLine(int argc, const char ** argv,
                      "Maximum is %u", cmdlineP->maxval, PNM_OVERALLMAXVAL);
         if (cmdlineP->maxval < 1)
             pm_error("-maxval must be at least 1");
-    }    
+    }
 
     if (oversampleSpec) {
         if (cmdlineP->oversample < 1)
@@ -106,8 +106,8 @@ parseCommandLine(int argc, const char ** argv,
         pm_error("Only two arguments allowed: width and height.  "
                  "You specified %d", argc-1);
     else {
-        cmdlineP->width = atoi(argv[1]);
-        cmdlineP->height = atoi(argv[2]);
+        cmdlineP->width  = pm_parse_width(argv[1]);
+        cmdlineP->height = pm_parse_height(argv[2]);
         if (cmdlineP->width <= 0)
             pm_error("width argument must be a positive number.  You "
                      "specified '%s'", argv[1]);
@@ -164,7 +164,7 @@ pixelValue(unsigned int const width,
   The gaussian function has standard deviation 'sigma' and amplitude 1.
 -----------------------------------------------------------------------------*/
     double const offset = 1.0 / (subpixDivision * 2);
-    double const y0     = (double)row + offset; 
+    double const y0     = (double)row + offset;
     double const x0     = (double)col + offset;
 
     double const subpixSize = 1.0 / subpixDivision;
@@ -236,7 +236,7 @@ maximumKernelValue(double **    const kernel,
        we know the maximum value is at the center.
     */
     return kernel[height/2][width/2];
-}        
+}
 
 
 
@@ -250,13 +250,13 @@ totalKernelValue(double **    const kernel,
 
     for (row = 0, total = 0.0; row < height; ++row) {
         unsigned int col;
-        
+
         for (col = 0; col < width; ++col)
             total += kernel[row][col];
     }
 
     return total;
-}        
+}
 
 
 
@@ -311,7 +311,7 @@ writePam(double **    const kernel,
         unsigned int col;
         for (col = 0; col < pam.width; ++col) {
             tuplerown[col][0] = kernel[row][col] / normalizer;
-        
+
             assert(tuplerown[col][0] <= 1.0);
         }
         pnm_writepamrown(&pam, tuplerown);
@@ -319,7 +319,7 @@ writePam(double **    const kernel,
 
     pnm_freepamrown(tuplerown);
 }
-    
+
 
 
 int
@@ -327,7 +327,7 @@ main(int argc, const char **argv) {
     struct CmdlineInfo cmdline;
     double ** kernel;
     double    normalizer;
-    
+
     pm_proginit(&argc, argv);
 
     parseCommandLine(argc, argv, &cmdline);
@@ -344,6 +344,9 @@ main(int argc, const char **argv) {
              normalizer, stdout);
 
     pm_freearray2((void **)kernel);
-    
+
     return 0;
 }
+
+
+
diff --git a/generator/pamgradient.c b/generator/pamgradient.c
index 526efdae..bbbaad30 100644
--- a/generator/pamgradient.c
+++ b/generator/pamgradient.c
@@ -53,8 +53,8 @@ parseCommandLine(int argc, const char **argv,
     else {
         if (cmdlineP->maxval > PAM_OVERALL_MAXVAL)
             pm_error("The value you specified for -maxval (%u) is too big.  "
-                     "Max allowed is %u", cmdlineP->maxval,
-                     PAM_OVERALL_MAXVAL);
+                     "Max allowed is %lu", cmdlineP->maxval,
+                     (unsigned long int) PAM_OVERALL_MAXVAL);
 
         if (cmdlineP->maxval < 1)
             pm_error("You cannot specify 0 for -maxval");
@@ -68,8 +68,8 @@ parseCommandLine(int argc, const char **argv,
         cmdlineP->colorTopRight    = pnm_parsecolor(argv[2], cmdlineP->maxval);
         cmdlineP->colorBottomLeft  = pnm_parsecolor(argv[3], cmdlineP->maxval);
         cmdlineP->colorBottomRight = pnm_parsecolor(argv[4], cmdlineP->maxval);
-        cmdlineP->cols = atoi(argv[5]);
-        cmdlineP->rows = atoi(argv[6]);
+        cmdlineP->cols = pm_parse_width(argv[5]);
+        cmdlineP->rows = pm_parse_height(argv[6]);
         if (cmdlineP->cols <= 0)
             pm_error("width argument must be a positive number.  You "
                      "specified '%s'", argv[5]);
@@ -211,3 +211,6 @@ main(int argc, const char *argv[]) {
 
     return 0;
 }
+
+
+
diff --git a/generator/pamseq.c b/generator/pamseq.c
index 1af5252a..71905a67 100644
--- a/generator/pamseq.c
+++ b/generator/pamseq.c
@@ -1,3 +1,4 @@
+#include <assert.h>
 #include <string.h>
 #include <unistd.h>
 #include <stdlib.h>
@@ -6,49 +7,173 @@
 #include "pm_c_util.h"
 #include "pam.h"
 #include "shhopt.h"
+#include "mallocvar.h"
+#include "nstring.h"
 
 
 
-struct cmdlineInfo {
+struct CmdlineInfo {
     /* All the information the user supplied in the command line,
        in a form easy for the program to use.
     */
     unsigned int depth;
     sample maxval;
     const char * tupletype;
+    sample * min;   /* array of size 'depth' */
+    sample * max;   /* array of size 'depth' */
+    sample * step;  /* array of size 'depth' */
 };
 
 
 
 static void
-parseCommandLine(int argc, char ** argv,
-                 struct cmdlineInfo * const cmdlineP) {
+destroyCmdline(struct CmdlineInfo * const cmdlineP)  {
+
+    if (cmdlineP->min)
+        free(cmdlineP->min);
+    if (cmdlineP->max)
+        free(cmdlineP->max);
+    if (cmdlineP->step)
+        free(cmdlineP->step);
+}
+
+
+
+static unsigned int
+entryCt(char ** const stringList) {
+
+    unsigned int i;
+
+    for (i = 0; stringList[i]; ++i) {}
+
+    return i;
+}
+
+
+
+static void
+parseOptList(bool         const isSpec,
+             char **      const stringList,
+             unsigned int const depth,
+             sample       const maxval,
+             const char * const optNm,
+             sample **    const sampleListP) {
+
+    if (!isSpec)
+        *sampleListP = NULL;
+    else {
+        unsigned int i;
+        sample * sampleList;
+        const char * memberError;
+
+        if (entryCt(stringList) != depth) {
+            pm_error("Wrong number of values for -%s: %u.  Need %u",
+                     optNm, entryCt(stringList), depth);
+        }
+
+        MALLOCARRAY(sampleList, depth);
+
+        for (i = 0, memberError = NULL; i < depth && !memberError; ++i) {
+            char * endPtr;
+            long const n = strtol(stringList[i], &endPtr, 10);
+
+            if (strlen(stringList[i]) == 0)
+                pm_asprintf(&memberError, "is null string");
+            else if (*endPtr != '\0')
+                pm_asprintf(&memberError,
+                            "contains non-numeric character '%c'",
+                            *endPtr);
+            else if (n < 0)
+                pm_asprintf(&memberError, "is negative");
+            else if (n > maxval)
+                pm_asprintf(&memberError, "is greater than maxval %lu",
+                            maxval);
+            else
+                sampleList[i] = n;
+        }
+        if (memberError) {
+            free(sampleList);
+            pm_errormsg("Value in -%s %s", optNm, memberError);
+            pm_longjmp();
+        }
+        *sampleListP = sampleList;
+    }
+}
+
+
+
+static void
+validateMinIsAtMostMax(sample *     const min,
+                       sample *     const max,
+                       unsigned int const depth) {
+
+    unsigned int plane;
+
+    for (plane = 0; plane < depth; ++plane) {
+        if (min[plane] > max[plane])
+            pm_error("-min for plane %u (%lu) is greater than -max (%lu)",
+                     plane, min[plane], max[plane]);
+    }
+}
+
+
+
+static void
+validateStepIsPositive(sample *     const step,
+                       unsigned int const depth) {
+
+    unsigned int plane;
+
+    for (plane = 0; plane < depth; ++plane) {
+        if (step[plane] <= 0)
+            pm_error("-step for plane %u (%lu) is not positive",
+                     plane, step[plane]);
+    }
+}
+
+
+
+static void
+parseCommandLine(int argc, const char ** argv,
+                 struct CmdlineInfo * const cmdlineP) {
 /*----------------------------------------------------------------------------
-  Convert program invocation arguments (argc,argv) into a format the 
+  Convert program invocation arguments (argc,argv) into a format the
   program can use easily, struct cmdlineInfo.  Validate arguments along
   the way and exit program with message if invalid.
 
-  Note that some string information we return as *cmdlineP is in the storage 
+  Note that some string information we return as *cmdlineP is in the storage
   argv[] points to.
 -----------------------------------------------------------------------------*/
-    optEntry *option_def = malloc(100*sizeof(optEntry));
-        /* Instructions to OptParseOptions2 on how to parse our options.
-         */
+    optEntry *option_def;
     optStruct3 opt;
-
+        /* Instructions to pm_optParseOptions3 on how to parse our options. */
+
+    unsigned int maxSpec;
+    char ** max;
+    unsigned int minSpec;
+    char ** min;
+    unsigned int stepSpec;
+    char ** step;
     unsigned int tupletypeSpec;
     unsigned int option_def_index;
 
+    MALLOCARRAY_NOFAIL(option_def, 100);
+
     option_def_index = 0;   /* incremented by OPTENT3 */
-    OPTENT3(0,   "tupletype",  OPT_STRING, &cmdlineP->tupletype, 
+    OPTENT3(0,   "tupletype",  OPT_STRING, &cmdlineP->tupletype,
             &tupletypeSpec,     0);
-
+    OPTENT3(0,   "min",         OPT_STRINGLIST, &min,
+            &minSpec,           0);
+    OPTENT3(0,   "max",         OPT_STRINGLIST, &max,
+            &maxSpec,           0);
+    OPTENT3(0,   "step",        OPT_STRINGLIST, &step,
+            &stepSpec,          0);
 
     opt.opt_table = option_def;
     opt.short_allowed = FALSE;  /* We have no short (old-fashioned) options */
     opt.allowNegNum = FALSE;  /* We have no parms that are negative numbers */
 
-    pm_optParseOptions3(&argc, argv, opt, sizeof(opt), 0);
+    pm_optParseOptions3(&argc, (char **)argv, opt, sizeof(opt), 0);
         /* Uses and sets argc, argv, and some of *cmdlineP and others. */
 
     if (!tupletypeSpec)
@@ -57,9 +182,9 @@ parseCommandLine(int argc, char ** argv,
         struct pam pam;
         if (strlen(cmdlineP->tupletype)+1 > sizeof(pam.tuple_type))
             pm_error("The tuple type you specified is too long.  "
-                     "Maximum %u characters.", 
+                     "Maximum %u characters.",
                      (unsigned)sizeof(pam.tuple_type)-1);
-    }        
+    }
 
     if (argc-1 < 2)
         pm_error("Need two arguments: depth and maxval.");
@@ -67,83 +192,175 @@ parseCommandLine(int argc, char ** argv,
         pm_error("Only two argumeents allowed: depth and maxval.  "
                  "You specified %d", argc-1);
     else {
-        cmdlineP->depth = atoi(argv[1]);
-        cmdlineP->maxval = atoi(argv[2]);
-        if (cmdlineP->depth <= 0)
+        const char * error;
+        unsigned int depth, maxval;
+
+        pm_string_to_uint(argv[1], &depth, &error);
+        if (error) {
+            pm_error("'%s' is invalid as an image depth.  %s", argv[1], error);
+            pm_strfree(error);
+        }
+        else if (depth <= 0)
             pm_error("depth argument must be a positive number.  You "
                      "specified '%s'", argv[1]);
-        if (cmdlineP->maxval <= 0)
-            pm_error("maxval argument must be a positive number.  You "
-                     "specified '%s'", argv[2]);
-        if (cmdlineP->maxval > PNM_OVERALLMAXVAL)
+        else
+            cmdlineP->depth = depth;
+
+        maxval = pm_parse_maxval(argv[2]);
+
+        if (maxval > PAM_OVERALL_MAXVAL)
             pm_error("The maxval you specified (%u) is too big.  "
-                     "Maximum is %u", (unsigned int) cmdlineP->maxval, 
-                     PNM_OVERALLMAXVAL);
-        if (pm_maxvaltobits(cmdlineP->maxval) + 
+                     "Maximum is %lu", maxval, PAM_OVERALL_MAXVAL);
+        else
+            cmdlineP->maxval = maxval;
+
+
+        if (pm_maxvaltobits(cmdlineP->maxval) +
             pm_maxvaltobits(cmdlineP->depth-1) > sizeof(unsigned int)*8)
             pm_error("The maxval (%u) and depth (%u) you specified result "
                      "in a larger number of tuples than this program can "
-                     "handle (roughly %u)", 
+                     "handle (roughly %u)",
                      (unsigned int) cmdlineP->maxval, cmdlineP->depth,
                      (unsigned int) -1);
     }
+    parseOptList(minSpec, min,  cmdlineP->depth, cmdlineP->maxval, "min",
+                 &cmdlineP->min);
+    parseOptList(maxSpec, max,  cmdlineP->depth, cmdlineP->maxval, "max",
+                 &cmdlineP->max);
+    parseOptList(stepSpec, step, cmdlineP->depth, cmdlineP->maxval, "step",
+                 &cmdlineP->step);
+
+    if (cmdlineP->min && cmdlineP->max)
+        validateMinIsAtMostMax(cmdlineP->min, cmdlineP->max, cmdlineP->depth);
+
+    if (cmdlineP->step)
+        validateStepIsPositive(cmdlineP->step, cmdlineP->depth);
+
+    if (minSpec)
+        free(min);
+    if (maxSpec)
+        free(max);
+    if (stepSpec)
+        free(step);
 }
 
 
 
-static unsigned int
-powint(unsigned int base, unsigned int exponent) {
+static void
+computeMinMaxStep(unsigned int   const depth,
+                  sample         const maxval,
+                  const sample * const min,
+                  const sample * const max,
+                  const sample * const step,
+                  sample **      const minP,
+                  sample **      const maxP,
+                  sample **      const stepP) {
+
+    unsigned int plane;
+
+    MALLOCARRAY(*minP,  depth);
+    MALLOCARRAY(*maxP,  depth);
+    MALLOCARRAY(*stepP, depth);
+
+    for (plane = 0; plane < depth; ++plane) {
+        (*minP)[plane]  = min  ? min[plane]  : 0;
+        (*maxP)[plane]  = max  ? max[plane]  : maxval;
+        (*stepP)[plane] = step ? step[plane] : 1;
+    }
+}
+
+
+
+static int
+imageWidth(unsigned int   const depth,
+           const sample * const min,
+           const sample * const max,
+           const sample * const step) {
 /*----------------------------------------------------------------------------
-   This is standard pow(), but for integers and optimized for small
-   exponents.
+   The width of the output image (i.e. the number of pixels in the image),
+   given that the minimum and maximum sample values in Plane P are min[P] and
+   max[P] and the samples step by step[P].
+
+   E.g. in the example case of min 0, max 4, and step 1 everywhere, with
+   depth 2,  We return 5*5 = 25.
 -----------------------------------------------------------------------------*/
-    unsigned int result;
-    unsigned int i;
+    unsigned int product;
+    unsigned int plane;
 
-    result = 1;  /* initial value */
-    for (i = 0; i < exponent; ++i) 
-        result *= base;
+    for (plane = 0, product=1; plane < depth; ++plane) {
+        assert(max[plane] >= min[plane]);
 
-    return(result);
+        unsigned int const valueCtThisPlane =
+            ROUNDUP((max[plane] - min[plane] + 1), step[plane])/step[plane];
+
+        if (INT_MAX / valueCtThisPlane < product)
+            pm_error("Uncomputably large number of pixels (greater than %u)",
+                     INT_MAX);
+
+        product *= valueCtThisPlane;
+    }
+    assert(product < INT_MAX);
+
+    return product;
 }
 
 
+
 static void
-permuteHigherPlanes(struct pam const pam, int const nextplane, 
-                    tuple * const tuplerow, int * const colP, 
-                    tuple const lowerPlanes) {
+permuteHigherPlanes(unsigned int   const depth,
+                    const sample * const min,
+                    const sample * const max,
+                    const sample * const step,
+                    unsigned int   const nextPlane,
+                    tuple *        const tuplerow,
+                    int *          const colP,
+                    tuple          const lowerPlanes) {
 /*----------------------------------------------------------------------------
    Create all the possible permutations of tuples whose lower-numbered planes
    contain the values from 'lowerPlanes'.  I.e. vary the higher-numbered
-   planes between zero and maxval.
+   planes according to min[], max[], and step[].
 
    Write them sequentially into *tuplerow, starting at *colP.  Adjust
    *colP to next the column after the ones we write.
 
-   lower-numbered means with plane numbers less than 'nextplane'.
+   lower-numbered means with plane numbers less than 'nextPlane'.
 
    We modify 'lowerPlanes' in the higher planes to undefined values.
 -----------------------------------------------------------------------------*/
-    if (nextplane == pam.depth - 1) {
+    if (nextPlane == depth - 1) {
+        /* lowerPlanes[] contains values for all the planes except the
+           highest, so we just vary the highest plane and combine that
+           with lowerPlanes[] and output that to tuplerow[].
+        */
         sample value;
-        for (value = 0; value <= pam.maxval; ++value) {
+
+        for (value = min[nextPlane];
+             value <= max[nextPlane];
+             value += step[nextPlane]) {
+
             unsigned int plane;
-            for (plane = 0; plane < nextplane; ++plane)
+
+            for (plane = 0; plane < nextPlane; ++plane)
                 tuplerow[*colP][plane] = lowerPlanes[plane];
-            tuplerow[*colP][nextplane] = value;
+
+            tuplerow[*colP][nextPlane] = value;
+
             ++(*colP);
         }
     } else {
         sample value;
 
-        for (value = 0; value <= pam.maxval; ++value) {
+        for (value = min[nextPlane];
+             value <= max[nextPlane];
+             value += step[nextPlane]) {
             /* We do something sleazy here and use Caller's lowerPlanes[]
                variable as a local variable, modifying it in the higher
                plane positions.  That's just for speed.
             */
-            lowerPlanes[nextplane] = value;
+            lowerPlanes[nextPlane] = value;
 
-            permuteHigherPlanes(pam, nextplane+1, tuplerow, colP, lowerPlanes);
+            permuteHigherPlanes(depth, min, max, step,
+                                nextPlane+1, tuplerow, colP, lowerPlanes);
         }
     }
 }
@@ -151,52 +368,65 @@ permuteHigherPlanes(struct pam const pam, int const nextplane,
 
 
 int
-main(int argc, char **argv) {
+main(int argc, const char **argv) {
 
-    struct cmdlineInfo cmdline;
+    struct CmdlineInfo cmdline;
     struct pam pam;
     int col;
     tuple lowerPlanes;
         /* This is working storage passed to permuteHigherPlanes(),
            which we call.  Note that because we always pass zero as the
-           "planes" argument to permuteHigherPlanes(), none of the 
-           "lower planes" value is defined as an input to 
+           "planes" argument to permuteHigherPlanes(), none of the
+           "lower planes" value is defined as an input to
            permuteHigherPlanes().
         */
     tuple * tuplerow;
-    
-    pnm_init(&argc, argv);
-   
+    sample * min;   /* malloc'ed array */
+    sample * max;   /* malloc'ed array */
+    sample * step;  /* malloc'ed array */
+
+    pm_proginit(&argc, argv);
+
     parseCommandLine(argc, argv, &cmdline);
 
+    computeMinMaxStep(cmdline.depth, cmdline.maxval,
+                      cmdline.min, cmdline.max, cmdline.step,
+                      &min, &max, &step);
+
     pam.size = sizeof(pam);
     pam.len = PAM_STRUCT_SIZE(tuple_type);
     pam.file = stdout;
     pam.format = PAM_FORMAT;
     pam.plainformat = 0;
-    pam.width = powint(cmdline.maxval+1, cmdline.depth);
+    pam.width = imageWidth(cmdline.depth, min, max, step);
     pam.height = 1;
     pam.depth = cmdline.depth;
     pam.maxval = cmdline.maxval;
     strcpy(pam.tuple_type, cmdline.tupletype);
 
     pnm_writepaminit(&pam);
-   
+
     tuplerow = pnm_allocpamrow(&pam);
 
     lowerPlanes = pnm_allocpamtuple(&pam);
 
     col = 0;
 
-    permuteHigherPlanes(pam, 0, tuplerow, &col, lowerPlanes);
+    permuteHigherPlanes(pam.depth, min, max, step,
+                        0, tuplerow, &col, lowerPlanes);
 
     if (col != pam.width)
         pm_error("INTERNAL ERROR: Wrote %d columns; should have written %d.",
                  col, pam.width);
 
     pnm_writepamrow(&pam, tuplerow);
-    
+
     pnm_freepamrow(tuplerow);
 
+    destroyCmdline(&cmdline);
+
     return 0;
 }
+
+
+
diff --git a/generator/pamshadedrelief.c b/generator/pamshadedrelief.c
index 35d1e3e0..80b34a0d 100644
--- a/generator/pamshadedrelief.c
+++ b/generator/pamshadedrelief.c
@@ -8,7 +8,7 @@
 
   The input array is a one-channel PAM image.  The sample values are
   elevations of terrain.
-  
+
   This is derived from John Walker's 'pgmcrater' which not only does this
   shading, but first generates a terrain map of fractal craters on which to
   run it.
@@ -95,7 +95,7 @@ parseCommandLine(int argc, const char ** const argv,
     if (cmdlineP->gamma <= 0.0)
         pm_error("gamma correction must be greater than 0");
 
-    if (argc-1 == 0) 
+    if (argc-1 == 0)
         cmdlineP->inputFileName = "-";
     else if (argc-1 != 1)
         pm_error("Program takes zero or one argument (filename).  You "
@@ -201,7 +201,7 @@ writeShadedRelief(struct pam * const terrainPamP,
         }
         {
             /* Wrap around to determine shade of pixel on right edge */
-            int const slope = 
+            int const slope =
                 terrain[row][0][0] - terrain[row][outpam.width-1][0];
             outrow[outpam.width - 1][0] =
                 brightnessOfSlope(slope, slopeGrayMap);
@@ -222,8 +222,8 @@ readTerrain(FILE *       const ifP,
 
     *tuplesP = pnm_readpam(ifP, pamP, PAM_STRUCT_SIZE(tuple_type));
 }
-            
-            
+
+
 
 int
 main(int argc, const char ** argv) {
@@ -243,7 +243,7 @@ main(int argc, const char ** argv) {
     readTerrain(ifP, &terrainPam, &terrain);
 
     writeShadedRelief(&terrainPam, terrain, cmdline.gamma, stdout);
-    
+
     return 0;
 }
 
diff --git a/generator/pamstereogram.c b/generator/pamstereogram.c
index 9b861b51..4bc1ea92 100644
--- a/generator/pamstereogram.c
+++ b/generator/pamstereogram.c
@@ -16,7 +16,7 @@
  *
  * ----------------------------------------------------------------------
  *
- * Copyright (C) 2006-2020 Scott Pakin <scott+pbm@pakin.org>
+ * Copyright (C) 2006-2021 Scott Pakin <scott+pbm@pakin.org>
  *
  * All rights reserved.
  *
@@ -58,11 +58,12 @@
 #include "pm_c_util.h"
 #include "mallocvar.h"
 #include "nstring.h"
+#include "rand.h"
 #include "shhopt.h"
 #include "pam.h"
 
 
-enum outputType {OUTPUT_BW, OUTPUT_GRAYSCALE, OUTPUT_COLOR};
+enum OutputType {OUTPUT_BW, OUTPUT_GRAYSCALE, OUTPUT_COLOR};
 
 /* ---------------------------------------------------------------------- */
 
@@ -85,13 +86,14 @@ struct cmdlineInfo {
     unsigned int magnifypat;     /* -magnifypat option */
     int xshift;                  /* -xshift option */
     int yshift;                  /* -yshift option */
+    int yfillshift;              /* -yfillshift option */
     const char * patfile;        /* -patfile option.  Null if none */
     const char * texfile;        /* -texfile option.  Null if none */
     const char * bgcolor;        /* -bgcolor option */
     unsigned int smoothing;      /* -smoothing option */
     unsigned int randomseed;     /* -randomseed option */
     unsigned int randomseedSpec; /* -randomseed option count */
-    enum outputType outputType;  /* Type of output file */
+    enum OutputType outputType;  /* Type of output file */
     unsigned int xbegin;         /* -xbegin option */
     unsigned int xbeginSpec;     /* -xbegin option count */
     unsigned int tileable;       /* -tileable option */
@@ -153,8 +155,8 @@ parseCommandLine(int                  argc,
     unsigned int option_def_index;
 
     unsigned int patfileSpec, texfileSpec, dpiSpec, eyesepSpec, depthSpec,
-        guidesizeSpec, magnifypatSpec, xshiftSpec, yshiftSpec,
-      bgcolorSpec, smoothingSpec, planesSpec;
+        guidesizeSpec, magnifypatSpec, xshiftSpec, yshiftSpec, yfillshiftSpec,
+        bgcolorSpec, smoothingSpec, planesSpec;
 
     unsigned int blackandwhite, grayscale, color;
     const char ** planes;
@@ -194,6 +196,8 @@ parseCommandLine(int                  argc,
             &xshiftSpec,              0);
     OPTENT3(0, "yshift",          OPT_INT,    &cmdlineP->yshift,
             &yshiftSpec,              0);
+    OPTENT3(0, "yfillshift",      OPT_INT,    &cmdlineP->yfillshift,
+            &yfillshiftSpec,          0);
     OPTENT3(0, "patfile",         OPT_STRING, &cmdlineP->patfile,
             &patfileSpec,             0);
     OPTENT3(0, "texfile",         OPT_STRING, &cmdlineP->texfile,
@@ -282,9 +286,10 @@ parseCommandLine(int                  argc,
 
     if (!xshiftSpec)
         cmdlineP->xshift = 0;
-
     if (!yshiftSpec)
         cmdlineP->yshift = 0;
+    if (!yfillshiftSpec)
+        cmdlineP->yfillshift = 0;
 
     if (xshiftSpec && !cmdlineP->patfile)
         pm_error("-xshift is valid only with -patfile");
@@ -402,11 +407,12 @@ typedef struct outGenerator {
 
 
 
-struct randomState {
+struct RandomState {
     /* The state of a randomColor generator. */
     unsigned int magnifypat;
     tuple *      currentRow;
     unsigned int prevy;
+    struct pm_randSt * randStP;
 };
 
 
@@ -421,7 +427,7 @@ randomColor(outGenerator * const outGenP,
 /*----------------------------------------------------------------------------
    Return a random RGB value.
 -----------------------------------------------------------------------------*/
-    struct randomState * const stateP = outGenP->stateP;
+    struct RandomState * const stateP = outGenP->stateP;
 
     /* Every time we start a new row, we select a new sequence of random
        colors.
@@ -436,7 +442,7 @@ randomColor(outGenerator * const outGenP,
             unsigned int plane;
 
             for (plane = 0; plane < outGenP->pam.depth; ++plane) {
-                unsigned int const randval = rand();
+                unsigned int const randval = pm_rand(stateP->randStP);
                 thisTuple[plane] = randval % modulus;
             }
         }
@@ -456,9 +462,13 @@ static outGenStateTerm termRandomColor;
 static void
 termRandomColor(outGenerator * const outGenP) {
 
-    struct randomState * const stateP = outGenP->stateP;
+    struct RandomState * const stateP = outGenP->stateP;
 
     pnm_freepamrow(stateP->currentRow);
+
+    pm_randterm(stateP->randStP);
+
+    free(stateP->randStP);
 }
 
 
@@ -468,7 +478,7 @@ initRandomColor(outGenerator *     const outGenP,
                 const struct pam * const inPamP,
                 struct cmdlineInfo const cmdline) {
 
-    struct randomState * stateP;
+    struct RandomState * stateP;
 
     outGenP->pam.format      = PAM_FORMAT;
     outGenP->pam.plainformat = 0;
@@ -499,6 +509,10 @@ initRandomColor(outGenerator *     const outGenP,
     stateP->magnifypat = cmdline.magnifypat;
     stateP->prevy      = (unsigned int)(-cmdline.magnifypat);
 
+    MALLOCVAR_NOFAIL(stateP->randStP);
+    pm_randinit(stateP->randStP);
+    pm_srand2(stateP->randStP, cmdline.randomseedSpec, cmdline.randomseed);
+
     outGenP->stateP         = stateP;
     outGenP->getTuple       = &randomColor;
     outGenP->terminateState = &termRandomColor;
@@ -1178,6 +1192,8 @@ static void
 makeImageRow(outGenerator *       const outGenP,
              unsigned int         const row,
              unsigned int         const xbegin,
+             unsigned int         const farWidth,
+             int                  const yfillshift,
              const unsigned int * const sameL,
              const unsigned int * const sameR,
              const tuple *        const outRow) {
@@ -1200,42 +1216,59 @@ makeImageRow(outGenerator *       const outGenP,
 
   sameL[N] > N is not allowed.
 -----------------------------------------------------------------------------*/
-    int col;
-    int lastLinked;
+    unsigned int const width  = outGenP->pam.width;
+    unsigned int const height = outGenP->pam.height;
 
-    for (col = (int)xbegin, lastLinked = INT_MIN;
-         col < outGenP->pam.width;
-         ++col) {
+    unsigned int col;
+    bool colHasBeenLinked;
+    unsigned int lastLinkedCol;
+        /* Last column to have been linked; meaningless if 'colHasBeenLinked'
+           is false.
+        */
+
+    for (col = xbegin, colHasBeenLinked = false; col < width; ++col) {
 
         tuple newtuple;
 
-        if (sameL[col] == col || sameL[col] < (int)xbegin) {
-            if (lastLinked == col - 1)
-                newtuple = outRow[col - 1];
-            else
-                newtuple = outGenP->getTuple(outGenP, col, row);
+        if (sameL[col] == col || sameL[col] < xbegin) {
+            if (colHasBeenLinked && lastLinkedCol == col - 1)
+                newtuple = outRow[lastLinkedCol];
+            else {
+                if (col < xbegin + farWidth)
+                    newtuple = outGenP->getTuple(outGenP, col, row);
+                else
+                    newtuple = outGenP->getTuple(
+                        outGenP, col, (row + height - yfillshift) % height);
+            }
         } else {
-          newtuple = outRow[sameL[col]];
-          lastLinked = col;
-              /* Keep track of the last pixel to be constrained. */
+            newtuple = outRow[sameL[col]];
+            colHasBeenLinked = true;
+            lastLinkedCol = col;
+                /* Keep track of the last pixel to be constrained. */
         }
         pnm_assigntuple(&outGenP->pam, outRow[col], newtuple);
     }
 
-    for (col = (int)xbegin - 1, lastLinked = INT_MIN; col >= 0; --col) {
+    for (col = xbegin, colHasBeenLinked = false; col > 0; --col) {
         tuple newtuple;
 
-        if (sameR[col] == col) {
-            if (lastLinked == col + 1)
-                newtuple = outRow[col + 1];
-            else
-                newtuple = outGenP->getTuple(outGenP, col, row);
+        if (sameR[col-1] == col-1) {
+            if (colHasBeenLinked && lastLinkedCol == col)
+                newtuple = outRow[lastLinkedCol];
+            else {
+                if (col > xbegin - farWidth)
+                    newtuple = outGenP->getTuple(outGenP, col-1, row);
+                else
+                    newtuple = outGenP->getTuple(
+                        outGenP, col-1, (row + height - yfillshift) % height);
+            }
         } else {
-            newtuple = outRow[sameR[col]];
-            lastLinked = col;
+            newtuple = outRow[sameR[col-1]];
+            colHasBeenLinked = true;
+            lastLinkedCol = col - 1;
                 /* Keep track of the last pixel to be constrained. */
         }
-        pnm_assigntuple(&outGenP->pam, outRow[col], newtuple);
+        pnm_assigntuple(&outGenP->pam, outRow[col-1], newtuple);
     }
 }
 
@@ -1261,6 +1294,8 @@ makeOneImageRow(unsigned int         const row,
                 const unsigned int * const sameR,
                 unsigned int *       const colNumBuffer,
                 unsigned int         const xbegin,
+                unsigned int         const farWidth,
+                int                  const yfillshift,
                 tuple *              const rowBuffer,
                 tuple *              const outRow) {
 
@@ -1272,7 +1307,7 @@ makeOneImageRow(unsigned int         const row,
                             rowBuffer, outRow);
         else
             makeImageRow(outputGeneratorP, row,
-                         xbegin, sameL, sameR, outRow);
+                         xbegin, farWidth, yfillshift, sameL, sameR, outRow);
     }
 }
 
@@ -1284,6 +1319,8 @@ constructRowTileable(const struct pam *   const inPamP,
                      bool                 const makeMask,
                      const unsigned int * const sameL,
                      const unsigned int * const sameR,
+                     unsigned int         const farWidth,
+                     int                  const yfillshift,
                      unsigned int         const row,
                      tuple *              const outRow,
                      tuple *              const outRowBuf1,
@@ -1300,10 +1337,10 @@ constructRowTileable(const struct pam *   const inPamP,
        xbegin=maximum case.
     */
     makeOneImageRow(row, outputGeneratorP, makeMask, sameL, sameR, colNumBuf2,
-                    0, outRowBuf2, outRow);
+                    farWidth, yfillshift, 0, outRowBuf2, outRow);
 
     makeOneImageRow(row, outputGeneratorP, makeMask, sameL, sameR, colNumBuf2,
-                    inPamP->width - 1, outRowBuf2, outRowMax);
+                    farWidth, yfillshift, inPamP->width - 1, outRowBuf2, outRowMax);
 
     for (col = 0; col < inPamP->width; ++col) {
         unsigned int plane;
@@ -1362,6 +1399,8 @@ doRow(const struct pam * const inPamP,
       unsigned int       const magnifypat,
       unsigned int       const smoothing,
       unsigned int       const xbegin,
+      unsigned int       const farWidth,
+      int                const yfillshift,
       unsigned int       const row,
       tuple *            const inRow,
       tuple *            const outRowBuf0,
@@ -1397,13 +1436,16 @@ doRow(const struct pam * const inPamP,
     /* Construct a single row. */
     if (tileable) {
         constructRowTileable(inPamP, outputGeneratorP, makeMask,
-                             sameL, sameR, row, outRow,
+                             sameL, sameR,
+                             farWidth, yfillshift,
+                             row, outRow,
                              outRowBuf1, outRowBuf2, colNumBuf2);
 
     } else {
         makeOneImageRow(row, outputGeneratorP, makeMask,
                         sameL, sameR, colNumBuf2,
-                        xbegin, outRowBuf1, outRow);
+                        xbegin, farWidth, yfillshift,
+                        outRowBuf1, outRow);
     }
 
     /* Write the resulting row. */
@@ -1423,7 +1465,8 @@ makeImageRows(const struct pam * const inPamP,
               bool               const tileable,
               unsigned int       const magnifypat,
               unsigned int       const smoothing,
-              unsigned int       const xbegin) {
+              unsigned int       const xbegin,
+              int                const yfillshift) {
 
     tuple * inRow;    /* Buffer for use in reading from the height-map image */
     tuple * outRowBuf0; /* Buffer for use in generating output rows */
@@ -1433,6 +1476,8 @@ makeImageRows(const struct pam * const inPamP,
     unsigned int * colNumBuf1;
     unsigned int * colNumBuf2;
     unsigned int row;      /* Current row in the input and output files */
+    unsigned int pixelEyesep;
+    unsigned int farWidth;
 
     inRow = pnm_allocpamrow(inPamP);
     outRowBuf0 = pnm_allocpamrow(&outputGeneratorP->pam);
@@ -1451,10 +1496,13 @@ makeImageRows(const struct pam * const inPamP,
         pm_error("Unable to allocate space for %u column buffer",
                  inPamP->width);
 
+    pixelEyesep = ROUNDU(eyesep * dpi);
+    farWidth = pixelEyesep/(magnifypat * 2);
+
     for (row = 0; row < inPamP->height; ++row) {
         doRow(inPamP, outputGeneratorP,  depthOfField, eyesep, dpi,
               crossEyed, makeMask, tileable, magnifypat, smoothing, xbegin,
-              row,
+              farWidth, yfillshift, row,
               inRow, outRowBuf0, outRowBuf1, outRowBuf2,
               colNumBuf0, colNumBuf1, colNumBuf2);
     }
@@ -1510,7 +1558,8 @@ produceStereogram(FILE *             const ifP,
     makeImageRows(&inPam, outputGeneratorP,
                   cmdline.depth, cmdline.eyesep, cmdline.dpi,
                   cmdline.crosseyed, cmdline.makemask, cmdline.tileable,
-                  cmdline.magnifypat, cmdline.smoothing, xbegin);
+                  cmdline.magnifypat, cmdline.smoothing, xbegin,
+                  cmdline.yfillshift);
 
     if (cmdline.guidebottom)
         drawguides(cmdline.guidesize, &outputGeneratorP->pam,
@@ -1567,8 +1616,6 @@ main(int argc, const char *argv[]) {
     if (cmdline.verbose)
         reportParameters(cmdline);
 
-    srand(cmdline.randomseedSpec ? cmdline.randomseed : pm_randseed());
-
     ifP = pm_openr(cmdline.inputFilespec);
 
     /* Produce a stereogram. */
@@ -1580,4 +1627,3 @@ main(int argc, const char *argv[]) {
 }
 
 
-
diff --git a/generator/pamstereogram.test b/generator/pamstereogram.test
deleted file mode 100644
index 80f70ee0..00000000
--- a/generator/pamstereogram.test
+++ /dev/null
@@ -1,70 +0,0 @@
-# Make some input files
-pamdepth -quiet 255 ../testgrid.pbm >/tmp/testgrid.pgm
-
-
-# Random pattern
-
-echo Test 01.  Should print 610673698 293:
-./pamstereogram -randomseed=1 ../testgrid.pbm | cksum 
-echo Test 02.  Should print 610673698 293:
-./pamstereogram -randomseed=1 -blackandwhite ../testgrid.pbm | cksum 
-echo Test 03.  Should print 3439084201 170:
-pamseq -tupletype=GRAYSCALE 1 100 | ./pamstereogram -randomseed=1 | cksum 
-echo Test 04.  Should print 2484923390 1070:
-pamgauss 100 10 -maxval=10000 -sigma 20 | pamfunc -multiplier=500 | \
-  ./pamstereogram -randomseed=1 -dpi=10 | cksum
-
-# Makemask
-
-echo Test 10.  Should print 1266273778 293:
-./pamstereogram -randomseed=1 -makemask ../testgrid.pbm | cksum 
-
-echo Test 11.  Should print 3034751595 1070:
-pamgauss 100 10 -maxval=10000 -sigma 20 | pamfunc -multiplier=500 | \
-  ./pamstereogram -randomseed=1 -dpi=10 -makemask | cksum
-
-# Grayscale
-
-echo Test 20.  Should print 2468969328 289:
-./pamstereogram -randomseed=1 -grayscale ../testgrid.pbm | cksum 
-echo Test 21.  Should print 1946982115 4068:
-pamseq 1 100 | pnmtile 200 20 | \
-  ./pamstereogram -randomseed=1 -dpi=10 -grayscale | \
-  cksum
-echo Test 22.  Should print 2078013430 4068:
-pamseq 1 100 | pnmtile 200 20 | \
-  ./pamstereogram -randomseed=1 -dpi=10 -grayscale -maxval 255 | \
-  cksum
-
-# Color
-
-echo Test 30.  Should print 1319392622 731:
-./pamstereogram -randomseed=1 -color ../testgrid.pbm | cksum 
-echo Test 31.  Should print 389886159 12062:
-pamseq 1 100 | pnmtile 200 20 | \
-  ./pamstereogram -randomseed=1 -dpi=10 -color | \
-  cksum
-
-# Pattern file
-
-echo Test 40.  Should print 1834916830 660:
-pamgradient black gray50 white gray50 100 50 | \
-  ./pamstereogram -patfile ../testgrid.pbm -eyesep=.1 -crosseyed | cksum
-
-echo Test 41.  Should print 4016818756 5014:
-pamgradient black gray50 white gray50 100 50 | \
-  ./pamstereogram -patfile /tmp/testgrid.pgm -eyesep=.1 -crosseyed | cksum
-
-# drawguides
-
-echo Test 51.  Should print 2365956562 11071:
-pamgradient black gray50 white gray50 100 50 | \
-  ./pamstereogram -randomseed=1 -dpi 10 -guidesize=20 | cksum
-
-echo Test 51.  Should print 3502025270 1441:
-pamgradient black gray50 white gray50 100 50 | \
-  ./pamstereogram -patfile=../testgrid.pbm -dpi 10 -guidesize=20 | cksum
-
-
-# Clean up files we created
-rm /tmp/testgrid.pgm
diff --git a/generator/pamtris/framebuffer.c b/generator/pamtris/framebuffer.c
index 5665e9a4..4318b1fc 100644
--- a/generator/pamtris/framebuffer.c
+++ b/generator/pamtris/framebuffer.c
@@ -320,7 +320,7 @@ draw_span(uint32_t           const base,
         fbi->z.buffer[j] = (fbi->z.buffer[j] & ~d_mask) | (d & d_mask);
 
         for (l = 0; l < z; l++) {
-	    varying const newval = multiply_varyings(attribs[l], inverse_w);
+            varying const newval = multiply_varyings(attribs[l], inverse_w);
 
             fbi->img.buffer[k + l] =
                 (fbi->img.buffer[k + l] & ~d_mask) |
diff --git a/generator/pamtris/pamtris.c b/generator/pamtris/pamtris.c
index e0becf7a..477b657e 100644
--- a/generator/pamtris/pamtris.c
+++ b/generator/pamtris/pamtris.c
@@ -54,7 +54,7 @@ parse_command_line(int *         const argc_ptr,
     if (!width_spec || !height_spec || (!attribs_spec && !(rgb_spec || grayscale_spec))) {
         pm_errormsg(
             "you must at least specify -width, -height and "
-	    "either -num_attribs, -rgb or -grayscale.");
+            "either -num_attribs, -rgb or -grayscale.");
 
         return 0;
     }
diff --git a/generator/pamtris/triangle.c b/generator/pamtris/triangle.c
index 5143f9ee..264fc221 100644
--- a/generator/pamtris/triangle.c
+++ b/generator/pamtris/triangle.c
@@ -190,8 +190,8 @@ draw_triangle(Xy                 const xy_input,
 
     for (i = 0; i < 3; i++) {
         int32_to_varying_array(attribs_input._[i], attribs[i], n);
-	attribs[i][z] = compute_varying_z(attribs_input._[i][z]);
-	attribs[i][w] = inverse_varying(attribs[i][w]);
+        attribs[i][z] = compute_varying_z(attribs_input._[i][z]);
+        attribs[i][w] = inverse_varying(attribs[i][w]);
         multiply_varying_array_by_varying(attribs[i], attribs[i][w], z);
     }
 
diff --git a/generator/pamtris/utils.c b/generator/pamtris/utils.c
index a6b6e7d4..53f1ea9e 100644
--- a/generator/pamtris/utils.c
+++ b/generator/pamtris/utils.c
@@ -61,7 +61,7 @@ multiply_varying_array_by_varying(varying * const vars,
 
     for (i = 0; i < elements; i++) {
         vars[i].v *= multiplier.v;
-	vars[i].s  = 0.0;
+        vars[i].s  = 0.0;
     }
 }
 
@@ -77,7 +77,7 @@ divide_varying_array_by_varying(varying * const vars,
 
     for (i = 0; i < elements; i++) {
         vars[i].v *= inverse_divisor;
-	vars[i].s  = 0.0;
+        vars[i].s  = 0.0;
     }
 }
 
diff --git a/generator/pbmnoise.c b/generator/pbmnoise.c
new file mode 100644
index 00000000..541ce92e
--- /dev/null
+++ b/generator/pbmnoise.c
@@ -0,0 +1,485 @@
+/* pbmnoise.c - create a random bitmap of a specified size
+                with a specified ratio of white/black pixels
+
+   Written by Akira F Urushibata and contributed to the public domain
+   December 2021
+*/
+
+#include <math.h>
+#include <string.h>
+#include <assert.h>
+
+#include "pm_c_util.h"
+#include "shhopt.h"
+#include "mallocvar.h"
+#include "rand.h"
+#include "nstring.h"
+
+#include "pbm.h"
+
+
+
+static void
+parseFraction(const char *   const fraction,
+              unsigned int * const numeratorP,
+              unsigned int * const precisionP) {
+
+    unsigned int numerator, denominator;
+
+    sscanf(fraction, "%u/%u", &numerator, &denominator);
+
+    if (denominator > 65536)
+        pm_error("Denominator (%u) too large.", denominator);
+    else if (denominator == 0 || (denominator & (denominator - 1)) != 0)
+        pm_error("Denominator must be a power of two.  You specified %u.",
+                 denominator);
+    else if (numerator > denominator)
+        pm_error("Invalid fraction (%s).  Denominator must be larger than "
+                 "numerator.", fraction);
+    else {
+        /* Reduce fraction to lowest terms */
+        unsigned int numerator2, denominator2;
+            /* The fraction reduced to lowest terms */
+        unsigned int precision2;
+
+        if (numerator == 0) { /* all white image */
+            numerator2   = 0;
+            denominator2 = 1;
+            precision2   = 0;
+        } else if (numerator == denominator) { /* all black */
+            numerator2   = 1;
+            denominator2 = 1;
+            precision2   = 0;
+        } else {
+            numerator2   = numerator;   /* initial value */
+            denominator2 = denominator; /* initial value */
+
+            while ((numerator2 & 0x01) != 0x01) {
+                denominator2 /= 2;
+                numerator2   /= 2;
+            }
+            precision2 = 1;
+        }
+
+      if (denominator != denominator2)
+          pm_message("Ratio %u/%u = %u/%u",
+                     numerator, denominator, numerator2, denominator2);
+
+      *precisionP = (precision2 == 0) ? 0 : pm_maxvaltobits(denominator2 - 1);
+          /* pm_maxvaltobits(N):  Max of N is 65535 */
+
+      *numeratorP = numerator2;
+    }
+}
+
+
+
+static void
+setRatio(const char *   const ratioArg,
+         unsigned int * const numeratorP,
+         unsigned int * const precisionP) {
+/*----------------------------------------------------------------------------
+    Convert string "ratioArg" to ratio: numerator / (2 ^ precision) The input
+    string must be in fraction "n/d" form and the denominator must be a power
+    of 2.
+
+    Ratio is the probability of one binary digit being "1".  The ratio of "1"
+    (=PBM black) pixels in the entire output image will be close to this
+    value.
+
+    Most invalid strings are rejected here.
+----------------------------------------------------------------------------*/
+    if (strspn(ratioArg, "0123456789/") == strlen(ratioArg) &&
+             ratioArg[0] != '/' &&
+             ratioArg[strlen(ratioArg) - 1] != '/' &&
+             strchr(ratioArg, '/') != NULL &&
+             strchr(ratioArg, '/') == strrchr(ratioArg, '/'))
+        parseFraction(ratioArg, numeratorP, precisionP);
+    else
+        pm_error("Invalid ratio: '%s'", ratioArg);
+}
+
+
+
+struct CmdlineInfo {
+    /* All the information the user supplied in the command line,
+       in a form easy for the program to use.
+    */
+    unsigned int width;
+    unsigned int height;
+    unsigned int numerator;
+    unsigned int precision;
+    unsigned int randomseed;
+    unsigned int randomseedSpec;
+    unsigned int bswap;   /* boolean */
+    unsigned int pack;    /* boolean */
+};
+
+
+
+static void
+parseCommandLine(int argc, const char ** argv,
+                 struct CmdlineInfo * const cmdlineP) {
+/*----------------------------------------------------------------------------
+   Note that the file spec array we return is stored in the storage that
+   was passed to us as the argv array.
+-----------------------------------------------------------------------------*/
+    optEntry *option_def;
+        /* Instructions to pm_optParseOptions3 on how to parse our options.
+         */
+    optStruct3 opt;
+
+    unsigned int option_def_index;
+    const char * ratioArg;
+    unsigned int ratioSpec;
+    const char * endianArg;
+    unsigned int endianSpec;
+
+    MALLOCARRAY_NOFAIL(option_def, 100);
+
+    option_def_index = 0;   /* incremented by OPTENTRY */
+    OPTENT3(0, "ratio",         OPT_STRING, &ratioArg,
+            &ratioSpec,                     0);
+    OPTENT3(0, "randomseed",    OPT_UINT,   &cmdlineP->randomseed,
+            &cmdlineP->randomseedSpec,      0);
+    OPTENT3(0, "endian",        OPT_STRING, &endianArg,
+            &endianSpec,                    0);
+    OPTENT3(0, "pack",          OPT_FLAG,   NULL,
+            &cmdlineP->pack,                0);
+
+    opt.opt_table = option_def;
+    opt.short_allowed = FALSE;  /* We have no short (old-fashioned) options */
+    opt.allowNegNum = FALSE;  /* We may have parms that are negative numbers */
+
+    pm_optParseOptions3(&argc, (char **)argv, opt, sizeof(opt), 0);
+    /* Uses and sets argc, argv, and some of *cmdlineP and others. */
+    free(option_def);
+
+    if (ratioSpec)
+        setRatio(ratioArg, &cmdlineP->numerator, &cmdlineP->precision);
+    else {
+        /* Set ratio to default: 1/2 */
+        cmdlineP->numerator = 1;
+        cmdlineP->precision = 1;
+    }
+
+    if (!endianSpec)
+        cmdlineP->bswap = false;
+    else {
+        if      (streq(endianArg, "native"))
+            cmdlineP->bswap = false;
+        else if (streq(endianArg, "swap"))
+            cmdlineP->bswap = true;
+        else if (streq(endianArg, "big"))
+            cmdlineP->bswap = (BYTE_ORDER == LITTLE_ENDIAN);
+        else if (streq(endianArg, "little"))
+            cmdlineP->bswap = (BYTE_ORDER != LITTLE_ENDIAN);
+        else
+            pm_error("Invalid value '%s' for -endian argument.", endianArg);
+    }
+
+    if (argc-1 != 2)
+        pm_error("Wrong number of arguments (%d).  There are two "
+                 "non-option arguments: width and height in pixels",
+                 argc-1);
+    else {
+        cmdlineP->width  = pm_parse_width (argv[1]);
+        cmdlineP->height = pm_parse_height(argv[2]);
+    }
+}
+
+
+
+static void
+writeSingleColorRaster(unsigned int const cols,
+                       unsigned int const rows,
+                       bit          const color,
+                       FILE *       const ofP) {
+/*-----------------------------------------------------------------------------
+  Generate a single-color raster of color 'color', dimensions
+  'cols' by 'rows', to output file *ofP.
+-----------------------------------------------------------------------------*/
+    unsigned int const lastColChar = (cols - 1) / 8;
+
+    unsigned char * bitrow0;
+    unsigned int i;
+
+    bitrow0 = pbm_allocrow_packed(cols + 32);
+
+    for (i = 0; i <= lastColChar; ++i)
+        bitrow0[i] = color * 0xff;
+
+    if (color != 0)
+        pbm_cleanrowend_packed(bitrow0, cols);
+
+    /* row end trimming, not necessary with white */
+
+    {
+        unsigned int row;
+        for (row = 0; row < rows; ++row)
+            pbm_writepbmrow_packed(ofP, bitrow0, cols, 0);
+    }
+    pbm_freerow(bitrow0);
+}
+
+
+
+static uint32_t
+randombits(unsigned int       const precision,
+           unsigned int       const numerator,
+           struct pm_randSt * const randStP) {
+/*----------------------------------------------------------------------------
+  Generate 32 random bits so that for each bit the probability of "1"
+  being generated is numerator / (2 ^ precision).
+
+  How this works:
+
+  Ratios such as 1/8, 7/8, 1/16, 15/16, 1/32, 31/32 are straightforward.  How
+  do you get intermediate values such as 3/8, 5/8, 3/16, 5/16, 7/16?
+
+  Imagine a set of 10 bits which are 90% 1, 10% 0 and a random number source
+  which produces 1 and 0 in even proportions.
+
+  Conduct "and" and "or" on these bits:
+
+           0011111111 (90%)       0011111111 (90%)
+      and) 0101010101 (50%)   or) 0101010101 (50%)
+      ---------------------   --------------------
+           0001010101 (45%)       0111111111 (95%)
+
+  It can be seen from this example that an "and" operation gives a new ratio
+  which is halfway between the old ratio (90% in this example) and 0%, while
+  "or" gives one at the middle of the old ratio and 100% The corresponding
+  binary operations for fixed-point fractions are: "right-shift by one and
+  insert a 0 behind the fixed point" and "right-shift by one and insert a 1
+  behind the fixed point" respecatbly.
+
+  115/128 = 89.84% (near 90%)  In binary fix-point: 0.1110011
+  0.01110011 = 115/256 = 44.92%
+  0.11110011 = 243/256 = 94.92%
+
+  So to achieve the desired ratio, start at the LSB (right end) of
+  'numerator'.  Initialize the output bits to zero.  Conduct an "and" for each
+  0 and an "or" for each 1 with a freshly drawn random number until the fixed
+  point is reached.
+
+  An "and" operation of a random number and zero always yields zero.  To avoid
+  waste, we reduce terms to eliminate the trailing zeroes in 'numerator' and
+  indicate the fixed point with 'precision'.  Each time the program is
+  executed the location of the fixed point is set anew, but it stays constant
+  until the program exits.
+----------------------------------------------------------------------------*/
+    unsigned int i;
+    uint32_t mask;
+    uint32_t retval;
+
+    for (i = 0, mask = 0x01, retval=0x00000000;
+         i < precision;
+         ++i, mask <<= 1) {
+
+        uint32_t const randval = pm_rand32(randStP);
+
+        if ((numerator & mask) != 0 )
+            retval |= randval;
+        else
+            retval &= randval;
+    }
+    return retval;
+}
+
+
+
+static uint32_t
+swapWord(uint32_t const word) {
+/*----------------------------------------------------------------------------
+  Swap four bytes.
+  This swap method works regardless of native system endianness.
+----------------------------------------------------------------------------*/
+    uint32_t const retval =
+        ((word >> 24) & 0xff) |
+        ((word >>  8) & 0xff00) |
+        ((word <<  8) & 0xff0000) |
+        ((word << 24) & 0xff000000)
+        ;
+
+    return retval;
+}
+
+
+
+static void
+swapBitrow(unsigned char * const bitrow,
+           unsigned int    const words,
+           bool            const bswap) {
+/*----------------------------------------------------------------------------
+  Modify bits in 'bitrow', swapping as indicated.
+----------------------------------------------------------------------------*/
+    uint32_t * const bitrowByWord = (uint32_t *) bitrow;
+
+    unsigned int wordCnt;
+
+    for (wordCnt=0; wordCnt < words; ++wordCnt) {
+        uint32_t const inWord = bitrowByWord[wordCnt];
+
+        bitrowByWord[wordCnt] = bswap ? swapWord(inWord) : inWord;
+    }
+}
+
+
+
+static void
+pbmnoise(FILE *             const ofP,
+         unsigned int       const cols,
+         unsigned int       const rows,
+         unsigned int       const numerator,
+         unsigned int       const precision,
+         bool               const bswap,
+         struct pm_randSt * const randStP) {
+/*----------------------------------------------------------------------------
+  Default method of constructing rows.
+
+  Generate pixels in units of 32 bits.
+
+  If cols is not a multiple of 32, discard pixels beyond row end.
+-----------------------------------------------------------------------------*/
+    unsigned int const words = (cols + 31) / 32;
+
+    unsigned char * bitrow;
+    unsigned int row;
+    unsigned int wordCnt;
+
+    bitrow = pbm_allocrow_packed(cols + 32);
+
+    for (row = 0; row < rows; ++row) {
+        uint32_t * const bitrowByWord = (uint32_t *) bitrow;
+
+        for (wordCnt = 0; wordCnt < words; ++wordCnt)
+            bitrowByWord[wordCnt] = randombits(precision, numerator, randStP);
+
+        if (bswap)
+            swapBitrow(bitrow, words, bswap);
+
+        pbm_cleanrowend_packed(bitrow, cols);
+        pbm_writepbmrow_packed(ofP, bitrow, cols, 0);
+    }
+    pbm_freerow(bitrow);
+}
+
+
+
+static void
+pbmnoise_packed(FILE *             const ofP,
+                unsigned int       const cols,
+                unsigned int       const rows,
+                unsigned int       const numerator,
+                unsigned int       const precision,
+                bool               const bswap,
+                struct pm_randSt * const randStP) {
+/*----------------------------------------------------------------------------
+  Alternate method of constructing rows.
+  Like the default pbmnoise(), generate pixels in units of 32 bits
+  but carry over unused pixel data at row end to the next row.
+-----------------------------------------------------------------------------*/
+    unsigned char * bitrow0;
+    uint32_t * bitrowByWord;
+    unsigned int offset;
+    unsigned int row;
+    uint32_t wordSave;    /* Pixels carried over to next row */
+
+    bitrow0 = pbm_allocrow_packed(cols + 63);
+    bitrowByWord = (uint32_t *) bitrow0;
+
+    for (row = 0, offset = 0; row < rows; ++row) {
+        if (offset == 0) {
+            unsigned int const words = (cols + 31 ) / 32;
+
+            unsigned int wordCnt;
+
+            for (wordCnt = 0; wordCnt< words; ++wordCnt) {
+                bitrowByWord[wordCnt] =
+                    randombits(precision, numerator, randStP);
+            }
+
+            if (bswap)
+                swapBitrow(bitrow0, words, bswap);
+
+            wordSave = bitrowByWord[words - 1];
+
+            pbm_cleanrowend_packed(bitrow0, cols);
+            pbm_writepbmrow_packed(ofP, bitrow0, cols, 0);
+            offset = cols % 32;
+        } else {
+            unsigned int const wordsToFetch = (cols - (32 - offset) + 31) / 32;
+            unsigned int const lastWord = wordsToFetch;
+
+            unsigned int wordCnt;
+
+            bitrowByWord[0] = wordSave;
+
+            for (wordCnt = 0; wordCnt < wordsToFetch; ++wordCnt) {
+                bitrowByWord[wordCnt + 1] =
+                    randombits(precision, numerator, randStP);
+            }
+
+            if (bswap)
+                swapBitrow((unsigned char *) & bitrowByWord[1],
+                           wordsToFetch, bswap);
+
+            wordSave = bitrowByWord [lastWord];
+
+            pbm_writepbmrow_bitoffset(ofP, bitrow0, cols, 0, offset);
+            offset = (offset + cols) % 32;
+        }
+    }
+    pbm_freerow(bitrow0);
+}
+
+
+int
+main(int argc, const char *argv[]) {
+
+    struct CmdlineInfo cmdline;
+
+    pm_proginit(&argc, argv);
+
+    parseCommandLine(argc, argv, &cmdline);
+
+    pbm_writepbminit(stdout, cmdline.width, cmdline.height, 0);
+
+    if (cmdline.precision == 0) {
+        bit color;
+
+        if (cmdline.numerator == 0)
+            color = PBM_WHITE;
+        else {
+            assert (cmdline.numerator == 1);
+            color = PBM_BLACK;
+        }
+        writeSingleColorRaster(cmdline.width, cmdline.height, color, stdout);
+    } else if (cmdline.width % 32 == 0 || !cmdline.pack) {
+        struct pm_randSt randSt;
+
+        pm_randinit(&randSt);
+        pm_srand2(&randSt, cmdline.randomseedSpec, cmdline.randomseed);
+
+        pbmnoise(stdout, cmdline.width, cmdline.height,
+                 cmdline.numerator, cmdline.precision,
+                 cmdline.bswap, &randSt);
+
+        pm_randterm(&randSt);
+    } else {
+        struct pm_randSt randSt;
+
+        pm_randinit(&randSt);
+        pm_srand2(&randSt, cmdline.randomseedSpec, cmdline.randomseed);
+
+        pbmnoise_packed(stdout, cmdline.width, cmdline.height,
+                        cmdline.numerator, cmdline.precision,
+                        cmdline.bswap, &randSt);
+
+        pm_randterm(&randSt);
+    }
+    return 0;
+}
+
+
diff --git a/generator/pbmtext.c b/generator/pbmtext.c
index 7ea64857..6d4ab8c5 100644
--- a/generator/pbmtext.c
+++ b/generator/pbmtext.c
@@ -1,4 +1,4 @@
-/* pbmtext.c - render text into a bitmap
+/* pbmtext.c - render text into a PBM
 **
 ** Copyright (C) 1991 by Jef Poskanzer.
 **
@@ -81,8 +81,13 @@ textFmCmdLine(int argc, const char ** argv) {
     text[0] = '\0';
 
     for (i = 1, totaltextsize = 0; i < argc; ++i) {
-        if (i > 1) {
+        if (i > 1)
             strcat(text, " ");
+
+        if (strlen(argv[i]) > MAXLINECHARS) { /* avoid arithmetic overflow */
+            pm_error("Command line argument %u is %u characters.  "
+                     "Cannot process longer than %u",
+                     i, (unsigned) strlen(argv[i]), (unsigned) MAXLINECHARS);
         }
         totaltextsize += strlen(argv[i]) + (i > 1 ? 1 : 0);
         if (totaltextsize > MAXLINECHARS)
@@ -1105,7 +1110,7 @@ getText(PM_WCHAR             const cmdlineText[],
 
         unsigned int const lineBufTerm = LINEBUFSIZE - 1;
 
-        unsigned int maxlines;
+        unsigned int textArraySz;
             /* Maximum number of lines for which we currently have space in
                the text array
             */
@@ -1122,12 +1127,12 @@ getText(PM_WCHAR             const cmdlineText[],
         buf[lineBufTerm] = L'\1';  /* Initialize to non-zero value */
                                    /* to detect input overrun */
 
-        maxlines = 50;  /* initial value */
-        MALLOCARRAY(textArray, maxlines);
+        textArraySz = 50;  /* initial value */
+        MALLOCARRAY(textArray, textArraySz);
 
         if (!textArray)
             pm_error("Unable to allocate memory for a buffer for up to %u "
-                     "lines of text", maxlines);
+                     "lines of text", textArraySz);
 
         for (lineCount = 0, eof = false; !eof; ) {
             const char * error;
@@ -1143,9 +1148,13 @@ getText(PM_WCHAR             const cmdlineText[],
                             "is longer than %u characters. "
                             "Cannot process",
                             lineCount, (unsigned int) MAXLINECHARS);
-                    if (lineCount >= maxlines) {
-                        maxlines *= 2;
-                        REALLOCARRAY(textArray, maxlines);
+                    if (lineCount >= textArraySz) {
+                        if (textArraySz > UINT_MAX/2)
+                            pm_error("Too many lines of input for "
+                                     "computation (more than %u)",
+                                     textArraySz);
+                        textArraySz *= 2;
+                        REALLOCARRAY(textArray, textArraySz);
                         if (textArray == NULL)
                             pm_error("out of memory");
                     }
@@ -1282,6 +1291,8 @@ computeImageWidth(struct Text          const formattedText,
                   unsigned int *       const colsP,
                   unsigned int *       const maxleftbP) {
 
+    assert (pbm_maxfontwidth() < (INT_MAX - 10) / LINEBUFSIZE);
+
     if (intercharacterSpace < 0 && fontP->maxwidth < -intercharacterSpace)
         pm_error("negative -space value %.2f exceeds font width",
                  intercharacterSpace);
@@ -1562,4 +1573,3 @@ main(int argc, const char *argv[]) {
 }
 
 
-
diff --git a/generator/pbmtextps.c b/generator/pbmtextps.c
index 0c3656e7..2a1173de 100644
--- a/generator/pbmtextps.c
+++ b/generator/pbmtextps.c
@@ -27,6 +27,7 @@
 
 #define _XOPEN_SOURCE 500
   /* Make sure popen() is in stdio.h, strdup() is in string.h */
+
 #include <unistd.h>
 #include <stdio.h>
 #include <stdlib.h>
@@ -41,6 +42,8 @@
 #include "pm_system.h"
 #include "pbm.h"
 
+enum InputFmt {INPUT_LITERAL, INPUT_ASCIIHEX, INPUT_ASCII85};
+
 static void
 validateFontName(const char * const name) {
 /*-----------------------------------------------------------------------------
@@ -52,6 +55,9 @@ validateFontName(const char * const name) {
 -----------------------------------------------------------------------------*/
     unsigned int idx;
 
+    if (name[0] == '\0')
+        pm_error("Font name is empty string");
+
     for (idx = 0; name[idx] != '\0'; ++idx) {
         char const c = name[idx];
 
@@ -71,8 +77,8 @@ validateFontName(const char * const name) {
 
 
 static void
-asciiHexEncode(char *          const inbuff,
-               char *          const outbuff) {
+asciiHexEncode(const char * const inbuff,
+               char *       const outbuff) {
 /*-----------------------------------------------------------------------------
   Convert the input text string to ASCII-Hex encoding.
 
@@ -83,69 +89,357 @@ asciiHexEncode(char *          const inbuff,
 
     unsigned int idx;
 
+    outbuff[0] = '<';
+
     for (idx = 0; inbuff[idx] != '\0'; ++idx) {
         unsigned int const item = (unsigned char) inbuff[idx];
 
-        outbuff[idx*2]   = hexits[item >> 4];
-        outbuff[idx*2+1] = hexits[item & 0xF];
+        outbuff[1 + idx * 2 + 0] = hexits[item >> 4];
+        outbuff[1 + idx * 2 + 1] = hexits[item & 0xF];
     }
 
-    outbuff[idx * 2] = '\0';
+    if (idx == 0)
+        pm_message("Empty input string");
+
+    outbuff[1 + idx * 2] = '>';
+    outbuff[1 + idx * 2 + 1] = '\0';
 }
 
 
 
 static void
-buildTextFromArgs(int           const argc,
-                  const char ** const argv,
-                  const char ** const asciiHexTextP) {
+failForInvalidChar(char         const c,
+                   const char * const type) {
+
+    if (c >= 0x32 || c < 0x7F)
+        pm_error("Invalid character '%c' in '%s' input string",   c, type);
+    else
+        pm_error("Invalid character 0x%02x in '%s' input string", c, type);
+}
+
+
+
+static void
+formatNonemptyAsciiHex(const char * const inbuff,
+                       char       * const outbuff,
+                       unsigned int const inLen) {
+
+    unsigned int inIdx, outIdx;
+        /* Cursors in input and output buffers, respectively */
+    unsigned int validCharCt;
+        /* Number of valid hex characters we've processed so far in input */
+    unsigned int startIdx, endIdx;
+        /* Limits of input buffer cursor ('inIdx') */
+
+     if (inbuff[0] == '<') {
+         startIdx = 1;
+         endIdx = inLen - 2;
+     } else {
+         startIdx = 0;
+         endIdx = inLen - 1;
+     }
+
+     validCharCt = 0;  /* No valid characters seen yet */
+
+     outIdx = 0;  /* Start at beginning of output buffer */
+
+     outbuff[outIdx++] = '<';
+
+     for (inIdx = startIdx; inIdx <= endIdx; ++inIdx) {
+         switch (inbuff[inIdx]) {
+         case '<':
+         case '>':
+             pm_error("Misplaced character '%c' in Ascii Hex input string",
+                      inbuff[inIdx]);
+           break;
+         case '\f':
+         case '\n':
+         case '\r':
+         case ' ':
+         case '\t':
+             /* ignore whitespace chars */
+             break;
+         default:
+             if ((inbuff [inIdx] >='0' && inbuff [inIdx] <='9') ||
+                 (inbuff [inIdx] >='A' && inbuff [inIdx] <='F') ||
+                 (inbuff [inIdx] >='a' && inbuff [inIdx] <='f')) {
+
+                 outbuff[outIdx++] = inbuff [inIdx];
+                 ++validCharCt;
+             } else
+                 failForInvalidChar(inbuff[inIdx], "Ascii Hex");
+             break;
+         }
+     }
+
+     if (validCharCt == 0)
+         pm_message("Empty Ascii Hex input string");
+     else if (validCharCt % 2 != 0)
+         pm_error("Number of characters in Ascii Hex input string "
+                  "is not even");
+
+     outbuff[outIdx++] = '>';
+     outbuff[outIdx++] = '\0';
+}
+
+
+
+static void
+formatAsciiHexString(const char * const inbuff,
+                     char       * const outbuff,
+                     unsigned int const inLen) {
 /*----------------------------------------------------------------------------
-   Build the array of text to be included in the Postscript program to
-   be rendered, from the arguments of this program.
-
-   We encode it in ASCII-Hex notation as opposed to using the plain text from
-   the command line because 1) the command line might have Postscript control
-   characters in it; and 2) the command line might have text in 8-bit or
-   multibyte code, but a Postscript program is supposed to be entirely
-   printable ASCII characters.
------------------------------------------------------------------------------*/
-    char * text;
+  Format the ASCII Hex input 'inbuff' as a Postscript ASCII Hex string,
+  e.g. "<313233>".  Input can be just the ASCII Hex (e.g. "313233") or already
+  formatted (e.g. "<313233>").  Input may also contain white space, which we
+  ignore -- our output never contains white space.  Though in Postscript, an
+  ASCII NUL character counts as white space, we consider it the end of the
+  input.
+
+  We consider white space outside of the <> delimiters to be an error.
+
+  Abort with error message if there is anything other than valid hex digits in
+  the ASCII hex string proper.  This is necessary to prevent code injection.
+----------------------------------------------------------------------------*/
+    if (inLen == 0 ||
+        (inLen == 2 && inbuff[0] == '<' && inbuff[inLen-1] == '>' )) {
+        pm_message("Empty Ascii Hex input string");
+        strncpy(outbuff, "<>", 3);
+    } else {
+        if (inbuff[0] == '<' && inbuff[inLen-1] != '>' )
+            pm_error("Ascii Hex input string starts with '<' "
+                     "but does not end with '>'");
+        else if (inbuff[0] != '<' && inbuff[inLen-1] == '>' )
+            pm_error("Ascii Hex input string ends with '>' "
+                     "but does not start with '<'");
+
+        formatNonemptyAsciiHex(inbuff, outbuff, inLen);
+    }
+}
+
+
+
+static void
+formatNonemptyAscii85(const char * const inbuff,
+                      char       * const outbuff,
+                      unsigned int const inLen) {
+
+    unsigned int inIdx, outIdx;
+        /* Cursors in input and output buffers, respectively */
+    unsigned int seqPos;
+        /* Position in 5-character Ascii-85 sequence where 'inIdx' points */
+    unsigned int startIdx, endIdx;
+        /* Limits of input buffer cursor ('inIdx') */
+
+    if (inLen > 4 && inbuff[0] == '<' && inbuff[1] == '~' &&
+        inbuff[inLen-2] == '~' && inbuff[inLen-1] == '>') {
+        startIdx = 2;
+        endIdx = inLen - 3;
+    } else {
+        startIdx = 0;
+        endIdx = inLen - 1;
+    }
+
+    seqPos = 0;  /* No 5-character Ascii-85 sequence encountered yet */
+    outIdx = 0;  /* Start filling output buffer from beginning */
+
+    outbuff[outIdx++] = '<';
+    outbuff[outIdx++] = '~';
+
+    for (inIdx = startIdx; inIdx <= endIdx; ++inIdx) {
+      switch (inbuff[inIdx]) {
+      case '~':
+          pm_error("Misplaced character '~' in Ascii 85 input string");
+          break;
+      case '\f':
+      case '\n':
+      case '\r':
+      case ' ':
+      case '\t':
+          break;
+      case 'z':
+          /* z extension */
+          if (seqPos > 0)
+              pm_error("Special 'z' character appears in the middle of a "
+                       "5-character Ascii-85 sequence, which is invalid");
+          else
+              outbuff[outIdx++] = inbuff[inIdx];
+          break;
+        default:
+          /* valid Ascii 85 char */
+          if (inbuff [inIdx] >='!' && inbuff [inIdx] <='u') {
+              outbuff[outIdx++] = inbuff[inIdx];
+              seqPos = (seqPos + 1) % 5;
+          } else
+              failForInvalidChar(inbuff[inIdx], "Ascii 85");
+          break;
+      }
+    }
+
+    if (outIdx == 2) {
+        pm_message("Empty Ascii 85 input string");
+    }
+
+    outbuff[outIdx++]   = '~';
+    outbuff[outIdx++] = '>';
+    outbuff[outIdx++] = '\0';
+}
+
+
+
+static void
+formatAscii85String(const char * const inbuff,
+                    char       * const outbuff,
+                    unsigned int const inLen) {
+/*----------------------------------------------------------------------------
+  Format the Ascii-85 input 'inbuff' as a Postscript Ascii-85 string,
+  e.g. "<~313233~>".  Input can be just the Ascii-85 (e.g. "313233") or
+  already formatted (e.g. "<~313233~>").  Input may also contain white space,
+  which we ignore -- our output never contains white space.  Though in
+  Postscript, an ASCII NUL character counts as white space, we consider it the
+  end of the input.
+
+  We consider white space outside of the <~~> delimiters to be an error.
+
+  Abort with error message if we encounter anything other than valid Ascii-85
+  encoding characters in the string proper.  Note that the Adobe variant
+  does not support the "y" extention.
+----------------------------------------------------------------------------*/
+    if (inLen == 0 || (inLen == 4 && strncmp (inbuff, "<~~>", 4) == 0)) {
+        pm_message("Empty Ascii 85 input string");
+        strncpy(outbuff,"<~~>", 5);
+    } else {
+        if (inLen >= 2) {
+            if (inbuff[0] == '<' && inbuff[1] == '~' &&
+                (inLen < 4 || inbuff[inLen-2] != '~'
+                 || inbuff[inLen-1] != '>' ))
+                pm_error("Ascii 85 input string starts with '<~' "
+                         "but does not end with '~>'");
+            else if (inbuff[inLen-2] == '~' && inbuff[inLen-1] == '>' &&
+                     (inLen < 4 || inbuff[0] != '<' || inbuff[1] != '~'))
+                pm_error("Ascii 85 input string ends with '~>' "
+                         "but does not start with '<~'");
+        }
+        formatNonemptyAscii85(inbuff, outbuff, inLen);
+    }
+}
+
+
+
+static void
+combineArgs(int            const argc,
+            const char **  const argv,
+            const char **  const textP,
+            unsigned int * const textSizeP) {
+
     unsigned int totalTextSize;
+    char * text;
+    size_t * argSize;
     unsigned int i;
+    size_t idx;
+
+    MALLOCARRAY_NOFAIL(argSize, argc);
+        /* argv[0] not accessed; argSize[0] not used */
+
+    for (i = 1, totalTextSize = 0; i < argc; ++i) {
+        argSize[i] = strlen(argv[i]);
+        totalTextSize += argSize[i];
+    }
+
+    totalTextSize = totalTextSize + (argc - 2);  /* adjust for spaces */
+
+    MALLOCARRAY(text, totalTextSize + 1); /* add one for \0 at end */
+    if (text == NULL)
+        pm_error("out of memory allocating buffer for "
+                 "%u characters of text", totalTextSize);
+
+    strncpy(text, argv[1], argSize[1]);
+    for (i = 2, idx = argSize[1]; i < argc; ++i) {
+        text[idx++] = ' ';
+        strncpy(&text[idx], argv[i], argSize[i]);
+        idx += argSize[i];
+    }
+
+    assert(idx == totalTextSize);
+
+    text[idx++] = '\0';
+
+    assert(strlen(text) == totalTextSize);
+
+    *textP     = text;
+    *textSizeP = totalTextSize;
+
+    free(argSize);
+}
+
+
 
-    text = strdup("");
-    totalTextSize = 1;
+static void
+buildTextFromArgs(int           const argc,
+                  const char ** const argv,
+                  const char ** const inputTextP,
+                  enum InputFmt const inputFmt) {
+/*----------------------------------------------------------------------------
+   Build the string of text to be included in the Postscript program to be
+   rendered, from the arguments of this program.
+
+   We encode it in either ASCII-Hex or ASCII-85 as opposed to using the plain
+   text from the command line because 1) the command line might have
+   Postscript control characters in it; and 2) the command line might have
+   text in 8-bit or multibyte code, but a Postscript program is supposed to be
+   entirely printable ASCII characters.
+
+   Official Postscript specifications have a limit on the length of a program
+   line, which means there is a limit on the length of text string such as we
+   generate.  But we don't worry about that because Ghostscript actually
+   accepts very long program lines.
+-----------------------------------------------------------------------------*/
+    const char * text;
+        /* All the arguments ('argv') concatenated */
+    unsigned int textSize;
+        /* Length of 'text' */
 
     if (argc-1 < 1)
         pm_error("No text");
 
-    for (i = 1; i < argc; ++i) {
-        if (i > 1) {
-            totalTextSize += 1;
-            text = realloc(text, totalTextSize);
-            if (text == NULL)
-                pm_error("out of memory");
-            strcat(text, " ");
-        }
-        totalTextSize += strlen(argv[i]);
-        text = realloc(text, totalTextSize);
-        if (text == NULL)
-            pm_error("out of memory");
-        strcat(text, argv[i]);
-    }
+    combineArgs(argc, argv, &text, &textSize);
 
-    {
+    switch (inputFmt) {
+    case INPUT_LITERAL: {
         char * asciiHexText;
 
-        MALLOCARRAY(asciiHexText, totalTextSize * 2);
-
+        MALLOCARRAY(asciiHexText, textSize * 2 + 3);
         if (!asciiHexText)
             pm_error("Unable to allocate memory for hex encoding of %u "
-                     "characters of text", totalTextSize);
+                     "characters of text", textSize);
 
         asciiHexEncode(text, asciiHexText);
-        *asciiHexTextP = asciiHexText;
+        *inputTextP = asciiHexText;
+    } break;
+    case INPUT_ASCIIHEX: {
+        char * asciiHexText;
+
+        MALLOCARRAY(asciiHexText, textSize + 3);
+        if (!asciiHexText)
+            pm_error("Unable to allocate memory for hex encoding of %u "
+                     "characters of text", textSize);
+
+        formatAsciiHexString(text, asciiHexText, textSize);
+        *inputTextP = asciiHexText;
+    } break;
+    case INPUT_ASCII85: {
+        char * ascii85Text;
+
+        MALLOCARRAY(ascii85Text, textSize + 5);
+        if (!ascii85Text)
+            pm_error("Unable to allocate memory for hex encoding of %u "
+                     "characters of text", textSize);
+
+        formatAscii85String(text, ascii85Text, textSize);
+        *inputTextP = ascii85Text;
+    } break;
     }
+
     pm_strfree(text);
 }
 
@@ -155,20 +449,23 @@ struct CmdlineInfo {
     /* All the information the user supplied in the command line,
        in a form easy for the program to use.
     */
-    unsigned int res;
-    float        fontsize;
-    const char * font;
-    float        stroke;
-    float        ascent;
-    float        descent;
-    float        leftmargin;
-    float        rightmargin;
-    float        topmargin;
-    float        bottommargin;
-    unsigned int pad;
-    unsigned int verbose;
-    unsigned int dump;
-    const char * text;
+    unsigned int  res;
+    float         fontsize;
+    const char *  font;
+    float         stroke;
+    float         ascent;
+    float         descent;
+    float         leftmargin;
+    float         rightmargin;
+    float         topmargin;
+    float         bottommargin;
+    unsigned int  pad;
+    unsigned int  verbose;
+    unsigned int  dump;
+    const char *  text;
+        /* Text to render, in Postscript format, either Ascii-hex
+           (e.g. <313233>) or Ascii-85 (e.g. <~aBc-~>)
+        */
 };
 
 
@@ -189,6 +486,7 @@ parseCommandLine(int argc, const char ** argv,
     unsigned int cropSpec, ascentSpec, descentSpec;
     unsigned int leftmarginSpec, rightmarginSpec;
     unsigned int topmarginSpec, bottommarginSpec;
+    unsigned int asciihexSpec, ascii85Spec;
 
     MALLOCARRAY_NOFAIL(option_def, 100);
 
@@ -217,6 +515,10 @@ parseCommandLine(int argc, const char ** argv,
             NULL,                    &cropSpec,                 0);
     OPTENT3(0, "pad",           OPT_FLAG,
             NULL,                    &cmdlineP->pad,            0);
+    OPTENT3(0, "asciihex",      OPT_FLAG,
+            NULL,                    &asciihexSpec,             0);
+    OPTENT3(0, "ascii85",       OPT_FLAG,
+            NULL,                    &ascii85Spec,              0);
     OPTENT3(0, "verbose",       OPT_FLAG,
             NULL,                    &cmdlineP->verbose,        0);
     OPTENT3(0, "dump-ps",       OPT_FLAG,
@@ -233,8 +535,6 @@ parseCommandLine(int argc, const char ** argv,
     cmdlineP->leftmargin  = 0;
     cmdlineP->topmargin   = 0;
     cmdlineP->bottommargin = 0;
-    cropSpec       = FALSE;
-    cmdlineP->pad  = FALSE;
 
     opt.opt_table = option_def;
     opt.short_allowed = FALSE;  /* We have no short (old-fashioned) options */
@@ -244,6 +544,8 @@ parseCommandLine(int argc, const char ** argv,
 
     validateFontName(cmdlineP->font);
 
+    if (cmdlineP->res <= 0)
+        pm_error("-resolution must be positive");
     if (cmdlineP->fontsize <= 0)
         pm_error("-fontsize must be positive");
     if (cmdlineP->ascent < 0)
@@ -259,7 +561,7 @@ parseCommandLine(int argc, const char ** argv,
     if (cmdlineP->bottommargin <0)
         pm_error("-bottommargin must not be negative");
 
-    if (cropSpec == TRUE) {
+    if (cropSpec) {
         if (ascentSpec || descentSpec ||
             leftmarginSpec || rightmarginSpec ||
             topmarginSpec || bottommarginSpec ||
@@ -275,8 +577,24 @@ parseCommandLine(int argc, const char ** argv,
              cmdlineP->leftmargin = cmdlineP->fontsize / 2;
     }
 
-    buildTextFromArgs(argc, argv, &cmdlineP->text);
+    {
+        enum InputFmt inputFmt;
+
+        if (asciihexSpec) {
+            if (ascii85Spec)
+                pm_error("You cannot specify both -asciihex and -ascii85");
+            else
+                inputFmt = INPUT_ASCIIHEX;
+        } else if (ascii85Spec)
+            inputFmt = INPUT_ASCII85;
+        else
+            inputFmt = INPUT_LITERAL;
+
+        if (argc-1 < 1)
+            pm_error("No text");
 
+        buildTextFromArgs(argc, argv, &cmdlineP->text, inputFmt);
+    }
     free(option_def);
 }
 
@@ -325,7 +643,7 @@ postscriptProgram(struct CmdlineInfo const cmdline) {
         "/FindFont {/%s findfont} def\n"
         "/fontsize %f def\n"
         "/pensize %f def\n"
-        "/textstring <%s> def\n"
+        "/textstring %s def\n"
         "/ascent %f def\n"
         "/descent %f def\n"
         "/leftmargin %f def\n"
@@ -386,6 +704,13 @@ postscriptProgram(struct CmdlineInfo const cmdline) {
     const char * retval;
     const char * psVariable;
 
+    /* According to Adobe, maximum line length in a Postscript program is
+       255 characters excluding the newline.  The following may generated a
+       line longer than that if 'cmdline.text' or 'cmdline.font' is long.
+       However, Ghostscript accepts much longer lines, so we don't worry
+       about that.
+    */
+
     pm_asprintf(&psVariable, psTemplate, cmdline.font,
                 cmdline.fontsize, cmdline.stroke, cmdline.text,
                 cmdline.ascent, cmdline.descent,
@@ -413,11 +738,8 @@ gsArgList(const char *       const outputFilename,
     const char ** retval;
     unsigned int argCt;  /* Number of arguments in 'retval' so far */
 
-    if (cmdline.res <= 0)
-         pm_error("Resolution (dpi) must be positive.");
-
-    if (cmdline.fontsize <= 0)
-         pm_error("Font size must be positive.");
+    assert(cmdline.res > 0);
+    assert(cmdline.fontsize > 0);
 
     MALLOCARRAY_NOFAIL(retval, maxArgCt+2);
 
diff --git a/generator/pbmupc.c b/generator/pbmupc.c
index 6ef75654..28ccffb7 100644
--- a/generator/pbmupc.c
+++ b/generator/pbmupc.c
@@ -26,146 +26,29 @@
 #define SHORT_HEIGHT ( 8 * LINES_WIDTH )
 #define TALL_HEIGHT ( SHORT_HEIGHT + DIGIT_HEIGHT / 2 )
 
-static int alldig ARGS(( char* cp ));
-static void putdigit ARGS(( int d, bit** bits, int row0, int col0 ));
-static int addlines ARGS(( int d, bit** bits, int row0, int col0, int height, bit color ));
-static int rect ARGS(( bit** bits, int row0, int col0, int height, int width, bit color ));
 
-int
-main( argc, argv )
-    int argc;
-    char* argv[];
-    {
-    register bit** bits;
-    int argn, style, rows, cols, row, digrow, col, digcolofs;
-    char* typecode;
-    char* manufcode;
-    char* prodcode;
-    int sum, p, lc0, lc1, lc2, lc3, lc4, rc0, rc1, rc2, rc3, rc4;
-    const char* const usage = "[-s1|-s2] <type> <manufac> <product>";
 
+static int
+alldig(const char * const cp) {
 
-    pbm_init( &argc, argv );
-
-    argn = 1;
-    style = 1;
-
-    /* Check for flags. */
-    while ( argn < argc && argv[argn][0] == '-' && argv[argn][1] != '\0' )
-	{
-	if ( pm_keymatch( argv[argn], "-s1", 3 ) )
-	    style = 1;
-	else if ( pm_keymatch( argv[argn], "-s2", 3 ) )
-	    style = 2;
-	else
-	    pm_usage( usage );
-	argn++;
-	}
-
-    if ( argn + 3 < argc )
-	pm_usage( usage );
-    typecode = argv[argn];
-    manufcode = argv[argn + 1];
-    prodcode = argv[argn + 2];
-    argn += 3;
-
-    if ( argn != argc )
-	pm_usage( usage );
+    unsigned int i;
 
-    if ( strlen( typecode ) != 1 || ( ! alldig( typecode ) ) ||
-	 strlen( manufcode ) != 5 || ( ! alldig ( manufcode ) ) ||
-	 strlen( prodcode ) != 5 || ( ! alldig ( prodcode ) ) )
-	pm_error(
-	    "type code must be one digit, and\n    manufacturer and product codes must be five digits" );
-    p = typecode[0] - '0';
-    lc0 = manufcode[0] - '0';
-    lc1 = manufcode[1] - '0';
-    lc2 = manufcode[2] - '0';
-    lc3 = manufcode[3] - '0';
-    lc4 = manufcode[4] - '0';
-    rc0 = prodcode[0] - '0';
-    rc1 = prodcode[1] - '0';
-    rc2 = prodcode[2] - '0';
-    rc3 = prodcode[3] - '0';
-    rc4 = prodcode[4] - '0';
-    sum = ( 10 - ( ( ( p + lc1 + lc3 + rc0 + rc2 + rc4 ) * 3 + lc0 + lc2 + lc4 + rc1 + rc3 ) % 10 ) ) % 10;
+    for (i = 0; cp[i] != '\0'; ++i)
+        if (cp[i] < '0' || cp[i] > '9')
+            return 0;
 
-    rows = 2 * MARGIN + SHORT_HEIGHT + DIGIT_HEIGHT;
-    cols = 2 * MARGIN + 12 * LINES_WIDTH + 11 * LINE1_WIDTH;
-    bits = pbm_allocarray( cols, rows );
+    return 1;
+}
 
-    (void) rect( bits, 0, 0, rows, cols, PBM_WHITE );
-    
-    row = MARGIN;
-    digrow = row + SHORT_HEIGHT;
-    col = MARGIN;
-    digcolofs = ( LINES_WIDTH - DIGIT_WIDTH ) / 2;
-
-    if ( style == 1 )
-	putdigit( p, bits, digrow, col - DIGIT_WIDTH - LINE1_WIDTH );
-    else if ( style == 2 )
-	putdigit(
-	    p, bits, row + SHORT_HEIGHT / 2, col - DIGIT_WIDTH - LINE1_WIDTH );
-    col = rect( bits, row, col, TALL_HEIGHT, LINE1_WIDTH, PBM_BLACK );
-    col = rect( bits, row, col, TALL_HEIGHT, LINE1_WIDTH, PBM_WHITE );
-    col = rect( bits, row, col, TALL_HEIGHT, LINE1_WIDTH, PBM_BLACK );
-    col = addlines( p, bits, row, col, TALL_HEIGHT, PBM_WHITE );
-    putdigit( lc0, bits, digrow, col + digcolofs );
-    col = addlines( lc0, bits, row, col, SHORT_HEIGHT, PBM_WHITE );
-    putdigit( lc1, bits, digrow, col + digcolofs );
-    col = addlines( lc1, bits, row, col, SHORT_HEIGHT, PBM_WHITE );
-    putdigit( lc2, bits, digrow, col + digcolofs );
-    col = addlines( lc2, bits, row, col, SHORT_HEIGHT, PBM_WHITE );
-    putdigit( lc3, bits, digrow, col + digcolofs );
-    col = addlines( lc3, bits, row, col, SHORT_HEIGHT, PBM_WHITE );
-    putdigit( lc4, bits, digrow, col + digcolofs );
-    col = addlines( lc4, bits, row, col, SHORT_HEIGHT, PBM_WHITE );
-    col = rect( bits, row, col, TALL_HEIGHT, LINE1_WIDTH, PBM_WHITE );
-    col = rect( bits, row, col, TALL_HEIGHT, LINE1_WIDTH, PBM_BLACK );
-    col = rect( bits, row, col, TALL_HEIGHT, LINE1_WIDTH, PBM_WHITE );
-    col = rect( bits, row, col, TALL_HEIGHT, LINE1_WIDTH, PBM_BLACK );
-    col = rect( bits, row, col, TALL_HEIGHT, LINE1_WIDTH, PBM_WHITE );
-    putdigit( rc0, bits, digrow, col + digcolofs );
-    col = addlines( rc0, bits, row, col, SHORT_HEIGHT, PBM_BLACK );
-    putdigit( rc1, bits, digrow, col + digcolofs );
-    col = addlines( rc1, bits, row, col, SHORT_HEIGHT, PBM_BLACK );
-    putdigit( rc2, bits, digrow, col + digcolofs );
-    col = addlines( rc2, bits, row, col, SHORT_HEIGHT, PBM_BLACK );
-    putdigit( rc3, bits, digrow, col + digcolofs );
-    col = addlines( rc3, bits, row, col, SHORT_HEIGHT, PBM_BLACK );
-    putdigit( rc4, bits, digrow, col + digcolofs );
-    col = addlines( rc4, bits, row, col, SHORT_HEIGHT, PBM_BLACK );
-    col = addlines( sum, bits, row, col, TALL_HEIGHT, PBM_BLACK );
-    col = rect( bits, row, col, TALL_HEIGHT, LINE1_WIDTH, PBM_BLACK );
-    col = rect( bits, row, col, TALL_HEIGHT, LINE1_WIDTH, PBM_WHITE );
-    col = rect( bits, row, col, TALL_HEIGHT, LINE1_WIDTH, PBM_BLACK );
-    if ( style == 1 )
-	putdigit( sum, bits, digrow, col + LINE1_WIDTH );
-
-    pbm_writepbm( stdout, bits, cols, rows, 0 );
-    pm_close( stdout );
-
-    exit( 0 );
-    }
 
-static int
-alldig( cp )
-    char* cp;
-    {
-    for ( ; *cp != '\0'; cp++ )
-	if ( *cp < '0' || *cp > '9' )
-	    return 0;
-    return 1;
-    }
 
 static void
-putdigit( d, bits, row0, col0 )
-    int d;
-    bit** bits;
-    int row0, col0;
-    {
-    int row, col;
-    static bit digits[10][DIGIT_HEIGHT][DIGIT_WIDTH] = {
+putDigit(int          const d,
+         bit **       const bits,
+         unsigned int const row0,
+         unsigned int const col0) {
+
+    static bit const digits[10][DIGIT_HEIGHT][DIGIT_WIDTH] = {
         /* 0 */
         {
             {0,0,0,0,0,0,0,0,0,0,0,0,0,0},
@@ -399,7 +282,7 @@ putdigit( d, bits, row0, col0 )
             {0,0,0,1,1,1,1,1,1,1,1,0,0,0},
             {0,0,0,0,0,0,0,0,0,0,0,0,0,0},
             {0,0,0,0,0,0,0,0,0,0,0,0,0,0}
-        }, 
+        },
         /* 9 */
         {
             {0,0,0,0,0,0,0,0,0,0,0,0,0,0},
@@ -425,103 +308,255 @@ putdigit( d, bits, row0, col0 )
             {0,0,0,0,0,1,1,0,0,0,0,0,0,0},
             {0,0,0,0,0,0,0,0,0,0,0,0,0,0},
             {0,0,0,0,0,0,0,0,0,0,0,0,0,0}
-        } 
+        }
     };
 
-    for ( row = 0; row < DIGIT_HEIGHT; row++ )
-	for ( col = 0; col < DIGIT_WIDTH; col++ )
-	    bits[row0 + row][col0 + col] = digits[d][row][col];
-    }
+    unsigned int row;
 
-static int
-addlines( int d, bit** bits, int row0, int col0, int height, bit color )
-    {
-    switch ( d )
-	{
-	case 0:
-	col0 = rect( bits, row0, col0, height, LINE3_WIDTH, color );
-	col0 = rect( bits, row0, col0, height, LINE2_WIDTH, 1 - color );
-	col0 = rect( bits, row0, col0, height, LINE1_WIDTH, color );
-	col0 = rect( bits, row0, col0, height, LINE1_WIDTH, 1 - color );
-	break;
-
-	case 1:
-	col0 = rect( bits, row0, col0, height, LINE2_WIDTH, color );
-	col0 = rect( bits, row0, col0, height, LINE2_WIDTH, 1 - color );
-	col0 = rect( bits, row0, col0, height, LINE2_WIDTH, color );
-	col0 = rect( bits, row0, col0, height, LINE1_WIDTH, 1 - color );
-	break;
-
-	case 2:
-	col0 = rect( bits, row0, col0, height, LINE2_WIDTH, color );
-	col0 = rect( bits, row0, col0, height, LINE1_WIDTH, 1 - color );
-	col0 = rect( bits, row0, col0, height, LINE2_WIDTH, color );
-	col0 = rect( bits, row0, col0, height, LINE2_WIDTH, 1 - color );
-	break;
-
-	case 3:
-	col0 = rect( bits, row0, col0, height, LINE1_WIDTH, color );
-	col0 = rect( bits, row0, col0, height, LINE4_WIDTH, 1 - color );
-	col0 = rect( bits, row0, col0, height, LINE1_WIDTH, color );
-	col0 = rect( bits, row0, col0, height, LINE1_WIDTH, 1 - color );
-	break;
-
-	case 4:
-	col0 = rect( bits, row0, col0, height, LINE1_WIDTH, color );
-	col0 = rect( bits, row0, col0, height, LINE1_WIDTH, 1 - color );
-	col0 = rect( bits, row0, col0, height, LINE3_WIDTH, color );
-	col0 = rect( bits, row0, col0, height, LINE2_WIDTH, 1 - color );
-	break;
-
-	case 5:
-	col0 = rect( bits, row0, col0, height, LINE1_WIDTH, color );
-	col0 = rect( bits, row0, col0, height, LINE2_WIDTH, 1 - color );
-	col0 = rect( bits, row0, col0, height, LINE3_WIDTH, color );
-	col0 = rect( bits, row0, col0, height, LINE1_WIDTH, 1 - color );
-	break;
-
-	case 6:
-	col0 = rect( bits, row0, col0, height, LINE1_WIDTH, color );
-	col0 = rect( bits, row0, col0, height, LINE1_WIDTH, 1 - color );
-	col0 = rect( bits, row0, col0, height, LINE1_WIDTH, color );
-	col0 = rect( bits, row0, col0, height, LINE4_WIDTH, 1 - color );
-	break;
-
-	case 7:
-	col0 = rect( bits, row0, col0, height, LINE1_WIDTH, color );
-	col0 = rect( bits, row0, col0, height, LINE3_WIDTH, 1 - color );
-	col0 = rect( bits, row0, col0, height, LINE1_WIDTH, color );
-	col0 = rect( bits, row0, col0, height, LINE2_WIDTH, 1 - color );
-	break;
-
-	case 8:
-	col0 = rect( bits, row0, col0, height, LINE1_WIDTH, color );
-	col0 = rect( bits, row0, col0, height, LINE2_WIDTH, 1 - color );
-	col0 = rect( bits, row0, col0, height, LINE1_WIDTH, color );
-	col0 = rect( bits, row0, col0, height, LINE3_WIDTH, 1 - color );
-	break;
-
-	case 9:
-	col0 = rect( bits, row0, col0, height, LINE3_WIDTH, color );
-	col0 = rect( bits, row0, col0, height, LINE1_WIDTH, 1 - color );
-	col0 = rect( bits, row0, col0, height, LINE1_WIDTH, color );
-	col0 = rect( bits, row0, col0, height, LINE2_WIDTH, 1 - color );
-	break;
-
-	default:
-	pm_error( "can't happen" );
-	}
+    for (row = 0; row < DIGIT_HEIGHT; ++row) {
+        unsigned int col;
 
-    return col0;
+        for (col = 0; col < DIGIT_WIDTH; ++col)
+            bits[row0 + row][col0 + col] = digits[d][row][col];
     }
+}
 
-static int
-rect( bit** bits, int row0, int col0, int height, int width, bit color )
-    {
-    int row, col;
 
-    for ( row = row0; row < row0 + height; row++ )
-	for ( col = col0; col < col0 + width; col++ )
-	    bits[row][col] = color;
+
+static unsigned int
+rect(bit ** const bits,
+     unsigned int const row0,
+     unsigned int const col0,
+     unsigned int const height,
+     unsigned int const width,
+     bit          const color) {
+
+    unsigned int row;
+
+    for (row = row0; row < row0 + height; ++row) {
+        unsigned int col;
+
+        for (col = col0; col < col0 + width; ++col)
+            bits[row][col] = color;
+    }
     return col0 + width;
+}
+
+
+
+static unsigned int
+addLines(int          const d,
+         bit **       const bits,
+         unsigned int const row0,
+         unsigned int const startCol,
+         unsigned int const height,
+         bit          const color) {
+
+    unsigned int col0;
+
+    col0 = startCol;  /* initial value */
+
+    switch (d) {
+    case 0:
+        col0 = rect(bits, row0, col0, height, LINE3_WIDTH, color);
+        col0 = rect(bits, row0, col0, height, LINE2_WIDTH, 1 - color);
+        col0 = rect(bits, row0, col0, height, LINE1_WIDTH, color);
+        col0 = rect(bits, row0, col0, height, LINE1_WIDTH, 1 - color);
+        break;
+
+    case 1:
+        col0 = rect(bits, row0, col0, height, LINE2_WIDTH, color);
+        col0 = rect(bits, row0, col0, height, LINE2_WIDTH, 1 - color);
+        col0 = rect(bits, row0, col0, height, LINE2_WIDTH, color);
+        col0 = rect(bits, row0, col0, height, LINE1_WIDTH, 1 - color);
+        break;
+
+    case 2:
+        col0 = rect(bits, row0, col0, height, LINE2_WIDTH, color);
+        col0 = rect(bits, row0, col0, height, LINE1_WIDTH, 1 - color);
+        col0 = rect(bits, row0, col0, height, LINE2_WIDTH, color);
+        col0 = rect(bits, row0, col0, height, LINE2_WIDTH, 1 - color);
+        break;
+
+    case 3:
+        col0 = rect(bits, row0, col0, height, LINE1_WIDTH, color);
+        col0 = rect(bits, row0, col0, height, LINE4_WIDTH, 1 - color);
+        col0 = rect(bits, row0, col0, height, LINE1_WIDTH, color);
+        col0 = rect(bits, row0, col0, height, LINE1_WIDTH, 1 - color);
+        break;
+
+    case 4:
+        col0 = rect(bits, row0, col0, height, LINE1_WIDTH, color);
+        col0 = rect(bits, row0, col0, height, LINE1_WIDTH, 1 - color);
+        col0 = rect(bits, row0, col0, height, LINE3_WIDTH, color);
+        col0 = rect(bits, row0, col0, height, LINE2_WIDTH, 1 - color);
+        break;
+
+    case 5:
+        col0 = rect(bits, row0, col0, height, LINE1_WIDTH, color);
+        col0 = rect(bits, row0, col0, height, LINE2_WIDTH, 1 - color);
+        col0 = rect(bits, row0, col0, height, LINE3_WIDTH, color);
+        col0 = rect(bits, row0, col0, height, LINE1_WIDTH, 1 - color);
+        break;
+
+    case 6:
+        col0 = rect(bits, row0, col0, height, LINE1_WIDTH, color);
+        col0 = rect(bits, row0, col0, height, LINE1_WIDTH, 1 - color);
+        col0 = rect(bits, row0, col0, height, LINE1_WIDTH, color);
+        col0 = rect(bits, row0, col0, height, LINE4_WIDTH, 1 - color);
+        break;
+
+    case 7:
+        col0 = rect(bits, row0, col0, height, LINE1_WIDTH, color);
+        col0 = rect(bits, row0, col0, height, LINE3_WIDTH, 1 - color);
+        col0 = rect(bits, row0, col0, height, LINE1_WIDTH, color);
+        col0 = rect(bits, row0, col0, height, LINE2_WIDTH, 1 - color);
+        break;
+
+    case 8:
+        col0 = rect(bits, row0, col0, height, LINE1_WIDTH, color);
+        col0 = rect(bits, row0, col0, height, LINE2_WIDTH, 1 - color);
+        col0 = rect(bits, row0, col0, height, LINE1_WIDTH, color);
+        col0 = rect(bits, row0, col0, height, LINE3_WIDTH, 1 - color);
+        break;
+
+    case 9:
+        col0 = rect(bits, row0, col0, height, LINE3_WIDTH, color);
+        col0 = rect(bits, row0, col0, height, LINE1_WIDTH, 1 - color);
+        col0 = rect(bits, row0, col0, height, LINE1_WIDTH, color);
+        col0 = rect(bits, row0, col0, height, LINE2_WIDTH, 1 - color);
+        break;
+
+    default:
+        pm_error("INTERNAL ERROR: invalid digit passed to 'addlines'");
     }
+
+    return col0;
+}
+
+
+
+int
+main(int argc, const char ** argv) {
+
+    const char* const usage = "[-s1|-s2] <type> <manufac> <product>";
+
+    bit ** bits;
+    int argn, style, rows, cols, row, digrow, col, digcolofs;
+    const char * typecode;
+    const char * manufcode;
+    const char * prodcode;
+    int sum, p, lc0, lc1, lc2, lc3, lc4, rc0, rc1, rc2, rc3, rc4;
+
+    pm_proginit(&argc, argv);
+
+    argn = 1;
+    style = 1;
+
+    /* Check for flags. */
+    while ( argn < argc && argv[argn][0] == '-' && argv[argn][1] != '\0' )
+        {
+        if ( pm_keymatch( argv[argn], "-s1", 3 ) )
+            style = 1;
+        else if ( pm_keymatch( argv[argn], "-s2", 3 ) )
+            style = 2;
+        else
+            pm_usage( usage );
+        argn++;
+        }
+
+    if ( argn + 3 < argc )
+        pm_usage( usage );
+    typecode = argv[argn];
+    manufcode = argv[argn + 1];
+    prodcode = argv[argn + 2];
+    argn += 3;
+
+    if ( argn != argc )
+        pm_usage( usage );
+
+    if ( strlen( typecode ) != 1 || ( ! alldig( typecode ) ) ||
+         strlen( manufcode ) != 5 || ( ! alldig ( manufcode ) ) ||
+         strlen( prodcode ) != 5 || ( ! alldig ( prodcode ) ) )
+        pm_error(
+            "type code must be one digit, and\n    manufacturer and product codes must be five digits" );
+    p = typecode[0] - '0';
+    lc0 = manufcode[0] - '0';
+    lc1 = manufcode[1] - '0';
+    lc2 = manufcode[2] - '0';
+    lc3 = manufcode[3] - '0';
+    lc4 = manufcode[4] - '0';
+    rc0 = prodcode[0] - '0';
+    rc1 = prodcode[1] - '0';
+    rc2 = prodcode[2] - '0';
+    rc3 = prodcode[3] - '0';
+    rc4 = prodcode[4] - '0';
+    sum = (10 -
+           (((p + lc1 + lc3 + rc0 + rc2 + rc4 ) * 3 +
+             lc0 + lc2 + lc4 + rc1 + rc3)
+            % 10)
+        )
+        % 10;
+
+    rows = 2 * MARGIN + SHORT_HEIGHT + DIGIT_HEIGHT;
+    cols = 2 * MARGIN + 12 * LINES_WIDTH + 11 * LINE1_WIDTH;
+    bits = pbm_allocarray(cols, rows);
+
+    rect(bits, 0, 0, rows, cols, PBM_WHITE);
+
+    row = MARGIN;
+    digrow = row + SHORT_HEIGHT;
+    col = MARGIN;
+    digcolofs = (LINES_WIDTH - DIGIT_WIDTH) / 2;
+
+    if (style == 1)
+        putDigit(p, bits, digrow, col - DIGIT_WIDTH - LINE1_WIDTH);
+    else if (style == 2)
+        putDigit(
+            p, bits, row + SHORT_HEIGHT / 2, col - DIGIT_WIDTH - LINE1_WIDTH);
+
+    col = rect(bits, row, col, TALL_HEIGHT, LINE1_WIDTH, PBM_BLACK);
+    col = rect(bits, row, col, TALL_HEIGHT, LINE1_WIDTH, PBM_WHITE);
+    col = rect(bits, row, col, TALL_HEIGHT, LINE1_WIDTH, PBM_BLACK);
+    col = addLines(p, bits, row, col, TALL_HEIGHT, PBM_WHITE);
+    putDigit(lc0, bits, digrow, col + digcolofs);
+    col = addLines(lc0, bits, row, col, SHORT_HEIGHT, PBM_WHITE);
+    putDigit(lc1, bits, digrow, col + digcolofs);
+    col = addLines(lc1, bits, row, col, SHORT_HEIGHT, PBM_WHITE);
+    putDigit(lc2, bits, digrow, col + digcolofs);
+    col = addLines(lc2, bits, row, col, SHORT_HEIGHT, PBM_WHITE);
+    putDigit(lc3, bits, digrow, col + digcolofs);
+    col = addLines(lc3, bits, row, col, SHORT_HEIGHT, PBM_WHITE);
+    putDigit(lc4, bits, digrow, col + digcolofs);
+    col = addLines(lc4, bits, row, col, SHORT_HEIGHT, PBM_WHITE);
+    col = rect(bits, row, col, TALL_HEIGHT, LINE1_WIDTH, PBM_WHITE);
+    col = rect(bits, row, col, TALL_HEIGHT, LINE1_WIDTH, PBM_BLACK);
+    col = rect(bits, row, col, TALL_HEIGHT, LINE1_WIDTH, PBM_WHITE);
+    col = rect(bits, row, col, TALL_HEIGHT, LINE1_WIDTH, PBM_BLACK);
+    col = rect(bits, row, col, TALL_HEIGHT, LINE1_WIDTH, PBM_WHITE);
+    putDigit(rc0, bits, digrow, col + digcolofs);
+    col = addLines(rc0, bits, row, col, SHORT_HEIGHT, PBM_BLACK);
+    putDigit(rc1, bits, digrow, col + digcolofs);
+    col = addLines(rc1, bits, row, col, SHORT_HEIGHT, PBM_BLACK);
+    putDigit(rc2, bits, digrow, col + digcolofs);
+    col = addLines(rc2, bits, row, col, SHORT_HEIGHT, PBM_BLACK);
+    putDigit(rc3, bits, digrow, col + digcolofs);
+    col = addLines(rc3, bits, row, col, SHORT_HEIGHT, PBM_BLACK);
+    putDigit(rc4, bits, digrow, col + digcolofs);
+    col = addLines(rc4, bits, row, col, SHORT_HEIGHT, PBM_BLACK);
+    col = addLines(sum, bits, row, col, TALL_HEIGHT, PBM_BLACK);
+    col = rect(bits, row, col, TALL_HEIGHT, LINE1_WIDTH, PBM_BLACK);
+    col = rect(bits, row, col, TALL_HEIGHT, LINE1_WIDTH, PBM_WHITE);
+    col = rect(bits, row, col, TALL_HEIGHT, LINE1_WIDTH, PBM_BLACK);
+    if (style == 1)
+        putDigit(sum, bits, digrow, col + LINE1_WIDTH);
+
+    pbm_writepbm(stdout, bits, cols, rows, 0);
+
+    pm_close(stdout );
+
+    exit(0);
+}
+
+
+
diff --git a/generator/pgmcrater b/generator/pgmcrater
index c66f5576..6d81df39 100755
--- a/generator/pgmcrater
+++ b/generator/pgmcrater
@@ -36,6 +36,16 @@ exec perl -w -x -S -- "$0" "$@"
 use strict;
 
 use Getopt::Long;
+use IO::Handle;
+
+
+
+sub pm_message($) {
+    STDERR->print("pgmcrater: $_[0]\n");
+}
+
+
+
 
 sub doVersionHack($) {
     my ($argvR) = @_;
@@ -69,7 +79,7 @@ my $validOptions = GetOptions(
     'randomseed=i' => \my $randomseedOpt);
 
 if (!$validOptions) {
-    print STDERR "Invalid syntax\n";
+    pm_message("Invalid syntax");
     exit(100);
 }
 
diff --git a/generator/pgmkernel.c b/generator/pgmkernel.c
index 37072c38..8d99a76d 100644
--- a/generator/pgmkernel.c
+++ b/generator/pgmkernel.c
@@ -20,7 +20,7 @@
 #include "shhopt.h"
 #include "mallocvar.h"
 #include "pgm.h"
-
+#include "nstring.h"
 
 
 struct CmdlineInfo {
@@ -39,11 +39,11 @@ static void
 parseCommandLine(int argc, const char ** argv,
                  struct CmdlineInfo * const cmdlineP) {
 /*----------------------------------------------------------------------------
-  Convert program invocation arguments (argc,argv) into a format the 
+  Convert program invocation arguments (argc,argv) into a format the
   program can use easily, struct cmdlineInfo.  Validate arguments along
   the way and exit program with message if invalid.
 
-  Note that some string information we return as *cmdlineP is in the storage 
+  Note that some string information we return as *cmdlineP is in the storage
   argv[] points to.
 -----------------------------------------------------------------------------*/
     optEntry *option_def;
@@ -57,9 +57,9 @@ parseCommandLine(int argc, const char ** argv,
     MALLOCARRAY_NOFAIL(option_def, 100);
 
     option_def_index = 0;   /* incremented by OPTENTRY */
-    OPTENT3(0,   "weight",  OPT_FLOAT, &cmdlineP->weight, 
+    OPTENT3(0,   "weight",  OPT_FLOAT, &cmdlineP->weight,
             &weightSpec,     0);
-    OPTENT3(0,   "maxval",  OPT_UINT, &cmdlineP->maxval, 
+    OPTENT3(0,   "maxval",  OPT_UINT, &cmdlineP->maxval,
             &maxvalSpec,     0);
 
     opt.opt_table = option_def;
@@ -89,20 +89,30 @@ parseCommandLine(int argc, const char ** argv,
     if (argc-1 < 1)
         pm_error("Need at least one argument: size of (square) kernel");
     else if (argc-1 == 1) {
-        if (atoi(argv[1]) <= 0)
+        unsigned int dimension;
+        const char * error;
+
+        pm_string_to_uint(argv[1], &dimension, &error);
+        if (error) {
+            pm_error("'%s' is invalid as an image width/height.  %s", argv[1], error);
+            pm_strfree(error);
+        }
+        if (dimension <= 0)
             pm_error("Dimension must be a positive number.  "
                      "You specified '%s'", argv[1]);
-        cmdlineP->cols = atoi(argv[1]);
-        cmdlineP->rows = atoi(argv[1]);
+        cmdlineP->cols = cmdlineP->rows = dimension;
+
     } else if (argc-1 == 2) {
-        if (atoi(argv[1]) <= 0)
+        unsigned int const width  = pm_parse_width(argv[1]);
+        unsigned int const height = pm_parse_height(argv[2]);
+        if (width <= 0)
             pm_error("Width must be a positive number.  "
                      "You specified '%s'", argv[1]);
-        if (atoi(argv[2]) <= 0)
+        if (height <= 0)
             pm_error("Height must be a positive number.  "
                      "You specified '%s'", argv[2]);
-        cmdlineP->cols = atoi(argv[1]);
-        cmdlineP->rows = atoi(argv[2]);
+        cmdlineP->cols = width;
+        cmdlineP->rows = height;
     } else
         pm_error("At most two arguments allowed.  "
                  "You specified %u", argc-1);
@@ -243,3 +253,6 @@ main(int argc, const char * argv[]) {
 
     return 0;
 }
+
+
+
diff --git a/generator/pgmmake.c b/generator/pgmmake.c
index ae706639..6fd8d426 100644
--- a/generator/pgmmake.c
+++ b/generator/pgmmake.c
@@ -52,11 +52,11 @@ static void
 parseCommandLine(int argc, const char ** argv,
                  struct CmdlineInfo * const cmdlineP) {
 /*----------------------------------------------------------------------------
-  Convert program invocation arguments (argc,argv) into a format the 
+  Convert program invocation arguments (argc,argv) into a format the
   program can use easily, struct cmdlineInfo.  Validate arguments along
   the way and exit program with message if invalid.
 
-  Note that some string information we return as *cmdlineP is in the storage 
+  Note that some string information we return as *cmdlineP is in the storage
   argv[] points to.
 -----------------------------------------------------------------------------*/
     optEntry * option_def;
diff --git a/generator/pgmnoise.c b/generator/pgmnoise.c
index e3e4eca6..ea35956b 100644
--- a/generator/pgmnoise.c
+++ b/generator/pgmnoise.c
@@ -7,12 +7,17 @@
 #include "pm_c_util.h"
 #include "mallocvar.h"
 #include "nstring.h"
+#include "rand.h"
 #include "shhopt.h"
 #include "pgm.h"
 
+/* constants */
+static unsigned long int const ceil31bits = 0x7fffffffUL;
+static unsigned long int const ceil32bits = 0xffffffffUL;
 
 
-struct cmdlineInfo {
+
+struct CmdlineInfo {
     /* All the information the user supplied in the command line,
        in a form easy for the program to use.
     */
@@ -21,13 +26,15 @@ struct cmdlineInfo {
     unsigned int maxval;
     unsigned int randomseed;
     unsigned int randomseedSpec;
+    unsigned int verbose;
 };
 
 
 
 static void
-parseCommandLine(int argc, const char ** const argv,
-                 struct cmdlineInfo * const cmdlineP) {
+parseCommandLine(int argc,
+                 const char **        const argv,
+                 struct CmdlineInfo * const cmdlineP) {
 /*----------------------------------------------------------------------------
    Note that the file spec array we return is stored in the storage that
    was passed to us as the argv array.
@@ -46,6 +53,8 @@ parseCommandLine(int argc, const char ** const argv,
             &cmdlineP->randomseedSpec,      0);
     OPTENT3(0,   "maxval",       OPT_UINT,    &cmdlineP->maxval,
             &maxvalSpec,                    0);
+    OPTENT3(0,   "verbose",      OPT_FLAG,    NULL,
+            &cmdlineP->verbose,             0);
 
     opt.opt_table = option_def;
     opt.short_allowed = FALSE;  /* We have no short (old-fashioned) options */
@@ -57,7 +66,7 @@ parseCommandLine(int argc, const char ** const argv,
 
     if (maxvalSpec) {
         if (cmdlineP->maxval > PGM_OVERALLMAXVAL)
-            pm_error("Maxval too large: %u.  Maximu is %u",
+            pm_error("Maxval too large: %u.  Maximum is %u",
                      cmdlineP->maxval, PGM_OVERALLMAXVAL);
         else if (cmdlineP->maxval == 0)
             pm_error("Maxval must not be zero");
@@ -95,38 +104,43 @@ parseCommandLine(int argc, const char ** const argv,
 
 
 static unsigned int
-randPool(unsigned int const digits) {
+randPool(unsigned int       const nDigits,
+         struct pm_randSt * const randStP) {
 /*----------------------------------------------------------------------------
-  Draw 'digits' bits from pool of random bits.  If the number of random bits
-  in pool is insufficient, call rand() and add 31 bits to it.
+  Draw 'nDigits' bits from pool of random bits.  If the number of random bits
+  in pool is insufficient, call pm_rand() and add N bits to it.
+
+  N is 31 or 32.  In raw mode we use N = 32 regardless of the actual number of
+  available bits.  If there are only 31 available, we use zero for the MSB.
 
-  'digits' must be at most 16.
+  'nDigits' must be at most 16.
 
-  We assume that each call to rand() generates 31 bits, or RAND_MAX ==
-  2147483647.
+  We assume that each call to pm_rand() generates 31 or 32 bits, or
+  randStP->max == 2147483647 or 4294967295.
 
-  The underlying logic is flexible and endian-free.  The above conditions
-  can be relaxed.
+  The underlying logic is flexible and endian-free.  The above conditions can
+  be relaxed.
 -----------------------------------------------------------------------------*/
     static unsigned long int hold=0;  /* entropy pool */
     static unsigned int len=0;        /* number of valid bits in pool */
 
-    unsigned int const mask = (1 << digits) - 1;
-
+    unsigned int const mask = (1 << nDigits) - 1;
+    unsigned int const randbits = (randStP->max == ceil31bits) ? 31 : 32;
     unsigned int retval;
 
-    assert(RAND_MAX == 2147483647 && digits <= 16);
+    assert(randStP->max == ceil31bits || randStP->max == ceil32bits);
+    assert(nDigits <= 16);
 
     retval = hold;  /* initial value */
 
-    if (len > digits) { /* Enough bits in hold to satisfy request */
-        hold >>= digits;
-        len   -= digits;
-    } else {              /* Load another 31 bits into hold */
-        hold    = rand();
+    if (len > nDigits) { /* Enough bits in hold to satisfy request */
+        hold >>= nDigits;
+        len   -= nDigits;
+    } else {            /* Load another 31 or 32 bits into hold */
+        hold    = pm_rand(randStP);
         retval |= (hold << len);
-        hold >>=  (digits - len);
-        len = 31 - digits + len;
+        hold >>=  (nDigits - len);
+        len = randbits - nDigits + len;
     }
     return (retval & mask);
 }
@@ -134,36 +148,61 @@ randPool(unsigned int const digits) {
 
 
 static void
-pgmnoise(FILE *       const ofP,
-         unsigned int const cols,
-         unsigned int const rows,
-         gray         const maxval) {
+reportVerbose(struct pm_randSt * const randStP,
+              gray               const maxval,
+              bool               const usingPool)  {
+
+    pm_message("random seed: %u", randStP->seed);
+    pm_message("random max: %u maxval: %u", randStP->max, maxval);
+    pm_message("method: %s", usingPool ? "pool" : "modulo");
+}
+
+
 
-    bool const usingPool = !(RAND_MAX==2147483647 && (maxval & (maxval+1)));
+static void
+pgmnoise(FILE *             const ofP,
+         unsigned int       const cols,
+         unsigned int       const rows,
+         gray               const maxval,
+         bool               const verbose,
+         struct pm_randSt * const randStP) {
+
+    bool const usingPool =
+        (randStP->max==ceil31bits || randStP->max==ceil32bits) &&
+        !(maxval & (maxval+1));
     unsigned int const bitLen = pm_maxvaltobits(maxval);
 
     unsigned int row;
     gray * destrow;
 
     /* If maxval is 2^n-1, we draw exactly n bits from the pool.
-       Otherwise call rand() and determine gray value by modulo.
+       Otherwise call pm_rand() and determine gray value by modulo.
 
        In the latter case, there is a minuscule skew toward 0 (=black)
        because smaller numbers are produced more frequently by modulo.
        Thus we employ the pool method only when it is certain that no
-       skew will ensue.
+       skew will result.
 
        To illustrate the point, consider converting the outcome of one
        roll of a fair, six-sided die to 5 values (0 to 4) by N % 5.  The
-       probability for values 1, 2, 3, 4 are 1/6, but 0 alone is 2/6.
+       probability for values 1, 2, 3, 4 is 1/6, but 0 alone is 2/6.
        Average is 10/6 or 1.6667, compared to 2.0 from an ideal
        generator which produces exactly 5 values.  With two dice
        average improves to 70/36 or 1.9444.
 
        The more (distinct) dice we roll, or the more binary digits we
        draw, the smaller the skew.
+
+       The pool method is economical.  But there is an additional merit:
+       No bits are lost this way.  This gives us a means to check the
+       integrity of the random number generator.
+
+       - Akira Urushibata, March 2021
     */
 
+    if (verbose)
+        reportVerbose(randStP, maxval, usingPool);
+
     destrow = pgm_allocrow(cols);
 
     pgm_writepgminit(ofP, cols, rows, maxval, 0);
@@ -172,12 +211,11 @@ pgmnoise(FILE *       const ofP,
         if (usingPool) {
             unsigned int col;
             for (col = 0; col < cols; ++col)
-                destrow[col] = randPool(bitLen);
-        }
-        else {
+                destrow[col] = randPool(bitLen, randStP);
+        } else {
             unsigned int col;
             for (col = 0; col < cols; ++col)
-                destrow[col] = rand() % (maxval + 1);
+                destrow[col] = pm_rand(randStP) % (maxval + 1);
         }
         pgm_writepgmrow(ofP, destrow, cols, maxval, 0);
     }
@@ -191,18 +229,22 @@ int
 main(int          argc,
      const char * argv[]) {
 
-    struct cmdlineInfo cmdline;
+    struct CmdlineInfo cmdline;
+    struct pm_randSt randSt;
 
     pm_proginit(&argc, argv);
 
     parseCommandLine(argc, argv, &cmdline);
 
-    srand(cmdline.randomseedSpec ? cmdline.randomseed : pm_randseed());
+    pm_randinit(&randSt);
+    pm_srand2(&randSt, cmdline.randomseedSpec, cmdline.randomseed);
+
+    pgmnoise(stdout, cmdline.width, cmdline.height, cmdline.maxval,
+             cmdline.verbose, &randSt);
 
-    pgmnoise(stdout, cmdline.width, cmdline.height, cmdline.maxval);
+    pm_randterm(&randSt);
 
     return 0;
 }
 
 
-
diff --git a/generator/ppmcie.c b/generator/ppmcie.c
index 86325ba6..26289c3c 100644
--- a/generator/ppmcie.c
+++ b/generator/ppmcie.c
@@ -26,8 +26,11 @@
   Introduced option to plot 1976 u' v' chromaticities.
 */
 
+#define _C99_SOURCE  /* Make sure snprintf() is in stdio.h */
+
 #include <assert.h>
 #include <math.h>
+#include <stdio.h>
 
 #include "pm_c_util.h"
 #include "ppm.h"
@@ -1114,15 +1117,15 @@ writeLabel(pixel **                   const pixels,
 
     PPM_ASSIGN(rgbcolor, maxval, maxval, maxval);
 
-    pm_snprintf(sysdesc, sizeof(sysdesc),
-                "System: %s\n"
-                "Primary illuminants (X, Y)\n"
-                "     Red:  %0.4f, %0.4f\n"
-                "     Green: %0.4f, %0.4f\n"
-                "     Blue:  %0.4f, %0.4f\n"
-                "White point (X, Y): %0.4f, %0.4f",
-                cs->name, cs->xRed, cs->yRed, cs->xGreen, cs->yGreen,
-                cs->xBlue, cs->yBlue, cs->xWhite, cs->yWhite);
+    snprintf(sysdesc, sizeof(sysdesc),
+             "System: %s\n"
+             "Primary illuminants (X, Y)\n"
+             "     Red:  %0.4f, %0.4f\n"
+             "     Green: %0.4f, %0.4f\n"
+             "     Blue:  %0.4f, %0.4f\n"
+             "White point (X, Y): %0.4f, %0.4f",
+             cs->name, cs->xRed, cs->yRed, cs->xGreen, cs->yGreen,
+             cs->xBlue, cs->yBlue, cs->xWhite, cs->yWhite);
     sysdesc[sizeof(sysdesc)-1] = '\0';  /* for robustness */
 
     ppmd_text(pixels, pixcols, pixrows, maxval,
diff --git a/generator/ppmcolors.c b/generator/ppmcolors.c
index 701812d1..ecbadf72 100644
--- a/generator/ppmcolors.c
+++ b/generator/ppmcolors.c
@@ -3,7 +3,7 @@
 *******************************************************************************
   Generate a color map containing all the colors representable with a certain
   maxval.
-  
+
   THIS PROGRAM IS OBSOLETE.  USE PAMSEQ INSTEAD.  WE KEEP THIS AROUND
   FOR BACKWARD COMPATIBILITY.
 
@@ -18,7 +18,7 @@ struct cmdlineInfo {
     /* All the information the user supplied in the command line,
        in a form easy for the program to use.
     */
-    unsigned int maxval;   
+    unsigned int maxval;
 };
 
 
@@ -34,9 +34,9 @@ parseCommandLine(int argc, char ** argv, struct cmdlineInfo *cmdlineP) {
     unsigned int option_def_index;
 
     option_def_index = 0;   /* incremented by OPTENT3 */
-    OPTENT3(0,   "maxval",       OPT_UINT,   
+    OPTENT3(0,   "maxval",       OPT_UINT,
             &cmdlineP->maxval,  NULL, 0);
-    
+
 
     opt.opt_table = option_def;
     opt.short_allowed = FALSE;  /* We have no short (old-fashioned) options */
@@ -76,7 +76,7 @@ main(int argc, char *argv[]) {
 
     rc = system(cmd);
 
-    if (rc != 0) 
+    if (rc != 0)
         pm_error("pamseq|pamtopnm pipeline failed.  system() rc = %d", rc);
 
     pm_strfree(cmd);
diff --git a/generator/ppmforge.c b/generator/ppmforge.c
index 114f7f18..e32d2b59 100644
--- a/generator/ppmforge.c
+++ b/generator/ppmforge.c
@@ -34,12 +34,14 @@
 #define _XOPEN_SOURCE 500  /* get M_PI in math.h */
 
 #include <math.h>
+#include <float.h>
 #include <assert.h>
 
 #include "pm_c_util.h"
-#include "ppm.h"
 #include "mallocvar.h"
+#include "rand.h"
 #include "shhopt.h"
+#include "ppm.h"
 
 static double const hugeVal = 1e50;
 
@@ -59,12 +61,8 @@ typedef struct {
 
 /* Definition for obtaining random numbers. */
 
-#define nrand 4               /* Gauss() sample count */
-#define Cast(low, high) ((low)+(((high)-(low)) * ((rand() & 0x7FFF) / arand)))
-
 /*  Local variables  */
 
-static double arand, gaussadd, gaussfac; /* Gaussian random parameters */
 static double fracdim;            /* Fractal dimension */
 static double powscale;           /* Power law scaling exponent */
 static int meshsize = 256;        /* FFT mesh size */
@@ -92,6 +90,7 @@ struct CmdlineInfo {
     float        ice;
     int          saturation;
     unsigned int seed;
+    unsigned int seedSpec;
     int          stars;
     unsigned int starsSpec;
     unsigned int width;
@@ -172,6 +171,11 @@ parseCommandLine(int argc, const char **argv,
         if (cmdlineP->dimension <= 0.0)
             pm_error("-dimension must be greater than zero.  "
                      "You specified %f", cmdlineP->dimension);
+        else if (cmdlineP->dimension > 5.0 + FLT_EPSILON)
+            pm_error("-dimension must not be greater than 5.  "
+                     "Results are not interesting with higher numbers, so "
+                     "we assume it is a mistake.  "
+                     "You specified %f", cmdlineP->dimension);
     } else
         cmdlineP->dimension = cmdlineP->clouds ? 2.15 : 2.4;
 
@@ -238,7 +242,7 @@ parseCommandLine(int argc, const char **argv,
 
 
 static void
-fourn(float *     const data,
+fourn(double *    const data,
       const int * const nn,
       int         const ndim,
       int         const isign) {
@@ -269,7 +273,7 @@ fourn(float *     const data,
     int i1, i2, i3;
     int i2rev, i3rev, ip1, ip2, ip3, ifp1, ifp2;
     int ibit, idim, k1, k2, n, nprev, nrem, ntot;
-    float tempi, tempr;
+    double tempi, tempr;
     double theta, wi, wpi, wpr, wr, wtemp;
 
 #define SWAP(a,b) tempr=(a); (a) = (b); (b) = tempr
@@ -332,72 +336,64 @@ fourn(float *     const data,
         nprev *= n;
     }
 }
-#undef SWAP
 
 
 
-static void
-initgauss(unsigned int const seed) {
+static double
+cast(double             const low,
+     double             const high,
+     struct pm_randSt * const randStP) {
 /*----------------------------------------------------------------------------
-  Initialize random number generators.
-
-  As given in Peitgen & Saupe, page 77.
+   A random number in the range ['low', 'high'].
 -----------------------------------------------------------------------------*/
-    /* Range of random generator */
-    arand = pow(2.0, 15.0) - 1.0;
-    gaussadd = sqrt(3.0 * nrand);
-    gaussfac = 2 * gaussadd / (nrand * arand);
-    srand(seed);
+    return (low + (high - low) * pm_drand(randStP));
+
 }
 
 
 
 static double
-gauss() {
+randPhase(struct pm_randSt * const randStP) {
 /*----------------------------------------------------------------------------
-  A Gaussian random number.
-
-  As given in Peitgen & Saupe, page 77.
+   A random number in the range [0, 2 * PI).
 -----------------------------------------------------------------------------*/
-    int i;
-    double sum;
+     return (2.0 * M_PI * pm_drand1(randStP));
 
-    for (i = 1, sum = 0.0; i <= nrand; ++i) {
-        sum += (rand() & 0x7FFF);
-    }
-    return gaussfac * sum - gaussadd;
 }
 
 
 
 static void
-spectralsynth(float **     const x,
-              unsigned int const n,
-              double        const h) {
+spectralsynth(double **          const aP,
+              unsigned int       const n,
+              double             const h,
+              struct pm_randSt * const randStP) {
 /*----------------------------------------------------------------------------
   Spectrally synthesized fractal motion in two dimensions.
 
   This algorithm is given under the name SpectralSynthesisFM2D on page 108 of
   Peitgen & Saupe.
 -----------------------------------------------------------------------------*/
-    unsigned bl;
+    unsigned int const bl = ((((unsigned long) n) * n) + 1) * 2;
+
     int i, j, i0, j0, nsize[3];
     double rad, phase, rcos, rsin;
-    float *a;
+    double * a;
+
+    MALLOCARRAY(a, bl);
 
-    bl = ((((unsigned long) n) * n) + 1) * 2 * sizeof(float);
-    a = (float *) calloc(bl, 1);
-    if (a == (float *) 0) {
-        pm_error("Cannot allocate %d x %d result array (% d bytes).",
+    if (!a) {
+        pm_error("Cannot allocate %u x %u result array (%u doubles).",
                  n, n, bl);
     }
-    *x = a;
+    for (i = 0; i < bl; ++i)
+        a[i] = 0.0;  /* initial value */
 
     for (i = 0; i <= n / 2; i++) {
         for (j = 0; j <= n / 2; j++) {
-            phase = 2 * M_PI * ((rand() & 0x7FFF) / arand);
+            phase = randPhase(randStP);
             if (i != 0 || j != 0) {
-                rad = pow((double) (i * i + j * j), -(h + 1) / 2) * gauss();
+                rad = pow( (double) (i*i + j*j), - (h + 1) / 2) * pm_gaussrand(randStP);
             } else {
                 rad = 0;
             }
@@ -416,8 +412,8 @@ spectralsynth(float **     const x,
     Imag(a, n / 2, n / 2) = 0;
     for (i = 1; i <= n / 2 - 1; i++) {
         for (j = 1; j <= n / 2 - 1; j++) {
-            phase = 2 * M_PI * ((rand() & 0x7FFF) / arand);
-            rad = pow((double) (i * i + j * j), -(h + 1) / 2) * gauss();
+            phase = randPhase(randStP);
+            rad = pow((double) (i * i + j * j), -(h + 1) / 2) * pm_gaussrand(randStP);
             rcos = rad * cos(phase);
             rsin = rad * sin(phase);
             Real(a, i, n - j) = rcos;
@@ -430,6 +426,8 @@ spectralsynth(float **     const x,
     nsize[0] = 0;
     nsize[1] = nsize[2] = n;          /* Dimension of frequency domain array */
     fourn(a, nsize, 2, -1);       /* Take inverse 2D Fourier transform */
+
+    *aP = a;
 }
 
 
@@ -469,22 +467,22 @@ temprgb(double   const temp,
 
 
 static void
-etoile(pixel * const pix) {
+etoile(pixel *        const pix,
+       struct pm_randSt * const randStP) {
 /*----------------------------------------------------------------------------
     Set a pixel in the starry sky.
 -----------------------------------------------------------------------------*/
-    if ((rand() % 1000) < starfraction) {
-#define StarQuality 0.5       /* Brightness distribution exponent */
-#define StarIntensity   8         /* Brightness scale factor */
-#define StarTintExp 0.5       /* Tint distribution exponent */
-        double v = StarIntensity * pow(1 / (1 - Cast(0, 0.9999)),
-                                       (double) StarQuality),
-            temp,
-            r, g, b;
-
-        if (v > 255) {
-            v = 255;
-        }
+    if ((pm_rand(randStP) % 1000) < starfraction) {
+        double const starQuality   = 0.5;
+            /* Brightness distribution exponent */
+        double const starIntensity = 8;
+            /* Brightness scale factor */
+        double const starTintExp = 0.5;
+            /* Tint distribution exponent */
+        double const v =
+            MIN(255.0,
+                starIntensity * pow(1 / (1 - cast(0, 0.9999, randStP)),
+                                    (double) starQuality));
 
         /* We make a special case for star color  of zero in order to
            prevent  floating  point  roundoff  which  would  otherwise
@@ -493,13 +491,17 @@ etoile(pixel * const pix) {
            256 shades in the image. */
 
         if (starcolor == 0) {
-            int vi = v;
+            pixval const vi = v;
 
             PPM_ASSIGN(*pix, vi, vi, vi);
         } else {
+            double temp;
+            double r, g, b;
+
             temp = 5500 + starcolor *
-                pow(1 / (1 - Cast(0, 0.9999)), StarTintExp) *
-                ((rand() & 7) ? -1 : 1);
+                pow(1 / (1 - cast(0, 0.9999, randStP)), starTintExp) *
+                ((pm_rand(randStP) & 7) ? -1 : 1);
+
             /* Constrain temperature to a reasonable value: >= 2600K
                (S Cephei/R Andromedae), <= 28,000 (Spica). */
             temp = MAX(2600, MIN(28000, temp));
@@ -535,9 +537,9 @@ atSat(double const x,
 
 
 static unsigned char *
-makeCp(float *      const a,
-       unsigned int const n,
-       pixval       const maxval) {
+makeCp(const double * const a,
+       unsigned int   const n,
+       pixval         const maxval) {
 
     /* Prescale the grid points into intensities. */
 
@@ -550,7 +552,7 @@ makeCp(float *      const a,
     if (cp == NULL)
         pm_error("Unable to allocate %u bytes for cp array", n);
 
-    ap = cp;
+    ap = cp;  /* initial value */
     {
         unsigned int i;
         for (i = 0; i < n; i++) {
@@ -565,17 +567,18 @@ makeCp(float *      const a,
 
 
 static void
-createPlanetStuff(bool             const clouds,
-                  float *          const a,
-                  unsigned int     const n,
-                  double **        const uP,
-                  double **        const u1P,
-                  unsigned int **  const bxfP,
-                  unsigned int **  const bxcP,
-                  unsigned char ** const cpP,
-                  Vector *         const sunvecP,
-                  unsigned int     const cols,
-                  pixval           const maxval) {
+createPlanetStuff(bool               const clouds,
+                  const double *     const a,
+                  unsigned int       const n,
+                  double **          const uP,
+                  double **          const u1P,
+                  unsigned int **    const bxfP,
+                  unsigned int **    const bxcP,
+                  unsigned char **   const cpP,
+                  Vector *           const sunvecP,
+                  unsigned int       const cols,
+                  pixval             const maxval,
+                  struct pm_randSt * const randStP) {
 
     double *u, *u1;
     unsigned int *bxf, *bxc;
@@ -585,8 +588,8 @@ createPlanetStuff(bool             const clouds,
 
     /* Compute incident light direction vector. */
 
-    shang = hourspec ? hourangle : Cast(0, 2 * M_PI);
-    siang = inclspec ? inclangle : Cast(-M_PI * 0.12, M_PI * 0.12);
+    shang = hourspec ? hourangle : randPhase(randStP);
+    siang = inclspec ? inclangle : cast(-M_PI * 0.12, M_PI * 0.12, randStP);
 
     sunvecP->x = sin(shang) * cos(siang);
     sunvecP->y = sin(siang);
@@ -594,7 +597,7 @@ createPlanetStuff(bool             const clouds,
 
     /* Allow only 25% of random pictures to be crescents */
 
-    if (!hourspec && ((rand() % 100) < 75)) {
+    if (!hourspec && ((pm_rand(randStP) % 100) < 75)) {
         flipped = (sunvecP->z < 0);
         sunvecP->z = fabs(sunvecP->z);
     } else
@@ -634,7 +637,7 @@ createPlanetStuff(bool             const clouds,
         pm_error("Cannot allocate %u element interpolation tables.", cols);
     {
         unsigned int j;
-        for (j = 0; j < cols; j++) {
+        for (j = 0; j < cols; ++j) {
             double const bx = (n - 1) * uprj(j, cols);
 
             bxf[j] = floor(bx);
@@ -651,8 +654,9 @@ createPlanetStuff(bool             const clouds,
 
 
 static void
-generateStarrySkyRow(pixel *      const pixels,
-                     unsigned int const cols) {
+generateStarrySkyRow(pixel *            const pixels,
+                     unsigned int       const cols,
+                     struct pm_randSt * const randStP) {
 /*----------------------------------------------------------------------------
   Generate a starry sky.  Note  that no FFT is performed;
   the output is  generated  directly  from  a  power  law
@@ -660,8 +664,8 @@ generateStarrySkyRow(pixel *      const pixels,
 -----------------------------------------------------------------------------*/
     unsigned int j;
 
-    for (j = 0; j < cols; j++)
-        etoile(pixels + j);
+    for (j = 0; j < cols; ++j)
+        etoile(pixels + j, randStP);
 }
 
 
@@ -867,21 +871,22 @@ limbDarken(int *          const irP,
 
 
 static void
-generatePlanetRow(pixel *         const pixelrow,
-                  unsigned int    const row,
-                  unsigned int    const rows,
-                  unsigned int    const cols,
-                  double          const t,
-                  double          const t1,
-                  double *        const u,
-                  double *        const u1,
-                  unsigned char * const cp,
-                  unsigned int *  const bxc,
-                  unsigned int *  const bxf,
-                  int             const byc,
-                  int             const byf,
-                  Vector          const sunvec,
-                  pixval          const maxval) {
+generatePlanetRow(pixel *            const pixelrow,
+                  unsigned int       const row,
+                  unsigned int       const rows,
+                  unsigned int       const cols,
+                  double             const t,
+                  double             const t1,
+                  double *           const u,
+                  double *           const u1,
+                  unsigned char *    const cp,
+                  unsigned int *     const bxc,
+                  unsigned int *     const bxf,
+                  int                const byc,
+                  int                const byf,
+                  Vector             const sunvec,
+                  pixval             const maxval,
+                  struct pm_randSt * const randStP) {
 
     unsigned int const StarClose = 2;
 
@@ -924,24 +929,25 @@ generatePlanetRow(pixel *         const pixelrow,
     /* Left stars */
 
     for (col = 0; (int)col < (int)(cols/2 - (lcos + StarClose)); ++col)
-        etoile(&pixelrow[col]);
+        etoile(&pixelrow[col], randStP);
 
     /* Right stars */
 
     for (col = cols/2 + (lcos + StarClose); col < cols; ++col)
-        etoile(&pixelrow[col]);
+        etoile(&pixelrow[col], randStP);
 }
 
 
 
 static void
-genplanet(bool         const stars,
-          bool         const clouds,
-          float *      const a,
-          unsigned int const cols,
-          unsigned int const rows,
-          unsigned int const n,
-          unsigned int const rseed) {
+genplanet(bool                const stars,
+          bool                const clouds,
+          const double *      const a,
+          unsigned int        const cols,
+          unsigned int        const rows,
+          unsigned int        const n,
+          unsigned int        const rseed,
+          struct pm_randSt *  const randStP) {
 /*----------------------------------------------------------------------------
   Generate planet from elevation array.
 
@@ -971,13 +977,13 @@ genplanet(bool         const stars,
                    clouds ? "clouds" : "planet",
                    rseed, fracdim, powscale, meshsize);
         createPlanetStuff(clouds, a, n, &u, &u1, &bxf, &bxc, &cp, &sunvec,
-                          cols, maxval);
+                          cols, maxval, randStP);
     }
 
     pixelrow = ppm_allocrow(cols);
     for (row = 0; row < rows; ++row) {
         if (stars)
-            generateStarrySkyRow(pixelrow, cols);
+            generateStarrySkyRow(pixelrow, cols, randStP);
         else {
             double const by = (n - 1) * uprj(row, rows);
             int    const byf = floor(by) * n;
@@ -993,7 +999,8 @@ genplanet(bool         const stars,
                 generatePlanetRow(pixelrow, row, rows, cols,
                                   t, t1, u, u1, cp, bxc, bxf, byc, byf,
                                   sunvec,
-                                  maxval);
+                                  maxval,
+                                  randStP);
         }
         ppm_writeppmrow(stdout, pixelrow, cols, maxval, FALSE);
     }
@@ -1010,9 +1017,9 @@ genplanet(bool         const stars,
 
 
 static void
-applyPowerLawScaling(float * const a,
-                     int     const meshsize,
-                     double  const powscale) {
+applyPowerLawScaling(double * const a,
+                     int      const meshsize,
+                     double   const powscale) {
 
     /* Apply power law scaling if non-unity scale is requested. */
 
@@ -1023,7 +1030,7 @@ applyPowerLawScaling(float * const a,
             for (j = 0; j < meshsize; j++) {
                 double const r = Real(a, i, j);
                 if (r > 0)
-                    Real(a, i, j) = pow(r, powscale);
+                    Real(a, i, j) = MIN(hugeVal, pow(r, powscale));
             }
         }
     }
@@ -1032,10 +1039,10 @@ applyPowerLawScaling(float * const a,
 
 
 static void
-computeExtremeReal(const float * const a,
-                   int           const meshsize,
-                   double *      const rminP,
-                   double *      const rmaxP) {
+computeExtremeReal(const double * const a,
+                   int            const meshsize,
+                   double *       const rminP,
+                   double *       const rmaxP) {
 
     /* Compute extrema for autoscaling. */
 
@@ -1061,8 +1068,8 @@ computeExtremeReal(const float * const a,
 
 
 static void
-replaceWithSpread(float * const a,
-                  int     const meshsize) {
+replaceWithSpread(double * const a,
+                  int      const meshsize) {
 /*----------------------------------------------------------------------------
   Replace the real part of each element of the 'a' array with a
   measure of how far the real is from the middle; sort of a standard
@@ -1096,17 +1103,19 @@ planet(unsigned int const cols,
 /*----------------------------------------------------------------------------
    Make a planet.
 -----------------------------------------------------------------------------*/
-    float * a;
+    double * a;
     bool error;
+    struct pm_randSt randSt;
 
-    initgauss(rseed);
+    pm_randinit(&randSt);
+    pm_srand(&randSt, rseed);
 
     if (stars) {
         a = NULL;
         error = FALSE;
     } else {
-        spectralsynth(&a, meshsize, 3.0 - fracdim);
-        if (a == NULL) {
+        spectralsynth(&a, meshsize, 3.0 - fracdim, &randSt);
+        if (!a) {
             error = TRUE;
         } else {
             applyPowerLawScaling(a, meshsize, powscale);
@@ -1117,7 +1126,7 @@ planet(unsigned int const cols,
         }
     }
     if (!error)
-        genplanet(stars, clouds, a, cols, rows, meshsize, rseed);
+        genplanet(stars, clouds, a, cols, rows, meshsize, rseed, &randSt);
 
     if (a != NULL)
         free(a);
@@ -1159,7 +1168,8 @@ main(int argc, const char ** argv) {
     cols = (MAX(cmdline.height, cmdline.width) + 1) & (~1);
     rows = cmdline.height;
 
-    success = planet(cols, rows, cmdline.night, cmdline.clouds, cmdline.seed);
+    success = planet(cols, rows, cmdline.night,
+                     cmdline.clouds, cmdline.seed);
 
     exit(success ? 0 : 1);
 }
diff --git a/generator/ppmmake.c b/generator/ppmmake.c
index 7bac9601..b1de7b52 100644
--- a/generator/ppmmake.c
+++ b/generator/ppmmake.c
@@ -31,11 +31,11 @@ static void
 parseCommandLine(int argc, char ** argv,
                  struct cmdlineInfo * const cmdlineP) {
 /*----------------------------------------------------------------------------
-  Convert program invocation arguments (argc,argv) into a format the 
+  Convert program invocation arguments (argc,argv) into a format the
   program can use easily, struct cmdlineInfo.  Validate arguments along
   the way and exit program with message if invalid.
 
-  Note that some string information we return as *cmdlineP is in the storage 
+  Note that some string information we return as *cmdlineP is in the storage
   argv[] points to.
 -----------------------------------------------------------------------------*/
     optEntry * option_def;
diff --git a/generator/ppmpat.c b/generator/ppmpat.c
index 908c200f..2f71914e 100644
--- a/generator/ppmpat.c
+++ b/generator/ppmpat.c
@@ -14,7 +14,6 @@
 #define _XOPEN_SOURCE 500  /* Make sure strdup() is in string.h */
                            /* get M_PI in math.h */
 #define _BSD_SOURCE  /* Make sure strdup() is in <string.h> */
-#define SPIROGRAPHS 0   /* Spirograph to be added soon */
 
 #include <assert.h>
 #include <math.h>
@@ -23,8 +22,9 @@
 
 #include "pm_c_util.h"
 #include "mallocvar.h"
-#include "shhopt.h"
 #include "nstring.h"
+#include "rand.h"
+#include "shhopt.h"
 #include "ppm.h"
 #include "ppmdraw.h"
 
@@ -39,12 +39,10 @@ typedef enum {
     PAT_POLES,
     PAT_SQUIG,
     PAT_CAMO,
-    PAT_ANTICAMO,
-    PAT_SPIRO1,
-    PAT_SPIRO2,
-    PAT_SPIRO3
+    PAT_ANTICAMO
 } Pattern;
 
+
 typedef struct {
 /*----------------------------------------------------------------------------
    An ordered list of colors with a cursor.
@@ -60,16 +58,79 @@ struct CmdlineInfo {
     /* All the information the user supplied in the command line,
        in a form easy for the program to use.
     */
-    Pattern      basePattern;
-    unsigned int width;
-    unsigned int height;
-    unsigned int colorSpec;
-    ColorTable   colorTable;
-    unsigned int randomseed;
-    unsigned int randomseedSpec;
+    Pattern         basePattern;
+    unsigned int    width;
+    unsigned int    height;
+    unsigned int    colorSpec;
+    ColorTable      colorTable;
+    unsigned int    randomseed;
+    unsigned int    randomseedSpec;
+    ppmd_drawproc * drawProc;
 };
 
 
+
+static pixel
+averageTwoColors(pixel const p1,
+                 pixel const p2) {
+
+    pixel p;
+
+    PPM_ASSIGN(p,
+               (PPM_GETR(p1) + PPM_GETR(p2)) / 2,
+               (PPM_GETG(p1) + PPM_GETG(p2)) / 2,
+               (PPM_GETB(p1) + PPM_GETB(p2)) / 2);
+
+    return p;
+}
+
+
+
+static ppmd_drawproc average_drawproc;
+
+static void
+average_drawproc(pixel **     const pixels,
+                 int          const cols,
+                 int          const rows,
+                 pixval       const maxval,
+                 int          const col,
+                 int          const row,
+                 const void * const clientdata) {
+/*----------------------------------------------------------------------------
+  Reset the pixel's color to the average of the original color and the color
+  indicated by * clientdata.
+-----------------------------------------------------------------------------*/
+
+    if (col >= 0 && col < cols && row >= 0 && row < rows)
+        pixels[row][col] =
+            averageTwoColors(pixels[row][col], *((const pixel*) clientdata));
+}
+
+
+
+static ppmd_drawproc checkerboard_drawproc;
+
+static void
+checkerboard_drawproc(pixel **     const pixels,
+                      int          const cols,
+                      int          const rows,
+                      pixval       const maxval,
+                      int          const col,
+                      int          const row,
+                      const void * const clientdata) {
+/*----------------------------------------------------------------------------
+  If col and row are both even or both odd, do nothing.
+  If one is even and the other is odd, set the pixel's color to that indicated
+  by * clientdata.
+-----------------------------------------------------------------------------*/
+    if (col >= 0 && col < cols && row >= 0 &&
+        row < rows && row % 2 != col % 2)
+
+        pixels[row][col] = *((const pixel*) clientdata);
+}
+
+
+
 static void
 validateColorCount(Pattern      const basePattern,
                    unsigned int const colorCount) {
@@ -80,7 +141,6 @@ validateColorCount(Pattern      const basePattern,
     switch (basePattern) {
     case PAT_GINGHAM2:
     case PAT_ARGYLE1:
-    case PAT_SPIRO1:
         if (colorCount != 2)
             pm_error("Wrong number of colors: %u. "
                      "2 colors are required for the specified pattern.",
@@ -112,8 +172,6 @@ validateColorCount(Pattern      const basePattern,
                      colorCount);
         break;
 
-    case PAT_SPIRO2:
-    case PAT_SPIRO3:
     default:
         pm_error("INTERNAL ERROR.");
     }
@@ -188,9 +246,7 @@ parseCommandLine(int argc, const char ** argv,
     unsigned int squig;
     unsigned int camo;
     unsigned int anticamo;
-    unsigned int spiro1;
-    unsigned int spiro2;
-    unsigned int spiro3;
+    unsigned int meshSpec;
 
     MALLOCARRAY_NOFAIL(option_def, 100);
 
@@ -208,9 +264,9 @@ parseCommandLine(int argc, const char ** argv,
     OPTENT3(0, "tartan",        OPT_FLAG,   NULL,
             &tartan,     0);
     OPTENT3(0, "argyle1",       OPT_FLAG,   NULL,
-            &argyle1,     0);
+            &argyle1,    0);
     OPTENT3(0, "argyle2",       OPT_FLAG,   NULL,
-            &argyle2,     0);
+            &argyle2,    0);
     OPTENT3(0, "poles",         OPT_FLAG,   NULL,
             &poles,      0);
     OPTENT3(0, "squig",         OPT_FLAG,   NULL,
@@ -219,20 +275,12 @@ parseCommandLine(int argc, const char ** argv,
             &camo,       0);
     OPTENT3(0, "anticamo",      OPT_FLAG,   NULL,
             &anticamo,   0);
-#if SPIROGRAPHS != 0
-    OPTENT3(0, "spiro1",        OPT_FLAG,   NULL,
-            &spiro1,     0);
-    OPTENT3(0, "spiro2",        OPT_FLAG,   NULL,
-            &spiro1,     0);
-    OPTENT3(0, "spiro3",        OPT_FLAG,   NULL,
-            &spiro1,     0);
-#else
-    spiro1 = spiro2 = spiro3 = 0;
-#endif
     OPTENT3(0, "color",         OPT_STRINGLIST, &colorText,
             &cmdlineP->colorSpec,           0);
     OPTENT3(0, "randomseed",    OPT_UINT,       &cmdlineP->randomseed,
             &cmdlineP->randomseedSpec,      0);
+    OPTENT3(0, "mesh",          OPT_FLAG,   NULL,
+            &meshSpec,   0);
 
     opt.opt_table = option_def;
     opt.short_allowed = FALSE;  /* We have no short (old-fashioned) options */
@@ -246,8 +294,7 @@ parseCommandLine(int argc, const char ** argv,
         gingham2 + gingham3 + madras + tartan + argyle1 + argyle2 +
         poles +
         squig +
-        camo + anticamo +
-        spiro1 + spiro2 + spiro3;
+        camo + anticamo;
 
     if (basePatternCount < 1)
         pm_error("You must specify a base pattern option such as -gingham2");
@@ -275,12 +322,6 @@ parseCommandLine(int argc, const char ** argv,
             cmdlineP->basePattern = PAT_CAMO;
         else if (anticamo)
             cmdlineP->basePattern = PAT_ANTICAMO;
-        else if (spiro1)
-            cmdlineP->basePattern = PAT_SPIRO1;
-        else if (spiro2)
-            cmdlineP->basePattern = PAT_SPIRO2;
-        else if (spiro3)
-            cmdlineP->basePattern = PAT_SPIRO3;
         else
             assert(false);  /* Every possibility is accounted for */
     }
@@ -291,12 +332,20 @@ parseCommandLine(int argc, const char ** argv,
     } else
         cmdlineP->colorTable.count = 0;
 
+    if (meshSpec) {
+        if (gingham2 + gingham3 + madras + tartan > 0)
+            cmdlineP->drawProc = &checkerboard_drawproc;
+        else
+            pm_message("-mesh ignored (no effect with specified pattern)");
+    } else
+        cmdlineP->drawProc = &average_drawproc;
+
     if (argc-1 != 2)
         pm_error("You must specify 2 non-option arguments: width and height "
                  "in pixels.  You specified %u", argc-1);
     else {
-        cmdlineP->width  = atoi(argv[1]);
-        cmdlineP->height = atoi(argv[2]);
+        cmdlineP->width  = pm_parse_width(argv[1]);
+        cmdlineP->height = pm_parse_height(argv[2]);
 
         if (cmdlineP->width < 1)
             pm_error("Width must be at least 1 pixel");
@@ -339,14 +388,15 @@ validateComputableDimensions(unsigned int const cols,
 
 
 static pixel
-randomColor(pixval const maxval) {
+randomColor(struct pm_randSt * const randStP,
+            pixval             const maxval) {
 
     pixel p;
 
     PPM_ASSIGN(p,
-               rand() % (maxval + 1),
-               rand() % (maxval + 1),
-               rand() % (maxval + 1)
+               pm_rand(randStP) % (maxval + 1),
+               pm_rand(randStP) % (maxval + 1),
+               pm_rand(randStP) % (maxval + 1)
         );
 
     return p;
@@ -354,15 +404,18 @@ randomColor(pixval const maxval) {
 
 
 
-#define DARK_THRESH 0.25
+static double const DARK_THRESH = 0.25;
+
+
 
 static pixel
-randomBrightColor(pixval const maxval) {
+randomBrightColor(struct pm_randSt * const randStP,
+                  pixval             const maxval) {
 
     pixel p;
 
     do {
-        p = randomColor(maxval);
+        p = randomColor(randStP, maxval);
     } while (PPM_LUMIN(p) <= maxval * DARK_THRESH);
 
     return p;
@@ -371,12 +424,13 @@ randomBrightColor(pixval const maxval) {
 
 
 static pixel
-randomDarkColor(pixval const maxval) {
+randomDarkColor(struct pm_randSt * const randStP,
+                pixval             const maxval) {
 
     pixel p;
 
     do {
-        p = randomColor(maxval);
+        p = randomColor(randStP, maxval);
     } while (PPM_LUMIN(p) > maxval * DARK_THRESH);
 
     return p;
@@ -384,40 +438,6 @@ randomDarkColor(pixval const maxval) {
 
 
 
-static pixel
-averageTwoColors(pixel const p1,
-                 pixel const p2) {
-
-    pixel p;
-
-    PPM_ASSIGN(p,
-               (PPM_GETR(p1) + PPM_GETR(p2)) / 2,
-               (PPM_GETG(p1) + PPM_GETG(p2)) / 2,
-               (PPM_GETB(p1) + PPM_GETB(p2)) / 2);
-
-    return p;
-}
-
-
-
-static ppmd_drawproc average_drawproc;
-
-static void
-average_drawproc(pixel **     const pixels,
-                 int          const cols,
-                 int          const rows,
-                 pixval       const maxval,
-                 int          const col,
-                 int          const row,
-                 const void * const clientdata) {
-
-    if (col >= 0 && col < cols && row >= 0 && row < rows)
-        pixels[row][col] =
-            averageTwoColors(pixels[row][col], *((const pixel*) clientdata));
-}
-
-
-
 static void
 nextColor(ColorTable * const colorTableP) {
 /*----------------------------------------------------------------------------
@@ -448,7 +468,8 @@ nextColorBg(ColorTable * const colorTableP) {
 
 
 static pixel
-randomAnticamoColor(pixval const maxval) {
+randomAnticamoColor(struct pm_randSt * const randStP,
+                    pixval             const maxval) {
 
     int v1, v2, v3;
     pixel p;
@@ -457,37 +478,49 @@ randomAnticamoColor(pixval const maxval) {
     v2 = (maxval + 1) / 2;
     v3 = 3 * v1;
 
-    switch (rand() % 15) {
+    switch (pm_rand(randStP) % 15) {
     case 0: case 1:
-        PPM_ASSIGN(p, rand() % v1 + v3, rand() % v2, rand() % v2);
+        PPM_ASSIGN(p, pm_rand(randStP) % v1 + v3,
+                      pm_rand(randStP) % v2,
+                      pm_rand(randStP) % v2);
         break;
 
     case 2:
     case 3:
-        PPM_ASSIGN(p, rand() % v2, rand() % v1 + v3, rand() % v2);
+        PPM_ASSIGN(p, pm_rand(randStP) % v2,
+                      pm_rand(randStP) % v1 + v3,
+                      pm_rand(randStP) % v2);
         break;
 
     case 4:
     case 5:
-        PPM_ASSIGN(p, rand() % v2, rand() % v2, rand() % v1 + v3);
+        PPM_ASSIGN(p, pm_rand(randStP) % v2,
+                      pm_rand(randStP) % v2,
+                      pm_rand(randStP) % v1 + v3);
         break;
 
     case 6:
     case 7:
     case 8:
-        PPM_ASSIGN(p, rand() % v2, rand() % v1 + v3, rand() % v1 + v3);
+        PPM_ASSIGN(p, pm_rand(randStP) % v2,
+                      pm_rand(randStP) % v1 + v3,
+                      pm_rand(randStP) % v1 + v3);
         break;
 
     case 9:
     case 10:
     case 11:
-        PPM_ASSIGN(p, rand() % v1 + v3, rand() % v2, rand() % v1 + v3);
+        PPM_ASSIGN(p, pm_rand(randStP) % v1 + v3,
+                      pm_rand(randStP) % v2,
+                      pm_rand(randStP) % v1 + v3);
         break;
 
     case 12:
     case 13:
     case 14:
-        PPM_ASSIGN(p, rand() % v1 + v3, rand() % v1 + v3, rand() % v2);
+        PPM_ASSIGN(p, pm_rand(randStP) % v1 + v3,
+                      pm_rand(randStP) % v1 + v3,
+                      pm_rand(randStP) % v2);
         break;
     }
 
@@ -497,7 +530,8 @@ randomAnticamoColor(pixval const maxval) {
 
 
 static pixel
-randomCamoColor(pixval const maxval) {
+randomCamoColor(struct pm_randSt * const randStP,
+                pixval             const maxval) {
 
     int const v1 = (maxval + 1 ) / 8;
     int const v2 = (maxval + 1 ) / 4;
@@ -505,31 +539,39 @@ randomCamoColor(pixval const maxval) {
 
     pixel p;
 
-    switch (rand() % 10) {
+    switch (pm_rand(randStP) % 10) {
     case 0:
     case 1:
     case 2:
         /* light brown */
-        PPM_ASSIGN(p, rand() % v3 + v3, rand() % v3 + v2, rand() % v3 + v2);
+        PPM_ASSIGN(p, pm_rand(randStP) % v3 + v3,
+                      pm_rand(randStP) % v3 + v2,
+                      pm_rand(randStP) % v3 + v2);
         break;
 
     case 3:
     case 4:
     case 5:
         /* dark green */
-        PPM_ASSIGN(p, rand() % v2, rand() % v2 + 3 * v1, rand() % v2);
+        PPM_ASSIGN(p, pm_rand(randStP) % v2,
+                      pm_rand(randStP) % v2 + 3 * v1,
+                      pm_rand(randStP) % v2);
         break;
 
     case 6:
     case 7:
         /* brown */
-        PPM_ASSIGN(p, rand() % v2 + v2, rand() % v2, rand() % v2);
+        PPM_ASSIGN(p, pm_rand(randStP) % v2 + v2,
+                      pm_rand(randStP) % v2,
+                      pm_rand(randStP) % v2);
         break;
 
     case 8:
     case 9:
         /* dark brown */
-        PPM_ASSIGN(p, rand() % v1 + v1, rand() % v1, rand() % v1);
+        PPM_ASSIGN(p, pm_rand(randStP) % v1 + v1,
+                      pm_rand(randStP) % v1,
+                      pm_rand(randStP) % v1);
         break;
     }
 
@@ -539,28 +581,30 @@ randomCamoColor(pixval const maxval) {
 
 
 static float
-rnduni(void) {
-    return rand() % 32767 / 32767.0;
+rnduni(struct pm_randSt * const randStP) {
+
+    return pm_rand(randStP) % 32767 / 32767.0;
 }
 
 
 
 static void
-clearBackgroundCamo(pixel **     const pixels,
-                    unsigned int const cols,
-                    unsigned int const rows,
-                    pixval       const maxval,
-                    ColorTable * const colorTableP,
-                    bool         const antiflag) {
+clearBackgroundCamo(pixel **           const pixels,
+                    unsigned int       const cols,
+                    unsigned int       const rows,
+                    pixval             const maxval,
+                    ColorTable *       const colorTableP,
+                    struct pm_randSt * const randStP,
+                    bool               const antiflag) {
 
     pixel color;
 
     if (colorTableP->count > 0) {
         color = colorTableP->color[0];
     } else if (antiflag)
-        color = randomAnticamoColor(maxval);
+        color = randomAnticamoColor(randStP, maxval);
     else
-        color = randomCamoColor(maxval);
+        color = randomCamoColor(randStP, maxval);
 
     ppmd_filledrectangle(
         pixels, cols, rows, maxval, 0, 0, cols, rows, PPMD_NULLDRAWPROC,
@@ -570,13 +614,14 @@ clearBackgroundCamo(pixel **     const pixels,
 
 
 static void
-camoFill(pixel **         const pixels,
-         unsigned int     const cols,
-         unsigned int     const rows,
-         pixval           const maxval,
-         struct fillobj * const fh,
-         ColorTable     * const colorTableP,
-         bool             const antiflag) {
+camoFill(pixel **           const pixels,
+         unsigned int       const cols,
+         unsigned int       const rows,
+         pixval             const maxval,
+         struct fillobj *   const fh,
+         ColorTable     *   const colorTableP,
+         struct pm_randSt * const randStP,
+         bool               const antiflag) {
 
     pixel color;
 
@@ -585,9 +630,9 @@ camoFill(pixel **         const pixels,
         color = colorTableP->color[colorTableP->index];
         nextColorBg(colorTableP);
     } else if (antiflag)
-        color = randomAnticamoColor(maxval);
+        color = randomAnticamoColor(randStP, maxval);
     else
-        color = randomCamoColor(maxval);
+        color = randomCamoColor(randStP, maxval);
 
     ppmd_fill(pixels, cols, rows, maxval, fh, PPMD_NULLDRAWPROC, &color);
 }
@@ -608,25 +653,29 @@ camoFill(pixel **         const pixels,
 
 
 static void
-computeXsYs(int *        const xs,
-            int *        const ys,
-            unsigned int const cols,
-            unsigned int const rows,
-            unsigned int const pointCt) {
-
-    unsigned int const cx = rand() % cols;
-    unsigned int const cy = rand() % rows;
-    double const a = rnduni() * (MAX_ELLIPSE_FACTOR - MIN_ELLIPSE_FACTOR) +
-        MIN_ELLIPSE_FACTOR;
-    double const b = rnduni() * (MAX_ELLIPSE_FACTOR - MIN_ELLIPSE_FACTOR) +
-        MIN_ELLIPSE_FACTOR;
-    double const theta = rnduni() * 2.0 * M_PI;
+computeXsYs(int *              const xs,
+            int *              const ys,
+            unsigned int       const cols,
+            unsigned int       const rows,
+            unsigned int       const pointCt,
+            struct pm_randSt * const randStP) {
+
+    unsigned int const cx = pm_rand(randStP) % cols;
+    unsigned int const cy = pm_rand(randStP) % rows;
+    double const a = rnduni(randStP) *
+                       (MAX_ELLIPSE_FACTOR - MIN_ELLIPSE_FACTOR) +
+                        MIN_ELLIPSE_FACTOR;
+    double const b = rnduni(randStP) *
+                       (MAX_ELLIPSE_FACTOR - MIN_ELLIPSE_FACTOR) +
+                        MIN_ELLIPSE_FACTOR;
+    double const theta = rnduni(randStP) * 2.0 * M_PI;
 
     unsigned int p;
 
     for (p = 0; p < pointCt; ++p) {
-        double const c = rnduni() * (MAX_POINT_FACTOR - MIN_POINT_FACTOR) +
-            MIN_POINT_FACTOR;
+        double const c = rnduni(randStP) *
+                           (MAX_POINT_FACTOR - MIN_POINT_FACTOR) +
+                            MIN_POINT_FACTOR;
         double const tx   = a * sin(p * 2.0 * M_PI / pointCt);
         double const ty   = b * cos(p * 2.0 * M_PI / pointCt);
         double const tang = atan2(ty, tx) + theta;
@@ -638,18 +687,20 @@ computeXsYs(int *        const xs,
 
 
 static void
-camo(pixel **     const pixels,
-     unsigned int const cols,
-     unsigned int const rows,
-     ColorTable * const colorTableP,
-     pixval       const maxval,
-     bool         const antiflag) {
+camo(pixel **           const pixels,
+     unsigned int       const cols,
+     unsigned int       const rows,
+     ColorTable *       const colorTableP,
+     struct pm_randSt * const randStP,
+     pixval             const maxval,
+     bool               const antiflag) {
 
     unsigned int const n = (rows * cols) / SQR(BLOBRAD) * 5;
 
     unsigned int i;
 
-    clearBackgroundCamo(pixels, cols, rows, maxval, colorTableP, antiflag);
+    clearBackgroundCamo(pixels, cols, rows, maxval,
+                        colorTableP, randStP, antiflag);
 
     if (colorTableP->count > 0) {
         assert(colorTableP->count > 1);
@@ -658,13 +709,13 @@ camo(pixel **     const pixels,
 
     for (i = 0; i < n; ++i) {
         unsigned int const pointCt =
-            rand() % (MAX_POINTS - MIN_POINTS + 1) + MIN_POINTS;
+            pm_rand(randStP) % (MAX_POINTS - MIN_POINTS + 1) + MIN_POINTS;
 
         int xs[MAX_POINTS], ys[MAX_POINTS];
         int x0, y0;
         struct fillobj * fh;
 
-        computeXsYs(xs, ys, cols, rows, pointCt);
+        computeXsYs(xs, ys, cols, rows, pointCt, randStP);
 
         x0 = (xs[0] + xs[pointCt - 1]) / 2;
         y0 = (ys[0] + ys[pointCt - 1]) / 2;
@@ -675,7 +726,8 @@ camo(pixel **     const pixels,
             pixels, cols, rows, maxval, x0, y0, pointCt, xs, ys, x0, y0,
             ppmd_fill_drawproc, fh);
 
-        camoFill(pixels, cols, rows, maxval, fh, colorTableP, antiflag);
+        camoFill(pixels, cols, rows, maxval, fh,
+                 colorTableP, randStP, antiflag);
 
         ppmd_fill_destroy(fh);
     }
@@ -688,17 +740,21 @@ camo(pixel **     const pixels,
 -----------------------------------------------------------------------------*/
 
 static void
-gingham2(pixel **     const pixels,
-         unsigned int const cols,
-         unsigned int const rows,
-         ColorTable   const colorTable,
-         pixval       const maxval) {
+gingham2(pixel **           const pixels,
+         unsigned int       const cols,
+         unsigned int       const rows,
+         ColorTable         const colorTable,
+         struct pm_randSt * const randStP,
+         ppmd_drawproc    * const drawproc,
+         pixval             const maxval) {
 
     bool  const colorSpec = (colorTable.count > 0);
     pixel const backcolor = colorSpec ?
-                            colorTable.color[0] : randomDarkColor(maxval);
+                              colorTable.color[0] :
+                              randomDarkColor(randStP, maxval);
     pixel const forecolor = colorSpec ?
-                            colorTable.color[1] : randomBrightColor(maxval);
+                              colorTable.color[1] :
+                              randomBrightColor(randStP, maxval);
     unsigned int const colso2 = cols / 2;
     unsigned int const rowso2 = rows / 2;
 
@@ -712,29 +768,34 @@ gingham2(pixel **     const pixels,
 
     /* Woof. */
     ppmd_filledrectangle(
-        pixels, cols, rows, maxval, 0, 0, cols, rowso2, average_drawproc,
+        pixels, cols, rows, maxval, 0, 0, cols, rowso2, drawproc,
         &backcolor);
     ppmd_filledrectangle(
         pixels, cols, rows, maxval, 0, rowso2, cols, rows - rowso2,
-        average_drawproc, &forecolor);
+        drawproc, &forecolor);
 }
 
 
 
 static void
-gingham3(pixel **     const pixels,
-         unsigned int const cols,
-         unsigned int const rows,
-         ColorTable   const colorTable,
-         pixval       const maxval) {
+gingham3(pixel **           const pixels,
+         unsigned int       const cols,
+         unsigned int       const rows,
+         ColorTable         const colorTable,
+         struct pm_randSt * const randStP,
+         ppmd_drawproc    * const drawproc,
+         pixval             const maxval) {
 
     bool  const colorSpec = (colorTable.count > 0);
-    pixel const backcolor = colorSpec ?
-                            colorTable.color[0] : randomDarkColor(maxval);
+    pixel const backcolor  = colorSpec ?
+                               colorTable.color[0] :
+                               randomDarkColor(randStP, maxval);
     pixel const fore1color = colorSpec ?
-                            colorTable.color[1] : randomBrightColor(maxval);
+                               colorTable.color[1] :
+                               randomBrightColor(randStP, maxval);
     pixel const fore2color = colorSpec ?
-                            colorTable.color[2] : randomBrightColor(maxval);
+                               colorTable.color[2] :
+                               randomBrightColor(randStP, maxval);
     unsigned int const colso4 = cols / 4;
     unsigned int const rowso4 = rows / 4;
 
@@ -754,35 +815,40 @@ gingham3(pixel **     const pixels,
 
     /* Woof. */
     ppmd_filledrectangle(
-        pixels, cols, rows, maxval, 0, 0, cols, rowso4, average_drawproc,
+        pixels, cols, rows, maxval, 0, 0, cols, rowso4, drawproc,
         &backcolor);
     ppmd_filledrectangle(
-        pixels, cols, rows, maxval, 0, rowso4, cols, rowso4, average_drawproc,
+        pixels, cols, rows, maxval, 0, rowso4, cols, rowso4, drawproc,
         &fore1color);
     ppmd_filledrectangle(
         pixels, cols, rows, maxval, 0, 2 * rowso4, cols, rowso4,
-        average_drawproc, &fore2color);
+        drawproc, &fore2color);
     ppmd_filledrectangle(
         pixels, cols, rows, maxval, 0, 3 * rowso4, cols, rows - rowso4,
-        average_drawproc, &fore1color);
+        drawproc, &fore1color);
 }
 
 
 
 static void
-madras(pixel **     const pixels,
-       unsigned int const cols,
-       unsigned int const rows,
-       ColorTable   const colorTable,
-       pixval       const maxval) {
+madras(pixel **           const pixels,
+       unsigned int       const cols,
+       unsigned int       const rows,
+       ColorTable         const colorTable,
+       struct pm_randSt * const randStP,
+       ppmd_drawproc    * const drawproc,
+       pixval             const maxval) {
 
     bool  const colorSpec = (colorTable.count > 0);
-    pixel const backcolor = colorSpec ?
-                            colorTable.color[0] : randomDarkColor(maxval);
+    pixel const backcolor  = colorSpec ?
+                               colorTable.color[0] :
+                               randomDarkColor(randStP, maxval);
     pixel const fore1color = colorSpec ?
-                            colorTable.color[1] : randomBrightColor(maxval);
+                               colorTable.color[1] :
+                               randomBrightColor(randStP, maxval);
     pixel const fore2color = colorSpec ?
-                            colorTable.color[2] : randomBrightColor(maxval);
+                               colorTable.color[2] :
+                               randomBrightColor(randStP, maxval);
     unsigned int const cols2  = cols * 2 / 44;
     unsigned int const rows2  = rows * 2 / 44;
     unsigned int const cols3  = cols * 3 / 44;
@@ -846,72 +912,77 @@ madras(pixel **     const pixels,
 
     /* Woof. */
     ppmd_filledrectangle(
-        pixels, cols, rows, maxval, 0, 0, cols, rows2, average_drawproc,
+        pixels, cols, rows, maxval, 0, 0, cols, rows2, drawproc,
         &backcolor);
     ppmd_filledrectangle(
-        pixels, cols, rows, maxval, 0, rows2, cols, rows3, average_drawproc,
+        pixels, cols, rows, maxval, 0, rows2, cols, rows3, drawproc,
         &fore2color);
     ppmd_filledrectangle(
         pixels, cols, rows, maxval, 0, rows2 + rows3, cols, rows2,
-        average_drawproc, &backcolor);
+        drawproc, &backcolor);
     ppmd_filledrectangle(
         pixels, cols, rows, maxval, 0, 2 * rows2 + rows3, cols, rows2,
-        average_drawproc, &fore1color);
+        drawproc, &fore1color);
     ppmd_filledrectangle(
         pixels, cols, rows, maxval, 0, 3 * rows2 + rows3, cols, rows2,
-        average_drawproc, &backcolor);
+        drawproc, &backcolor);
     ppmd_filledrectangle(
         pixels, cols, rows, maxval, 0, 4 * rows2 + rows3, cols, rows6a,
-        average_drawproc, &fore2color);
+        drawproc, &fore2color);
     ppmd_filledrectangle(
         pixels, cols, rows, maxval, 0, 4 * rows2 + rows3 + rows6a, cols, rows2,
-        average_drawproc, &backcolor);
+        drawproc, &backcolor);
     ppmd_filledrectangle(
         pixels, cols, rows, maxval, 0, 5 * rows2 + rows3 + rows6a, cols, rows3,
-        average_drawproc, &fore1color);
+        drawproc, &fore1color);
     ppmd_filledrectangle(
         pixels, cols, rows, maxval, 0, 5 * rows2 + 2 * rows3 + rows6a, cols,
-        rows2, average_drawproc, &backcolor);
+        rows2, drawproc, &backcolor);
     ppmd_filledrectangle(
         pixels, cols, rows, maxval, 0, 6 * rows2 + 2 * rows3 + rows6a, cols,
-        rows3, average_drawproc, &fore1color);
+        rows3, drawproc, &fore1color);
     ppmd_filledrectangle(
         pixels, cols, rows, maxval, 0, 6 * rows2 + 3 * rows3 + rows6a, cols,
-        rows2, average_drawproc, &backcolor);
+        rows2, drawproc, &backcolor);
     ppmd_filledrectangle(
         pixels, cols, rows, maxval, 0, 7 * rows2 + 3 * rows3 + rows6a, cols,
-        rows6b, average_drawproc, &fore2color);
+        rows6b, drawproc, &fore2color);
     ppmd_filledrectangle(
         pixels, cols, rows, maxval, 0, 7 * rows2 + 3 * rows3 + rows6a + rows6b,
-        cols, rows2, average_drawproc, &backcolor);
+        cols, rows2, drawproc, &backcolor);
     ppmd_filledrectangle(
         pixels, cols, rows, maxval, 0, 8 * rows2 + 3 * rows3 + rows6a + rows6b,
-        cols, rows2, average_drawproc, &fore1color);
+        cols, rows2, drawproc, &fore1color);
     ppmd_filledrectangle(
         pixels, cols, rows, maxval, 0, 9 * rows2 + 3 * rows3 + rows6a + rows6b,
-        cols, rows2, average_drawproc, &backcolor);
+        cols, rows2, drawproc, &backcolor);
     ppmd_filledrectangle(
         pixels, cols, rows, maxval, 0,
         10 * rows2 + 3 * rows3 + rows6a + rows6b,
-        cols, rows3, average_drawproc, &fore2color);
+        cols, rows3, drawproc, &fore2color);
 }
 
 
 
 static void
-tartan(pixel **     const pixels,
-       unsigned int const cols,
-       unsigned int const rows,
-       ColorTable   const colorTable,
-       pixval       const maxval) {
+tartan(pixel **           const pixels,
+       unsigned int       const cols,
+       unsigned int       const rows,
+       ColorTable         const colorTable,
+       struct pm_randSt * const randStP,
+       ppmd_drawproc    * const drawproc,
+       pixval             const maxval) {
 
     bool  const colorSpec = (colorTable.count > 0);
-    pixel const backcolor = colorSpec ?
-                            colorTable.color[0] : randomDarkColor(maxval);
+    pixel const backcolor  = colorSpec ?
+                               colorTable.color[0] :
+                               randomDarkColor(randStP, maxval);
     pixel const fore1color = colorSpec ?
-                            colorTable.color[1] : randomBrightColor(maxval);
+                               colorTable.color[1] :
+                               randomBrightColor(randStP, maxval);
     pixel const fore2color = colorSpec ?
-                            colorTable.color[2] : randomBrightColor(maxval);
+                               colorTable.color[2] :
+                               randomBrightColor(randStP, maxval);
     unsigned int const cols1  = cols / 22;
     unsigned int const rows1  = rows / 22;
     unsigned int const cols3  = cols * 3 / 22;
@@ -951,29 +1022,29 @@ tartan(pixel **     const pixels,
 
     /* Woof. */
     ppmd_filledrectangle(
-        pixels, cols, rows, maxval, 0, 0, cols, rows5a, average_drawproc,
+        pixels, cols, rows, maxval, 0, 0, cols, rows5a, drawproc,
         &backcolor);
     ppmd_filledrectangle(
-        pixels, cols, rows, maxval, 0, rows5a, cols, rows1, average_drawproc,
+        pixels, cols, rows, maxval, 0, rows5a, cols, rows1, drawproc,
         &fore1color);
     ppmd_filledrectangle(
         pixels, cols, rows, maxval, 0, rows5a + rows1, cols, rows5b,
-        average_drawproc, &backcolor);
+        drawproc, &backcolor);
     ppmd_filledrectangle(
         pixels, cols, rows, maxval, 0, rows10 + rows1, cols, rows3,
-        average_drawproc, &fore2color);
+        drawproc, &fore2color);
     ppmd_filledrectangle(
         pixels, cols, rows, maxval, 0, rows10 + rows1 + rows3, cols, rows1,
-        average_drawproc, &backcolor);
+        drawproc, &backcolor);
     ppmd_filledrectangle(
         pixels, cols, rows, maxval, 0, rows10 + 2 * rows1 + rows3, cols, rows3,
-        average_drawproc, &fore2color);
+        drawproc, &fore2color);
     ppmd_filledrectangle(
         pixels, cols, rows, maxval, 0, rows10 + 2 * rows1 + 2 * rows3, cols,
-        rows1, average_drawproc, &backcolor);
+        rows1, drawproc, &backcolor);
     ppmd_filledrectangle(
         pixels, cols, rows, maxval, 0, rows10 + 3 * rows1 + 2 * rows3, cols,
-        rows3, average_drawproc, &fore2color);
+        rows3, drawproc, &fore2color);
 }
 
 
@@ -1013,14 +1084,15 @@ argyle(pixel **     const pixels,
        unsigned int const cols,
        unsigned int const rows,
        ColorTable   const colorTable,
+       struct pm_randSt * const randStP,
        pixval       const maxval,
        bool         const stripes) {
 
     bool  const colorSpec = (colorTable.count > 0);
     pixel const backcolor = colorSpec ?
-        colorTable.color[0] : randomDarkColor(maxval);
+        colorTable.color[0] : randomDarkColor(randStP, maxval);
     pixel const forecolor = colorSpec ?
-        colorTable.color[1] : randomBrightColor(maxval);
+        colorTable.color[1] : randomBrightColor(randStP, maxval);
 
     /* Fill canvas with background to start */
     ppmd_filledrectangle(
@@ -1032,7 +1104,8 @@ argyle(pixel **     const pixels,
     if (stripes) {
          /* Connect corners with thin stripes */
          pixel const stripecolor =
-             colorSpec ? colorTable.color[2] : randomBrightColor(maxval);
+             colorSpec ? colorTable.color[2] :
+                         randomBrightColor(randStP, maxval);
 
          ppmd_line(pixels, cols, rows, maxval, 0, 0, cols-1, rows-1,
               PPMD_NULLDRAWPROC, (char *) &stripecolor);
@@ -1054,27 +1127,28 @@ argyle(pixel **     const pixels,
 
 
 static void
-placeAndColorPolesRandomly(int *        const xs,
-                           int *        const ys,
-                           pixel *      const colors,
-                           unsigned int const cols,
-                           unsigned int const rows,
-                           pixval       const maxval,
-                           ColorTable * const colorTableP,
-                           unsigned int const poleCt) {
+placeAndColorPolesRandomly(int *              const xs,
+                           int *              const ys,
+                           pixel *            const colors,
+                           unsigned int       const cols,
+                           unsigned int       const rows,
+                           pixval             const maxval,
+                           ColorTable *       const colorTableP,
+                           struct pm_randSt * const randStP,
+                           unsigned int       const poleCt) {
 
     unsigned int i;
 
     for (i = 0; i < poleCt; ++i) {
 
-        xs[i] = rand() % cols;
-        ys[i] = rand() % rows;
+        xs[i] = pm_rand(randStP) % cols;
+        ys[i] = pm_rand(randStP) % rows;
 
         if (colorTableP->count > 0) {
             colors[i] = colorTableP->color[colorTableP->index];
             nextColor(colorTableP);
         } else
-            colors[i] = randomBrightColor(maxval);
+            colors[i] = randomBrightColor(randStP, maxval);
     }
 }
 
@@ -1104,11 +1178,12 @@ assignInterpolatedColor(pixel * const resultP,
 
 
 static void
-poles(pixel **     const pixels,
-      unsigned int const cols,
-      unsigned int const rows,
-      ColorTable * const colorTableP,
-      pixval       const maxval) {
+poles(pixel **           const pixels,
+      unsigned int       const cols,
+      unsigned int       const rows,
+      ColorTable *       const colorTableP,
+      struct pm_randSt * const randStP,
+      pixval             const maxval) {
 
     unsigned int const poleCt = MAX(2, MIN(MAXPOLES, cols * rows / 30000));
 
@@ -1117,7 +1192,7 @@ poles(pixel **     const pixels,
     unsigned int row;
 
     placeAndColorPolesRandomly(xs, ys, colors, cols, rows, maxval,
-                               colorTableP, poleCt);
+                               colorTableP, randStP, poleCt);
 
     /* Interpolate points */
 
@@ -1236,11 +1311,12 @@ sqRainbowCircleDrawproc(pixel **     const pixels,
 
 
 static void
-chooseSqPoleColors(ColorTable * const colorTableP,
-                   pixval       const maxval,
-                   pixel *      const color1P,
-                   pixel *      const color2P,
-                   pixel *      const color3P) {
+chooseSqPoleColors(ColorTable *       const colorTableP,
+                   pixval             const maxval,
+                   pixel *            const color1P,
+                   pixel *            const color2P,
+                   pixel *            const color3P,
+                   struct pm_randSt * const randStP) {
 
     if (colorTableP->count > 0) {
         *color1P = colorTableP->color[colorTableP->index];
@@ -1250,19 +1326,20 @@ chooseSqPoleColors(ColorTable * const colorTableP,
         *color3P = colorTableP->color[colorTableP->index];
         nextColor(colorTableP);
     } else {
-        *color1P = randomBrightColor(maxval);
-        *color2P = randomBrightColor(maxval);
-        *color3P = randomBrightColor(maxval);
+        *color1P = randomBrightColor(randStP, maxval);
+        *color2P = randomBrightColor(randStP, maxval);
+        *color3P = randomBrightColor(randStP, maxval);
     }
 }
 
 
 
 static void
-sqAssignColors(unsigned int const circlecount,
-               pixval       const maxval,
-               ColorTable * const colorTableP,
-               pixel *      const colors) {
+sqAssignColors(unsigned int       const circlecount,
+               pixval             const maxval,
+               ColorTable *       const colorTableP,
+               pixel *            const colors,
+               struct pm_randSt * const randStP) {
 
     float const cco3 = (circlecount - 1) / 3.0;
 
@@ -1271,7 +1348,7 @@ sqAssignColors(unsigned int const circlecount,
     pixel rc3;
     unsigned int i;
 
-    chooseSqPoleColors(colorTableP, maxval, &rc1, &rc2, &rc3);
+    chooseSqPoleColors(colorTableP, maxval, &rc1, &rc2, &rc3, randStP);
 
     for (i = 0; i < circlecount; ++i) {
         if (i < cco3) {
@@ -1333,24 +1410,25 @@ clearBackgroundSquig(pixel **     const pixels,
 
 
 static void
-chooseWrapAroundPoint(unsigned int const cols,
-                      unsigned int const rows,
-                      ppmd_point * const pFirstP,
-                      ppmd_point * const pLastP,
-                      ppmd_point * const p0P,
-                      ppmd_point * const p1P,
-                      ppmd_point * const p2P,
-                      ppmd_point * const p3P) {
-
-    switch (rand() % 4) {
+chooseWrapAroundPoint(unsigned int       const cols,
+                      unsigned int       const rows,
+                      ppmd_point *       const pFirstP,
+                      ppmd_point *       const pLastP,
+                      ppmd_point *       const p0P,
+                      ppmd_point *       const p1P,
+                      ppmd_point *       const p2P,
+                      ppmd_point *       const p3P,
+                      struct pm_randSt * const randStP) {
+
+    switch (pm_rand(randStP) % 4) {
     case 0:
-        p1P->x = rand() % cols;
+        p1P->x = pm_rand(randStP) % cols;
         p1P->y = 0;
         if (p1P->x < cols / 2)
-            pFirstP->x = rand() % (p1P->x * 2 + 1);
+            pFirstP->x = pm_rand(randStP) % (p1P->x * 2 + 1);
         else
-            pFirstP->x = cols - 1 - rand() % ((cols - p1P->x) * 2);
-        pFirstP->y = rand() % rows;
+            pFirstP->x = cols - 1 - pm_rand(randStP) % ((cols - p1P->x) * 2);
+        pFirstP->y = pm_rand(randStP) % rows;
         p2P->x = p1P->x;
         p2P->y = rows - 1;
         pLastP->x = 2 * p2P->x - pFirstP->x;
@@ -1362,13 +1440,13 @@ chooseWrapAroundPoint(unsigned int const cols,
         break;
 
     case 1:
-        p2P->x = rand() % cols;
+        p2P->x = pm_rand(randStP) % cols;
         p2P->y = 0;
         if (p2P->x < cols / 2)
-            pLastP->x = rand() % (p2P->x * 2 + 1);
+            pLastP->x = pm_rand(randStP) % (p2P->x * 2 + 1);
         else
-            pLastP->x = cols - 1 - rand() % ((cols - p2P->x) * 2);
-        pLastP->y = rand() % rows;
+            pLastP->x = cols - 1 - pm_rand(randStP) % ((cols - p2P->x) * 2);
+        pLastP->y = pm_rand(randStP) % rows;
         p1P->x = p2P->x;
         p1P->y = rows - 1;
         pFirstP->x = 2 * p1P->x - pLastP->x;
@@ -1381,12 +1459,12 @@ chooseWrapAroundPoint(unsigned int const cols,
 
     case 2:
         p1P->x = 0;
-        p1P->y = rand() % rows;
-        pFirstP->x = rand() % cols;
+        p1P->y = pm_rand(randStP) % rows;
+        pFirstP->x = pm_rand(randStP) % cols;
         if (p1P->y < rows / 2)
-            pFirstP->y = rand() % (p1P->y * 2 + 1);
+            pFirstP->y = pm_rand(randStP) % (p1P->y * 2 + 1);
         else
-            pFirstP->y = rows - 1 - rand() % ((rows - p1P->y) * 2);
+            pFirstP->y = rows - 1 - pm_rand(randStP) % ((rows - p1P->y) * 2);
         p2P->x = cols - 1;
         p2P->y = p1P->y;
         pLastP->x = p2P->x - pFirstP->x;
@@ -1399,12 +1477,12 @@ chooseWrapAroundPoint(unsigned int const cols,
 
     case 3:
         p2P->x = 0;
-        p2P->y = rand() % rows;
-        pLastP->x = rand() % cols;
+        p2P->y = pm_rand(randStP) % rows;
+        pLastP->x = pm_rand(randStP) % cols;
         if (p2P->y < rows / 2)
-            pLastP->y = rand() % (p2P->y * 2 + 1);
+            pLastP->y = pm_rand(randStP) % (p2P->y * 2 + 1);
         else
-            pLastP->y = rows - 1 - rand() % ((rows - p2P->y) * 2);
+            pLastP->y = rows - 1 - pm_rand(randStP) % ((rows - p2P->y) * 2);
         p1P->x = cols - 1;
         p1P->y = p2P->y;
         pFirstP->x = p1P->x - pLastP->x;
@@ -1420,11 +1498,12 @@ chooseWrapAroundPoint(unsigned int const cols,
 
 
 static void
-squig(pixel **     const pixels,
-      unsigned int const cols,
-      unsigned int const rows,
-      ColorTable * const colorTableP,
-      pixval       const maxval) {
+squig(pixel **           const pixels,
+      unsigned int       const cols,
+      unsigned int       const rows,
+      ColorTable *       const colorTableP,
+      struct pm_randSt * const randStP,
+      pixval             const maxval) {
 
     int i;
 
@@ -1453,10 +1532,11 @@ squig(pixel **     const pixels,
         ppmd_circlep(pixels, cols, rows, maxval,
                      ppmd_makePoint(0, 0), radius,
                      sqMeasureCircleDrawproc, &sqClientData);
-        sqAssignColors(squig.circleCt, maxval, colorTableP, squig.color);
+        sqAssignColors(squig.circleCt, maxval, colorTableP, squig.color,
+                       randStP);
 
         chooseWrapAroundPoint(cols, rows, &c[0], &c[SQ_POINTS-1],
-                              &p0, &p1, &p2, &p3);
+                              &p0, &p1, &p2, &p3, randStP);
 
         {
             /* Do the middle points */
@@ -1466,8 +1546,8 @@ squig(pixel **     const pixels,
               /* validateSquigAspect() assures that
                  cols - 2 * radius, rows -2 * radius are positive
               */
-                c[j].x = (rand() % (cols - 2 * radius)) + radius;
-                c[j].y = (rand() % (rows - 2 * radius)) + radius;
+                c[j].x = (pm_rand(randStP) % (cols - 2 * radius)) + radius;
+                c[j].y = (pm_rand(randStP) % (rows - 2 * radius)) + radius;
             }
         }
 
@@ -1490,6 +1570,7 @@ main(int argc, const char ** argv) {
 
     struct CmdlineInfo cmdline;
     pixel ** pixels;
+    struct pm_randSt randSt;
 
     pm_proginit(&argc, argv);
 
@@ -1497,65 +1578,68 @@ main(int argc, const char ** argv) {
 
     validateComputableDimensions(cmdline.width, cmdline.height);
 
-    srand(cmdline.randomseedSpec ? cmdline.randomseed : pm_randseed());
+    pm_randinit(&randSt);
+    pm_srand2(&randSt, cmdline.randomseedSpec, cmdline.randomseed);
 
     pixels = ppm_allocarray(cmdline.width, cmdline.height);
 
     switch (cmdline.basePattern) {
     case PAT_GINGHAM2:
         gingham2(pixels, cmdline.width, cmdline.height,
-                 cmdline.colorTable, PPM_MAXMAXVAL);
+                 cmdline.colorTable, &randSt, cmdline.drawProc, PPM_MAXMAXVAL);
         break;
 
     case PAT_GINGHAM3:
         gingham3(pixels, cmdline.width, cmdline.height,
-                 cmdline.colorTable, PPM_MAXMAXVAL);
+                 cmdline.colorTable, &randSt, cmdline.drawProc, PPM_MAXMAXVAL);
         break;
 
     case PAT_MADRAS:
         madras(pixels, cmdline.width, cmdline.height,
-               cmdline.colorTable, PPM_MAXMAXVAL);
+               cmdline.colorTable, &randSt, cmdline.drawProc, PPM_MAXMAXVAL);
         break;
 
     case PAT_TARTAN:
         tartan(pixels, cmdline.width, cmdline.height,
-               cmdline.colorTable, PPM_MAXMAXVAL);
+               cmdline.colorTable, &randSt, cmdline.drawProc, PPM_MAXMAXVAL);
         break;
 
     case PAT_ARGYLE1:
         argyle(pixels, cmdline.width, cmdline.height,
-               cmdline.colorTable, PPM_MAXMAXVAL, FALSE);
+               cmdline.colorTable, &randSt, PPM_MAXMAXVAL, FALSE);
         break;
 
     case PAT_ARGYLE2:
         argyle(pixels, cmdline.width, cmdline.height,
-               cmdline.colorTable, PPM_MAXMAXVAL, TRUE);
+               cmdline.colorTable, &randSt, PPM_MAXMAXVAL, TRUE);
         break;
 
     case PAT_POLES:
         poles(pixels, cmdline.width, cmdline.height,
-              &cmdline.colorTable, PPM_MAXMAXVAL);
+              &cmdline.colorTable, &randSt, PPM_MAXMAXVAL);
         break;
 
     case PAT_SQUIG:
         squig(pixels, cmdline.width, cmdline.height,
-              &cmdline.colorTable, PPM_MAXMAXVAL);
+              &cmdline.colorTable, &randSt, PPM_MAXMAXVAL);
         break;
 
     case PAT_CAMO:
         camo(pixels, cmdline.width, cmdline.height,
-             &cmdline.colorTable, PPM_MAXMAXVAL, 0);
+             &cmdline.colorTable, &randSt, PPM_MAXMAXVAL, 0);
         break;
 
     case PAT_ANTICAMO:
         camo(pixels, cmdline.width, cmdline.height,
-             &cmdline.colorTable, PPM_MAXMAXVAL, 1);
+             &cmdline.colorTable, &randSt, PPM_MAXMAXVAL, 1);
         break;
 
     default:
         pm_error("can't happen!");
     }
 
+    pm_randterm(&randSt);
+
     ppm_writeppm(stdout, pixels, cmdline.width, cmdline.height,
                  PPM_MAXMAXVAL, 0);
 
diff --git a/generator/ppmrainbow b/generator/ppmrainbow
index e8a329ff..68d519a0 100755
--- a/generator/ppmrainbow
+++ b/generator/ppmrainbow
@@ -26,6 +26,19 @@ exec perl -w -x -S -- "$0" "$@"
 use strict;
 use Getopt::Long;
 use File::Temp;
+use IO::Handle;
+
+
+
+sub pm_message($) {
+    STDERR->print("ppmrainbow: $_[0]\n");
+}
+
+sub pm_error($) {
+    pm_message($_[0]);
+    exit(1);
+}
+
 
 my ($FALSE, $TRUE) = (0,1);
 
@@ -46,15 +59,6 @@ sub doVersionHack($) {
 
 
 
-sub fatal($) {
-    my ($msg) = @_;
-
-    print(STDERR "ppmrainbow: $msg\n");
-    exit(1);
-}
-
-
-
 ##############################################################################
 #
 #                                 MAINLINE
@@ -79,14 +83,14 @@ GetOptions("width=i"   => \$Twid,
            "verbose!"  => \$verbose);
 
 if ($Twid < 1 || $Thgt < 1) {
-    fatal("invalid width and/or height");
+    pm_error("invalid width and/or height");
 }
 my $verboseCommand = $verbose ? "set -x;" : "";
 
 if (@ARGV < 1) {
-    fatal("You must specify at least one color as an argument");
+    pm_error("You must specify at least one color as an argument");
 } elsif (@ARGV < 2 && ! $repeat) {
-    fatal("With the -norepeat option, you must specify at least two colors " .
+    pm_error("With the -norepeat option, you must specify at least two colors " .
           "as arguments.");
 }
 
@@ -115,15 +119,18 @@ while (@colorlist >= 2) {
     my $rc = system("$verboseCommand pgmramp -lr $w $Thgt | " .
                     "pgmtoppm \"$colorlist[0]-$colorlist[1]\" >$outfile");
     if ($rc != 0) {
-        fatal("pgmramp|pgmtoppm pipe failed.");
+        pm_error("pgmramp|pgmtoppm pipe failed.");
     }
     $widthRemaining -= $w;
     $n++;
     shift @colorlist;
 }
 
-0 == system qq{$verboseCommand pnmcat -lr @outlist}
-    or exit 1;
+my $termStat =
+    system("$verboseCommand pamcat -leftright @outlist");
+if ($termStat != 0) {
+    exit 1;
+}
 
 exit 0;
 
diff --git a/generator/ppmrough.c b/generator/ppmrough.c
index c87a0364..d9f1bb65 100644
--- a/generator/ppmrough.c
+++ b/generator/ppmrough.c
@@ -16,11 +16,10 @@
 
 #include "pm_c_util.h"
 #include "mallocvar.h"
+#include "rand.h"
 #include "shhopt.h"
 #include "ppm.h"
 
-static pixel** PIX;
-static pixval BG_RED, BG_GREEN, BG_BLUE;
 
 
 struct CmdlineInfo {
@@ -28,9 +27,12 @@ struct CmdlineInfo {
      in a form easy for the program to use.
   */
     unsigned int left, right, top, bottom;
-    unsigned int width, height, var;
-    const char * bg_rgb;
-    const char * fg_rgb;
+    unsigned int leftSpec, rightSpec, topSpec, bottomSpec;
+    unsigned int width;
+    unsigned int height;
+    unsigned int var;
+    const char * bg;  /* Null if not specified */
+    const char * fg;  /* Null if not specified */
     unsigned int randomseed;
     unsigned int randomseedSpec;
     unsigned int verbose;
@@ -42,6 +44,8 @@ static void
 parseCommandLine(int argc, const char ** argv,
                  struct CmdlineInfo * const cmdlineP) {
 
+    unsigned int widthSpec, heightSpec, bgSpec, fgSpec, varSpec;
+
     optEntry * option_def;
         /* Instructions to OptParseOptions2 on how to parse our options.    */
     optStruct3 opt;
@@ -51,28 +55,30 @@ parseCommandLine(int argc, const char ** argv,
     MALLOCARRAY_NOFAIL(option_def, 100);
 
     option_def_index = 0;   /* incremented by OPTENTRY */
-    OPTENT3(0, "width",       OPT_UINT,   &cmdlineP->width,   NULL, 0);
-    OPTENT3(0, "height",      OPT_UINT,   &cmdlineP->height,  NULL, 0);
-    OPTENT3(0, "left",        OPT_UINT,   &cmdlineP->left,    NULL, 0);
-    OPTENT3(0, "right",       OPT_UINT,   &cmdlineP->right,   NULL, 0);
-    OPTENT3(0, "top",         OPT_UINT,   &cmdlineP->top,     NULL, 0);
-    OPTENT3(0, "bottom",      OPT_UINT,   &cmdlineP->bottom,  NULL, 0);
-    OPTENT3(0, "bg",          OPT_STRING, &cmdlineP->bg_rgb,  NULL, 0);
-    OPTENT3(0, "fg",          OPT_STRING, &cmdlineP->fg_rgb,  NULL, 0);
-    OPTENT3(0, "var",         OPT_UINT,   &cmdlineP->var,     NULL, 0);
+    OPTENT3(0, "width",       OPT_UINT,   &cmdlineP->width,
+            &widthSpec, 0);
+    OPTENT3(0, "height",      OPT_UINT,   &cmdlineP->height,
+            &heightSpec, 0);
+    OPTENT3(0, "left",        OPT_UINT,   &cmdlineP->left,
+            &cmdlineP->leftSpec, 0);
+    OPTENT3(0, "right",       OPT_UINT,   &cmdlineP->right,
+            &cmdlineP->rightSpec, 0);
+    OPTENT3(0, "top",         OPT_UINT,   &cmdlineP->top,
+            &cmdlineP->topSpec, 0);
+    OPTENT3(0, "bottom",      OPT_UINT,   &cmdlineP->bottom,
+            &cmdlineP->bottomSpec, 0);
+    OPTENT3(0, "bg",          OPT_STRING, &cmdlineP->bg,
+            &bgSpec, 0);
+    OPTENT3(0, "fg",          OPT_STRING, &cmdlineP->fg,
+            &fgSpec, 0);
+    OPTENT3(0, "var",         OPT_UINT,   &cmdlineP->var,
+            &varSpec, 0);
     OPTENT3(0, "randomseed",  OPT_UINT,   &cmdlineP->randomseed,
             &cmdlineP->randomseedSpec, 0);
     OPTENT3(0, "init",        OPT_UINT,   &cmdlineP->randomseed,
             &cmdlineP->randomseedSpec, 0);
-    OPTENT3(0, "verbose",     OPT_FLAG,   NULL, &cmdlineP->verbose, 0);
-
-    /* Set the defaults */
-    cmdlineP->width = 100;
-    cmdlineP->height = 100;
-    cmdlineP->left = cmdlineP->right = cmdlineP->top = cmdlineP->bottom = -1;
-    cmdlineP->bg_rgb = NULL;
-    cmdlineP->fg_rgb = NULL;
-    cmdlineP->var = 10;
+    OPTENT3(0, "verbose",     OPT_FLAG,   NULL,
+            &cmdlineP->verbose, 0);
 
     opt.opt_table = option_def;
     opt.short_allowed = FALSE;  /* We have no short (old-fashioned) options */
@@ -80,6 +86,26 @@ parseCommandLine(int argc, const char ** argv,
 
     pm_optParseOptions3(&argc, (char **)argv, opt, sizeof(opt), 0);
 
+    if (!widthSpec)
+        cmdlineP->width = 100;
+    if (!heightSpec)
+        cmdlineP->height = 100;
+    if (!bgSpec)
+        cmdlineP->bg = NULL;
+    if (!fgSpec)
+        cmdlineP->fg = NULL;
+    if (!varSpec)
+        cmdlineP->var = 10;
+
+    if (cmdlineP->topSpec && cmdlineP->top > cmdlineP->height)
+        pm_error("-top value too large.  Max is %u", cmdlineP->height);
+    if (cmdlineP->bottomSpec && cmdlineP->bottom > cmdlineP->height)
+        pm_error("-bottom value too large.  Max is %u", cmdlineP->height);
+    if (cmdlineP->leftSpec && cmdlineP->left > cmdlineP->width)
+        pm_error("-left value too large.  Max is %u", cmdlineP->width);
+    if (cmdlineP->rightSpec && cmdlineP->right > cmdlineP->width)
+        pm_error("-right value too large.  Max is %u", cmdlineP->width);
+
     if (argc-1 != 0)
         pm_error("There are no arguments.  You specified %d.", argc-1);
 
@@ -88,240 +114,353 @@ parseCommandLine(int argc, const char ** argv,
 
 
 
-static void
-procLeft(int          const r1,
-         int          const r2,
-         int          const c1,
-         int          const c2,
-         unsigned int const var) {
+static int
+mean(int const a,
+     int const b) {
 
-    int cm, rm, c;
+    return (a + b) / 2;
+}
 
-    if (r1 + 1 == r2)  return;
-    rm = (r1 + r2) >> 1;
-    cm = (c1 + c2) >> 1;
-    cm += (int)floor(((float)rand() / RAND_MAX - 0.5) * var + 0.5);
 
-    for (c = 0; c < cm; c++)
-        PPM_ASSIGN(PIX[rm][c], BG_RED, BG_GREEN, BG_BLUE);
 
-    procLeft(r1, rm, c1, cm, var);
-    procLeft(rm, r2, cm, c2, var);
+static void
+reportParameters(struct CmdlineInfo const cmdline,
+                 pixel              const bgcolor,
+                 pixel              const fgcolor) {
+
+    pm_message("width is %d, height is %d, variance is %d.",
+               cmdline.width, cmdline.height, cmdline.var);
+    if (cmdline.leftSpec)
+        pm_message("ragged left border is required");
+    if (cmdline.rightSpec)
+        pm_message("ragged right border is required");
+    if (cmdline.topSpec)
+        pm_message("ragged top border is required");
+    if (cmdline.bottomSpec)
+        pm_message("ragged bottom border is required");
+    pm_message("background is %s",
+               ppm_colorname(&bgcolor, PPM_MAXMAXVAL, 1));
+    pm_message("foreground is %s",
+               ppm_colorname(&fgcolor, PPM_MAXMAXVAL, 1));
+    if (cmdline.randomseedSpec)
+        pm_message("pm_rand() initialized with seed %u",
+                   cmdline.randomseed);
 }
 
 
 
 static void
-procRight(int          const r1,
-          int          const r2,
-          int          const c1,
-          int          const c2,
-          unsigned int const width,
-          unsigned int const var) {
+makeAllForegroundColor(pixel **     const pixels,
+                       unsigned int const rows,
+                       unsigned int const cols,
+                       pixel        const fgcolor) {
 
-    int cm, rm, c;
+    pixval const r = PPM_GETR(fgcolor);
+    pixval const g = PPM_GETG(fgcolor);
+    pixval const b = PPM_GETB(fgcolor);
 
-    if (r1 + 1 == r2)  return;
-    rm = (r1 + r2) >> 1;
-    cm = (c1 + c2) >> 1;
-    cm += (int)floor(((float)rand() / RAND_MAX - 0.5) * var + 0.5);
+    unsigned int row;
 
-    for (c = cm; c < width; c++)
-        PPM_ASSIGN(PIX[rm][c], BG_RED, BG_GREEN, BG_BLUE);
+    for (row = 0; row < rows; ++row) {
+        unsigned int col;
 
-    procRight(r1, rm, c1, cm, width, var);
-    procRight(rm, r2, cm, c2, width, var);
+        for (col = 0; col < cols; ++col)
+            PPM_ASSIGN(pixels[row][col], r, g, b);
+    }
 }
 
 
 
 static void
-procTop(int          const c1,
-        int          const c2,
-        int          const r1,
-        int          const r2,
-        unsigned int const var) {
+procLeft(pixel **           const pixels,
+         int                const r1,
+         int                const r2,
+         int                const c1,
+         int                const c2,
+         unsigned int       const width,
+         unsigned int       const var,
+         pixel              const bgcolor,
+         struct pm_randSt * const randStP) {
+
+    if (r1 + 1 != r2) {
+        int const rm = mean(r1, r2);
+        int const cm = mean(c1, c2) +
+            (int)floor(((float)pm_drand(randStP) - 0.5) * var + 0.5);
+
+        unsigned int c;
+
+        for (c = 0; c < MIN(width, MAX(0, cm)); ++c)
+            pixels[rm][c] = bgcolor;
+
+        procLeft(pixels, r1, rm, c1, cm, width, var, bgcolor, randStP);
+        procLeft(pixels, rm, r2, cm, c2, width, var, bgcolor, randStP);
+    }
+}
 
-    int rm, cm, r;
 
-    if (c1 + 1 == c2)  return;
-    cm = (c1 + c2) >> 1;
-    rm = (r1 + r2) >> 1;
-    rm += (int)floor(((float)rand() / RAND_MAX - 0.5) * var + 0.5);
 
-    for (r = 0; r < rm; r++)
-        PPM_ASSIGN(PIX[r][cm], BG_RED, BG_GREEN, BG_BLUE);
+static void
+procRight(pixel **           const pixels,
+          int                const r1,
+          int                const r2,
+          int                const c1,
+          int                const c2,
+          unsigned int       const width,
+          unsigned int       const var,
+          pixel              const bgcolor,
+          struct pm_randSt * const randStP) {
+
+    if (r1 + 1 != r2) {
+        int const rm = mean(r1, r2);
+        int const cm = mean(c1, c2) +
+            (int)floor(((float)pm_drand(randStP) - 0.5) * var + 0.5);
+
+        unsigned int c;
+
+        for (c = MAX(0, cm); c < width; ++c)
+            pixels[rm][c] = bgcolor;
+
+        procRight(pixels, r1, rm, c1, cm, width, var, bgcolor, randStP);
+        procRight(pixels, rm, r2, cm, c2, width, var, bgcolor, randStP);
+    }
+}
 
-    procTop(c1, cm, r1, rm, var);
-    procTop(cm, c2, rm, r2, var);
+
+
+static void
+procTop(pixel **           const pixels,
+        int                const c1,
+        int                const c2,
+        int                const r1,
+        int                const r2,
+        unsigned int       const height,
+        unsigned int       const var,
+        pixel              const bgcolor,
+        struct pm_randSt * const randStP) {
+
+    if (c1 + 1 != c2) {
+        int const cm = mean(c1, c2);
+        int const rm = mean(r1, r2) +
+            (int)floor(((float)pm_drand(randStP) - 0.5) * var + 0.5);
+
+        unsigned int r;
+
+        for (r = 0; r < MIN(height, MAX(0, rm)); ++r)
+            pixels[r][cm] = bgcolor;
+
+        procTop(pixels, c1, cm, r1, rm, height, var, bgcolor, randStP);
+        procTop(pixels, cm, c2, rm, r2, height, var, bgcolor, randStP);
+    }
 }
 
 
 
 static void
-procBottom(int          const c1,
-           int          const c2,
-           int          const r1,
-           int          const r2,
-           unsigned int const height,
-           unsigned int const var) {
+procBottom(pixel **           const pixels,
+           int                const c1,
+           int                const c2,
+           int                const r1,
+           int                const r2,
+           unsigned int       const height,
+           unsigned int       const var,
+           pixel              const bgcolor,
+           struct pm_randSt * const randStP) {
+
+    if (c1 + 1 != c2) {
+        int const cm = mean(c1, c2);
+        int const rm = mean(r1, r2) +
+            (int)floor(((float)pm_drand(randStP) - 0.5) * var + 0.5);
+
+        unsigned int r;
+
+        for (r = MAX(0, rm); r < height; ++r)
+            pixels[r][cm] = bgcolor;
+
+        procBottom(pixels, c1, cm, r1, rm, height, var, bgcolor, randStP);
+        procBottom(pixels, cm, c2, rm, r2, height, var, bgcolor, randStP);
+    }
+}
 
-    int rm, cm, r;
 
-    if (c1 + 1 == c2)  return;
-    cm = (c1 + c2) >> 1;
-    rm = (r1 + r2) >> 1;
-    rm += (int)floor(((float)rand() / RAND_MAX - 0.5) * var + 0.5);
 
-    for (r = rm; r < height; r++)
-        PPM_ASSIGN(PIX[r][cm], BG_RED, BG_GREEN, BG_BLUE);
+static void
+makeRaggedLeftBorder(pixel **           const pixels,
+                     unsigned int       const rows,
+                     unsigned int       const cols,
+                     bool               const leftSpec,
+                     unsigned int       const left,
+                     unsigned int       const var,
+                     pixel              const bgcolor,
+                     struct pm_randSt * const randStP) {
+
+    if (leftSpec) {
+        int const leftC1 = left;
+        int const leftC2 = left;
+        int const leftR1 = 0;
+        int const leftR2 = rows - 1;
+
+        unsigned int col;
 
-    procBottom(c1, cm, r1, rm, height, var);
-    procBottom(cm, c2, rm, r2, height, var);
+        for (col = 0; col < leftC1; ++col)
+            pixels[leftR1][col] = bgcolor;
+        for (col = 0; col < leftC2; ++col)
+            pixels[leftR2][col] = bgcolor;
+
+        procLeft(pixels, leftR1, leftR2, leftC1, leftC2, cols, var,
+                 bgcolor, randStP);
+    }
 }
 
 
 
-int
-main(int argc, const char * argv[]) {
+static void
+makeRaggedRightBorder(pixel **           const pixels,
+                      unsigned int       const rows,
+                      unsigned int       const cols,
+                      bool               const rightSpec,
+                      unsigned int       const right,
+                      unsigned int       const width,
+                      unsigned int       const var,
+                      pixel              const bgcolor,
+                      struct pm_randSt * const randStP) {
+
+    if (rightSpec) {
+        int const rightC1 = cols - right - 1;
+        int const rightC2 = cols - right - 1;
+        int const rightR1 = 0;
+        int const rightR2 = rows - 1;
 
-    struct CmdlineInfo cmdline;
-    pixel bgcolor, fgcolor;
-    pixval fg_red, fg_green, fg_blue;
-    int rows, cols, row;
-    int left, right, top, bottom;
+        unsigned int col;
 
-    pm_proginit(&argc, argv);
+        for (col = rightC1; col < cols; ++col)
+            pixels[rightR1][col] = bgcolor;
+        for (col = rightC2; col < cols; ++col)
+            pixels[rightR2][col] = bgcolor;
 
-    parseCommandLine(argc, argv, &cmdline);
+        procRight(pixels, rightR1, rightR2, rightC1, rightC2, width, var,
+                  bgcolor, randStP);
+    }
+}
 
-    srand(cmdline.randomseedSpec ? cmdline.randomseed : pm_randseed());
 
-    cols = cmdline.width;
-    rows = cmdline.height;
-    left = cmdline.left;
-    right = cmdline.right;
-    top = cmdline.top;
-    bottom = cmdline.bottom;
 
-    if (cmdline.bg_rgb)
-        bgcolor = ppm_parsecolor(cmdline.bg_rgb, PPM_MAXMAXVAL);
-    else
-        PPM_ASSIGN(bgcolor, 0, 0, 0);
-    BG_RED = PPM_GETR(bgcolor);
-    BG_GREEN = PPM_GETG(bgcolor);
-    BG_BLUE = PPM_GETB(bgcolor);
+static void
+makeRaggedTopBorder(pixel **           const pixels,
+                    unsigned int       const rows,
+                    unsigned int       const cols,
+                    bool               const topSpec,
+                    unsigned int       const top,
+                    unsigned int       const var,
+                    pixel              const bgcolor,
+                    struct pm_randSt * const randStP) {
+
+    if (topSpec) {
+        unsigned int const topR1 = top;
+        unsigned int const topR2 = top;
+        unsigned int const topC1 = 0;
+        unsigned int const topC2 = cols - 1;
 
-    if (cmdline.fg_rgb)
-        fgcolor = ppm_parsecolor(cmdline.fg_rgb, PPM_MAXMAXVAL);
-    else
-        PPM_ASSIGN(fgcolor, PPM_MAXMAXVAL, PPM_MAXMAXVAL, PPM_MAXMAXVAL);
-    fg_red = PPM_GETR(fgcolor);
-    fg_green = PPM_GETG(fgcolor);
-    fg_blue = PPM_GETB(fgcolor);
-
-    if (cmdline.verbose) {
-        pm_message("width is %d, height is %d, variance is %d.",
-                   cols, rows, cmdline.var);
-        if (left >= 0)
-            pm_message("ragged left border is required");
-        if (right >= 0)
-            pm_message("ragged right border is required");
-        if (top >= 0)
-            pm_message("ragged top border is required");
-        if (bottom >= 0)
-            pm_message("ragged bottom border is required");
-        pm_message("background is %s",
-                   ppm_colorname(&bgcolor, PPM_MAXMAXVAL, 1));
-        pm_message("foreground is %s",
-                   ppm_colorname(&fgcolor, PPM_MAXMAXVAL, 1));
-        if (cmdline.randomseedSpec)
-            pm_message("srand() initialized with seed %u", cmdline.randomseed);
-    }
+        unsigned int row;
 
-    /* Allocate memory for the whole pixmap */
-    PIX = ppm_allocarray(cols, rows);
+        for (row = 0; row < topR1; ++row)
+            pixels[row][topC1] = bgcolor;
+        for (row = 0; row < topR2; ++row)
+            pixels[row][topC2] = bgcolor;
 
-    /* First, set all pixel to foreground color */
-    for (row = 0; row < rows; row++) {
-        unsigned int col;
-        for (col = 0; col < cols; ++col)
-            PPM_ASSIGN(PIX[row][col], fg_red, fg_green, fg_blue);
+        procTop(pixels, topC1, topC2, topR1, topR2, rows,
+                var, bgcolor, randStP);
     }
-    /* Make a ragged left border */
-    if (left >= 0) {
-        int const left_c1 = left;
-        int const left_c2 = left;
-        int const left_r1 = 0;
-        int const left_r2 = rows - 1;
+}
 
-        unsigned int col;
 
-        for (col = 0; col < left_c1; ++col)
-            PPM_ASSIGN(PIX[left_r1][col], BG_RED, BG_GREEN, BG_BLUE);
-        for (col = 0; col < left_c2; ++col)
-            PPM_ASSIGN(PIX[left_r2][col], BG_RED, BG_GREEN, BG_BLUE);
 
-        procLeft(left_r1, left_r2, left_c1, left_c2, cmdline.var);
+static void
+makeRaggedBottomBorder(pixel **            const pixels,
+                       unsigned int        const rows,
+                       unsigned int        const cols,
+                       bool                const bottomSpec,
+                       unsigned int        const bottom,
+                       unsigned int        const height,
+                       unsigned int        const var,
+                       pixel               const bgcolor,
+                       struct pm_randSt *  const randStP) {
+
+    if (bottomSpec) {
+        unsigned int const bottomR1 = rows - bottom - 1;
+        unsigned int const bottomR2 = rows - bottom - 1;
+        unsigned int const bottomC1 = 0;
+        unsigned int const bottomC2 = cols - 1;
+
+        unsigned int row;
+
+        for (row = bottomR1; row < rows; ++row)
+            pixels[row][bottomC1] = bgcolor;
+        for (row = bottomR2; row < rows; ++row)
+            pixels[row][bottomC2] = bgcolor;
+
+        procBottom(pixels, bottomC1, bottomC2, bottomR1, bottomR2,
+                   height, var, bgcolor, randStP);
     }
+}
 
-    /* Make a ragged right border */
-    if (right >= 0) {
-        int const right_c1 = cols - right - 1;
-        int const right_c2 = cols - right - 1;
-        int const right_r1 = 0;
-        int const right_r2 = rows - 1;
 
-        unsigned int col;
 
-        for (col = right_c1; col < cols; col++)
-            PPM_ASSIGN(PIX[right_r1][col], BG_RED, BG_GREEN, BG_BLUE);
-        for (col = right_c2; col < cols; col++)
-            PPM_ASSIGN(PIX[right_r2][col], BG_RED, BG_GREEN, BG_BLUE);
+int
+main(int argc, const char ** const argv) {
 
-        procRight(right_r1, right_r2, right_c1, right_c2,
-                   cmdline.width, cmdline.var);
-    }
+    struct CmdlineInfo cmdline;
+    pixel bgcolor, fgcolor;
+    struct pm_randSt randSt;
+    static pixel** pixels;
 
-    /* Make a ragged top border */
-    if (top >= 0) {
-        int const top_r1 = top;
-        int const top_r2 = top;
-        int const top_c1 = 0;
-        int const top_c2 = cols - 1;
+    pm_proginit(&argc, argv);
 
-        unsigned int row;
+    parseCommandLine(argc, argv, &cmdline);
 
-        for (row = 0; row < top_r1; ++row)
-            PPM_ASSIGN(PIX[row][top_c1], BG_RED, BG_GREEN, BG_BLUE);
-        for (row = 0; row < top_r2; ++row)
-            PPM_ASSIGN(PIX[row][top_c2], BG_RED, BG_GREEN, BG_BLUE);
+    pm_randinit(&randSt);
+    pm_srand(&randSt,
+             cmdline.randomseedSpec ? cmdline.randomseed : pm_randseed());
 
-        procTop(top_c1, top_c2, top_r1, top_r2, cmdline.var);
-    }
+    if (cmdline.bg)
+        bgcolor = ppm_parsecolor(cmdline.bg, PPM_MAXMAXVAL);
+    else
+        PPM_ASSIGN(bgcolor, 0, 0, 0);
+
+    if (cmdline.fg)
+        fgcolor = ppm_parsecolor(cmdline.fg, PPM_MAXMAXVAL);
+    else
+        PPM_ASSIGN(fgcolor, PPM_MAXMAXVAL, PPM_MAXMAXVAL, PPM_MAXMAXVAL);
 
-    /* Make a ragged bottom border */
-    if (bottom >= 0) {
-        int const bottom_r1 = rows - bottom - 1;
-        int const bottom_r2 = rows - bottom - 1;
-        int const bottom_c1 = 0;
-        int const bottom_c2 = cols - 1;
+    if (cmdline.verbose)
+        reportParameters(cmdline, bgcolor, fgcolor);
 
-        unsigned int row;
+    pixels = ppm_allocarray(cmdline.width, cmdline.height);
 
-        for (row = bottom_r1; row < rows; ++row)
-            PPM_ASSIGN(PIX[row][bottom_c1], BG_RED, BG_GREEN, BG_BLUE);
-        for (row = bottom_r2; row < rows; ++row)
-            PPM_ASSIGN(PIX[row][bottom_c2], BG_RED, BG_GREEN, BG_BLUE);
+    makeAllForegroundColor(pixels, cmdline.height, cmdline.width, fgcolor);
 
-        procBottom(bottom_c1, bottom_c2, bottom_r1, bottom_r2,
-                   cmdline.height, cmdline.var);
-    }
+    makeRaggedLeftBorder(pixels, cmdline.height, cmdline.width,
+                         cmdline.leftSpec, cmdline.left,
+                         cmdline.var, bgcolor, &randSt);
+
+    makeRaggedRightBorder(pixels, cmdline.height, cmdline.width,
+                          cmdline.rightSpec, cmdline.right,
+                          cmdline.width, cmdline.var, bgcolor, &randSt);
+
+    makeRaggedTopBorder(pixels, cmdline.height, cmdline.width,
+                        cmdline.topSpec, cmdline.top,
+                        cmdline.var, bgcolor, &randSt);
+
+    makeRaggedBottomBorder(pixels, cmdline.height, cmdline.width,
+                           cmdline.bottomSpec, cmdline.bottom,
+                           cmdline.height, cmdline.var, bgcolor, &randSt);
+
+    pm_randterm(&randSt);
 
     /* Write pixmap */
-    ppm_writeppm(stdout, PIX, cols, rows, PPM_MAXMAXVAL, 0);
+    ppm_writeppm(stdout, pixels, cmdline.width, cmdline.height,
+                 PPM_MAXMAXVAL, 0);
 
-    ppm_freearray(PIX, rows);
+    ppm_freearray(pixels, cmdline.height);
 
     pm_close(stdout);
 
@@ -329,4 +468,3 @@ main(int argc, const char * argv[]) {
 }
 
 
-
diff --git a/lib/Makefile b/lib/Makefile
index bc758df4..a633cf7b 100644
--- a/lib/Makefile
+++ b/lib/Makefile
@@ -33,7 +33,6 @@ LIBOBJECTS = libpm.o pmfileio.o fileio.o colorname.o \
 	libpgm1.o libpgm2.o \
 	libppm1.o libppm2.o libppmcmap.o libppmcolor.o libppmfuzzy.o \
 	libppmd.o ppmdfont.o standardppmdfont.o path.o \
-	libppmfloyd.o \
 	libpnm1.o libpnm2.o libpnm3.o \
 	libpam.o libpamread.o libpamwrite.o \
 	libpamn.o libpammap.o libpamcolor.o \
@@ -48,6 +47,10 @@ LIBOBJECTS_X = \
   util/matrix.o \
   util/nsleep.o \
   util/nstring.o \
+  util/rand.o \
+  util/randsysrand.o \
+  util/randsysrandom.o \
+  util/randmersenne.o \
   util/runlength.o \
   util/shhopt.o \
   util/token.o \
@@ -59,7 +62,7 @@ MANUALS5 = pbm pgm ppm pnm pam
 INTERFACE_HEADERS = colorname.h \
 	pam.h pamdraw.h pammap.h pbm.h pbmfont.h pbmfontdata.h \
 	pgm.h pm.h pm_gamma.h pm_system.h pnm.h \
-	ppm.h ppmcmap.h ppmdfont.h ppmdraw.h ppmfloyd.h \
+	ppm.h ppmcmap.h ppmdfont.h ppmdraw.h \
 	util/mallocvar.h util/runlength.h util/shhopt.h \
 
 DATAFILES = rgb.txt
@@ -93,11 +96,36 @@ $(LIBOBJECTS): CFLAGS_TARGET=$(CFLAGS_SHLIB)
 
 libpbm3.o: CFLAGS_TARGET+=$(CFLAGS_SSE)
 
-$(LIBOBJECTS): %.o: %.c importinc
+# libsystem_dummy.o is in the following rule because we like to compile it
+# even when it's not part of the library, just for a test.
+
+$(LIBOBJECTS) libsystem_dummy.o: %.o: %.c importinc
 	$(CC) -c $(INCLUDES) $(CFLAGS_ALL) -o $@ $<
 
-MAJ = 11
-MIN = $(NETPBM_MINOR_RELEASE)
+# The major number increases when there is a non-backward-compatible change
+# to the library at the binary level, meaning any client of the library needs
+# to keep using the old library until it has been recompiled for the new
+# library.  We try very hard never to lose backward compatibility at the
+# source level, which would mean the client source code has to be modified
+# before it can use the new library.
+#
+# The major number might seem like it corresponds to the major version number
+# of Netpbm, but it does not.  It is independent.
+#
+# Adding functions is backward compatible, so does not require a major number
+# change.
+#
+# The minor number must always increase within a major number.
+#
+# It is convenient to have the minor number equal to the minor version number
+# of Netpbm, but when we changed the Netpbm major version number from 10 to 11
+# just to keep the minor version number 2 digits, we had to continue
+# increasing the library minor number, so we went to 100 + minor version
+# number.  If we ever increase the major number to 12, we can go back to using
+# the minor version number for the library minor number.
+
+MAJ := 11
+$(eval MIN:=$(shell echo $$((100+$(NETPBM_MINOR_RELEASE)))))
 
 SONAME = libnetpbm.$(NETPBMLIBSUFFIX).$(MAJ)
 
@@ -111,7 +139,7 @@ PERLPROG = print "sgi$(MAJ)." . join(":sgi$(MAJ) . ", (0..$(MIN))) . "\n"
 
 $(SONAME): \
     $(LIBOBJECTS) $(LIBOBJECTS_X) 
-	$(LD) $(LDSHLIB) -o $@ $(LIBOBJECTS) $(LIBOBJECTS_X) \
+	$(LD) $(LDSHLIB) $(LDFLAGS) -o $@ $(LIBOBJECTS) $(LIBOBJECTS_X) \
           -lc \
 	  -soname libnetpbm.$(NETPBMLIBSUFFIX) \
 	  -set_version $(shell perl -e '$(PERLPROG)') \
@@ -130,7 +158,7 @@ $(SONAME): libnetpbm.$(NETPBMLIBSUFFIX).$(MAJ).$(MIN)
 	rm -f $@
 	$(SYMLINK) $< $@
 libnetpbm.$(NETPBMLIBSUFFIX).$(MAJ).$(MIN): $(LIBOBJECTS) $(LIBOBJECTS_X)
-	$(LD) $(LDSHLIB) -o $@ $(LIBOBJECTS) $(LIBOBJECTS_X) \
+	$(LD) $(LDSHLIB) $(LDFLAGS) -o $@ $(LIBOBJECTS) $(LIBOBJECTS_X) \
           $(SHLIB_CLIB) -lm $(LADD)
 endif
 
@@ -140,10 +168,10 @@ $(NETPBMSHLIBPREFIX)netpbm$(DLLVER).dll: $(LIBOBJECTS) $(LIBOBJECTS_X) libnetpbm
 else
 $(NETPBMSHLIBPREFIX)netpbm$(DLLVER).dll: $(LIBOBJECTS) $(LIBOBJECTS_X)
 endif
-	$(LD) $(LDSHLIB) -Wl,--export-all-symbols \
+	$(LD) $(LDSHLIB) $(LDFLAGS) -Wl,--export-all-symbols \
             -Wl,-soname,$(NETPBMSHLIBPREFIX)netpbm$(DLLVER).dll \
 	    -Wl,--output-def,$(NETPBMSHLIBPREFIX)netpbm$(DLLVER).def \
-            -Wl,--out-implib,libnetpbm.dll.a -o $@ $(LDFLAGS) \
+            -Wl,--out-implib,libnetpbm.dll.a -o $@ \
             $(LIBOBJECTS) $(LIBOBJECTS_X) $(LDLIBS) $(LADD) 
 endif
 
@@ -157,7 +185,7 @@ libnetpbm.$(MAJ).dylib: libnetpbm.$(MAJ).$(MIN).dylib
 	$(SYMLINK) $< $@
 
 libnetpbm.$(MAJ).$(MIN).dylib: $(LIBOBJECTS) $(LIBOBJECTS_X) 
-	$(LD) $(LDSHLIB) -o $@ $(LIBOBJECTS) $(LIBOBJECTS_X) \
+	$(LD) $(LDSHLIB) $(LDFLAGS) -o $@ $(LIBOBJECTS) $(LIBOBJECTS_X) \
            -lc $(LADD)
 endif
 
diff --git a/lib/colorname.c b/lib/colorname.c
index fe580cb9..3e51055c 100644
--- a/lib/colorname.c
+++ b/lib/colorname.c
@@ -16,13 +16,14 @@
 #define _BSD_SOURCE 1      /* Make sure strdup() is in string.h */
 #define _XOPEN_SOURCE 500  /* Make sure strdup() is in string.h */
 
-#include "netpbm/pm_c_util.h"
+#include <stdbool.h>
 #include <ctype.h>
 #include <string.h>
 #include <stdlib.h>
 #include <errno.h>
 #include <math.h>
 
+#include "netpbm/pm_c_util.h"
 #include "netpbm/nstring.h"
 #include "netpbm/mallocvar.h"
 
@@ -68,7 +69,7 @@ openColornameFileSearch(const char * const searchPath,
         bool eol;
 
         cursor = &buffer[0];
-        eol = FALSE;    /* initial value */
+        eol = false;    /* initial value */
         *filePP = NULL;  /* initial value */
         while (!eol && !*filePP) {
             const char * token;
@@ -76,7 +77,7 @@ openColornameFileSearch(const char * const searchPath,
             if (token) {
                 *filePP = fopen(token, "r");
             } else
-                eol = TRUE;
+                eol = true;
         }
         free(buffer);
     } else
@@ -86,7 +87,8 @@ openColornameFileSearch(const char * const searchPath,
 
 
 FILE *
-pm_openColornameFile(const char * const fileName, const int must_open) {
+pm_openColornameFile(const char * const fileName,
+                     int          const mustOpen) {
 /*----------------------------------------------------------------------------
    Open the colorname dictionary file.  Its file name is 'fileName', unless
    'fileName' is NULL.  In that case, its file name is the value of the
@@ -94,19 +96,19 @@ pm_openColornameFile(const char * const fileName, const int must_open) {
    if that environment variable is not set, it is the first file found,
    if any, in the search path RGB_DB_PATH.
 
-   'must_open' is a logical: we must get the file open or die.  If
-   'must_open' is true and we can't open the file (e.g. it doesn't
-   exist), exit the program with an error message.  If 'must_open' is
+   'mustOpen' is a logical: we must get the file open or die.  If
+   'mustOpen' is true and we can't open the file (e.g. it doesn't
+   exist), exit the program with an error message.  If 'mustOpen' is
    false and we can't open the file, just return a null pointer.
 -----------------------------------------------------------------------------*/
-    FILE *f;
+    FILE * fileP;
 
     if (fileName == NULL) {
         const char * rgbdef = getenv(RGBENV);
         if (rgbdef) {
             /* The environment variable is set */
-            f = fopen(rgbdef, "r");
-            if (f == NULL && must_open)
+            fileP = fopen(rgbdef, "r");
+            if (fileP == NULL && mustOpen)
                 pm_error("Can't open the color names dictionary file "
                          "named %s, per the %s environment variable.  "
                          "errno = %d (%s)",
@@ -115,9 +117,9 @@ pm_openColornameFile(const char * const fileName, const int must_open) {
             /* The environment variable isn't set, so try the hardcoded
                default color name dictionary locations.
             */
-            openColornameFileSearch(RGB_DB_PATH, &f);
+            openColornameFileSearch(RGB_DB_PATH, &fileP);
 
-            if (f == NULL && must_open) {
+            if (fileP == NULL && mustOpen) {
                 pm_error("can't open color names dictionary file from the "
                          "path '%s' "
                          "and Environment variable %s not set.  Set %s to "
@@ -127,20 +129,20 @@ pm_openColornameFile(const char * const fileName, const int must_open) {
             }
         }
     } else {
-        f = fopen(fileName, "r");
-        if (f == NULL && must_open)
+        fileP = fopen(fileName, "r");
+        if (fileP == NULL && mustOpen)
             pm_error("Can't open the color names dictionary file '%s'.  "
                      "errno = %d (%s)", fileName, errno, strerror(errno));
 
     }
     lineNo = 0;
-    return(f);
+    return fileP;
 }
 
 
 
 struct colorfile_entry
-pm_colorget(FILE * const f) {
+pm_colorget(FILE * const fileP) {
 /*----------------------------------------------------------------------------
    Get next color entry from the color name dictionary file 'f'.
 
@@ -155,20 +157,18 @@ pm_colorget(FILE * const f) {
     struct colorfile_entry retval;
     char * rc;
 
-    gotOne = FALSE;  /* initial value */
-    eof = FALSE;
-    while (!gotOne && !eof) {
+    for (gotOne = false, eof = false; !gotOne && !eof; ) {
         lineNo++;
-        rc = fgets(buf, sizeof(buf), f);
+        rc = fgets(buf, sizeof(buf), fileP);
         if (rc == NULL)
-            eof = TRUE;
+            eof = true;
         else {
             if (buf[0] != '#' && buf[0] != '\n' && buf[0] != '!' &&
                 buf[0] != '\0') {
                 if (sscanf(buf, "%ld %ld %ld %[^\n]",
                            &retval.r, &retval.g, &retval.b, colorname)
                     == 4 )
-                    gotOne = TRUE;
+                    gotOne = true;
                 else {
                     if (buf[strlen(buf)-1] == '\n')
                         buf[strlen(buf)-1] = '\0';
@@ -191,14 +191,27 @@ pm_colorget(FILE * const f) {
 void
 pm_parse_dictionary_namen(char   const colorname[],
                           tuplen const color) {
+/*----------------------------------------------------------------------------
+   Return as *tuplen a tuple of type RGB that represents the color named
+   'colorname'.  This is an actual name, like "pink", not just a color
+   specification, like "rgb:0/0/0".
+
+   If the color name is unknown, abort the program.  If there are two entries
+   in the dictionary for the same color name, use the first one.
+
+   We use the Netpbm color dictionary used by 'pm_openColornamefile'.
 
-    FILE * fP;
+   Caller must ensure there is enough memory at 'tuplen' for at least 3
+   samples.  We set the first 3 samples of the tuple value and ignore any
+   others.
+-----------------------------------------------------------------------------*/
+    FILE * fileP;
     bool gotit;
     bool colorfileExhausted;
     struct colorfile_entry colorfileEntry;
     char * canoncolor;
 
-    fP = pm_openColornameFile(NULL, TRUE);  /* exits if error */
+    fileP = pm_openColornameFile(NULL, true);  /* exits if error */
     canoncolor = strdup(colorname);
 
     if (!canoncolor)
@@ -207,18 +220,18 @@ pm_parse_dictionary_namen(char   const colorname[],
 
     pm_canonstr(canoncolor);
 
-    for(gotit = FALSE, colorfileExhausted = FALSE;
+    for (gotit = false, colorfileExhausted = false;
         !gotit && !colorfileExhausted; ) {
 
-        colorfileEntry = pm_colorget(fP);
+        colorfileEntry = pm_colorget(fileP);
         if (colorfileEntry.colorname) {
             pm_canonstr(colorfileEntry.colorname);
             if (streq(canoncolor, colorfileEntry.colorname))
-                gotit = TRUE;
+                gotit = true;
         } else
-            colorfileExhausted = TRUE;
+            colorfileExhausted = true;
     }
-    fclose(fP);
+    fclose(fileP);
 
     if (!gotit)
         pm_error("unknown color '%s'", colorname);
@@ -237,7 +250,15 @@ pm_parse_dictionary_name(char    const colorname[],
                          pixval  const maxval,
                          int     const closeOk,
                          pixel * const colorP) {
+/*----------------------------------------------------------------------------
+   Same as 'pm_parse_dictionary_name' except return the color as a
+   pixel value of type 'pixel', with a maxval of 'maxval'.
 
+   We round the color to the nearest one that can be represented with the
+   resolution indicated by 'maxval' (rounding each component independently).
+   Iff rounding is necessary and 'closeOK' is false, we issue an informational
+   message about the rounding.
+-----------------------------------------------------------------------------*/
     double const epsilon = 1.0/65536.0;
 
     tuplen color;
@@ -271,4 +292,3 @@ pm_parse_dictionary_name(char    const colorname[],
 }
 
 
-
diff --git a/lib/dithers.h b/lib/dithers.h
index 05531a32..d47c39ec 100644
--- a/lib/dithers.h
+++ b/lib/dithers.h
@@ -42,7 +42,7 @@ static int const dither8[16][16] = {
   {  11,227, 51,211,  7,237, 61,221,  8,224, 48,208,  4,238, 62,222},
   { 139, 75,179,115,135, 71,189,125,136, 72,176,112,132, 68,190,126},
   {  43,203, 27,243, 39,199, 23,253, 40,200, 24,240, 36,196, 20,254},
-  { 171,107,155, 91,167,103,151, 87,168,104,152, 88,164,100,148, 84} 
+  { 171,107,155, 91,167,103,151, 87,168,104,152, 88,164,100,148, 84}
 };
 
 /* Order-3 clustered dithering matrix. */
diff --git a/lib/fileio.c b/lib/fileio.c
index 300ae303..d95e5f8c 100644
--- a/lib/fileio.c
+++ b/lib/fileio.c
@@ -25,7 +25,7 @@ pm_getc(FILE * const fileP) {
     if (ich == EOF)
         pm_error("EOF / read error reading a byte");
     ch = (char) ich;
-    
+
     if (ch == '#') {
         do {
             ich = getc(fileP);
@@ -88,7 +88,7 @@ pm_getuint(FILE * const ifP) {
         if (i > INT_MAX/10)
             pm_error("ASCII decimal integer in file is "
                      "too large to be processed.  ");
-        
+
         i *= 10;
 
         if (i > INT_MAX - digitVal)
@@ -106,7 +106,7 @@ pm_getuint(FILE * const ifP) {
 
 
 unsigned int
-pm_getraw(FILE *       const file, 
+pm_getraw(FILE *       const file,
           unsigned int const bytes) {
 
     unsigned int value;  /* our return value */
@@ -129,11 +129,11 @@ pm_getraw(FILE *       const file,
         int n_read;
 
         n_read = fread(inval, bytes, 1, file);
-        if (n_read < 1) 
+        if (n_read < 1)
             pm_error("EOF/error reading %d byte sample from file.", bytes);
         value = 0;  /* initial value */
         cursor = 0;
-        for (shift = (bytes-1)*8; shift >= 0; shift-=8) 
+        for (shift = (bytes-1)*8; shift >= 0; shift-=8)
             value += inval[cursor++] << shift;
     }
     return(value);
@@ -142,8 +142,8 @@ pm_getraw(FILE *       const file,
 
 
 void
-pm_putraw(FILE *       const file, 
-          unsigned int const value, 
+pm_putraw(FILE *       const file,
+          unsigned int const value,
           unsigned int const bytes) {
 
     if (bytes == 1) {
@@ -169,7 +169,7 @@ pm_putraw(FILE *       const file,
             outval[cursor++] = (value >> shift) & 0xFF;
         }
         n_written = fwrite(&outval, bytes, 1, file);
-        if (n_written == 0) 
+        if (n_written == 0)
             pm_error("Error writing %d byte sample to file.", bytes);
     }
 }
diff --git a/lib/libpam.c b/lib/libpam.c
index d19534e2..9875331d 100644
--- a/lib/libpam.c
+++ b/lib/libpam.c
@@ -90,7 +90,12 @@ validateComputableSize(struct pam * const pamP) {
    the size of a tuple row, in bytes, can be represented by an 'int'.
 
    Another common operation is adding 1 or 2 to the highest row, column,
-   or plane number in the image, so we make sure that's possible.
+   or plane number in the image, so we make sure that's possible.  And in
+   bitmap images, rounding up to multiple of 8 is common, so we provide for
+   that too.
+
+   Note that it's still the programmer's responsibility to ensure that his
+   code, using values known to have been validated here, cannot overflow.
 -----------------------------------------------------------------------------*/
     if (pamP->width == 0)
         pm_error("Width is zero.  Image must be at least one pixel wide");
@@ -111,10 +116,10 @@ validateComputableSize(struct pam * const pamP) {
 
         if (depth > INT_MAX - 2)
             pm_error("image depth (%u) too large to be processed", depth);
-        if (pamP->width > INT_MAX - 2)
+        if (pamP->width > INT_MAX - 10)
             pm_error("image width (%u) too large to be processed",
                      pamP->width);
-        if (pamP->height > INT_MAX - 2)
+        if (pamP->height > INT_MAX - 10)
             pm_error("image height (%u) too large to be processed",
                      pamP->height);
     }
@@ -122,12 +127,22 @@ validateComputableSize(struct pam * const pamP) {
 
 
 
+static void
+validateComputableMaxval(const struct pam * const pamP) {
+/*----------------------------------------------------------------------------
+  This is similar to validateComputableSize, but for the maxval.
+-----------------------------------------------------------------------------*/
+    pgm_validateComputableMaxval(pamP->maxval);
+}
+
+
+
 tuple
 pnm_allocpamtuple(const struct pam * const pamP) {
 
     tuple retval;
 
-    retval = malloc(allocationDepth(pamP) * sizeof(retval[0]));
+    MALLOCARRAY(retval, allocationDepth(pamP));
 
     if (retval == NULL)
         pm_error("Out of memory allocating %u-plane tuple",
@@ -211,6 +226,24 @@ pnm_createBlackTuple(const struct pam * const pamP,
 
 
 
+void
+pnm_createWhiteTuple(const struct pam * const pamP,
+                     tuple *            const whiteTupleP) {
+/*----------------------------------------------------------------------------
+   Create a "white" tuple.  By that we mean a tuple all of whose elements are
+   the maxval.  If it's an RGB, grayscale, or b&w pixel, that means it's
+   white.
+-----------------------------------------------------------------------------*/
+    unsigned int i;
+
+    *whiteTupleP = pnm_allocpamtuple(pamP);
+
+    for (i = 0; i < pamP->depth; ++i)
+        (*whiteTupleP)[i] = pamP->maxval;
+}
+
+
+
 static tuple *
 allocPamRow(const struct pam * const pamP) {
 /*----------------------------------------------------------------------------
@@ -289,7 +322,7 @@ pnm_allocrowimage(const struct pam * const pamP) {
 
     unsigned char * retval;
 
-    retval = malloc(size);
+    MALLOCARRAY(retval, size);
 
     if (retval == NULL)
         pm_error("Unable to allocate %u bytes for a row image buffer",
@@ -405,9 +438,9 @@ pnm_setpamrow(const struct pam * const pamP,
               tuple *            const tuplerow,
               sample             const value) {
 
-    int col;
+    unsigned int col;
     for (col = 0; col < pamP->width; ++col) {
-        int plane;
+        unsigned int plane;
         for (plane = 0; plane < pamP->depth; ++plane)
             tuplerow[col][plane] = value;
     }
@@ -416,6 +449,22 @@ pnm_setpamrow(const struct pam * const pamP,
 
 
 
+static void
+setSeekableAndRasterPos(struct pam * const pamP) {
+
+    if (pamP->size >= PAM_STRUCT_SIZE(is_seekable))
+        pamP->is_seekable = pm_is_seekable(pamP->file);
+
+    if (pamP->size >= PAM_STRUCT_SIZE(raster_pos)) {
+        if (pamP->is_seekable)
+            pm_tell2(pamP->file, &pamP->raster_pos, sizeof(pamP->raster_pos));
+    }
+}
+
+
+#pragma GCC diagnostic push
+#pragma GCC diagnostic ignored "-Wstringop-truncation"
+
 #define MAX_LABEL_LENGTH 8
 #define MAX_VALUE_LENGTH 255
 
@@ -424,7 +473,7 @@ parseHeaderLine(const char * const buffer,
                 char *       const label,
                 char *       const value) {
 /*----------------------------------------------------------------------------
-   We truncate the labe to MAX_LABEL_LENGTH and the value to
+   We truncate the label to MAX_LABEL_LENGTH and the value to
    MAX_VALUE_LENGTH.  There must be at least that much space (plus space
    for a terminating NUL) at 'label' and 'value', respectively.
 -----------------------------------------------------------------------------*/
@@ -465,6 +514,7 @@ parseHeaderLine(const char * const buffer,
         value[valueCurs] = '\0';
     }
 }
+#pragma GCC diagnostic pop
 
 
 
@@ -699,7 +749,7 @@ readpaminitrest(struct pam * const pamP) {
     if (pamP->maxval == 0)
         pm_error("MAXVAL value is zero in PAM header");
     if (pamP->maxval > PAM_OVERALL_MAXVAL)
-        pm_error("MAXVAL value (%lu) in PAM header is greater than %u",
+        pm_error("MAXVAL value (%lu) in PAM header is greater than %lu",
                  pamP->maxval, PAM_OVERALL_MAXVAL);
 }
 
@@ -945,9 +995,13 @@ pnm_readpaminit(FILE *       const file,
     pamP->plainformat = FALSE;
         /* See below for complex explanation of why this is FALSE. */
 
+    setSeekableAndRasterPos(pamP);
+
     interpretTupleType(pamP);
 
     validateComputableSize(pamP);
+
+    validateComputableMaxval(pamP);
 }
 
 
@@ -1032,7 +1086,7 @@ pnm_writepaminit(struct pam * const pamP) {
 
     if (pamP->maxval > PAM_OVERALL_MAXVAL)
         pm_error("maxval (%lu) passed to pnm_writepaminit() "
-                 "is greater than %u", pamP->maxval, PAM_OVERALL_MAXVAL);
+                 "is greater than %lu", pamP->maxval, PAM_OVERALL_MAXVAL);
 
     if (pamP->len < PAM_STRUCT_SIZE(tuple_type)) {
         tupleType = "";
@@ -1053,10 +1107,10 @@ pnm_writepaminit(struct pam * const pamP) {
 
     interpretTupleType(pamP);
 
-    pamP->len = MIN(pamP->size, PAM_STRUCT_SIZE(opacity_plane));
-
     switch (PAM_FORMAT_TYPE(pamP->format)) {
     case PAM_TYPE:
+        validateComputableSize(pamP);
+        validateComputableMaxval(pamP);
         /* See explanation below of why we ignore 'pm_plain_output' here. */
         fprintf(pamP->file, "P7\n");
         writeComments(pamP);
@@ -1113,6 +1167,10 @@ pnm_writepaminit(struct pam * const pamP) {
         pm_error("Invalid format passed to pnm_writepaminit(): %d",
                  pamP->format);
     }
+
+    setSeekableAndRasterPos(pamP);
+
+    pamP->len = MIN(pamP->size, PAM_STRUCT_SIZE(raster_pos));
 }
 
 
@@ -1394,6 +1452,66 @@ pnm_backgroundtuple(struct pam *  const pamP,
 
 
 
+tuple
+pnm_backgroundtuplerow(const struct pam * const pamP,
+                       tuple            * const tuplerow) {
+/*-----------------------------------------------------------------------------
+  Guess a good background color for an image that contains row 'tuplerow'
+  (probably top or bottom edge), described by *pamP.
+
+  This function was copied from libpnm3.c's pnm_backgroundxelrow() and
+  modified to use tuples instead of xels.
+-----------------------------------------------------------------------------*/
+    tuple bgtuple;
+
+    bgtuple = pnm_allocpamtuple(pamP);
+
+    assert(pamP->width > 0);
+
+    if (pamP->width == 1)
+        pnm_assigntuple(pamP, bgtuple, tuplerow[0]);
+    else {
+        tuple const l = tuplerow[0];
+        tuple const r = tuplerow[pamP->width-1];
+
+        if (pnm_tupleequal(pamP, l, r)) {
+            /* Both corners are same color, so that's the background color,
+               without any extra computation.
+            */
+            pnm_assigntuple(pamP, bgtuple, l);
+        } else {
+            /* Corners are different */
+
+            if (pamP->depth == 1 && pamP->maxval == 1) {
+                /* It's black and white, with one corner black, the other
+                   white.  We consider whichever color is most prevalent in
+                   the row the background color.
+                */
+                unsigned int col;
+                unsigned int blackCt;
+
+                for (col = 0, blackCt = 0; col < pamP->width; ++col) {
+                    if (tuplerow[col] == 0)
+                        ++blackCt;
+                }
+                if (blackCt > pamP->width / 2)
+                    bgtuple[0] = 0;
+                else
+                    bgtuple[0] = pamP->maxval;
+            } else {
+                /* Use the cartesian mean of the two corner colors */
+                unsigned int plane;
+
+                for (plane = 0; plane < pamP->depth; ++plane)
+                    bgtuple[plane] = (l[plane] + r[plane])/2;
+            }
+        }
+    }
+    return bgtuple;
+}
+
+
+
 /*=============================================================================
    pm_system() Standard Input feeder and Standard Output accepter functions.
 =============================================================================*/
@@ -1433,3 +1551,6 @@ pm_accept_to_pamtuples(int    const pipeToSuckFd,
 
     pm_close(inpamP->file);
 }
+
+
+
diff --git a/lib/libpamcolor.c b/lib/libpamcolor.c
index 718df89f..831057ab 100644
--- a/lib/libpamcolor.c
+++ b/lib/libpamcolor.c
@@ -130,21 +130,29 @@ isNormal(samplen const arg) {
 static void
 parseNewDecX11(const char * const colorname,
                tuplen       const color) {
-
+/*----------------------------------------------------------------------------
+   Return as *colorP the color specified by the new-style decimal specifier
+   colorname[] (e.g. "rgbi:0/.5/1").
+-----------------------------------------------------------------------------*/
+    char invalidExtra;
     int rc;
 
-    rc = sscanf(colorname, "rgbi:%f/%f/%f",
+    rc = sscanf(colorname, "rgbi:%f/%f/%f%c",
                 &color[PAM_RED_PLANE],
                 &color[PAM_GRN_PLANE],
-                &color[PAM_BLU_PLANE]);
+                &color[PAM_BLU_PLANE],
+                &invalidExtra);
 
     if (rc != 3)
-        pm_error("invalid color specifier '%s'", colorname);
+        pm_error("invalid rgbi: color specifier '%s' - "
+                 "does not have form rgbi:n/n/n "
+                 "(where n is floating point number)",
+                 colorname);
 
     if (!(isNormal(color[PAM_RED_PLANE]) &&
           isNormal(color[PAM_GRN_PLANE]) &&
           isNormal(color[PAM_BLU_PLANE]))) {
-        pm_error("invalid color specifier '%s' - "
+        pm_error("invalid rgbi: color specifier '%s' - "
                  "values must be between 0.0 and 1.0", colorname);
     }
 }
@@ -154,16 +162,21 @@ parseNewDecX11(const char * const colorname,
 static void
 parseInteger(const char * const colorname,
              tuplen       const color) {
-
+/*----------------------------------------------------------------------------
+   Return as *colorP the color specified by the integer specifier
+   colorname[] (e.g. "rgb-255/10/20/30").
+-----------------------------------------------------------------------------*/
     unsigned int maxval;
     unsigned int r, g, b;
+    char invalidExtra;
     int rc;
 
-    rc = sscanf(colorname, "rgb-%u:%u/%u/%u", &maxval, &r, &g, &b);
+    rc = sscanf(colorname, "rgb-%u:%u/%u/%u%c",
+                &maxval, &r, &g, &b, &invalidExtra);
 
     if (rc != 4)
-        pm_error("invalid color specifier '%s'.  "
-                 "If it starts with \"rgb-\", then it must have the format "
+        pm_error("invalid rgb- color specifier '%s' - "
+                 "Does not have form "
                  "rgb-<MAXVAL>:<RED>:<GRN>:<BLU>, "
                  "where <MAXVAL>, <RED>, <GRN>, and <BLU> are "
                  "unsigned integers",
@@ -200,7 +213,7 @@ parseOldX11(const char * const colorname,
             tuplen       const color) {
 /*----------------------------------------------------------------------------
    Return as *colorP the color specified by the old X11 style color
-   specififier colorname[] (e.g. #554055).
+   specifier colorname[] (e.g. #554055).
 -----------------------------------------------------------------------------*/
     if (!pm_strishex(&colorname[1]))
         pm_error("Non-hexadecimal characters in #-type color specification");
@@ -276,21 +289,29 @@ parseOldX11(const char * const colorname,
 static void
 parseOldX11Dec(const char* const colorname,
                tuplen      const color) {
-
+/*----------------------------------------------------------------------------
+   Return as *colorP the color specified by the old X11 style decimal color
+   specifier colorname[] (e.g. 0,.5,1).
+-----------------------------------------------------------------------------*/
+    char invalidExtra;
     int rc;
 
-    rc = sscanf(colorname, "%f,%f,%f",
+    rc = sscanf(colorname, "%f,%f,%f%c",
                 &color[PAM_RED_PLANE],
                 &color[PAM_GRN_PLANE],
-                &color[PAM_BLU_PLANE]);
+                &color[PAM_BLU_PLANE],
+                &invalidExtra);
 
     if (rc != 3)
-        pm_error("invalid color specifier '%s'", colorname);
+        pm_error("invalid old-style X11 decimal color specifier '%s' - "
+                 "does not have form n,n,n (where n is a floating point "
+                 "decimal number",
+                 colorname);
 
     if (!(isNormal(color[PAM_RED_PLANE]) &&
           isNormal(color[PAM_GRN_PLANE]) &&
           isNormal(color[PAM_BLU_PLANE]))) {
-        pm_error("invalid color specifier '%s' - "
+        pm_error("invalid old-style X11 decimal color specifier '%s' - "
                  "values must be between 0.0 and 1.0", colorname);
     }
 }
@@ -338,7 +359,7 @@ warnIfNotExact(const char * const colorname,
 
     float const epsilon = 1.0/65536.0;
 
-    if (fabs((float)(rounded[plane] / maxval) - exact[plane]) > epsilon) {
+    if (fabs(((float)rounded[plane] / maxval) - exact[plane]) > epsilon) {
         pm_message("WARNING: Component %u of color '%s' is %f, "
                    "which cannot be represented precisely with maxval %lu.  "
                    "Approximating as %lu.",
diff --git a/lib/libpammap.c b/lib/libpammap.c
index 569156fe..a0e7fb55 100644
--- a/lib/libpammap.c
+++ b/lib/libpammap.c
@@ -102,12 +102,15 @@ static struct tupleint_list_item *
 allocTupleIntListItem(struct pam * const pamP) {
 
 
-    /* This is complicated by the fact that the last element of a
-       tupleint_list_item is of variable length, because the last element
+    /* This is complicated by the fact that the last member of a
+       tupleint_list_item is of variable length, because the last member
        of _it_ is of variable length
     */
     struct tupleint_list_item * retval;
 
+    if (pamP->depth > (UINT_MAX - sizeof(*retval)) / sizeof(sample))
+        pm_error("Depth %u is too large for computation", pamP->depth);
+
     unsigned int const size =
         sizeof(*retval) - sizeof(retval->tupleint.tuple)
         + pamP->depth * sizeof(sample);
diff --git a/lib/libpamread.c b/lib/libpamread.c
index 74b1ab83..1ebf4b2f 100644
--- a/lib/libpamread.c
+++ b/lib/libpamread.c
@@ -13,7 +13,7 @@
    offset stuff.
 */
 #define _FILE_OFFSET_BITS 64
-#define _LARGE_FILES  
+#define _LARGE_FILES
 
 #include <string.h>
 #include <limits.h>
@@ -49,11 +49,11 @@ readPbmRow(const struct pam * const pamP,
 
             pbm_readpbmrow_packed(pamP->file, bitrow, pamP->width,
                                   pamP->format);
-    
+
             if (tuplerow) {
                 unsigned int col;
                 for (col = 0; col < pamP->width; ++col) {
-                    tuplerow[col][0] = 
+                    tuplerow[col][0] =
                         ( ((bitrow[col/8] >> (7-col%8)) & 1 ) == PBM_BLACK)
                         ? PAM_PBM_BLACK : PAM_PBM_WHITE
                         ;
@@ -207,7 +207,7 @@ validatePamRow(const struct pam * const pamP,
                tuple *            const tuplerow,
                const char **      const errorP) {
 /*----------------------------------------------------------------------------
-  Check for sample values above maxval in input.  
+  Check for sample values above maxval in input.
 
   Note: a program that wants to deal with invalid sample values itself can
   simply make sure it sets pamP->maxval sufficiently high, so this validation
@@ -251,7 +251,7 @@ static void
 readRawNonPbmRow(const struct pam * const pamP,
                  tuple *            const tuplerow) {
 
-    unsigned int const rowImageSize = 
+    unsigned int const rowImageSize =
         pamP->width * pamP->bytes_per_sample * pamP->depth;
 
     unsigned char * inbuf;
@@ -259,14 +259,14 @@ readRawNonPbmRow(const struct pam * const pamP,
     const char * error;
 
     inbuf = pnm_allocrowimage(pamP);
-    
+
     bytesRead = fread(inbuf, 1, rowImageSize, pamP->file);
 
     if (bytesRead != rowImageSize) {
         if (feof(pamP->file))
             pm_asprintf(&error, "End of file encountered "
                         "when trying to read a row from input file.");
-        else 
+        else
             pm_asprintf(&error, "Error reading a row from input file.  "
                         "fread() fails with errno=%d (%s)",
                         errno, strerror(errno));
@@ -297,23 +297,23 @@ readRawNonPbmRow(const struct pam * const pamP,
 
 
 
-void 
-pnm_readpamrow(const struct pam * const pamP, 
+void
+pnm_readpamrow(const struct pam * const pamP,
                tuple *            const tuplerow) {
 /*----------------------------------------------------------------------------
    Read a row from the Netpbm image file into tuplerow[], at the
    current file position.  If 'tuplerow' is NULL, advance the file
    pointer to the next row, but don't return the contents of the
    current one.
-   
+
    We assume the file is positioned to the beginning of a row of the
    image's raster.
 -----------------------------------------------------------------------------*/
-    /* For speed, we don't check any of the inputs for consistency 
+    /* For speed, we don't check any of the inputs for consistency
        here (unless it's necessary to avoid crashing).  Any consistency
-       checking should have been done by a prior call to 
+       checking should have been done by a prior call to
        pnm_readpaminit().
-    */  
+    */
 
     /* Need a special case for raw PBM because it has multiple tuples (8)
        packed into one byte.
@@ -340,9 +340,9 @@ pnm_readpamrow(const struct pam * const pamP,
 
 
 
-tuple ** 
+tuple **
 pnm_readpam(FILE *       const fileP,
-            struct pam * const pamP, 
+            struct pam * const pamP,
             int          const size) {
 
     jmp_buf jmpbuf;
@@ -350,9 +350,9 @@ pnm_readpam(FILE *       const fileP,
     tuple ** tuplearray;
 
     pnm_readpaminit(fileP, pamP, size);
-    
+
     tuplearray = pnm_allocpamarray(pamP);
-    
+
     if (setjmp(jmpbuf) != 0) {
         pnm_freepamarray(tuplearray, pamP);
         pm_setjmpbuf(origJmpbufP);
@@ -361,8 +361,8 @@ pnm_readpam(FILE *       const fileP,
         unsigned int row;
 
         pm_setjmpbufsave(&jmpbuf, &origJmpbufP);
-            
-        for (row = 0; row < pamP->height; ++row) 
+
+        for (row = 0; row < pamP->height; ++row)
             pnm_readpamrow(pamP, tuplearray[row]);
 
         pm_setjmpbuf(origJmpbufP);
diff --git a/lib/libpamwrite.c b/lib/libpamwrite.c
index 7edc90dc..0e1ff469 100644
--- a/lib/libpamwrite.c
+++ b/lib/libpamwrite.c
@@ -71,7 +71,7 @@ writePamPlainPbmRow(const struct pam *  const pamP,
 
 static void
 writePamPlainRow(const struct pam *  const pamP,
-                    const tuple *       const tuplerow) {
+                 const tuple *       const tuplerow) {
 
     int const samplesPerLine =
         samplesPerPlainLine(pamP->maxval, pamP->depth, 79);
@@ -101,17 +101,25 @@ writePamPlainRow(const struct pam *  const pamP,
 
 
 static void
-formatPbmRow(const struct pam * const pamP,
-             const tuple *      const tuplerow,
-             unsigned char *    const outbuf,
-             unsigned int *     const rowSizeP) {
+formatPbm(const struct pam * const pamP,
+          const tuple *      const tuplerow,
+          unsigned char *    const outbuf,
+          unsigned int       const nTuple,
+          unsigned int *     const rowSizeP) {
+/*----------------------------------------------------------------------------
+   Create the image of 'nTuple' consecutive tuples of a row in the raster of a
+   raw format PBM image.
 
+   Put the image at *outbuf; put the number of bytes of it at *rowSizeP.
+-----------------------------------------------------------------------------*/
     unsigned char accum;
     int col;
 
+    assert(nTuple <= pamP->width);
+
     accum = 0;  /* initial value */
 
-    for (col=0; col < pamP->width; ++col) {
+    for (col=0; col < nTuple; ++col) {
         accum |=
             (tuplerow[col][0] == PAM_PBM_BLACK ? PBM_BLACK : PBM_WHITE)
                 << (7-col%8);
@@ -120,12 +128,12 @@ formatPbmRow(const struct pam * const pamP,
                 accum = 0;
         }
     }
-    if (pamP->width % 8 != 0) {
-        unsigned int const lastByteIndex = pamP->width/8;
+    if (nTuple % 8 != 0) {
+        unsigned int const lastByteIndex = nTuple/8;
         outbuf[lastByteIndex] = accum;
         *rowSizeP = lastByteIndex + 1;
     } else
-        *rowSizeP = pamP->width/8;
+        *rowSizeP = nTuple/8;
 }
 
 
@@ -171,36 +179,40 @@ sampleToBytes4(unsigned char       buf[4],
 
 
 static __inline__ void
-format1BpsRow(const struct pam * const pamP,
-              const tuple *      const tuplerow,
-              unsigned char *    const outbuf,
-              unsigned int *     const rowSizeP) {
+format1Bps(const struct pam * const pamP,
+           const tuple *      const tuplerow,
+           unsigned char *    const outbuf,
+           unsigned int       const nTuple,
+           unsigned int *     const rowSizeP) {
 /*----------------------------------------------------------------------------
-   Create the image of a row in the raster of a raw format Netpbm
-   image that has one byte per sample (ergo not PBM).
+   Create the image of 'nTuple' consecutive tuples of a row in the raster of a
+   raw format Netpbm image that has one byte per sample (ergo not PBM).
 
    Put the image at *outbuf; put the number of bytes of it at *rowSizeP.
 -----------------------------------------------------------------------------*/
     int col;
     unsigned int bufferCursor;
 
+    assert(nTuple <= pamP->width);
+
     bufferCursor = 0;  /* initial value */
 
-    for (col = 0; col < pamP->width; ++col) {
+    for (col = 0; col < nTuple; ++col) {
         unsigned int plane;
         for (plane=0; plane < pamP->depth; ++plane)
             outbuf[bufferCursor++] = (unsigned char)tuplerow[col][plane];
     }
-    *rowSizeP = pamP->width * 1 * pamP->depth;
+    *rowSizeP = nTuple * 1 * pamP->depth;
 }
 
 
 
 static __inline__ void
-format2BpsRow(const struct pam * const pamP,
-              const tuple *      const tuplerow,
-              unsigned char *    const outbuf,
-              unsigned int *     const rowSizeP) {
+format2Bps(const struct pam * const pamP,
+           const tuple *      const tuplerow,
+           unsigned char *    const outbuf,
+           unsigned int       const nTuple,
+           unsigned int *     const rowSizeP) {
 /*----------------------------------------------------------------------------
   Analogous to format1BpsRow().
 -----------------------------------------------------------------------------*/
@@ -209,24 +221,27 @@ format2BpsRow(const struct pam * const pamP,
     int col;
     unsigned int bufferCursor;
 
+    assert(nTuple <= pamP->width);
+
     bufferCursor = 0;  /* initial value */
 
-    for (col=0; col < pamP->width; ++col) {
+    for (col=0; col < nTuple; ++col) {
         unsigned int plane;
         for (plane = 0; plane < pamP->depth; ++plane)
             sampleToBytes2(ob[bufferCursor++], tuplerow[col][plane]);
     }
 
-    *rowSizeP = pamP->width * 2 * pamP->depth;
+    *rowSizeP = nTuple * 2 * pamP->depth;
 }
 
 
 
 static __inline__ void
-format3BpsRow(const struct pam * const pamP,
-              const tuple *      const tuplerow,
-              unsigned char *    const outbuf,
-              unsigned int *     const rowSizeP) {
+format3Bps(const struct pam * const pamP,
+           const tuple *      const tuplerow,
+           unsigned char *    const outbuf,
+           unsigned int       const nTuple,
+           unsigned int *     const rowSizeP) {
 /*----------------------------------------------------------------------------
   Analogous to format1BpsRow().
 -----------------------------------------------------------------------------*/
@@ -235,24 +250,27 @@ format3BpsRow(const struct pam * const pamP,
     int col;
     unsigned int bufferCursor;
 
+    assert(nTuple <= pamP->width);
+
     bufferCursor = 0;  /* initial value */
 
-    for (col=0; col < pamP->width; ++col) {
+    for (col=0; col < nTuple; ++col) {
         unsigned int plane;
         for (plane = 0; plane < pamP->depth; ++plane)
             sampleToBytes3(ob[bufferCursor++], tuplerow[col][plane]);
     }
 
-    *rowSizeP = pamP->width * 3 * pamP->depth;
+    *rowSizeP = nTuple * 3 * pamP->depth;
 }
 
 
 
 static __inline__ void
-format4BpsRow(const struct pam * const pamP,
-              const tuple *      const tuplerow,
-              unsigned char *    const outbuf,
-              unsigned int *     const rowSizeP) {
+format4Bps(const struct pam * const pamP,
+           const tuple *      const tuplerow,
+           unsigned char *    const outbuf,
+           unsigned int       const nTuple,
+           unsigned int *     const rowSizeP) {
 /*----------------------------------------------------------------------------
   Analogous to format1BpsRow().
 -----------------------------------------------------------------------------*/
@@ -261,41 +279,49 @@ format4BpsRow(const struct pam * const pamP,
     int col;
     unsigned int bufferCursor;
 
+    assert(nTuple <= pamP->width);
+
     bufferCursor = 0;  /* initial value */
 
-    for (col=0; col < pamP->width; ++col) {
+    for (col=0; col < nTuple; ++col) {
         unsigned int plane;
         for (plane = 0; plane < pamP->depth; ++plane)
             sampleToBytes4(ob[bufferCursor++], tuplerow[col][plane]);
     }
 
-    *rowSizeP = pamP->width * 4 * pamP->depth;
+    *rowSizeP = nTuple * 4 * pamP->depth;
 }
 
 
 
 void
-pnm_formatpamrow(const struct pam * const pamP,
-                 const tuple *      const tuplerow,
-                 unsigned char *    const outbuf,
-                 unsigned int *     const rowSizeP) {
-/*----------------------------------------------------------------------------
-   Create the image of a row in the raster of a raw (not plain) format
-   Netpbm image, as described by *pamP and tuplerow[].  Put the image
-   at *outbuf.
+pnm_formatpamtuples(const struct pam * const pamP,
+                    const tuple *      const tuplerow,
+                    unsigned char *    const outbuf,
+                    unsigned int       const nTuple,
+                    unsigned int *     const rowSizeP) {
+/*----------------------------------------------------------------------------   Create the image of 'nTuple' consecutive tuples of a row in the raster of a
+   raw (not plain) format Netpbm image, as described by *pamP and tuplerow[].
+   Put the image at *outbuf.
 
    'outbuf' must be the address of space allocated with pnm_allocrowimage().
 
-   We return as *rowSizeP the number of bytes in the row image.
+   We return as *rowSizeP the number of bytes in the image.
 -----------------------------------------------------------------------------*/
+    if (nTuple > pamP->width) {
+        pm_error("pnm_formatpamtuples called to write more tuples (%u) "
+                 "than the width of a row (%u)",
+                 nTuple, pamP->width);
+    }
+
     if (PAM_FORMAT_TYPE(pamP->format) == PBM_TYPE)
-        formatPbmRow(pamP, tuplerow, outbuf, rowSizeP);
+        formatPbm(pamP, tuplerow, outbuf, nTuple, rowSizeP);
     else {
         switch(pamP->bytes_per_sample){
-        case 1: format1BpsRow(pamP, tuplerow, outbuf, rowSizeP); break;
-        case 2: format2BpsRow(pamP, tuplerow, outbuf, rowSizeP); break;
-        case 3: format3BpsRow(pamP, tuplerow, outbuf, rowSizeP); break;
-        case 4: format4BpsRow(pamP, tuplerow, outbuf, rowSizeP); break;
+        case 1: format1Bps(pamP, tuplerow, outbuf, nTuple, rowSizeP); break;
+        case 2: format2Bps(pamP, tuplerow, outbuf, nTuple, rowSizeP); break;
+        case 3: format3Bps(pamP, tuplerow, outbuf, nTuple, rowSizeP); break;
+        case 4: format4Bps(pamP, tuplerow, outbuf, nTuple, rowSizeP); break;
         default:
             pm_error("invalid bytes per sample passed to "
                      "pnm_formatpamrow(): %u",  pamP->bytes_per_sample);
@@ -305,6 +331,19 @@ pnm_formatpamrow(const struct pam * const pamP,
 
 
 
+void
+pnm_formatpamrow(const struct pam * const pamP,
+                 const tuple *      const tuplerow,
+                 unsigned char *    const outbuf,
+                 unsigned int *     const rowSizeP) {
+/*----------------------------------------------------------------------------
+  Same as 'pnm_formatpamtuples', except formats an entire row.
+-----------------------------------------------------------------------------*/
+    pnm_formatpamtuples(pamP, tuplerow, outbuf, pamP->width, rowSizeP);
+}
+
+
+
 static void
 writePamRawRow(const struct pam * const pamP,
                const tuple *      const tuplerow,
@@ -398,6 +437,74 @@ pnm_writepamrowmult(const struct pam * const pamP,
 
 
 void
+pnm_writepamrowpart(const struct pam * const pamP,
+                    const tuple *      const tuplerow,
+                    unsigned int       const firstRow,
+                    unsigned int       const firstCol,
+                    unsigned int       const rowCt,
+                    unsigned int       const colCt) {
+/*----------------------------------------------------------------------------
+   Write part of multiple consecutive rows to the file.
+
+   For each of 'rowCt' consecutive rows starting at 'firstRow', write the
+   'colCt' columns starting at 'firstCol'.  The tuples to write are those in
+   'tuplerow', starting at the beginning of 'tuplerow'.
+
+   Fail if the file is not seekable (or not known to be seekable) or the
+   output format is not raw (i.e. is plain) or the output format is PBM.
+-----------------------------------------------------------------------------*/
+    unsigned int const bytesPerTuple = pamP->depth * pamP->bytes_per_sample;
+
+    jmp_buf jmpbuf;
+    jmp_buf * origJmpbufP;
+    unsigned int tupleImageSize;
+    unsigned char * outbuf;  /* malloc'ed */
+
+    if (pamP->len < PAM_STRUCT_SIZE(raster_pos) || !pamP->raster_pos)
+        pm_error("pnm_writepamrowpart called on nonseekable file");
+
+    if (PAM_FORMAT_TYPE(pamP->format) == PBM_TYPE)
+        pm_error("pnm_witepamrowpart called for PBM image");
+
+    if (pm_plain_output || pamP->plainformat)
+        pm_error("pnm_writepamrowpart called for plain format image");
+
+    outbuf = pnm_allocrowimage(pamP);
+
+    pnm_formatpamtuples(pamP, tuplerow, outbuf, colCt, &tupleImageSize);
+
+    if (setjmp(jmpbuf) != 0) {
+        pnm_freerowimage(outbuf);
+        pm_setjmpbuf(origJmpbufP);
+        pm_longjmp();
+    } else {
+        unsigned int row;
+
+        pm_setjmpbufsave(&jmpbuf, &origJmpbufP);
+
+        for (row = firstRow; row < firstRow + rowCt; ++row) {
+            pm_filepos const firstTuplePos =
+                pamP->raster_pos +
+                (row * pamP->width + firstCol) * bytesPerTuple;
+            size_t bytesWritten;
+
+            pm_seek2(pamP->file, &firstTuplePos, sizeof(firstTuplePos));
+
+            bytesWritten = fwrite(outbuf, 1, tupleImageSize, pamP->file);
+
+            if (bytesWritten != tupleImageSize)
+                pm_error("fwrite() failed to write %u image tuples "
+                         "to the file.  errno=%d (%s)",
+                         colCt, errno, strerror(errno));
+        }
+        pm_setjmpbuf(origJmpbufP);
+    }
+    pnm_freerowimage(outbuf);
+}
+
+
+
+void
 pnm_writepam(struct pam * const pamP,
              tuple **     const tuplearray) {
 
diff --git a/lib/libpbm.h b/lib/libpbm.h
index 827c9d7e..f3e6962a 100644
--- a/lib/libpbm.h
+++ b/lib/libpbm.h
@@ -4,9 +4,15 @@
 #ifndef LIBPBM_H_INCLUDED
 #define LIBPBM_H_INCLUDED
 
+#include <stdio.h>
+
 void
 pbm_readpbminitrest(FILE * file,
                     int  * colsP,
                     int *  rowsP);
 
+void
+pbm_validateComputableSize(unsigned int const cols,
+                           unsigned int const rows);
+
 #endif
diff --git a/lib/libpbm1.c b/lib/libpbm1.c
index 49ab7fdf..9e51970c 100644
--- a/lib/libpbm1.c
+++ b/lib/libpbm1.c
@@ -14,7 +14,7 @@
    offset stuff.
 */
 #define _FILE_OFFSET_BITS 64
-#define _LARGE_FILES  
+#define _LARGE_FILES
 
 #include <stdio.h>
 
@@ -22,6 +22,7 @@
 #include "netpbm/mallocvar.h"
 #include "netpbm/shhopt.h"
 
+#include "libpbm.h"
 #include "pbm.h"
 
 
@@ -59,7 +60,7 @@ pbm_nextimage(FILE *file, int * const eofP) {
 
 void
 pbm_check(FILE *               const fileP,
-          enum pm_check_type   const checkType, 
+          enum pm_check_type   const checkType,
           int                  const format,
           int                  const cols,
           int                  const rows,
@@ -69,14 +70,14 @@ pbm_check(FILE *               const fileP,
         pm_error("Invalid number of rows passed to pbm_check(): %d", rows);
     if (cols < 0)
         pm_error("Invalid number of columns passed to pbm_check(): %d", cols);
-    
+
     if (checkType != PM_CHECK_BASIC) {
         if (retvalP)
             *retvalP = PM_CHECK_UNKNOWN_TYPE;
     } else if (format != RPBM_FORMAT) {
         if (retvalP)
             *retvalP = PM_CHECK_UNCHECKABLE;
-    } else {        
+    } else {
         pm_filepos const bytesPerRow    = (cols+7)/8;
         pm_filepos const needRasterSize = rows * bytesPerRow;
         pm_check(fileP, checkType, needRasterSize, retvalP);
@@ -85,6 +86,28 @@ pbm_check(FILE *               const fileP,
 
 
 
+void
+pbm_validateComputableSize(unsigned int const cols,
+                           unsigned int const rows) {
+/*----------------------------------------------------------------------------
+   Validate that the dimensions of the image are such that it can be
+   processed in typical ways on this machine without worrying about
+   overflows.  Note that in C, arithmetic is always modulus
+   arithmetic, so if your values are too big, the result is not what
+   you expect.  That failed expectation can be disastrous if you use
+   it to allocate memory.
+
+   See comments at 'validateComputableSize' in libpam.c for details on
+   the purpose of these validations.
+-----------------------------------------------------------------------------*/
+    if (cols > INT_MAX - 10)
+        pm_error("image width (%u) too large to be processed", cols);
+    if (rows > INT_MAX - 10)
+        pm_error("image height (%u) too large to be processed", rows);
+}
+
+
+
 static unsigned int
 bitpop8(unsigned char const x) {
 /*----------------------------------------------------------------------------
@@ -179,3 +202,6 @@ pbm_backgroundbitrow(unsigned const char * const packedBits,
     }
     return retval;
 }
+
+
+
diff --git a/lib/libpbm2.c b/lib/libpbm2.c
index a35004f9..8668356e 100644
--- a/lib/libpbm2.c
+++ b/lib/libpbm2.c
@@ -35,47 +35,36 @@ getbit (FILE * const file) {
 
 
 void
-pbm_readpbminitrest( FILE * const file,
-                     int  * const colsP,
-                     int  * const rowsP ) {
+pbm_readpbminitrest(FILE * const ifP,
+                    int  * const colsP,
+                    int  * const rowsP ) {
+
+    unsigned int cols;
+    unsigned int rows;
+
     /* Read size. */
-    *colsP = (int)pm_getuint( file );
-    *rowsP = (int)pm_getuint( file );
+    cols = pm_getuint(ifP);
+    rows = pm_getuint(ifP);
 
     /* *colsP and *rowsP really should be unsigned int, but they come
        from the time before unsigned ints (or at least from a person
-       trained in that tradition), so they are int.  We could simply
-       consider negative numbers to mean values > INT_MAX/2 and much
+       trained in that tradition), so they are int.  Caller could simply
+       consider negative numbers to mean values > INT_MAX and much
        code would just automatically work.  But some code would fail
        miserably.  So we consider values that won't fit in an int to
        be unprocessable.
     */
-    if (*colsP < 0)
-        pm_error("Number of columns in header is too large.");
-    if (*rowsP < 0)
-        pm_error("Number of columns in header is too large.");
-}
-
-
-
-static void
-validateComputableSize(unsigned int const cols,
-                       unsigned int const rows) {
-/*----------------------------------------------------------------------------
-   Validate that the dimensions of the image are such that it can be
-   processed in typical ways on this machine without worrying about
-   overflows.  Note that in C, arithmetic is always modulus
-   arithmetic, so if your values are too big, the result is not what
-   you expect.  That failed expectation can be disastrous if you use
-   it to allocate memory.
-
-   A common operation is adding 1 or 2 to the highest row or
-   column number in the image, so we make sure that's possible.
------------------------------------------------------------------------------*/
-    if (cols > INT_MAX - 2)
-        pm_error("image width (%u) too large to be processed", cols);
-    if (rows > INT_MAX - 2)
-        pm_error("image height (%u) too large to be processed", rows);
+    if (cols > INT_MAX)
+        pm_error("Number of columns in header is too large (%u).  "
+                 "The maximum allowed by the format is %u",
+                 cols, INT_MAX);
+    if (rows > INT_MAX)
+        pm_error("Number of rows in header is too large (%u).  "
+                 "The maximum allowed by the format is %u",
+                 rows, INT_MAX);
+
+    *colsP = (int)cols;
+    *rowsP = (int)rows;
 }
 
 
@@ -115,7 +104,7 @@ pbm_readpbminit(FILE * const ifP,
         pm_error("bad magic number 0x%x - not a PPM, PGM, PBM, or PAM file",
                  realFormat);
     }
-    validateComputableSize(*colsP, *rowsP);
+    pbm_validateComputableSize(*colsP, *rowsP);
 }
 
 
@@ -216,6 +205,9 @@ pbm_readpbmrow_bitoffset(FILE *          const ifP,
    Read it into packedBits[], preserving surrounding image data.
 
    Logic not tested for negative offsets.
+
+   Because we are reading in packed mode large cols and offset values are
+   acceptable; dividing by 8 prevents overflows.
 -----------------------------------------------------------------------------*/
     unsigned int const rsh = offset % 8;
     unsigned int const lsh = (8 - rsh) % 8;
@@ -224,13 +216,15 @@ pbm_readpbmrow_bitoffset(FILE *          const ifP,
            Aligned to nearest byte boundary to the left, so the first
            few bits might contain original data, not output.
         */
-    unsigned int const last = pbm_packed_bytes(cols+rsh) - 1;
+    unsigned int const last = pbm_packed_bytes((unsigned int)cols + rsh) - 1;
         /* Position within window of rightmost byte after shift */
 
     /* The original leftmost and rightmost chars. */
     unsigned char const origHead = window[0];
     unsigned char const origEnd  = window[last];
 
+    assert(cols > 0 && pbm_packed_bytes(cols) > 0);
+
     pbm_readpbmrow_packed(ifP, window, cols, format);
 
     if (rsh > 0) {
diff --git a/lib/libpbm3.c b/lib/libpbm3.c
index 456d3986..b566202f 100644
--- a/lib/libpbm3.c
+++ b/lib/libpbm3.c
@@ -14,6 +14,7 @@
 
 #include "netpbm/pm_c_util.h"
 
+#include "libpbm.h"
 #include "pbm.h"
 
 #ifndef PACKBITS_SSE
@@ -45,6 +46,12 @@ pbm_writepbminit(FILE * const fileP,
                  int    const rows,
                  int    const forceplain) {
 
+    /* For Caller's convenience, we include validating computability of the
+       image dimensions, since Caller may be using them in arithmetic after
+       our return.
+    */
+    pbm_validateComputableSize(cols, rows);
+
     if (!forceplain && !pm_plain_output) {
         fprintf(fileP, "%c%c\n%d %d\n", PBM_MAGIC1, RPBM_MAGIC2, cols, rows);
     } else
@@ -317,7 +324,15 @@ pbm_writepbmrow_packed(FILE *                const fileP,
                        const unsigned char * const packedBits,
                        int                   const cols,
                        int                   const forceplain) {
+/*----------------------------------------------------------------------------
+   Write to file *fileP the PBM row 'cols' columns wide in packed bit buffer
+   'packedBits'.
+
+   Write it in PBM plain format iff 'forceplain' is nonzero.
 
+   In raw format, the don't-care bits at the end of the row are the same as
+   in the input buffer.
+-----------------------------------------------------------------------------*/
     if (!forceplain && !pm_plain_output)
         writePackedRawRow(fileP, packedBits, cols);
     else {
@@ -378,10 +393,14 @@ pbm_writepbmrow_bitoffset(FILE *          const fileP,
                           int             const format,
                           unsigned int    const offset) {
 /*----------------------------------------------------------------------------
-   Write PBM row from a packed bit buffer 'packedBits, starting at the
-   specified offset 'offset' in the buffer.
+   Write to file *fileP the tail of the PBM row 'cols' columns wide in packed
+   bit buffer 'packedBits'.  Start at column 'offset' of the row.
+
+   Write it in PBM raw format.
+
+   Make any don't-care bits at the end of the row written zero.
 
-   We destroy the buffer.
+   We destroy the contents of the buffer.
 -----------------------------------------------------------------------------*/
     unsigned int const rsh = offset % 8;
     unsigned int const lsh = (8 - rsh) % 8;
diff --git a/lib/libpbmfont1.c b/lib/libpbmfont1.c
index fe014150..a76d0e6b 100644
--- a/lib/libpbmfont1.c
+++ b/lib/libpbmfont1.c
@@ -184,7 +184,7 @@ computeCharacterSize(const bit **   const font,
 
 
 
-struct font*
+struct font *
 pbm_dissectfont(const bit ** const fontsheet,
                 unsigned int const frows,
                 unsigned int const fcols) {
@@ -222,56 +222,61 @@ pbm_dissectfont(const bit ** const fontsheet,
     unsigned int charWidth, charHeight;
         /* Maximum dimensions of glyph itself, inside its cell */
 
-    int row, col, ch, r, c, i;
-    struct font * fn;
+    unsigned int row, col;
+    int ch;
+    unsigned int i;
+    struct font * fontP;
 
     computeCharacterSize(fontsheet, fcols, frows,
                          &cellWidth, &cellHeight, &charWidth, &charHeight);
 
     /* Now convert to a general font */
 
-    MALLOCVAR(fn);
-    if (fn == NULL)
+    MALLOCVAR(fontP);
+    if (fontP == NULL)
         pm_error("out of memory allocating font structure");
 
-    fn->maxwidth  = charWidth;
-    fn->maxheight = charHeight;
-    fn->x = fn->y = 0;
+    fontP->maxwidth  = charWidth;
+    fontP->maxheight = charHeight;
+    fontP->x = fontP->y = 0;
 
-    fn->oldfont = fontsheet;
-    fn->frows = frows;
-    fn->fcols = fcols;
+    fontP->oldfont = fontsheet;
+    fontP->frows = frows;
+    fontP->fcols = fcols;
 
     /* Now fill in the 0,0 coords. */
     row = cellHeight * 2;
     col = cellWidth  * 2;
 
     /* Load individual glyphs */
-    for ( ch = 0; ch < nCharsInFont; ++ch ) {
+    for (ch = 0; ch < nCharsInFont; ++ch) {
         /* Allocate memory separately for each glyph.
            pbm_loadbdffont2() does this in exactly the same manner.
          */
-        struct glyph * const glyph =
+        struct glyph * const glyphP =
              (struct glyph *) malloc (sizeof (struct glyph));
-        char * const bmap = (char*) malloc(fn->maxwidth * fn->maxheight);
+        char * const bmap = (char*) malloc(fontP->maxwidth * fontP->maxheight);
 
-        if ( bmap == NULL || glyph == NULL )
-            pm_error( "out of memory allocating glyph data" );
+        unsigned int r;
 
-        glyph->width  = fn->maxwidth;
-        glyph->height = fn->maxheight;
-        glyph->x = glyph->y = 0;
-        glyph->xadd = cellWidth;
+        if (bmap == NULL || glyphP == NULL)
+            pm_error( "out of memory allocating glyph data" );
 
-        for ( r = 0; r < glyph->height; ++r )
-            for ( c = 0; c < glyph->width; ++c )
-                bmap[r * glyph->width + c] = fontsheet[row + r][col + c];
+        glyphP->width  = fontP->maxwidth;
+        glyphP->height = fontP->maxheight;
+        glyphP->x = glyphP->y = 0;
+        glyphP->xadd = cellWidth;
 
-        glyph->bmap = bmap;
-        fn->glyph[firstCodePoint + ch] = glyph;
+        for (r = 0; r < glyphP->height; ++r) {
+            unsigned int c;
+            for (c = 0; c < glyphP->width; ++c)
+                bmap[r * glyphP->width + c] = fontsheet[row + r][col + c];
+        }
+        glyphP->bmap = bmap;
+        fontP->glyph[firstCodePoint + ch] = glyphP;
 
         col += cellWidth;
-        if ( col >= cellWidth * 14 ) {
+        if (col >= cellWidth * 14) {
             col = cellWidth * 2;
             row += cellHeight;
         }
@@ -279,12 +284,12 @@ pbm_dissectfont(const bit ** const fontsheet,
 
     /* Initialize all remaining character positions to "undefined." */
     for (i = 0; i < firstCodePoint; ++i)
-        fn->glyph[i] = NULL;
+        fontP->glyph[i] = NULL;
 
     for (i = firstCodePoint + nCharsInFont; i <= PM_FONT_MAXGLYPH; ++i)
-        fn->glyph[i] = NULL;
+        fontP->glyph[i] = NULL;
 
-    return fn;
+    return fontP;
 }
 
 
diff --git a/lib/libpbmfont2.c b/lib/libpbmfont2.c
index 6007d7f6..7c0415c1 100644
--- a/lib/libpbmfont2.c
+++ b/lib/libpbmfont2.c
@@ -193,9 +193,12 @@ pm_selector_mark(struct pm_selector * const selectorP,
     }
 }
 
+
+
 /* There is no function for erasing a marked bit */
 
 
+
 int  /* boolean */
 pm_selector_is_marked(const struct pm_selector * const selectorP,
                       unsigned int               const index) {
@@ -312,14 +315,13 @@ tokenize(char *         const s,
 
     while (*p) {
         if (!ISGRAPH(*p)) {
-            if(!ISSPACE(*p)) {
-              /* Control chars excluding 09 - 0d (space), 80-ff */
-            pm_message("Warning: non-ASCII character '%x' in "
-                       "BDF font file", *p);
+            if (!ISSPACE(*p)) {
+                /* Control chars excluding 09 - 0d (space), 80-ff */
+                pm_message("Warning: non-ASCII character '%x' in "
+                           "BDF font file", *p);
             }
             *p++ = '\0';
-        }
-        else {
+        } else {
             words[n++] = p;
             if (n >= wordsSz - 1)
                 break;
@@ -395,6 +397,7 @@ parseBitmapRow(const char *    const hex,
                         glyphWidth, hex);
         else {
             char const hdig = *p++;
+
             unsigned int hdigValue;
 
             if (hdig >= '0' && hdig <= '9')
@@ -517,7 +520,7 @@ static void
 validateWordCount(Readline *    const readlineP,
                   unsigned int  const nWords) {
 
-    if( readlineP->wordCt != nWords )
+    if (readlineP->wordCt != nWords)
         pm_error("Wrong number of arguments in '%s' line in BDF font file",
                  readlineP->arg[0]);
 
@@ -536,7 +539,6 @@ readExpectedStatement(Readline *    const readlineP,
   beginning of the line is that, e.g. "STARTFONT").  Check for the number
   of words: 'nWords'.  If either condition is not met, fail the program.
 -----------------------------------------------------------------------------*/
-
     bool eof;
 
     readline_read(readlineP, &eof);
@@ -561,7 +563,6 @@ skipCharacter(Readline * const readlineP) {
 
   At entry the stream must be positioned at the end of the ENCODING line.
 -----------------------------------------------------------------------------*/
-
     char * rc;
     do {
         rc = fgets(readlineP->line, MAXBDFLINE+1, readlineP->ifP);
@@ -625,10 +626,12 @@ interpEncoding(const char **  const arg,
 
    'maxmaxglyph' is the maximum codepoint in the font.
 -----------------------------------------------------------------------------*/
-    bool gotCodepoint = false;   /* initial value */
+    bool gotCodepoint;
     bool badCodepoint;
     unsigned int codepoint;
 
+    gotCodepoint = false;  /* initial value */
+
     if (wordToInt(arg[1]) >= 0) {
         codepoint = wordToInt(arg[1]);
         gotCodepoint = true;
@@ -662,8 +665,9 @@ readEncoding(Readline *     const readlineP,
              bool *         const badCodepointP,
              PM_WCHAR       const maxmaxglyph) {
 
+    const char * const expected = "ENCODING";
+
     bool eof;
-    const char * expected = "ENCODING";
 
     readline_read(readlineP, &eof);
 
@@ -672,7 +676,7 @@ readEncoding(Readline *     const readlineP,
     else if (!streq(readlineP->arg[0], expected))
         pm_error("Statement of type '%s' where '%s' expected in BDF font file",
                  readlineP->arg[0], expected);
-    else if(readlineP->wordCt != 2 &&  readlineP->wordCt != 3)
+    else if (readlineP->wordCt != 2 &&  readlineP->wordCt != 3)
         pm_error("Wrong number of arguments in '%s' line in BDF font file",
                  readlineP->arg[0]);
 
@@ -747,7 +751,7 @@ validateGlyphLimits(const struct font2 * const font2P,
 static void
 readStartchar(Readline * const readlineP,
               const char ** charNameP) {
-        
+
         const char * charName;
         bool eof;
 
@@ -786,6 +790,7 @@ readGlyph(Readline * const readlineP,
           struct glyph ** const glyphPP) {
 
     struct glyph * glyphP;
+
     MALLOCVAR(glyphP);
     if (glyphP == NULL)
         pm_error("no memory for font glyph for '%s' character",
@@ -959,8 +964,11 @@ loadCharsetString(const char *  const registry,
 }
 
 
+
 static unsigned int const maxTokenLen = 60;
 
+
+
 static void
 doCharsetRegistry(Readline *    const readlineP,
                   bool *        const gotRegistryP,
@@ -1178,7 +1186,6 @@ initializeGlyphArray(struct font2 * const font2P,
            It may not be defined in the font, but the program may try
            to use space as a substitute char
         */
-
 }
 
 
@@ -1220,7 +1227,7 @@ pbm_loadbdffont2select(const char *               const filename,
     if (font2P->selectorP == NULL) {
         PM_WCHAR i;
 
-        for(i = 0; i <= maxmaxglyph; ++i)
+        for (i = 0; i <= maxmaxglyph; ++i)
             font2P->glyph[i] = NULL;
             /* Initial value.  Overwrite later if codepoint i is defined. */
     }
@@ -1252,10 +1259,10 @@ pbm_loadbdffont2select(const char *               const filename,
     }
     fclose(ifP);
 
-    if(font2P->total_chars == 0)
+    if (font2P->total_chars == 0)
         pm_error("No glyphs found in BDF font file "
                  "in codepoint range 0 - %u", (unsigned int) maxmaxglyph);
-    if(font2P->chars == 0)
+    if (font2P->chars == 0)
         pm_error("Not any requested glyphs found in BDF font file "
                  "in codepoint range 0 - %u", (unsigned int) maxmaxglyph);
 
@@ -1272,23 +1279,21 @@ pbm_loadbdffont2select(const char *               const filename,
 }
 
 
+
 struct font2 *
 pbm_loadbdffont2(const char * const filename,
                  PM_WCHAR     const maxmaxglyph) {
 
-  return (pbm_loadbdffont2select(filename, maxmaxglyph, NULL));
-
-  return(0);
+    return pbm_loadbdffont2select(filename, maxmaxglyph, NULL);
 }
 
 
 
-
 static struct font *
 font2ToFont(const struct font2 * const font2P) {
 
-            struct font  * fontP;
-            unsigned int   codePoint;
+    struct font  * fontP;
+    unsigned int   codePoint;
 
     MALLOCVAR(fontP);
     if (fontP == NULL)
diff --git a/lib/libpgm.h b/lib/libpgm.h
index eb292c80..49939a26 100644
--- a/lib/libpgm.h
+++ b/lib/libpgm.h
@@ -12,4 +12,11 @@ pgm_readpgminitrest(FILE * const file,
                     int *  const rowsP,
                     gray * const maxvalP);
 
+void
+pgm_validateComputableSize(unsigned int const cols,
+                           unsigned int const rows);
+
+void
+pgm_validateComputableMaxval(gray const maxval);
+
 #endif
diff --git a/lib/libpgm1.c b/lib/libpgm1.c
index 9ef5d2c1..0656e1e0 100644
--- a/lib/libpgm1.c
+++ b/lib/libpgm1.c
@@ -14,7 +14,7 @@
    offset stuff.
 */
 #define _FILE_OFFSET_BITS 64
-#define _LARGE_FILES  
+#define _LARGE_FILES
 
 #include <string.h>
 #include <stdio.h>
@@ -47,7 +47,7 @@ pgm_allocrow(unsigned int const cols) {
 
 
 
-void 
+void
 pgm_init(int *   const argcP,
          char ** const argv) {
 
@@ -65,22 +65,21 @@ pgm_nextimage(FILE * const file,
 
 
 void
-pgm_readpgminitrest(FILE * const fileP, 
-                    int *  const colsP, 
-                    int *  const rowsP, 
+pgm_readpgminitrest(FILE * const ifP,
+                    int *  const colsP,
+                    int *  const rowsP,
                     gray * const maxvalP) {
 
     gray maxval;
-    
+
     /* Read size. */
-    *colsP = (int)pm_getuint(fileP);
-    *rowsP = (int)pm_getuint(fileP);
+    pbm_readpbminitrest(ifP, colsP, rowsP);
 
     /* Read maxval. */
-    maxval = pm_getuint(fileP);
+    maxval = pm_getuint(ifP);
     if (maxval > PGM_OVERALLMAXVAL)
         pm_error("maxval of input image (%u) is too large.  "
-                 "The maximum allowed by PGM is %u.", 
+                 "The maximum allowed by the format is %u.",
                  maxval, PGM_OVERALLMAXVAL);
     if (maxval == 0)
         pm_error("maxval of input image is zero.");
@@ -90,9 +89,9 @@ pgm_readpgminitrest(FILE * const fileP,
 
 
 
-static void
-validateComputableSize(unsigned int const cols,
-                       unsigned int const rows) {
+void
+pgm_validateComputableSize(unsigned int const cols,
+                           unsigned int const rows) {
 /*----------------------------------------------------------------------------
    Validate that the dimensions of the image are such that it can be
    processed in typical ways on this machine without worrying about
@@ -116,8 +115,34 @@ validateComputableSize(unsigned int const cols,
 
 
 void
+pgm_validateComputableMaxval(gray const maxval) {
+/*----------------------------------------------------------------------------
+  This is similar to validateComputableSize, but for the maxval.
+-----------------------------------------------------------------------------*/
+    /* Code sometimes allocates an array indexed by sample values and
+       represents the size of that array as an INT.  (UNSIGNED INT would be
+       more proper, but there's no need to be that permissive).
+
+       Code also sometimes iterates through sample values and quits when the
+       value is greater than the maxval.
+
+       Code often divides by the maxval, but we don't have to check for maxval
+       == 0 as a computability problem because that is not a valid maxval.
+
+       Note that in the PNM Plain formats, there is no upper limit for a
+       maxval, though the 'gray' type does constrain what has been passed to
+       us.
+    */
+
+    if (maxval > INT_MAX-1)
+        pm_error("Maxval (%u) is too large to be processed", maxval);
+}
+
+
+
+void
 pgm_readpgminit(FILE * const fileP,
-                int *  const colsP, 
+                int *  const colsP,
                 int *  const rowsP,
                 gray * const maxvalP,
                 int *  const formatP) {
@@ -130,7 +155,7 @@ pgm_readpgminit(FILE * const fileP,
     case PBM_TYPE:
         *formatP = realFormat;
         pbm_readpbminitrest(fileP, colsP, rowsP);
-        
+
         /* Mathematically, it makes the most sense for the maxval of a PBM
            file seen as a PGM to be 1.  But we tried this for a while and
            found that it causes unexpected results and frequent need for a
@@ -139,14 +164,14 @@ pgm_readpgminit(FILE * const fileP,
            there's no in-between value to use when maxval is 1.  It's really
            hard even to discover that your lack of Pnmdepth is your problem.
            So we pick 255, which is the most common PGM maxval, and the highest
-           resolution you can get without increasing the size of the PGM 
+           resolution you can get without increasing the size of the PGM
            image.
 
            So this means some programs that are capable of exploiting the
            bi-level nature of a PBM file must be PNM programs instead of PGM
            programs.
         */
-        
+
         *maxvalP = PGM_MAXMAXVAL;
         break;
 
@@ -154,7 +179,7 @@ pgm_readpgminit(FILE * const fileP,
         *formatP = realFormat;
         pgm_readpgminitrest(fileP, colsP, rowsP, maxvalP);
         break;
-        
+
     case PPM_TYPE:
         pm_error("Input file is a PPM, which this program cannot process.  "
                  "You may want to convert it to PGM with 'ppmtopgm'");
@@ -171,18 +196,20 @@ pgm_readpgminit(FILE * const fileP,
         pm_error("bad magic number 0x%x - not a PPM, PGM, PBM, or PAM file",
                  realFormat);
     }
-    validateComputableSize(*colsP, *rowsP);
+    pgm_validateComputableSize(*colsP, *rowsP);
+
+    pgm_validateComputableMaxval(*maxvalP);
 }
 
 
 
 static void
-validateRpgmRow(gray *         const grayrow, 
+validateRpgmRow(gray *         const grayrow,
                 unsigned int   const cols,
                 gray           const maxval,
                 const char **  const errorP) {
 /*----------------------------------------------------------------------------
-  Check for sample values above maxval in input.  
+  Check for sample values above maxval in input.
 
   Note: a program that wants to deal with invalid sample values itself can
   simply make sure it uses a sufficiently high maxval on the read function
@@ -205,23 +232,23 @@ validateRpgmRow(gray *         const grayrow,
         }
         *errorP = NULL;
     }
-}  
+}
 
 
 
 static void
 readRpgmRow(FILE * const fileP,
-            gray * const grayrow, 
+            gray * const grayrow,
             int    const cols,
             gray   const maxval,
             int    const format) {
 
     unsigned int const bytesPerSample = maxval < 256 ? 1 : 2;
     int          const bytesPerRow    = cols * bytesPerSample;
-    
+
     unsigned char * rowBuffer;
     const char * error;
-    
+
     MALLOCARRAY(rowBuffer, bytesPerRow);
     if (rowBuffer == NULL)
         pm_asprintf(&error, "Unable to allocate memory for row buffer "
@@ -243,19 +270,19 @@ readRpgmRow(FILE * const fileP,
             } else {
                 unsigned int bufferCursor;
                 unsigned int col;
-                
+
                 bufferCursor = 0;  /* Start at beginning of rowBuffer[] */
-                
+
                 for (col = 0; col < cols; ++col) {
                     gray g;
-                    
+
                     g = rowBuffer[bufferCursor++] << 8;
                     g |= rowBuffer[bufferCursor++];
-                    
+
                     grayrow[col] = g;
                 }
             }
-            validateRpgmRow(grayrow, cols, maxval, &error); 
+            validateRpgmRow(grayrow, cols, maxval, &error);
         }
         free(rowBuffer);
     }
@@ -264,13 +291,13 @@ readRpgmRow(FILE * const fileP,
         pm_strfree(error);
         pm_longjmp();
     }
-} 
+}
 
 
 
 static void
 readPbmRow(FILE * const fileP,
-           gray * const grayrow, 
+           gray * const grayrow,
            int    const cols,
            gray   const maxval,
            int    const format) {
@@ -278,7 +305,7 @@ readPbmRow(FILE * const fileP,
     jmp_buf jmpbuf;
     jmp_buf * origJmpbufP;
     bit * bitrow;
-    
+
     bitrow = pbm_allocrow_packed(cols);
     if (setjmp(jmpbuf) != 0) {
         pbm_freerow(bitrow);
@@ -306,7 +333,7 @@ readPbmRow(FILE * const fileP,
 
 void
 pgm_readpgmrow(FILE * const fileP,
-               gray * const grayrow, 
+               gray * const grayrow,
                int    const cols,
                gray   const maxval,
                int    const format) {
@@ -322,16 +349,16 @@ pgm_readpgmrow(FILE * const fileP,
         }
     }
     break;
-        
+
     case RPGM_FORMAT:
         readRpgmRow(fileP, grayrow, cols, maxval, format);
         break;
-    
+
     case PBM_FORMAT:
     case RPBM_FORMAT:
         readPbmRow(fileP, grayrow, cols, maxval, format);
         break;
-        
+
     default:
         pm_error("can't happen");
     }
@@ -342,7 +369,7 @@ pgm_readpgmrow(FILE * const fileP,
 gray **
 pgm_readpgm(FILE * const fileP,
             int *  const colsP,
-            int *  const rowsP, 
+            int *  const rowsP,
             gray * const maxvalP) {
 
     gray ** grays;
@@ -353,7 +380,7 @@ pgm_readpgm(FILE * const fileP,
     jmp_buf * origJmpbufP;
 
     pgm_readpgminit(fileP, &cols, &rows, &maxval, &format);
-    
+
     grays = pgm_allocarray(cols, rows);
 
     if (setjmp(jmpbuf) != 0) {
@@ -362,7 +389,7 @@ pgm_readpgm(FILE * const fileP,
         pm_longjmp();
     } else {
         unsigned int row;
-    
+
         pm_setjmpbufsave(&jmpbuf, &origJmpbufP);
 
         for (row = 0; row < rows; ++row)
@@ -379,11 +406,11 @@ pgm_readpgm(FILE * const fileP,
 
 
 void
-pgm_check(FILE *               const file, 
-          enum pm_check_type   const checkType, 
-          int                  const format, 
-          int                  const cols, 
-          int                  const rows, 
+pgm_check(FILE *               const file,
+          enum pm_check_type   const checkType,
+          int                  const format,
+          int                  const cols,
+          int                  const rows,
           gray                 const maxval,
           enum pm_check_code * const retvalP) {
 
@@ -391,7 +418,7 @@ pgm_check(FILE *               const file,
         pm_error("Invalid number of rows passed to pgm_check(): %d", rows);
     if (cols < 0)
         pm_error("Invalid number of columns passed to pgm_check(): %d", cols);
-    
+
     if (checkType != PM_CHECK_BASIC) {
         if (retvalP)
             *retvalP = PM_CHECK_UNKNOWN_TYPE;
@@ -400,10 +427,13 @@ pgm_check(FILE *               const file,
     } else if (format != RPGM_FORMAT) {
         if (retvalP)
             *retvalP = PM_CHECK_UNCHECKABLE;
-    } else {        
+    } else {
         pm_filepos const bytesPerRow    = cols * (maxval > 255 ? 2 : 1);
         pm_filepos const needRasterSize = rows * bytesPerRow;
-        
+
         pm_check(file, checkType, needRasterSize, retvalP);
     }
 }
+
+
+
diff --git a/lib/libpgm2.c b/lib/libpgm2.c
index 80b5cf42..ec3539a2 100644
--- a/lib/libpgm2.c
+++ b/lib/libpgm2.c
@@ -15,34 +15,42 @@
 
 #include "netpbm/pm_c_util.h"
 #include "netpbm/mallocvar.h"
+#include "libpgm.h"
 #include "pgm.h"
 
 
 
 void
-pgm_writepgminit(FILE * const fileP, 
-                 int    const cols, 
-                 int    const rows, 
-                 gray   const maxval, 
+pgm_writepgminit(FILE * const fileP,
+                 int    const cols,
+                 int    const rows,
+                 gray   const maxval,
                  int    const forceplain) {
 
     bool const plainFormat = forceplain || pm_plain_output;
 
-    if (maxval > PGM_OVERALLMAXVAL && !plainFormat) 
+    /* For Caller's convenience, we include validating computability of the
+       image parameters, since Caller may be using them in arithmetic after
+       our return.
+    */
+    pgm_validateComputableSize(cols, rows);
+    pgm_validateComputableMaxval(maxval);
+
+    if (maxval > PGM_OVERALLMAXVAL && !plainFormat)
         pm_error("too-large maxval passed to ppm_writepgminit(): %d.\n"
                  "Maximum allowed by the PGM format is %d.",
                  maxval, PGM_OVERALLMAXVAL);
 
-    fprintf(fileP, "%c%c\n%d %d\n%d\n", 
-            PGM_MAGIC1, 
-            plainFormat || maxval >= 1<<16 ? PGM_MAGIC2 : RPGM_MAGIC2, 
+    fprintf(fileP, "%c%c\n%d %d\n%d\n",
+            PGM_MAGIC1,
+            plainFormat || maxval >= 1<<16 ? PGM_MAGIC2 : RPGM_MAGIC2,
             cols, rows, maxval );
 }
 
 
 
 static void
-putus(unsigned short const n, 
+putus(unsigned short const n,
       FILE *         const fileP) {
 
     if (n >= 10)
@@ -85,7 +93,7 @@ format2bpsRow(const gray    * const grayrow,
 
     for (col = 0; col < cols; ++col) {
         gray const val = grayrow[col];
-        
+
         rowBuffer[bufferCursor++] = val >> 8;
         rowBuffer[bufferCursor++] = (unsigned char) val;
     }
@@ -134,8 +142,8 @@ writepgmrowraw(FILE *       const fileP,
 
 static void
 writepgmrowplain(FILE *       const fileP,
-                 const gray * const grayrow, 
-                 unsigned int const cols, 
+                 const gray * const grayrow,
+                 unsigned int const cols,
                  gray         const maxval) {
 
     int col, charcount;
@@ -163,10 +171,10 @@ writepgmrowplain(FILE *       const fileP,
 
 
 void
-pgm_writepgmrow(FILE *       const fileP, 
-                const gray * const grayrow, 
-                int          const cols, 
-                gray         const maxval, 
+pgm_writepgmrow(FILE *       const fileP,
+                const gray * const grayrow,
+                int          const cols,
+                gray         const maxval,
                 int          const forceplain) {
 
     if (forceplain || pm_plain_output || maxval >= 1<<16)
diff --git a/lib/libpm.c b/lib/libpm.c
index 6f9dea3d..4dd19b70 100644
--- a/lib/libpm.c
+++ b/lib/libpm.c
@@ -442,12 +442,20 @@ pm_maxvaltobits(int const maxval) {
     assert(false);
 }
 
+
+
 int
-pm_bitstomaxval(int const bits) {
-    return ( 1 << bits ) - 1;
+pm_bitstomaxval(int const bitCt) {
+
+    if (bitCt > 16)
+        pm_error("Bits per sample %u too large.  16 is maximum acceptable",
+                 bitCt);
+
+    return (1 << bitCt) - 1;
 }
 
 
+
 unsigned int PURE_FN_ATTR
 pm_lcm(unsigned int const x,
        unsigned int const y,
@@ -698,7 +706,16 @@ pm_proginit(int *         const argcP,
    find.  We remove the common options from argv[], updating *argcP
    accordingly.
 
-   This includes calling pm_init() to initialize the Netpbm libraries.
+   This includes calling 'pm_init' to initialize the Netpbm libraries.
+
+   argv[] is intended to be the program's POSIX arguments (as passed to the
+   program's main function).  But note that POSIX arguments are modifiable and
+   as such, the conventional way to declare them in a program is with "char
+   **", as opposed to pm_proginit's "const char **".  To avoid a compiler
+   warning, the program has to use the unconventional "const char **" type in
+   the declaration of its main function.  (Alternatively, it can just cast it
+   to const char ** later).  'pm_proginit' does not modify any argument
+   strings.
 -----------------------------------------------------------------------------*/
     const char * const progname = pm_arg0toprogname(argv[0]);
         /* points to static memory in this library */
@@ -844,6 +861,14 @@ pm_parse_width(const char * const arg) {
    Return the image width represented by the decimal ASCIIZ string
    'arg'.  Fail if it doesn't validly represent a width or represents
    a width that can't be conveniently used in computation.
+
+   See comments at 'validateComputableSize' in libpam.c for details on
+   the purpose of these validations.
+
+   This isn't just for Netpbm format images.
+
+   Typical places from which widths come: headers of non-Netpbm images;
+   command line options.
 -----------------------------------------------------------------------------*/
     unsigned int width;
     const char * error;
@@ -890,3 +915,27 @@ pm_parse_height(const char * const arg) {
 
 
 
+unsigned int
+pm_parse_maxval(const char * const arg) {
+/*----------------------------------------------------------------------------
+  Same as pm_parse_width(), but for maxval.
+-----------------------------------------------------------------------------*/
+    unsigned int maxval;
+    const char * error;
+
+    pm_string_to_uint(arg, &maxval, &error);
+
+    if (error) {
+        pm_error("'%s' is invalid as a maxval.  %s", arg, error);
+        pm_strfree(error);
+    } else {
+        if (maxval > INT_MAX-1)
+            pm_error("Maxval %u is too large for computations.", maxval);
+        if (maxval == 0)
+            pm_error("Maxval argument must be a positive number.  You "
+                     "specified 0.");
+    }
+    return maxval;
+}
+
+
diff --git a/lib/libpnm1.c b/lib/libpnm1.c
index db21b078..ed5b5e37 100644
--- a/lib/libpnm1.c
+++ b/lib/libpnm1.c
@@ -83,6 +83,28 @@ validateComputableSize(unsigned int const cols,
 
 
 
+static void
+validateComputableMaxval(pixval const maxval) {
+/*----------------------------------------------------------------------------
+  This is similar to validateComputableSize, but for the maxval.
+-----------------------------------------------------------------------------*/
+    /* Code sometimes allocates an array indexed by sample values and
+       represents the size of that array as an INT.  (UNSIGNED INT would be
+       more proper, but there's no need to be that permissive).
+
+       Code also sometimes iterates through sample values and quits when the
+       value is greater than the maxval.
+    */
+
+    if (maxval == 0)
+        pm_error("Maxval is zero.  Must be at least one.");
+
+    if (maxval > INT_MAX-1)
+        pm_error("Maxval (%u) is too large to be processed", maxval);
+}
+
+
+
 void
 pnm_readpnminit(FILE *   const fileP,
                 int *    const colsP,
@@ -130,6 +152,8 @@ pnm_readpnminit(FILE *   const fileP,
                  realFormat);
     }
     validateComputableSize(*colsP, *rowsP);
+
+    validateComputableMaxval(*maxvalP);
 }
 
 
@@ -220,7 +244,7 @@ pnm_readpnmrow(FILE * const fileP,
     case PGM_TYPE:
         readpgmrow(fileP, xelrow, cols, maxval, format);
         break;
-        
+
     case PBM_TYPE:
         readpbmrow(fileP, xelrow, cols, maxval, format);
         break;
@@ -276,7 +300,7 @@ pnm_readpnm(FILE *   const fileP,
 
 void
 pnm_check(FILE *               const fileP,
-          enum pm_check_type   const check_type, 
+          enum pm_check_type   const check_type,
           int                  const format,
           int                  const cols,
           int                  const rows,
@@ -287,7 +311,7 @@ pnm_check(FILE *               const fileP,
     case PBM_TYPE:
         pbm_check(fileP, check_type, format, cols, rows, retvalP);
         break;
-    case PGM_TYPE: 
+    case PGM_TYPE:
         pgm_check(fileP, check_type, format, cols, rows, maxval, retvalP);
         break;
     case PPM_TYPE:
diff --git a/lib/libpnm2.c b/lib/libpnm2.c
index fa4bb8be..6fec91e9 100644
--- a/lib/libpnm2.c
+++ b/lib/libpnm2.c
@@ -23,11 +23,11 @@
 
 
 void
-pnm_writepnminit(FILE * const fileP, 
-                 int    const cols, 
-                 int    const rows, 
-                 xelval const maxval, 
-                 int    const format, 
+pnm_writepnminit(FILE * const fileP,
+                 int    const cols,
+                 int    const rows,
+                 xelval const maxval,
+                 int    const format,
                  int    const forceplain) {
 
     bool const plainFormat = forceplain || pm_plain_output;
@@ -47,7 +47,7 @@ pnm_writepnminit(FILE * const fileP,
 
     default:
         pm_error("invalid format argument received by pnm_writepnminit(): %d"
-                 "PNM_FORMAT_TYPE(format) must be %d, %d, or %d", 
+                 "PNM_FORMAT_TYPE(format) must be %d, %d, or %d",
                  format, PBM_TYPE, PGM_TYPE, PPM_TYPE);
     }
 }
@@ -55,19 +55,19 @@ pnm_writepnminit(FILE * const fileP,
 
 
 static void
-writepgmrow(FILE *       const fileP, 
-            const xel *  const xelrow, 
-            unsigned int const cols, 
-            xelval       const maxval, 
-            int          const format, 
+writepgmrow(FILE *       const fileP,
+            const xel *  const xelrow,
+            unsigned int const cols,
+            xelval       const maxval,
+            int          const format,
             bool         const plainFormat) {
-    
+
     jmp_buf jmpbuf;
     jmp_buf * origJmpbufP;
     gray * grayrow;
-    
+
     grayrow = pgm_allocrow(cols);
-    
+
     if (setjmp(jmpbuf) != 0) {
         pgm_freerow(grayrow);
         pm_setjmpbuf(origJmpbufP);
@@ -76,10 +76,10 @@ writepgmrow(FILE *       const fileP,
         unsigned int col;
 
         pm_setjmpbufsave(&jmpbuf, &origJmpbufP);
-        
+
         for (col = 0; col < cols; ++col)
             grayrow[col] = PNM_GET1(xelrow[col]);
-    
+
         pgm_writepgmrow(fileP, grayrow, cols, (gray) maxval, plainFormat);
 
         pm_setjmpbuf(origJmpbufP);
@@ -100,7 +100,7 @@ writepbmrow(FILE *       const fileP,
     bit * bitrow;
 
     bitrow = pbm_allocrow(cols);
-    
+
     if (setjmp(jmpbuf) != 0) {
         pbm_freerow(bitrow);
         pm_setjmpbuf(origJmpbufP);
@@ -112,29 +112,29 @@ writepbmrow(FILE *       const fileP,
 
         for (col = 0; col < cols; ++col)
             bitrow[col] = PNM_GET1(xelrow[col]) == 0 ? PBM_BLACK : PBM_WHITE;
-    
+
         pbm_writepbmrow(fileP, bitrow, cols, plainFormat);
 
         pm_setjmpbuf(origJmpbufP);
     }
     pbm_freerow(bitrow);
-}    
+}
 
 
 
 void
-pnm_writepnmrow(FILE *      const fileP, 
-                const xel * const xelrow, 
-                int         const cols, 
-                xelval      const maxval, 
-                int         const format, 
+pnm_writepnmrow(FILE *      const fileP,
+                const xel * const xelrow,
+                int         const cols,
+                xelval      const maxval,
+                int         const format,
                 int         const forceplain) {
 
     bool const plainFormat = forceplain || pm_plain_output;
-    
+
     switch (PNM_FORMAT_TYPE(format)) {
     case PPM_TYPE:
-        ppm_writeppmrow(fileP, (pixel*) xelrow, cols, (pixval) maxval, 
+        ppm_writeppmrow(fileP, (pixel*) xelrow, cols, (pixval) maxval,
                         plainFormat);
         break;
 
@@ -145,10 +145,10 @@ pnm_writepnmrow(FILE *      const fileP,
     case PBM_TYPE:
         writepbmrow(fileP, xelrow, cols, plainFormat);
         break;
-    
+
     default:
         pm_error("invalid format argument received by pnm_writepnmrow(): %d"
-                 "PNM_FORMAT_TYPE(format) must be %d, %d, or %d", 
+                 "PNM_FORMAT_TYPE(format) must be %d, %d, or %d",
                  format, PBM_TYPE, PGM_TYPE, PPM_TYPE);
     }
 }
@@ -167,7 +167,10 @@ pnm_writepnm(FILE * const fileP,
     unsigned int row;
 
     pnm_writepnminit(fileP, cols, rows, maxval, format, forceplain);
-    
+
     for (row = 0; row < rows; ++row)
         pnm_writepnmrow(fileP, xels[row], cols, maxval, format, forceplain);
 }
+
+
+
diff --git a/lib/libpnm3.c b/lib/libpnm3.c
index 3970c734..4d88a2c1 100644
--- a/lib/libpnm3.c
+++ b/lib/libpnm3.c
@@ -106,10 +106,14 @@ pnm_backgroundxelrow(xel *  const xelrow,
                      int    const cols,
                      xelval const maxval,
                      int    const format) {
+/*----------------------------------------------------------------------------
+   Guess a good background color for an image that contains row 'xelrow'
+   (probably top or bottom edge).
 
+   'cols', 'maxval', and 'format' describe 'xelrow'.
+-----------------------------------------------------------------------------*/
     xel bgxel, l, r;
 
-    /* Guess a good background value. */
     l = xelrow[0];
     r = xelrow[cols-1];
 
@@ -236,6 +240,19 @@ pnm_invertxel(xel*   const xP,
 
 
 
+const char *
+pnm_formattypenm(int const format) {
+
+    switch (PPM_FORMAT_TYPE(format)) {
+    case PPM_TYPE: return "PPM"; break;
+    case PGM_TYPE: return "PGM"; break;
+    case PBM_TYPE: return "PBM"; break;
+    default: return "???";
+    }
+}
+
+
+
 void
 pnm_promoteformat(xel ** const xels,
                   int    const cols,
diff --git a/lib/libppm.h b/lib/libppm.h
index ec2a173d..620768a2 100644
--- a/lib/libppm.h
+++ b/lib/libppm.h
@@ -7,9 +7,13 @@
 #include "ppm.h"
 
 void
-ppm_readppminitrest(FILE *   const file, 
-                    int *    const colsP, 
-                    int *    const rowsP, 
+ppm_readppminitrest(FILE *   const file,
+                    int *    const colsP,
+                    int *    const rowsP,
                     pixval * const maxvalP);
 
+void
+ppm_validateComputableSize(unsigned int const cols,
+                           unsigned int const rows);
+
 #endif
diff --git a/lib/libppm1.c b/lib/libppm1.c
index ccc8adb5..01539169 100644
--- a/lib/libppm1.c
+++ b/lib/libppm1.c
@@ -64,33 +64,19 @@ ppm_nextimage(FILE * const fileP,
 
 
 void
-ppm_readppminitrest(FILE *   const fileP,
+ppm_readppminitrest(FILE *   const ifP,
                     int *    const colsP,
                     int *    const rowsP,
                     pixval * const maxvalP) {
-    unsigned int maxval;
-
-    /* Read size. */
-    *colsP = (int)pm_getuint(fileP);
-    *rowsP = (int)pm_getuint(fileP);
-
-    /* Read maxval. */
-    maxval = pm_getuint(fileP);
-    if (maxval > PPM_OVERALLMAXVAL)
-        pm_error("maxval of input image (%u) is too large.  "
-                 "The maximum allowed by the PPM format is %u.",
-                 maxval, PPM_OVERALLMAXVAL);
-    if (maxval == 0)
-        pm_error("maxval of input image is zero.");
-
-    *maxvalP = maxval;
+
+    pgm_readpgminitrest(ifP, colsP, rowsP, maxvalP);
 }
 
 
 
-static void
-validateComputableSize(unsigned int const cols,
-                       unsigned int const rows) {
+void
+ppm_validateComputableSize(unsigned int const cols,
+                           unsigned int const rows) {
 /*----------------------------------------------------------------------------
    Validate that the dimensions of the image are such that it can be
    processed in typical ways on this machine without worrying about
@@ -150,7 +136,9 @@ ppm_readppminit(FILE *   const fileP,
         pm_error("bad magic number 0x%x - not a PPM, PGM, PBM, or PAM file",
                  realFormat);
     }
-    validateComputableSize(*colsP, *rowsP);
+    ppm_validateComputableSize(*colsP, *rowsP);
+
+    pgm_validateComputableMaxval(*maxvalP);
 }
 
 
@@ -502,3 +490,6 @@ ppm_check(FILE *               const fileP,
         pm_check(fileP, checkType, needRasterSize, retvalP);
     }
 }
+
+
+
diff --git a/lib/libppm2.c b/lib/libppm2.c
index 694ecdd7..f54f2cef 100644
--- a/lib/libppm2.c
+++ b/lib/libppm2.c
@@ -16,25 +16,36 @@
 
 #include "netpbm/pm_c_util.h"
 #include "netpbm/mallocvar.h"
+#include "libpgm.h"
+#include "libppm.h"
 #include "ppm.h"
 
+
+
 void
-ppm_writeppminit(FILE*  const fileP, 
-                 int    const cols, 
-                 int    const rows, 
-                 pixval const maxval, 
+ppm_writeppminit(FILE*  const fileP,
+                 int    const cols,
+                 int    const rows,
+                 pixval const maxval,
                  int    const forceplain) {
 
     bool const plainFormat = forceplain || pm_plain_output;
 
-    if (maxval > PPM_OVERALLMAXVAL && !plainFormat) 
+    /* For Caller's convenience, we include validating computability of the
+       image parameters, since Caller may be using them in arithmetic after
+       our return.
+    */
+    ppm_validateComputableSize(cols, rows);
+    pgm_validateComputableMaxval(maxval);
+
+    if (maxval > PPM_OVERALLMAXVAL && !plainFormat)
         pm_error("too-large maxval passed to ppm_writeppminit(): %d."
                  "Maximum allowed by the PPM format is %d.",
                  maxval, PPM_OVERALLMAXVAL);
 
-    fprintf(fileP, "%c%c\n%d %d\n%d\n", 
-            PPM_MAGIC1, 
-            plainFormat || maxval >= 1<<16 ? PPM_MAGIC2 : RPPM_MAGIC2, 
+    fprintf(fileP, "%c%c\n%d %d\n%d\n",
+            PPM_MAGIC1,
+            plainFormat || maxval >= 1<<16 ? PPM_MAGIC2 : RPPM_MAGIC2,
             cols, rows, maxval );
 }
 
@@ -77,7 +88,7 @@ static void
 format2bpsRow(const pixel *   const pixelrow,
               unsigned int    const cols,
               unsigned char * const rowBuffer) {
-    
+
     /* two byte samples. */
 
     unsigned int col;
@@ -89,7 +100,7 @@ format2bpsRow(const pixel *   const pixelrow,
         pixval const r = PPM_GETR(pixelrow[col]);
         pixval const g = PPM_GETG(pixelrow[col]);
         pixval const b = PPM_GETB(pixelrow[col]);
-        
+
         rowBuffer[bufferCursor++] = r >> 8;
         rowBuffer[bufferCursor++] = (unsigned char)r;
         rowBuffer[bufferCursor++] = g >> 8;
@@ -176,31 +187,31 @@ ppm_writeppmrowplain(FILE *        const fileP,
 
 
 void
-ppm_writeppmrow(FILE *        const fileP, 
-                const pixel * const pixelrow, 
-                int           const cols, 
-                pixval        const maxval, 
+ppm_writeppmrow(FILE *        const fileP,
+                const pixel * const pixelrow,
+                int           const cols,
+                pixval        const maxval,
                 int           const forceplain) {
 
-    if (forceplain || pm_plain_output || maxval >= 1<<16) 
+    if (forceplain || pm_plain_output || maxval >= 1<<16)
         ppm_writeppmrowplain(fileP, pixelrow, cols, maxval);
-    else 
+    else
         ppm_writeppmrowraw(fileP, pixelrow, cols, maxval);
 }
 
 
 
 void
-ppm_writeppm(FILE *  const file, 
-             pixel** const pixels, 
-             int     const cols, 
-             int     const rows, 
-             pixval  const maxval, 
+ppm_writeppm(FILE *  const file,
+             pixel** const pixels,
+             int     const cols,
+             int     const rows,
+             pixval  const maxval,
              int     const forceplain)  {
     int row;
-    
+
     ppm_writeppminit(file, cols, rows, maxval, forceplain);
-    
+
     for (row = 0; row < rows; ++row)
         ppm_writeppmrow(file, pixels[row], cols, maxval, forceplain);
 }
diff --git a/lib/libppmcmap.c b/lib/libppmcmap.c
index 0f6439ae..24302c6a 100644
--- a/lib/libppmcmap.c
+++ b/lib/libppmcmap.c
@@ -784,17 +784,23 @@ int
 ppm_findclosestcolor(const pixel * const colormap,
                      int           const ncolors,
                      const pixel * const pP) {
+/*----------------------------------------------------------------------------
+  The index in colormap[] (which has 'ncolors' entries) of the color that is
+  closest to color *pP.
 
-    /* Search colormap for closest match.       */
+  Where two entries in colormap[] are identical, return the lesser of their
+  two indices.
 
-    int i;
+  Iff there are no colors in the amp ('ncolors' is zero), return -1.
+-----------------------------------------------------------------------------*/
+    unsigned int i;
     int ind;
     unsigned int bestDist;
 
     bestDist = UINT_MAX;
     ind = -1;
 
-    for(i = 0; i < ncolors && bestDist > 0; ++i) {
+    for (i = 0; i < ncolors && bestDist > 0; ++i) {
         unsigned int const dist = PPM_DISTANCE(*pP, colormap[i]);
 
         if (dist < bestDist ) {
@@ -806,6 +812,7 @@ ppm_findclosestcolor(const pixel * const colormap,
 }
 
 
+
 void
 ppm_colorrowtomapfile(FILE *ofp, pixel *colormap, int ncolors, pixval maxval)
 {
diff --git a/lib/libppmcolor.c b/lib/libppmcolor.c
index c0a88dc2..04858f6a 100644
--- a/lib/libppmcolor.c
+++ b/lib/libppmcolor.c
@@ -9,6 +9,7 @@
 ** implied warranty.
 */
 
+#include <stdbool.h>
 #include <assert.h>
 #include <stdlib.h>
 #include <string.h>
@@ -22,182 +23,98 @@
 #include "pam.h"
 
 
-pixel
-ppm_parsecolor2(const char * const colorname,
-                pixval       const maxval,
-                int          const closeOk) {
 
-    tuple const color = pnm_parsecolor2(colorname, maxval, closeOk);
+#define MAXCOLORNAMES 1000u
+    /* The maximum size of a colornames array, in the old interface */
 
-    pixel retval;
+static colorhash_table
+allocColorHash(void) {
 
-    PPM_PUTR(retval, color[PAM_RED_PLANE]);
-    PPM_PUTG(retval, color[PAM_GRN_PLANE]);
-    PPM_PUTB(retval, color[PAM_BLU_PLANE]);
+    colorhash_table cht;
+    jmp_buf jmpbuf;
+    jmp_buf * origJmpbufP;
 
-    free(color);
+    if (setjmp(jmpbuf) != 0)
+        cht = NULL;
+    else {
+        pm_setjmpbufsave(&jmpbuf, &origJmpbufP);
+        cht = ppm_alloccolorhash();
+    }
+    pm_setjmpbuf(origJmpbufP);
 
-    return retval;
+    return cht;
 }
 
 
 
-pixel
-ppm_parsecolor(const char * const colorname,
-               pixval       const maxval) {
+static ppm_ColorDict *
+colorDict_newEmpty() {
 
-    return ppm_parsecolor2(colorname, maxval, TRUE);
-}
+    ppm_ColorDict * colorDictP;
 
+    MALLOCVAR_NOFAIL(colorDictP);
 
+    colorDictP->version = 0;
+    colorDictP->size    = 0;
+    colorDictP->name    = NULL;
+    colorDictP->color   = NULL;
+    colorDictP->cht     = allocColorHash();
+    colorDictP->count   = 0;
 
-char *
-ppm_colorname(const pixel * const colorP,
-              pixval        const maxval,
-              int           const hexok)   {
+    if (!colorDictP->cht)
+        pm_error("Unable to allocate space for color hash");
 
-    int r, g, b;
-    FILE * f;
-    static char colorname[200];
-        /* Null string means no suitable name so far */
-
-    if (maxval == 255) {
-        r = PPM_GETR(*colorP);
-        g = PPM_GETG(*colorP);
-        b = PPM_GETB(*colorP);
-    } else {
-        r = (int) PPM_GETR(*colorP) * 255 / (int) maxval;
-        g = (int) PPM_GETG(*colorP) * 255 / (int) maxval;
-        b = (int) PPM_GETB(*colorP) * 255 / (int) maxval;
-    }
-
-    f = pm_openColornameFile(NULL, !hexok);
-
-    if (!f)
-        STRSCPY(colorname, "");
-    else {
-        int bestDiff;
-        bool eof;
-
-        for (bestDiff = 32767, eof = FALSE;
-             !eof && bestDiff > 0; ) {
-            struct colorfile_entry const ce = pm_colorget(f);
-            if (ce.colorname)  {
-                int const thisDiff =
-                    abs(r - (int)ce.r) +
-                    abs(g - (int)ce.g) +
-                    abs(b - (int)ce.b);
-
-                if (thisDiff < bestDiff) {
-                    bestDiff = thisDiff;
-                    STRSCPY(colorname, ce.colorname);
-                }
-            } else
-                eof = TRUE;
-        }
-        fclose(f);
-
-        if (bestDiff == 32767) {
-            /* Color file contain no entries, so we can't even pick a close
-               one
-            */
-            STRSCPY(colorname, "");
-        } else if (bestDiff > 0 && hexok) {
-            /* We didn't find an exact match and user is willing to accept
-               hex, so we don't have to use an approximate match.
-            */
-            STRSCPY(colorname, "");
-        }
-    }
-
-    if (streq(colorname, "")) {
-        if (hexok) {
-            /* Color lookup failed, but caller is willing to take an X11-style
-               hex specifier, so return that.
-            */
-            sprintf(colorname, "#%02x%02x%02x", r, g, b);
-        } else {
-            pm_error("Couldn't find any name colors at all");
-        }
-    }
-
-    return colorname;
+    return colorDictP;
 }
 
 
 
-#define MAXCOLORNAMES 1000u
-
-static const char **
-allocColorNames() {
-
-    const char ** colornames;
-
-    MALLOCARRAY(colornames, MAXCOLORNAMES);
-
-    if (colornames) {
-        unsigned int i;
-        for (i = 0; i < MAXCOLORNAMES; ++i)
-            colornames[i] = NULL;
-    }
-    return colornames;
-}
-
+void
+ppm_colorDict_destroy(ppm_ColorDict * const colorDictP) {
 
+    unsigned int i;
 
-static colorhash_table
-allocColorHash(void) {
+    for (i = 0; i < colorDictP->size; ++i)
+        pm_strfree(colorDictP->name[i]);
 
-    colorhash_table cht;
-    jmp_buf jmpbuf;
-    jmp_buf * origJmpbufP;
+    if (colorDictP->name)
+        free(colorDictP->name);
+    if (colorDictP->color)
+        free(colorDictP->color);
 
-    if (setjmp(jmpbuf) != 0)
-        cht = NULL;
-    else {
-        pm_setjmpbufsave(&jmpbuf, &origJmpbufP);
-        cht = ppm_alloccolorhash();
-    }
-    pm_setjmpbuf(origJmpbufP);
+    ppm_freecolorhash(colorDictP->cht);
 
-    return cht;
+    free(colorDictP);
 }
 
 
 
 static void
-processColorfileEntry(struct colorfile_entry const ce,
-                      colorhash_table        const cht,
-                      const char **          const colornames,
-                      pixel *                const colors,
-                      unsigned int *         const colornameIndexP,
-                      const char **          const errorP) {
+colorDict_resize(ppm_ColorDict * const colorDictP,
+                 unsigned int    const newSz,
+                 const char **   const errorP) {
+
+    const char ** newName;
 
-    if (*colornameIndexP >= MAXCOLORNAMES)
-        pm_asprintf(errorP, "Too many colors in colorname dictionary.  "
-                    "Max allowed is %u", MAXCOLORNAMES);
+    newName = realloc(colorDictP->name, newSz * sizeof(colorDictP->name[0]));
+    if (!newName)
+        pm_asprintf(errorP, "Failed to extend allocation for color "
+                    "dictionary to %u entries", newSz);
     else {
-        pixel color;
+        pixel * newColor;
 
-        PPM_ASSIGN(color, ce.r, ce.g, ce.b);
+        colorDictP->name = newName;
 
-        if (ppm_lookupcolor(cht, &color) >= 0) {
-            /* The color is already in the hash, which means we saw it
-               earlier in the file.  We prefer the first name that the
-               file gives for each color, so we just ignore the
-               current entry.
-            */
+        newColor =
+            realloc(colorDictP->color, newSz * sizeof(colorDictP->color[0]));
+
+        if (!newColor)
+            pm_asprintf(errorP, "Failed to extend allocation for color "
+                        "dictionary to %u entries", newSz);
+        else {
             *errorP = NULL;
-        } else {
-            ppm_addtocolorhash(cht, &color, *colornameIndexP);
-            colornames[*colornameIndexP] = pm_strdup(ce.colorname);
-            colors[*colornameIndexP] = color;
-            if (colornames[*colornameIndexP] == pm_strsol)
-                pm_asprintf(errorP, "Unable to allocate space for color name");
-            else {
-                *errorP = NULL;
-                ++(*colornameIndexP);
-            }
+            colorDictP->color = newColor;
+            colorDictP->size  = newSz;
         }
     }
 }
@@ -228,44 +145,41 @@ openColornameFile(const char *  const fileName,
 
 
 static void
-readOpenColorFile(FILE *          const colorFileP,
-                  unsigned int *  const nColorsP,
-                  const char **   const colornames,
-                  pixel *         const colors,
-                  colorhash_table const cht,
-                  const char **   const errorP) {
+processColorfileEntry(struct colorfile_entry const ce,
+                      ppm_ColorDict *        const colorDictP,
+                      const char **          const errorP) {
 /*----------------------------------------------------------------------------
-   Read the color dictionary file *colorFileP and add the colors in it
-   to colornames[], colors[], and 'cht'.
-
-   colornames[] and colors[] must be allocated with MAXCOLORNAMES entries
-   at entry.
-
-   We may add colors to 'cht' even if we fail.
+   Add the color file entry 'ce' to *colorDictP as required.
 -----------------------------------------------------------------------------*/
-    unsigned int nColorsDone;
-    bool done;
+    pixel color;
 
-    nColorsDone = 0;
-    done = FALSE;
-    *errorP = NULL;
+    PPM_ASSIGN(color, ce.r, ce.g, ce.b);
 
-    while (!done && !*errorP) {
-        struct colorfile_entry const ce = pm_colorget(colorFileP);
-
-        if (!ce.colorname)
-            done = TRUE;
-        else
-            processColorfileEntry(ce, cht, colornames, colors,
-                                  &nColorsDone, errorP);
-    }
-    *nColorsP = nColorsDone;
+    if (ppm_lookupcolor(colorDictP->cht, &color) >= 0) {
+        /* The color is already in the hash, which means we saw it earlier in
+           the file.  We prefer the first name that the file gives for each
+           color, so we just ignore the current entry.
+        */
+        *errorP = NULL;
+    } else {
+        ppm_addtocolorhash(colorDictP->cht, &color, colorDictP->count);
+        if (colorDictP->count >= colorDictP->size) {
+            colorDict_resize(colorDictP,
+                             MAX(1024, colorDictP->size * 2),
+                             errorP);
+        } else
+            *errorP = NULL;
 
-    if (*errorP) {
-        unsigned int colorIndex;
+        assert(colorDictP->size >= colorDictP->count);
 
-        for (colorIndex = 0; colorIndex < nColorsDone; ++colorIndex)
-            pm_strfree(colornames[colorIndex]);
+        if (!*errorP) {
+            colorDictP->name[colorDictP->count]  = pm_strdup(ce.colorname);
+            colorDictP->color[colorDictP->count] = color;
+            if (colorDictP->name[colorDictP->count] == pm_strsol)
+                pm_asprintf(errorP, "Unable to allocate space for color name");
+            else
+                ++colorDictP->count;
+        }
     }
 }
 
@@ -274,38 +188,37 @@ readOpenColorFile(FILE *          const colorFileP,
 static void
 readColorFile(const char *    const fileName,
               bool            const mustOpen,
-              unsigned int *  const nColorsP,
-              const char **   const colornames,
-              pixel *         const colors,
-              colorhash_table const cht,
+              ppm_ColorDict * const colorDictP,
               const char **   const errorP) {
 /*----------------------------------------------------------------------------
    Read the color dictionary file named 'fileName' and add the colors in it
-   to colornames[], colors[], and 'cht'.  Return as *nColorsP the number
-   of colors in it.
+   to *colorDictP.
 
-   If the file is not openable (e.g. not file by that name exists), abort the
+   If the file is not openable (e.g. no file by that name exists), abort the
    program if 'mustOpen' is true; otherwise, return values indicating a
    dictionary with no colors.
 
-   colornames[] and colors[] must be allocated with MAXCOLORNAMES entries
-   at entry.
-
-   We may add colors to 'cht' even if we fail.
+   We may add colors to *colorDictP even if we fail.
 -----------------------------------------------------------------------------*/
     FILE * colorFileP;
 
     openColornameFile(fileName, mustOpen, &colorFileP, errorP);
     if (!*errorP) {
-        if (colorFileP == NULL) {
-            /* Couldn't open it, but Caller says treat same as
-               empty file
-            */
-            *nColorsP = 0;
+        if (!colorFileP) {
+            /* Couldn't open it, but Caller says treat same as empty file */
             *errorP = NULL;
         } else {
-            readOpenColorFile(colorFileP, nColorsP, colornames, colors, cht,
-                              errorP);
+            bool done;
+
+            for (done = false, *errorP = NULL; !done && !*errorP; ) {
+
+                struct colorfile_entry const ce = pm_colorget(colorFileP);
+
+                if (!ce.colorname)
+                    done = true;
+                else
+                    processColorfileEntry(ce, colorDictP, errorP);
+            }
 
             fclose(colorFileP);
         }
@@ -314,55 +227,127 @@ readColorFile(const char *    const fileName,
 
 
 
-static void
-readcolordict(const char *      const fileName,
-              bool              const mustOpen,
-              unsigned int *    const nColorsP,
-              const char ***    const colornamesP,
-              pixel **          const colorsP,
-              colorhash_table * const chtP,
-              const char **     const errorP) {
+ppm_ColorDict *
+ppm_colorDict_new(const char * const fileName,
+                  int          const mustOpen) {
 
-    const char ** colornames;
+    ppm_ColorDict * colorDictP;
+    const char * error;
 
-    colornames = allocColorNames();
+    colorDictP = colorDict_newEmpty();
 
-    if (colornames == NULL)
-        pm_asprintf(errorP, "Unable to allocate space for colorname table.");
-    else {
-        pixel * colors;
+    readColorFile(fileName, mustOpen, colorDictP, &error);
+
+    if (error) {
+        pm_errormsg("%s", error);
+        pm_strfree(error);
+        pm_longjmp();
+    }
+    return colorDictP;
+}
 
-        MALLOCARRAY(colors, MAXCOLORNAMES);
 
-        if (colors == NULL)
-            pm_asprintf(errorP, "Unable to allocate space for color table.");
-        else {
-            colorhash_table cht;
 
-            cht = allocColorHash();
+pixel
+ppm_parsecolor2(const char * const colorname,
+                pixval       const maxval,
+                int          const closeOk) {
 
-            if (cht == NULL)
-                pm_asprintf(errorP, "Unable to allocate space for color hash");
-            else {
-                readColorFile(fileName, mustOpen,
-                              nColorsP, colornames, colors, cht,
-                              errorP);
+    tuple const color = pnm_parsecolor2(colorname, maxval, closeOk);
 
-                if (*errorP)
-                    ppm_freecolorhash(cht);
-                else
-                    *chtP = cht;
-            }
-            if (*errorP)
-                free(colors);
-            else
-                *colorsP = colors;
+    pixel retval;
+
+    PPM_PUTR(retval, color[PAM_RED_PLANE]);
+    PPM_PUTG(retval, color[PAM_GRN_PLANE]);
+    PPM_PUTB(retval, color[PAM_BLU_PLANE]);
+
+    free(color);
+
+    return retval;
+}
+
+
+
+pixel
+ppm_parsecolor(const char * const colorname,
+               pixval       const maxval) {
+
+    return ppm_parsecolor2(colorname, maxval, true);
+}
+
+
+
+char *
+ppm_colorname(const pixel * const colorP,
+              pixval        const maxval,
+              int           const hexok)   {
+
+    int r, g, b;
+    FILE * fileP;
+    static char colorname[200];
+        /* Null string means no suitable name so far */
+
+    if (maxval == 255) {
+        r = PPM_GETR(*colorP);
+        g = PPM_GETG(*colorP);
+        b = PPM_GETB(*colorP);
+    } else {
+        r = (int) PPM_GETR(*colorP) * 255 / (int) maxval;
+        g = (int) PPM_GETG(*colorP) * 255 / (int) maxval;
+        b = (int) PPM_GETB(*colorP) * 255 / (int) maxval;
+    }
+
+    fileP = pm_openColornameFile(NULL, !hexok);
+
+    if (!fileP)
+        STRSCPY(colorname, "");
+    else {
+        int bestDiff;
+        bool eof;
+
+        for (bestDiff = 32767, eof = false;
+             !eof && bestDiff > 0; ) {
+            struct colorfile_entry const ce = pm_colorget(fileP);
+            if (ce.colorname)  {
+                int const thisDiff =
+                    abs(r - (int)ce.r) +
+                    abs(g - (int)ce.g) +
+                    abs(b - (int)ce.b);
+
+                if (thisDiff < bestDiff) {
+                    bestDiff = thisDiff;
+                    STRSCPY(colorname, ce.colorname);
+                }
+            } else
+                eof = true;
+        }
+        fclose(fileP);
+
+        if (bestDiff == 32767) {
+            /* Color file contain no entries, so we can't even pick a close
+               one
+            */
+            STRSCPY(colorname, "");
+        } else if (bestDiff > 0 && hexok) {
+            /* We didn't find an exact match and user is willing to accept
+               hex, so we don't have to use an approximate match.
+            */
+            STRSCPY(colorname, "");
+        }
+    }
+
+    if (streq(colorname, "")) {
+        if (hexok) {
+            /* Color lookup failed, but caller is willing to take an X11-style
+               hex specifier, so return that.
+            */
+            sprintf(colorname, "#%02x%02x%02x", r, g, b);
+        } else {
+            pm_error("Couldn't find any name colors at all");
         }
-        if (*errorP)
-            free(colornames);
-        else
-            *colornamesP = colornames;
     }
+
+    return colorname;
 }
 
 
@@ -371,60 +356,80 @@ void
 ppm_readcolordict(const char *      const fileName,
                   int               const mustOpen,
                   unsigned int *    const nColorsP,
-                  const char ***    const colornamesP,
+                  const char ***    const colorNamesP,
                   pixel **          const colorsP,
                   colorhash_table * const chtP) {
 /*----------------------------------------------------------------------------
-   Read the color dictionary from the file named 'fileName'.  If we can't open
-   the file (e.g. because it does not exist), and 'mustOpen' is false, return
-   an empty dictionary (it contains no colors).  But if 'mustOpen' is true,
-   abort the program instead of returning an empty dictionary.
+   Read the color dictionary from the file named 'fileName' (NULL means
+   default).  If we can't open the file (e.g. because it does not exist), and
+   'mustOpen' is false, return an empty dictionary (it contains no colors).
+   But if 'mustOpen' is true, abort the program instead of returning an empty
+   dictionary.
 
    Return as *nColorsP the number of colors in the dictionary.
 
-   Return as *colornamesP the names of those colors.  *colornamesP is a
-   malloced array that Caller must free with ppm_freecolornames().
+   Return as *colorNamesP the names of those colors.  *colorNamesP is a
+   malloced array that Caller must free with ppm_freecolorNames().
    The first *nColorsP entries are valid; *chtP contains indices into this
    array.
 
-   Return as *colorsP the colors.  *colorsP is a malloced array of size
-   MAXCOLORS with the first elements filled in and the rest undefined.
+   Return as *colorsP a malloced array of the colors.  (*colorsP)[i] is
+   the color that goes with (*colorNamesP)[i].
 
    Return as *chtP a color hash table mapping each color in the dictionary
-   to the index into *colornamesP for the name of the color.
+   to the index into *colorNamesP for the name of the color.
 
-   Each of 'nColorsP, 'colornamesP', and 'colorsP' may be null, in which case
+   Each of 'nColorsP, 'colorNamesP', and 'colorsP' may be null, in which case
    we do not return the corresponding information (or allocate memory for it).
 -----------------------------------------------------------------------------*/
-    colorhash_table cht;
-    const char ** colornames;
-    pixel * colors;
-    unsigned int nColors;
-    const char * error;
+    ppm_ColorDict * colorDictP;
 
-    readcolordict(fileName, mustOpen, &nColors, &colornames, &colors, &cht,
-                  &error);
+    colorDictP = ppm_colorDict_new(fileName, mustOpen);
 
-    if (error) {
-        pm_errormsg("%s", error);
-        pm_strfree(error);
-        pm_longjmp();
+    if (chtP)
+        *chtP = colorDictP->cht;
+    else
+        ppm_freecolorhash(colorDictP->cht);
+
+    if (colorNamesP) {
+        /* We have a simplistic, primitive interface where the array must
+           be exactly MAXCOLORNAMES entries in size with unused entries
+           set to NULL so that caller can free it with a call to
+           'ppm_freecolornames' (which has no size argument).
+
+           So we fail now (as the old interface would) if there are more
+           than MAXCOLORNAMES colors and expand the array if there are
+           fewer.
+        */
+        if (colorDictP->count > MAXCOLORNAMES)
+            pm_error("Too many color names (%u) in color dictionary.  "
+                     "Max allowed is %u",
+                     colorDictP->count, MAXCOLORNAMES);
+        else {
+            unsigned int i;
+
+            REALLOCARRAY(colorDictP->name, MAXCOLORNAMES);
+            if (!colorDictP->name)
+                pm_error("Failed to allocate color name array for "
+                         "maximum colors %u", MAXCOLORNAMES);
+            for (i = colorDictP->count; i < MAXCOLORNAMES; ++i)
+                colorDictP->name[i] = NULL;
+        }
+        *colorNamesP = colorDictP->name;
     } else {
-        if (chtP)
-            *chtP = cht;
-        else
-            ppm_freecolorhash(cht);
-        if (colornamesP)
-            *colornamesP = colornames;
-        else
-            ppm_freecolornames(colornames);
-        if (colorsP)
-            *colorsP = colors;
-        else
-            ppm_freerow(colors);
-        if (nColorsP)
-            *nColorsP = nColors;
+        unsigned int i;
+        for (i = 0; i < colorDictP->count; ++i)
+            pm_strfree(colorDictP->name[i]);
+        free(colorDictP->name);
     }
+
+    if (colorsP)
+        *colorsP = colorDictP->color;
+    else
+        free(colorDictP->color);
+
+    if (nColorsP)
+        *nColorsP = colorDictP->count;
 }
 
 
@@ -433,23 +438,23 @@ void
 ppm_readcolornamefile(const char *      const fileName,
                       int               const mustOpen,
                       colorhash_table * const chtP,
-                      const char ***    const colornamesP) {
+                      const char ***    const colorNamesP) {
 
-    ppm_readcolordict(fileName, mustOpen, NULL, colornamesP, NULL, chtP);
+    ppm_readcolordict(fileName, mustOpen, NULL, colorNamesP, NULL, chtP);
 }
 
 
 
 void
-ppm_freecolornames(const char ** const colornames) {
+ppm_freecolornames(const char ** const colorNames) {
 
     unsigned int i;
 
     for (i = 0; i < MAXCOLORNAMES; ++i)
-        if (colornames[i])
-            free((char *)colornames[i]);
+        if (colorNames[i])
+            free((char *)colorNames[i]);
 
-    free(colornames);
+    free(colorNames);
 }
 
 
diff --git a/lib/libppmfloyd.c b/lib/libppmfloyd.c
deleted file mode 100644
index a7117c8e..00000000
--- a/lib/libppmfloyd.c
+++ /dev/null
@@ -1,312 +0,0 @@
-/*
-These functions were taken from Ingo Wilken's ilbm package by Bryan
-Henderson on 01.03.10.  Because ppmtoilbm and ilbmtoppm are the only
-programs that will use these in the foreseeable future, they remain
-lightly documented and tested.
-
-But they look like they would be useful in other Netpbm programs that
-do Floyd-Steinberg.
-*/
-
-
-
-/* libfloyd.c - generic Floyd-Steinberg error distribution routines for PBMPlus
-**
-** Copyright (C) 1994 Ingo Wilken (Ingo.Wilken@informatik.uni-oldenburg.de)
-**
-** Permission to use, copy, modify, and distribute this software and its
-** documentation for any purpose and without fee is hereby granted, provided
-** that the above copyright notice appear in all copies and that both that
-** copyright notice and this permission notice appear in supporting
-** documentation.  This software is provided "as is" without express or
-** implied warranty.
-*/
-
-#include "netpbm/mallocvar.h"
-#include "ppm.h"
-#include "ppmfloyd.h"
-
-
-
-static void
-fs_adjust(ppm_fs_info * const fi,
-          int           const col) {
-
-    int     const errcol = col+1;
-    pixel * const pP     = &(fi->pixrow[col]);
-    pixval  const maxval = fi->maxval;
-
-    long r, g, b;
-
-    /* Use Floyd-Steinberg errors to adjust actual color. */
-    r = fi->thisrederr  [errcol]; if( r < 0 ) r -= 8; else r += 8; r /= 16;
-    g = fi->thisgreenerr[errcol]; if( g < 0 ) g -= 8; else g += 8; g /= 16;
-    b = fi->thisblueerr [errcol]; if( b < 0 ) b -= 8; else b += 8; b /= 16;
-
-    r += PPM_GETR(*pP); if ( r < 0 ) r = 0; else if ( r > maxval ) r = maxval;
-    g += PPM_GETG(*pP); if ( g < 0 ) g = 0; else if ( g > maxval ) g = maxval;
-    b += PPM_GETB(*pP); if ( b < 0 ) b = 0; else if ( b > maxval ) b = maxval;
-
-    PPM_ASSIGN(*pP, r, g, b);
-    fi->red = r; fi->green = g; fi->blue = b;
-}
-
-
-
-static ppm_fs_info *
-allocateFi(int const cols) {
-
-    ppm_fs_info * fi;
-
-    MALLOCVAR(fi);
-
-    if (fi != NULL) {
-        MALLOCARRAY(fi->thisrederr  , cols + 2);
-        MALLOCARRAY(fi->thisgreenerr, cols + 2);
-        MALLOCARRAY(fi->thisblueerr , cols + 2);
-        MALLOCARRAY(fi->nextrederr  , cols + 2);
-        MALLOCARRAY(fi->nextgreenerr, cols + 2);
-        MALLOCARRAY(fi->nextblueerr , cols + 2);
-
-        if (fi->thisrederr   == NULL ||
-            fi->thisgreenerr == NULL ||
-            fi->thisblueerr  == NULL ||
-            fi->nextrederr   == NULL ||
-            fi->nextgreenerr == NULL ||
-            fi->nextblueerr  == NULL)
-            pm_error("out of memory allocating "
-                     "Floyd-Steinberg control structure");
-    } else
-        pm_error("out of memory allocating Floyd-Steinberg control structure");
-
-    return(fi);
-}
-
-
-
-ppm_fs_info *
-ppm_fs_init(unsigned int const cols,
-            pixval       const maxval,
-            unsigned int const flags) {
-
-    ppm_fs_info * fiP;
-
-    fiP = allocateFi(cols);
-
-    fiP->lefttoright = 1;
-    fiP->cols        = cols;
-    fiP->maxval      = maxval;
-    fiP->flags       = flags;
-
-    if (flags & FS_RANDOMINIT) {
-        unsigned int i;
-        srand(pm_randseed());
-        for (i = 0; i < cols +2; ++i) {
-            /* random errors in [-1..+1] */
-            fiP->thisrederr[i]   = rand() % 32 - 16;
-            fiP->thisgreenerr[i] = rand() % 32 - 16;
-            fiP->thisblueerr[i]  = rand() % 32 - 16;
-        }
-    } else {
-        unsigned int i;
-
-        for (i = 0; i < cols + 2; ++i)
-            fiP->thisrederr[i] = fiP->thisgreenerr[i] =
-                fiP->thisblueerr[i] = 0;
-    }
-    return fiP;
-}
-
-
-
-void
-ppm_fs_free(ppm_fs_info * const fiP) {
-
-    if (fiP) {
-        free(fiP->thisrederr); free(fiP->thisgreenerr); free(fiP->thisblueerr);
-        free(fiP->nextrederr); free(fiP->nextgreenerr); free(fiP->nextblueerr);
-        free(fiP);
-    }
-}
-
-
-
-int
-ppm_fs_startrow(ppm_fs_info * const fiP,
-                pixel *       const pixrow) {
-
-    int retval;
-
-    if (!fiP)
-        retval = 0;
-    else {
-        unsigned int col;
-
-        fiP->pixrow = pixrow;
-
-        for (col = 0; col < fiP->cols + 2; ++col) {
-            fiP->nextrederr  [col] = 0;
-            fiP->nextgreenerr[col] = 0;
-            fiP->nextblueerr [col] = 0;
-        }
-
-        if(fiP->lefttoright) {
-            fiP->col_end = fiP->cols;
-            col = 0;
-        } else {
-            fiP->col_end = -1;
-            col = fiP->cols - 1;
-        }
-        fs_adjust(fiP, col);
-
-        retval = col;
-    }
-    return retval;
-}
-
-
-
-int
-ppm_fs_next(ppm_fs_info * const fiP,
-            int           const startCol) {
-
-    int col;
-
-    col = startCol;  /* initial value */
-
-    if (!fiP)
-        ++col;
-    else {
-        if (fiP->lefttoright)
-            ++col;
-        else
-            --col;
-        if (col == fiP->col_end)
-            col = fiP->cols;
-        else
-            fs_adjust(fiP, col);
-    }
-    return col;
-}
-
-
-
-void
-ppm_fs_endrow(ppm_fs_info * const fiP) {
-
-    if (fiP) {
-        {
-            long * const tmp = fiP->thisrederr;
-            fiP->thisrederr = fiP->nextrederr;
-            fiP->nextrederr = tmp;
-        }
-        {
-            long * const tmp = fiP->thisgreenerr;
-            fiP->thisgreenerr = fiP->nextgreenerr;
-            fiP->nextgreenerr = tmp;
-        }
-        {
-            long * const tmp = fiP->thisblueerr;
-            fiP->thisblueerr = fiP->nextblueerr;
-            fiP->nextblueerr = tmp;
-        }
-        if (fiP->flags & FS_ALTERNATE)
-            fiP->lefttoright = !fiP->lefttoright;
-    }
-}
-
-
-
-void
-ppm_fs_update(ppm_fs_info * const fiP,
-              int           const col,
-              pixel *       const pP) {
-
-    if (fiP)
-        ppm_fs_update3(fiP, col, PPM_GETR(*pP), PPM_GETG(*pP), PPM_GETB(*pP));
-}
-
-
-
-void
-ppm_fs_update3(ppm_fs_info * const fiP,
-               int           const col,
-               pixval        const r,
-               pixval        const g,
-               pixval        const b) {
-
-    int const errcol = col + 1;
-
-    if (fiP) {
-        long const rerr = (long)(fiP->red)   - (long)r;
-        long const gerr = (long)(fiP->green) - (long)g;
-        long const berr = (long)(fiP->blue)  - (long)b;
-
-        if ( fiP->lefttoright ) {
-            {
-                long const two_err = 2*rerr;
-
-                long err;
-
-                err = rerr;     fiP->nextrederr[errcol+1] += err;    /* 1/16 */
-                err += two_err; fiP->nextrederr[errcol-1] += err;    /* 3/16 */
-                err += two_err; fiP->nextrederr[errcol  ] += err;    /* 5/16 */
-                err += two_err; fiP->thisrederr[errcol+1] += err;    /* 7/16 */
-            }
-            {
-                long const two_err = 2*gerr;
-
-                long err;
-
-                err = gerr;     fiP->nextgreenerr[errcol+1] += err;  /* 1/16 */
-                err += two_err; fiP->nextgreenerr[errcol-1] += err;  /* 3/16 */
-                err += two_err; fiP->nextgreenerr[errcol  ] += err;  /* 5/16 */
-                err += two_err; fiP->thisgreenerr[errcol+1] += err;  /* 7/16 */
-            }
-            {
-                long const two_err = 2*berr;
-
-                long err;
-
-                err = berr;     fiP->nextblueerr[errcol+1] += err;  /* 1/16 */
-                err += two_err; fiP->nextblueerr[errcol-1] += err;  /* 3/16 */
-                err += two_err; fiP->nextblueerr[errcol  ] += err;  /* 5/16 */
-                err += two_err; fiP->thisblueerr[errcol+1] += err;  /* 7/16 */
-            }
-        } else {
-            {
-                long const two_err = 2*rerr;
-
-                long err;
-
-                err = rerr;     fiP->nextrederr[errcol-1] += err;    /* 1/16 */
-                err += two_err; fiP->nextrederr[errcol+1] += err;    /* 3/16 */
-                err += two_err; fiP->nextrederr[errcol  ] += err;    /* 5/16 */
-                err += two_err; fiP->thisrederr[errcol-1] += err;    /* 7/16 */
-            }
-            {
-                long const two_err = 2*gerr;
-
-                long err;
-
-                err = gerr;     fiP->nextgreenerr[errcol-1] += err;  /* 1/16 */
-                err += two_err; fiP->nextgreenerr[errcol+1] += err;  /* 3/16 */
-                err += two_err; fiP->nextgreenerr[errcol  ] += err;  /* 5/16 */
-                err += two_err; fiP->thisgreenerr[errcol-1] += err;  /* 7/16 */
-            }
-            {
-                long const two_err = 2*berr;
-
-                long err;
-
-                err = berr;     fiP->nextblueerr[errcol-1] += err;  /* 1/16 */
-                err += two_err; fiP->nextblueerr[errcol+1] += err;  /* 3/16 */
-                err += two_err; fiP->nextblueerr[errcol  ] += err;  /* 5/16 */
-                err += two_err; fiP->thisblueerr[errcol-1] += err;  /* 7/16 */
-            }
-        }
-    }
-}
-
-
-
diff --git a/lib/libppmfuzzy.c b/lib/libppmfuzzy.c
index 902d684d..37fa02ca 100644
--- a/lib/libppmfuzzy.c
+++ b/lib/libppmfuzzy.c
@@ -62,7 +62,7 @@ memberTrapez(fzLog const x1,
              fzLog const x) {
 
     fzLog retval;
-    
+
     if (x <= x1 || x > x4)
         retval = 0;
     else if (x > x1 && x <= x2)
@@ -301,7 +301,7 @@ matchBk(pixel     const color,
 
     (*bkMatchP)[BKCOLOR_WHITE]  =
         fzAnd(satVeryLow, valVeryHigh);
-    
+
     (*bkMatchP)[BKCOLOR_RED]    =
         fzAnd(fzAnd(fzOr(hueAround000, hueAround360), fzNot(satVeryLow)),
               fzOr(valMedium, valHigh)
@@ -342,7 +342,7 @@ matchBk(pixel     const color,
              fzAnd(fzOr(hueAround015, hueAround360),
                    fzAnd(fzNot(satVeryLow), fzOr(valLow, valMedium))),
              fzAnd(hueAround015, satLow)
-	    );
+            );
 }
 
 
diff --git a/lib/libsystem.c b/lib/libsystem.c
index ba48ed85..332cc5e2 100644
--- a/lib/libsystem.c
+++ b/lib/libsystem.c
@@ -40,8 +40,8 @@
 
 
 static void
-closeUninheritableFds(int const stdinFd,
-                      int const stdoutFd) {
+closeUninheritableFds(int const keepFdA,
+                      int const keepFdB) {
 /*----------------------------------------------------------------------------
   Close all the file descriptors that we declare uninheritable -- files Parent
   has open that Child has no business accessing.
@@ -49,14 +49,21 @@ closeUninheritableFds(int const stdinFd,
   Closing an extra file descriptor is essential to allow the file to close
   when Parent closes it.
 
+  It is also essential to prevent the system from messing with the position of
+  the file as the child process exits.  If the file descriptor is backing a
+  stream (FILE *), some process-exit code seeks the file to the current stream
+  position (from the readahead position), but having the file descriptor
+  closed defeats that.
+
   We define uninheritable as less than 64 and not Standard Input, Output,
-  or Error, or 'stdinFd' or 'stdoutFd'.
+  or Error, or 'keepFdA' or 'keepFdB'.
 -----------------------------------------------------------------------------*/
     int fd;
 
     for (fd = 0; fd < 64; ++fd) {
-        if (fd == stdinFd) {
-        } else if (fd == stdoutFd) {
+        if (false) {
+        } else if (fd == keepFdA) {
+        } else if (fd == keepFdB) {
         } else if (fd == STDIN_FILENO) {
         } else if (fd == STDOUT_FILENO) {
         } else if (fd == STDERR_FILENO) {
@@ -148,6 +155,9 @@ createPipeFeeder(void          pipeFeederRtn(int, void *),
     } else if (rc == 0) {
         /* This is the child -- the stdin feeder process */
         close(pipeToFeed[0]);
+
+        closeUninheritableFds(pipeToFeed[1], pipeToFeed[1]);
+
         (*pipeFeederRtn)(pipeToFeed[1], feederParm);
         exit(0);
     } else {
@@ -513,10 +523,7 @@ pm_system2_lp(const char *    const progName,
 
     va_start(args, termStatusP);
 
-    endOfArgs = FALSE;
-    argArray = NULL;
-
-    for (endOfArgs = FALSE, argArray = NULL, n = 0;
+    for (endOfArgs = false, argArray = NULL, n = 0;
          !endOfArgs;
         ) {
         const char * const arg = va_arg(args, const char *);
@@ -526,7 +533,7 @@ pm_system2_lp(const char *    const progName,
         argArray[n++] = arg;
 
         if (!arg)
-            endOfArgs = TRUE;
+            endOfArgs = true;
     }
 
     va_end(args);
@@ -618,9 +625,6 @@ pm_system_lp(const char *    const progName,
 
     va_start(args, accepterParm);
 
-    endOfArgs = FALSE;
-    argArray = NULL;
-
     for (endOfArgs = FALSE, argArray = NULL, n = 0;
          !endOfArgs;
         ) {
@@ -631,7 +635,7 @@ pm_system_lp(const char *    const progName,
         argArray[n++] = arg;
 
         if (!arg)
-            endOfArgs = TRUE;
+            endOfArgs = true;
     }
 
     va_end(args);
@@ -680,7 +684,7 @@ pm_feed_null(int    const pipeToFeedFd,
 
 
 void
-pm_accept_null(int    const pipetosuckFd,
+pm_accept_null(int    const pipeToSuckFd,
                void * const accepterParm ) {
 
     size_t const bufferSize = 4096;
@@ -695,7 +699,7 @@ pm_accept_null(int    const pipetosuckFd,
         for (eof = false; !eof; ) {
             ssize_t rc;
 
-            rc = read(pipetosuckFd, buffer, bufferSize);
+            rc = read(pipeToSuckFd, buffer, bufferSize);
 
             if (rc < 0) {
                 /* No way to report the problem; just say we're done */
@@ -706,7 +710,7 @@ pm_accept_null(int    const pipetosuckFd,
         }
         free(buffer);
     }
-    close(pipetosuckFd);
+    close(pipeToSuckFd);
 }
 
 
@@ -719,16 +723,16 @@ pm_feed_from_memory(int    const pipeToFeedFd,
 
     FILE * const outFileP = fdopen(pipeToFeedFd, "w");
 
-    size_t bytesTransferred;
+    size_t byteCtTransferred;
 
     /* The following signals (and normally kills) the process with
        SIGPIPE if the pipe does not take all 'size' bytes.
     */
-    bytesTransferred =
+    byteCtTransferred =
         fwrite(inputBufferP->buffer, 1, inputBufferP->size, outFileP);
 
     if (inputBufferP->bytesTransferredP)
-        *(inputBufferP->bytesTransferredP) = bytesTransferred;
+        *(inputBufferP->bytesTransferredP) = byteCtTransferred;
 
     fclose(outFileP);
 }
@@ -736,23 +740,173 @@ pm_feed_from_memory(int    const pipeToFeedFd,
 
 
 void
-pm_accept_to_memory(int             const pipetosuckFd,
+pm_accept_to_memory(int             const pipeToSuckFd,
                     void *          const accepterParm ) {
 
     pm_bufferDesc * const outputBufferP = accepterParm;
 
-    FILE * const inFileP = fdopen(pipetosuckFd, "r");
+    FILE * const inFileP = fdopen(pipeToSuckFd, "r");
 
-    size_t bytesTransferred;
+    size_t byteCtTransferred;
 
-    bytesTransferred =
+    byteCtTransferred =
         fread(outputBufferP->buffer, 1, outputBufferP->size, inFileP);
 
     fclose(inFileP);
 
     if (outputBufferP->bytesTransferredP)
-        *(outputBufferP->bytesTransferredP) = bytesTransferred;
+        *(outputBufferP->bytesTransferredP) = byteCtTransferred;
 }
 
 
 
+void
+pm_feed_from_file(int    const pipeToFeedFd,
+                  void * const feederParm) {
+
+    const char * const inFileNm = feederParm;
+
+    size_t const bufferSz = 64*1024;
+
+    FILE * const outFileP = fdopen(pipeToFeedFd, "w");
+
+    FILE * inFileP;
+    unsigned char * buffer;
+    bool eof;
+
+    inFileP = pm_openr(inFileNm);
+
+    MALLOCARRAY(buffer, bufferSz);
+
+    if (!buffer)
+        pm_error("Failed to allocate %u bytes for I/O buffer",
+                 (unsigned) bufferSz);
+
+    for (eof = false; !eof; ) {
+        size_t byteCtRead;
+
+        byteCtRead = fread(buffer, 1, bufferSz, inFileP);
+
+        if (ferror(inFileP))
+            pm_error("Error reading file.  errno=%d (%s)",
+                     errno, strerror(errno));
+
+        if (byteCtRead > 0) {
+            /* The following signals (and normally kills) the process with
+               SIGPIPE if the pipe does not take all 'size' bytes.
+            */
+            fwrite(buffer, 1, byteCtRead, outFileP);
+        } else
+            eof = true;
+    }
+
+    pm_close(inFileP);
+    fclose(outFileP);
+
+    free(buffer);
+}
+
+
+
+void
+pm_accept_to_file(int             const pipeToSuckFd,
+                  void *          const accepterParm ) {
+
+    const char * const outFileNm = accepterParm;
+
+    size_t const bufferSz = 64*1024;
+
+    FILE * const inFileP = fdopen(pipeToSuckFd, "r");
+
+    FILE * outFileP;
+    unsigned char * buffer;
+    bool eof;
+
+    outFileP = pm_openw(outFileNm);
+
+    MALLOCARRAY(buffer, bufferSz);
+
+    if (!buffer)
+        pm_error("Failed to allocate %u bytes for I/O buffer",
+                 (unsigned) bufferSz);
+
+    for (eof = false; !eof; ) {
+        size_t byteCtRead;
+
+        byteCtRead = fread(buffer, 1, bufferSz, inFileP);
+
+        if (ferror(inFileP))
+            pm_error("Error reading Standard Output accepter pipe.  "
+                     "errno=%d (%s)",
+                     errno, strerror(errno));
+
+        if (byteCtRead > 0) {
+            fwrite(buffer, 1, byteCtRead, outFileP);
+
+            if (ferror(outFileP))
+                pm_error("Error writing to file.  errno=%d (%s)",
+                         errno, strerror(errno));
+        } else
+            eof = true;
+    }
+
+    pm_close(outFileP);
+    fclose(inFileP);
+
+    free(buffer);
+}
+
+
+
+/* Note that pm_feed_from_filestream is not possible because Standard Input is
+   feed by a child process and we can't properly pass a FILE * to a child
+   process.
+*/
+
+
+
+void
+pm_accept_to_filestream(int             const pipeToSuckFd,
+                        void *          const accepterParm ) {
+
+    FILE * const outFileP = accepterParm;
+
+    size_t const bufferSz = 64*1024;
+
+    FILE * const inFileP = fdopen(pipeToSuckFd, "r");
+
+    unsigned char * buffer;
+    bool eof;
+
+    MALLOCARRAY(buffer, bufferSz);
+
+    if (!buffer)
+        pm_error("Failed to allocate %u bytes for I/O buffer",
+                 (unsigned) bufferSz);
+
+    for (eof = false; !eof; ) {
+        size_t byteCtRead;
+
+        byteCtRead = fread(buffer, 1, bufferSz, inFileP);
+
+        if (ferror(inFileP))
+            pm_error("Error reading Standard Output accepter pipe.  "
+                     "errno=%d (%s)",
+                     errno, strerror(errno));
+
+        if (byteCtRead > 0) {
+            fwrite(buffer, 1, byteCtRead, outFileP);
+
+            if (ferror(outFileP))
+                pm_error("Error writing to file.  errno=%d (%s)",
+                         errno, strerror(errno));
+        } else
+            eof = true;
+    }
+
+    fclose(inFileP);
+
+    free(buffer);
+}
+
+
diff --git a/lib/libsystem_dummy.c b/lib/libsystem_dummy.c
index 97dd8984..e8acf387 100644
--- a/lib/libsystem_dummy.c
+++ b/lib/libsystem_dummy.c
@@ -9,6 +9,7 @@
   the facility is not available.
 =============================================================================*/
 
+#include <stdbool.h>
 #include <assert.h>
 
 #include "pm.h"
@@ -29,6 +30,8 @@ pm_system_vp(const char *    const progName,
              "requires.");
 }
 
+
+
 void
 pm_system_lp(const char *    const progName,
              void stdinFeeder(int, void *),
@@ -44,6 +47,8 @@ pm_system_lp(const char *    const progName,
              "requires.");
 }
 
+
+
 void
 pm_system(void                  stdinFeeder(int, void *),
           void *          const feederParm,
@@ -59,11 +64,30 @@ pm_system(void                  stdinFeeder(int, void *),
 }
 
 
+
+void
+pm_feed_null(int    const pipeToFeedFd,
+             void * const feederParm) {
+
+    assert(false);  /* Can't ever run, since pm_system() is a dummy */
+}
+
+
+
+void
+pm_accept_null(int    const pipetosuckFd,
+               void * const accepterParm ) {
+
+    assert(false);  /* Can't ever run, since pm_system() is a dummy */
+}
+
+
+
 void
 pm_feed_from_memory(int    const pipeToFeedFd,
                     void * const feederParm) {
 
-    assert(FALSE);  /* Can't ever run, since pm_system() is a dummy */
+    assert(false);  /* Can't ever run, since pm_system() is a dummy */
 }
 
 
@@ -72,6 +96,8 @@ void
 pm_accept_to_memory(int    const pipetosuckFd,
                     void * const accepterParm) {
 
-    assert(FALSE);  /* Can't ever run, since pm_system() is a dummy */
+    assert(false);  /* Can't ever run, since pm_system() is a dummy */
 }
 
+
+
diff --git a/lib/lum.h b/lib/lum.h
index 3d20032b..b80d602e 100644
--- a/lib/lum.h
+++ b/lib/lum.h
@@ -2,104 +2,104 @@
 
     /* Lookup tables for fast RGB -> luminance calculation. */
     static int times77[256] = {
-	    0,    77,   154,   231,   308,   385,   462,   539,
-	  616,   693,   770,   847,   924,  1001,  1078,  1155,
-	 1232,  1309,  1386,  1463,  1540,  1617,  1694,  1771,
-	 1848,  1925,  2002,  2079,  2156,  2233,  2310,  2387,
-	 2464,  2541,  2618,  2695,  2772,  2849,  2926,  3003,
-	 3080,  3157,  3234,  3311,  3388,  3465,  3542,  3619,
-	 3696,  3773,  3850,  3927,  4004,  4081,  4158,  4235,
-	 4312,  4389,  4466,  4543,  4620,  4697,  4774,  4851,
-	 4928,  5005,  5082,  5159,  5236,  5313,  5390,  5467,
-	 5544,  5621,  5698,  5775,  5852,  5929,  6006,  6083,
-	 6160,  6237,  6314,  6391,  6468,  6545,  6622,  6699,
-	 6776,  6853,  6930,  7007,  7084,  7161,  7238,  7315,
-	 7392,  7469,  7546,  7623,  7700,  7777,  7854,  7931,
-	 8008,  8085,  8162,  8239,  8316,  8393,  8470,  8547,
-	 8624,  8701,  8778,  8855,  8932,  9009,  9086,  9163,
-	 9240,  9317,  9394,  9471,  9548,  9625,  9702,  9779,
-	 9856,  9933, 10010, 10087, 10164, 10241, 10318, 10395,
-	10472, 10549, 10626, 10703, 10780, 10857, 10934, 11011,
-	11088, 11165, 11242, 11319, 11396, 11473, 11550, 11627,
-	11704, 11781, 11858, 11935, 12012, 12089, 12166, 12243,
-	12320, 12397, 12474, 12551, 12628, 12705, 12782, 12859,
-	12936, 13013, 13090, 13167, 13244, 13321, 13398, 13475,
-	13552, 13629, 13706, 13783, 13860, 13937, 14014, 14091,
-	14168, 14245, 14322, 14399, 14476, 14553, 14630, 14707,
-	14784, 14861, 14938, 15015, 15092, 15169, 15246, 15323,
-	15400, 15477, 15554, 15631, 15708, 15785, 15862, 15939,
-	16016, 16093, 16170, 16247, 16324, 16401, 16478, 16555,
-	16632, 16709, 16786, 16863, 16940, 17017, 17094, 17171,
-	17248, 17325, 17402, 17479, 17556, 17633, 17710, 17787,
-	17864, 17941, 18018, 18095, 18172, 18249, 18326, 18403,
-	18480, 18557, 18634, 18711, 18788, 18865, 18942, 19019,
-	19096, 19173, 19250, 19327, 19404, 19481, 19558, 19635 };
+            0,    77,   154,   231,   308,   385,   462,   539,
+          616,   693,   770,   847,   924,  1001,  1078,  1155,
+         1232,  1309,  1386,  1463,  1540,  1617,  1694,  1771,
+         1848,  1925,  2002,  2079,  2156,  2233,  2310,  2387,
+         2464,  2541,  2618,  2695,  2772,  2849,  2926,  3003,
+         3080,  3157,  3234,  3311,  3388,  3465,  3542,  3619,
+         3696,  3773,  3850,  3927,  4004,  4081,  4158,  4235,
+         4312,  4389,  4466,  4543,  4620,  4697,  4774,  4851,
+         4928,  5005,  5082,  5159,  5236,  5313,  5390,  5467,
+         5544,  5621,  5698,  5775,  5852,  5929,  6006,  6083,
+         6160,  6237,  6314,  6391,  6468,  6545,  6622,  6699,
+         6776,  6853,  6930,  7007,  7084,  7161,  7238,  7315,
+         7392,  7469,  7546,  7623,  7700,  7777,  7854,  7931,
+         8008,  8085,  8162,  8239,  8316,  8393,  8470,  8547,
+         8624,  8701,  8778,  8855,  8932,  9009,  9086,  9163,
+         9240,  9317,  9394,  9471,  9548,  9625,  9702,  9779,
+         9856,  9933, 10010, 10087, 10164, 10241, 10318, 10395,
+        10472, 10549, 10626, 10703, 10780, 10857, 10934, 11011,
+        11088, 11165, 11242, 11319, 11396, 11473, 11550, 11627,
+        11704, 11781, 11858, 11935, 12012, 12089, 12166, 12243,
+        12320, 12397, 12474, 12551, 12628, 12705, 12782, 12859,
+        12936, 13013, 13090, 13167, 13244, 13321, 13398, 13475,
+        13552, 13629, 13706, 13783, 13860, 13937, 14014, 14091,
+        14168, 14245, 14322, 14399, 14476, 14553, 14630, 14707,
+        14784, 14861, 14938, 15015, 15092, 15169, 15246, 15323,
+        15400, 15477, 15554, 15631, 15708, 15785, 15862, 15939,
+        16016, 16093, 16170, 16247, 16324, 16401, 16478, 16555,
+        16632, 16709, 16786, 16863, 16940, 17017, 17094, 17171,
+        17248, 17325, 17402, 17479, 17556, 17633, 17710, 17787,
+        17864, 17941, 18018, 18095, 18172, 18249, 18326, 18403,
+        18480, 18557, 18634, 18711, 18788, 18865, 18942, 19019,
+        19096, 19173, 19250, 19327, 19404, 19481, 19558, 19635 };
     static int times150[256] = {
-	    0,   150,   300,   450,   600,   750,   900,  1050,
-	 1200,  1350,  1500,  1650,  1800,  1950,  2100,  2250,
-	 2400,  2550,  2700,  2850,  3000,  3150,  3300,  3450,
-	 3600,  3750,  3900,  4050,  4200,  4350,  4500,  4650,
-	 4800,  4950,  5100,  5250,  5400,  5550,  5700,  5850,
-	 6000,  6150,  6300,  6450,  6600,  6750,  6900,  7050,
-	 7200,  7350,  7500,  7650,  7800,  7950,  8100,  8250,
-	 8400,  8550,  8700,  8850,  9000,  9150,  9300,  9450,
-	 9600,  9750,  9900, 10050, 10200, 10350, 10500, 10650,
-	10800, 10950, 11100, 11250, 11400, 11550, 11700, 11850,
-	12000, 12150, 12300, 12450, 12600, 12750, 12900, 13050,
-	13200, 13350, 13500, 13650, 13800, 13950, 14100, 14250,
-	14400, 14550, 14700, 14850, 15000, 15150, 15300, 15450,
-	15600, 15750, 15900, 16050, 16200, 16350, 16500, 16650,
-	16800, 16950, 17100, 17250, 17400, 17550, 17700, 17850,
-	18000, 18150, 18300, 18450, 18600, 18750, 18900, 19050,
-	19200, 19350, 19500, 19650, 19800, 19950, 20100, 20250,
-	20400, 20550, 20700, 20850, 21000, 21150, 21300, 21450,
-	21600, 21750, 21900, 22050, 22200, 22350, 22500, 22650,
-	22800, 22950, 23100, 23250, 23400, 23550, 23700, 23850,
-	24000, 24150, 24300, 24450, 24600, 24750, 24900, 25050,
-	25200, 25350, 25500, 25650, 25800, 25950, 26100, 26250,
-	26400, 26550, 26700, 26850, 27000, 27150, 27300, 27450,
-	27600, 27750, 27900, 28050, 28200, 28350, 28500, 28650,
-	28800, 28950, 29100, 29250, 29400, 29550, 29700, 29850,
-	30000, 30150, 30300, 30450, 30600, 30750, 30900, 31050,
-	31200, 31350, 31500, 31650, 31800, 31950, 32100, 32250,
-	32400, 32550, 32700, 32850, 33000, 33150, 33300, 33450,
-	33600, 33750, 33900, 34050, 34200, 34350, 34500, 34650,
-	34800, 34950, 35100, 35250, 35400, 35550, 35700, 35850,
-	36000, 36150, 36300, 36450, 36600, 36750, 36900, 37050,
-	37200, 37350, 37500, 37650, 37800, 37950, 38100, 38250 };
+            0,   150,   300,   450,   600,   750,   900,  1050,
+         1200,  1350,  1500,  1650,  1800,  1950,  2100,  2250,
+         2400,  2550,  2700,  2850,  3000,  3150,  3300,  3450,
+         3600,  3750,  3900,  4050,  4200,  4350,  4500,  4650,
+         4800,  4950,  5100,  5250,  5400,  5550,  5700,  5850,
+         6000,  6150,  6300,  6450,  6600,  6750,  6900,  7050,
+         7200,  7350,  7500,  7650,  7800,  7950,  8100,  8250,
+         8400,  8550,  8700,  8850,  9000,  9150,  9300,  9450,
+         9600,  9750,  9900, 10050, 10200, 10350, 10500, 10650,
+        10800, 10950, 11100, 11250, 11400, 11550, 11700, 11850,
+        12000, 12150, 12300, 12450, 12600, 12750, 12900, 13050,
+        13200, 13350, 13500, 13650, 13800, 13950, 14100, 14250,
+        14400, 14550, 14700, 14850, 15000, 15150, 15300, 15450,
+        15600, 15750, 15900, 16050, 16200, 16350, 16500, 16650,
+        16800, 16950, 17100, 17250, 17400, 17550, 17700, 17850,
+        18000, 18150, 18300, 18450, 18600, 18750, 18900, 19050,
+        19200, 19350, 19500, 19650, 19800, 19950, 20100, 20250,
+        20400, 20550, 20700, 20850, 21000, 21150, 21300, 21450,
+        21600, 21750, 21900, 22050, 22200, 22350, 22500, 22650,
+        22800, 22950, 23100, 23250, 23400, 23550, 23700, 23850,
+        24000, 24150, 24300, 24450, 24600, 24750, 24900, 25050,
+        25200, 25350, 25500, 25650, 25800, 25950, 26100, 26250,
+        26400, 26550, 26700, 26850, 27000, 27150, 27300, 27450,
+        27600, 27750, 27900, 28050, 28200, 28350, 28500, 28650,
+        28800, 28950, 29100, 29250, 29400, 29550, 29700, 29850,
+        30000, 30150, 30300, 30450, 30600, 30750, 30900, 31050,
+        31200, 31350, 31500, 31650, 31800, 31950, 32100, 32250,
+        32400, 32550, 32700, 32850, 33000, 33150, 33300, 33450,
+        33600, 33750, 33900, 34050, 34200, 34350, 34500, 34650,
+        34800, 34950, 35100, 35250, 35400, 35550, 35700, 35850,
+        36000, 36150, 36300, 36450, 36600, 36750, 36900, 37050,
+        37200, 37350, 37500, 37650, 37800, 37950, 38100, 38250 };
     static int times29[256] = {
-	    0,    29,    58,    87,   116,   145,   174,   203,
-	  232,   261,   290,   319,   348,   377,   406,   435,
-	  464,   493,   522,   551,   580,   609,   638,   667,
-	  696,   725,   754,   783,   812,   841,   870,   899,
-	  928,   957,   986,  1015,  1044,  1073,  1102,  1131,
-	 1160,  1189,  1218,  1247,  1276,  1305,  1334,  1363,
-	 1392,  1421,  1450,  1479,  1508,  1537,  1566,  1595,
-	 1624,  1653,  1682,  1711,  1740,  1769,  1798,  1827,
-	 1856,  1885,  1914,  1943,  1972,  2001,  2030,  2059,
-	 2088,  2117,  2146,  2175,  2204,  2233,  2262,  2291,
-	 2320,  2349,  2378,  2407,  2436,  2465,  2494,  2523,
-	 2552,  2581,  2610,  2639,  2668,  2697,  2726,  2755,
-	 2784,  2813,  2842,  2871,  2900,  2929,  2958,  2987,
-	 3016,  3045,  3074,  3103,  3132,  3161,  3190,  3219,
-	 3248,  3277,  3306,  3335,  3364,  3393,  3422,  3451,
-	 3480,  3509,  3538,  3567,  3596,  3625,  3654,  3683,
-	 3712,  3741,  3770,  3799,  3828,  3857,  3886,  3915,
-	 3944,  3973,  4002,  4031,  4060,  4089,  4118,  4147,
-	 4176,  4205,  4234,  4263,  4292,  4321,  4350,  4379,
-	 4408,  4437,  4466,  4495,  4524,  4553,  4582,  4611,
-	 4640,  4669,  4698,  4727,  4756,  4785,  4814,  4843,
-	 4872,  4901,  4930,  4959,  4988,  5017,  5046,  5075,
-	 5104,  5133,  5162,  5191,  5220,  5249,  5278,  5307,
-	 5336,  5365,  5394,  5423,  5452,  5481,  5510,  5539,
-	 5568,  5597,  5626,  5655,  5684,  5713,  5742,  5771,
-	 5800,  5829,  5858,  5887,  5916,  5945,  5974,  6003,
-	 6032,  6061,  6090,  6119,  6148,  6177,  6206,  6235,
-	 6264,  6293,  6322,  6351,  6380,  6409,  6438,  6467,
-	 6496,  6525,  6554,  6583,  6612,  6641,  6670,  6699,
-	 6728,  6757,  6786,  6815,  6844,  6873,  6902,  6931,
-	 6960,  6989,  7018,  7047,  7076,  7105,  7134,  7163,
-	 7192,  7221,  7250,  7279,  7308,  7337,  7366,  7395 };
+            0,    29,    58,    87,   116,   145,   174,   203,
+          232,   261,   290,   319,   348,   377,   406,   435,
+          464,   493,   522,   551,   580,   609,   638,   667,
+          696,   725,   754,   783,   812,   841,   870,   899,
+          928,   957,   986,  1015,  1044,  1073,  1102,  1131,
+         1160,  1189,  1218,  1247,  1276,  1305,  1334,  1363,
+         1392,  1421,  1450,  1479,  1508,  1537,  1566,  1595,
+         1624,  1653,  1682,  1711,  1740,  1769,  1798,  1827,
+         1856,  1885,  1914,  1943,  1972,  2001,  2030,  2059,
+         2088,  2117,  2146,  2175,  2204,  2233,  2262,  2291,
+         2320,  2349,  2378,  2407,  2436,  2465,  2494,  2523,
+         2552,  2581,  2610,  2639,  2668,  2697,  2726,  2755,
+         2784,  2813,  2842,  2871,  2900,  2929,  2958,  2987,
+         3016,  3045,  3074,  3103,  3132,  3161,  3190,  3219,
+         3248,  3277,  3306,  3335,  3364,  3393,  3422,  3451,
+         3480,  3509,  3538,  3567,  3596,  3625,  3654,  3683,
+         3712,  3741,  3770,  3799,  3828,  3857,  3886,  3915,
+         3944,  3973,  4002,  4031,  4060,  4089,  4118,  4147,
+         4176,  4205,  4234,  4263,  4292,  4321,  4350,  4379,
+         4408,  4437,  4466,  4495,  4524,  4553,  4582,  4611,
+         4640,  4669,  4698,  4727,  4756,  4785,  4814,  4843,
+         4872,  4901,  4930,  4959,  4988,  5017,  5046,  5075,
+         5104,  5133,  5162,  5191,  5220,  5249,  5278,  5307,
+         5336,  5365,  5394,  5423,  5452,  5481,  5510,  5539,
+         5568,  5597,  5626,  5655,  5684,  5713,  5742,  5771,
+         5800,  5829,  5858,  5887,  5916,  5945,  5974,  6003,
+         6032,  6061,  6090,  6119,  6148,  6177,  6206,  6235,
+         6264,  6293,  6322,  6351,  6380,  6409,  6438,  6467,
+         6496,  6525,  6554,  6583,  6612,  6641,  6670,  6699,
+         6728,  6757,  6786,  6815,  6844,  6873,  6902,  6931,
+         6960,  6989,  7018,  7047,  7076,  7105,  7134,  7163,
+         7192,  7221,  7250,  7279,  7308,  7337,  7366,  7395 };
 
 /* The ppm_fastlumin() macro is a way to compute luminosity without
    floating point arithmetic.  On modern computers, floating point often isn't
diff --git a/lib/pam.h b/lib/pam.h
index aebf529a..0b8c068a 100644
--- a/lib/pam.h
+++ b/lib/pam.h
@@ -136,6 +136,18 @@ struct pam {
         /* The plane number of the opacity plane;  meaningless if
            'haveOpacity' is false or 'visual' is false.
         */
+    int is_seekable;  /* boolean */
+        /* The file 'file' is seekable -- you can set the position of next
+           reading or writing to anything and any time.
+
+           If libnetpbm cannot tell if it is seekable or not, this is false.
+        */
+    pm_filepos raster_pos;
+        /* The file position of the raster (which is also the end of the
+           header).
+
+           Meaningless if 'is_seekable' is false.
+        */
 };
 
 #define PAM_HAVE_ALLOCATION_DEPTH 1
@@ -198,7 +210,7 @@ typedef sample *tuple;
        of the image (see pam.depth above).
     */
 
-#define PAM_OVERALL_MAXVAL 65535
+#define PAM_OVERALL_MAXVAL 65535lu
 
 /* Note: xv uses the same "P7" signature for its thumbnail images (it
    started using it years before PAM and unbeknownst to the designer
@@ -251,8 +263,6 @@ pnm_scalesample(sample const source,
         return (source * newmaxval + (oldmaxval/2)) / oldmaxval;
 }
 
-
-
 void
 pnm_scaletuple(const struct pam * const pamP,
                tuple              const dest,
@@ -293,6 +303,9 @@ pnm_getopacity(const struct pam * const pamP,
 void
 pnm_createBlackTuple(const struct pam * const pamP, tuple * const blackTupleP);
 
+void
+pnm_createWhiteTuple(const struct pam * const pamP, tuple * const whiteTupleP);
+
 tuple
 pnm_allocpamtuple(const struct pam * const pamP);
 
@@ -341,6 +354,12 @@ void
 pnm_writepaminit(struct pam * const pamP);
 
 void
+pnm_formatpamtuples(const struct pam * const pamP,
+                    const tuple *      const tuplerow,
+                    unsigned char *    const outbuf,
+                    unsigned int       const nTuple,
+                    unsigned int *     const rowSizeP);
+void
 pnm_formatpamrow(const struct pam * const pamP,
                  const tuple *      const tuplerow,
                  unsigned char *    const outbuf,
@@ -355,6 +374,14 @@ pnm_writepamrowmult(const struct pam * const pamP,
                     unsigned int       const rptcnt);
 
 void
+pnm_writepamrowpart(const struct pam * const pamP,
+                    const tuple *      const tuplerow,
+                    unsigned int       const firstRow,
+                    unsigned int       const firstCol,
+                    unsigned int       const rowCt,
+                    unsigned int       const colCt);
+
+void
 pnm_writepam(struct pam * const pamP, tuple ** const tuplearray);
 
 void
@@ -564,6 +591,10 @@ tuple
 pnm_backgroundtuple(struct pam *  const pamP,
                     tuple      ** const tuples);
 
+tuple
+pnm_backgroundtuplerow(const struct pam * const pamP,
+                       tuple      *       const tuplerow);
+
 /*----------------------------------------------------------------------------
    These are meant for passing to pm_system() as Standard Input feeder
    and Standard Output accepter.
diff --git a/lib/pamdraw.h b/lib/pamdraw.h
index aaa6f20e..03bffbbf 100644
--- a/lib/pamdraw.h
+++ b/lib/pamdraw.h
@@ -65,7 +65,7 @@ typedef struct {
 -----------------------------------------------------------------------------*/
     unsigned int version;
         /* Must be zero.  For future expansion. */
-    pamd_point   begPoint;  
+    pamd_point   begPoint;
     unsigned int legCount;
         /* Number of legs in the path; i.e. size of 'legs' array */
     size_t       legSize;
@@ -111,7 +111,7 @@ pamd_drawproc pamd_point_drawproc;
 
 /* Outline drawing routines.  Lines, splines, circles, etc. */
 
-int 
+int
 pamd_setlinetype(int const type);
 
 #define PAMD_LINETYPE_NORMAL 0
@@ -132,11 +132,11 @@ pamd_setlineclip(int const clip);
 */
 
 void
-pamd_line(tuple **      const tuples, 
-          int           const cols, 
-          int           const rows, 
-          int           const depth, 
-          sample        const maxval, 
+pamd_line(tuple **      const tuples,
+          int           const cols,
+          int           const rows,
+          int           const depth,
+          sample        const maxval,
           pamd_point    const p0,
           pamd_point    const p1,
           pamd_drawproc       drawProc,
@@ -145,11 +145,11 @@ pamd_line(tuple **      const tuples,
     /* Draws a line from p0 to p1.  */
 
 void
-pamd_spline3(tuple **      const tuples, 
-             int           const cols, 
-             int           const rows, 
-             int           const depth, 
-             sample        const maxval, 
+pamd_spline3(tuple **      const tuples,
+             int           const cols,
+             int           const rows,
+             int           const depth,
+             sample        const maxval,
              pamd_point    const p0,
              pamd_point    const p1,
              pamd_point    const p2,
@@ -158,15 +158,15 @@ pamd_spline3(tuple **      const tuples,
 
     /* Draws a three-point spline from p0 to p2, with p1
        as the control point.  All drawing is done via pamd_line(),
-       so the routines that control it control pamd_spline3p() as well. 
+       so the routines that control it control pamd_spline3p() as well.
     */
 
 void
-pamd_polyspline(tuple **      const tuples, 
-                unsigned int  const cols, 
-                unsigned int  const rows, 
-                unsigned int  const depth, 
-                sample        const maxval, 
+pamd_polyspline(tuple **      const tuples,
+                unsigned int  const cols,
+                unsigned int  const rows,
+                unsigned int  const depth,
+                sample        const maxval,
                 pamd_point    const p0,
                 unsigned int  const nc,
                 pamd_point *  const c,
@@ -180,11 +180,11 @@ pamd_polyspline(tuple **      const tuples,
     */
 
 void
-pamd_spline4(tuple **      const tuples, 
-             unsigned int  const cols, 
-             unsigned int  const rows, 
-             unsigned int  const depth, 
-             sample        const maxval, 
+pamd_spline4(tuple **      const tuples,
+             unsigned int  const cols,
+             unsigned int  const rows,
+             unsigned int  const depth,
+             sample        const maxval,
              pamd_point    const endPt0,
              pamd_point    const endPt1,
              pamd_point    const ctlPt0,
@@ -193,13 +193,13 @@ pamd_spline4(tuple **      const tuples,
              const void *  const clientdata);
 
 void
-pamd_circle(tuple **      const tuples, 
-            unsigned int  const cols, 
-            unsigned int  const rows, 
-            unsigned int  const depth, 
-            sample        const maxval, 
+pamd_circle(tuple **      const tuples,
+            unsigned int  const cols,
+            unsigned int  const rows,
+            unsigned int  const depth,
+            sample        const maxval,
             pamd_point    const center,
-            unsigned int  const radius, 
+            unsigned int  const radius,
             pamd_drawproc       drawProc,
             const void *  const clientData);
     /* Draws a circle centered at 'center' with radius 'radius' */
@@ -207,25 +207,25 @@ pamd_circle(tuple **      const tuples,
 /* Simple filling routines.  */
 
 void
-pamd_filledrectangle(tuple **      const tuples, 
-                     int           const cols, 
-                     int           const rows, 
-                     int           const depth, 
-                     sample        const maxval, 
-                     int           const left, 
-                     int           const top, 
-                     int           const width, 
-                     int           const height, 
+pamd_filledrectangle(tuple **      const tuples,
+                     int           const cols,
+                     int           const rows,
+                     int           const depth,
+                     sample        const maxval,
+                     int           const left,
+                     int           const top,
+                     int           const width,
+                     int           const height,
                      pamd_drawproc       drawProc,
                      const void *  const clientdata);
     /* Fills in the rectangle [left, top, width, height]. */
 
 
 void
-pamd_fill_path(tuple **      const tuples, 
-               int           const cols, 
-               int           const rows, 
-               int           const depth, 
+pamd_fill_path(tuple **      const tuples,
+               int           const cols,
+               int           const rows,
+               int           const depth,
                sample        const maxval,
                pamd_path *   const pathP,
                tuple         const color);
@@ -248,11 +248,11 @@ void
 pamd_fill_destroy(struct fillobj * fillObjP);
 
 void
-pamd_fill_drawproc(tuple **     const tuples, 
-                   unsigned int const cols, 
-                   unsigned int const rows, 
-                   unsigned int const depth, 
-                   sample       const maxval, 
+pamd_fill_drawproc(tuple **     const tuples,
+                   unsigned int const cols,
+                   unsigned int const rows,
+                   unsigned int const depth,
+                   sample       const maxval,
                    pamd_point   const p,
                    const void * const clientdata);
     /* Use this drawproc to trace the outline you want filled.  Use
@@ -260,11 +260,11 @@ pamd_fill_drawproc(tuple **     const tuples,
     */
 
 void
-pamd_fill(tuple **         const tuples, 
-          int              const cols, 
-          int              const rows, 
-          int              const depth, 
-          sample           const maxval, 
+pamd_fill(tuple **         const tuples,
+          int              const cols,
+          int              const rows,
+          int              const depth,
+          sample           const maxval,
           struct fillobj * const fillObjP,
           pamd_drawproc          drawProc,
           const void *     const clientdata);
@@ -277,15 +277,15 @@ pamd_fill(tuple **         const tuples,
 /* Text drawing routines. */
 
 void
-pamd_text(tuple**       const tuples, 
-          int           const cols, 
-          int           const rows, 
-          int           const depth, 
-          sample        const maxval, 
+pamd_text(tuple**       const tuples,
+          int           const cols,
+          int           const rows,
+          int           const depth,
+          sample        const maxval,
           pamd_point    const pos,
-          int           const height, 
-          int           const angle, 
-          const char *  const sArg, 
+          int           const height,
+          int           const angle,
+          const char *  const sArg,
           pamd_drawproc       drawProc,
           const void *  const clientdata);
 
@@ -297,12 +297,12 @@ pamd_text(tuple**       const tuples,
     */
 
 void
-pamd_text_box(int          const height, 
-              int          const angle, 
-              const char * const s, 
-              int *        const leftP, 
-              int *        const topP, 
-              int *        const rightP, 
+pamd_text_box(int          const height,
+              int          const angle,
+              const char * const s,
+              int *        const leftP,
+              int *        const topP,
+              int *        const rightP,
               int *        const bottomP);
     /* Calculates the extents box for text drawn by pamd_text with the given
        string, size, and orientation.  Most extent box calculations should use
diff --git a/lib/path.c b/lib/path.c
index 8d53eb9e..3323cf6b 100644
--- a/lib/path.c
+++ b/lib/path.c
@@ -33,7 +33,7 @@
    visited that row, and then remove that entry from the stack.  Note
    that because we go one point at a time, the entry on the stack for
    the row we're at now will always be on the top of stack.
-   
+
    Note that the points on the stack always have consecutive row
    numbers, monotonically increasing or decreasing, whichever is the
    direction we started out in.
@@ -131,7 +131,7 @@ ppmd_pathbuilder_setLegArray(ppmd_pathbuilder * const pathBuilderP,
         pm_error("Leg array pointer is null");
 
     pathBuilderP->legsAreAutoAllocated = false;
-    
+
     pathBuilderP->legsAllocSize = legCount;
 
     pathBuilderP->path.legs = legs;
@@ -164,7 +164,7 @@ ppmd_pathbuilder_setBegPoint(ppmd_pathbuilder * const pathBuilderP,
                              ppmd_point         const begPoint) {
 
     pathBuilderP->path.begPoint = begPoint;
-    
+
     pathBuilderP->begIsSet = true;
 }
 
@@ -183,11 +183,11 @@ ppmd_pathbuilder_addLineLeg(ppmd_pathbuilder * const pathBuilderP,
             pathBuilderP->legsAllocSize =
                 MAX(16, pathBuilderP->legsAllocSize * 2);
 
-            REALLOCARRAY(pathBuilderP->path.legs, 
+            REALLOCARRAY(pathBuilderP->path.legs,
                          pathBuilderP->legsAllocSize);
 
             if (pathBuilderP->path.legs == NULL)
-                pm_error("Unable to allocate memory for %u legs", 
+                pm_error("Unable to allocate memory for %u legs",
                          pathBuilderP->legsAllocSize);
         } else
             pm_error("Out of space in user-supplied legs array "
@@ -252,7 +252,7 @@ isOnLineSeg(ppmd_point const here,
         here.y <= MAX(begPoint.y, endPoint.y) &&
         here.x >= MIN(begPoint.x, endPoint.x) &&
         here.x <= MAX(begPoint.x, endPoint.x);
-}    
+}
 
 
 
@@ -496,13 +496,13 @@ fillPoint(fillStack * const stackP,
     } else {
         if (againstStackDirection(stackP, point))
             popStack(stackP);
-        
+
         if (stackIsEmpty(stackP)) {
             reverseStackDirection(stackP);
             pushStack(stackP, point);
         } else {
             assert(isLateralFromTopOfStack(stackP, point));
-            
+
             drawFillLine(topOfStack(stackP), point, pixels, color);
             replaceTopOfStack(stackP, point);
         }
@@ -539,7 +539,7 @@ fillLeg(ppmd_point  const begPoint,
         ppmd_point here;
 
         here = begPoint;
-    
+
         while (here.y != endPoint.y) {
             here.y += step;
             here.x = ROUNDU(begPoint.x + vertDisp(begPoint, here) * invSlope);
@@ -554,9 +554,9 @@ fillLeg(ppmd_point  const begPoint,
 
 
 void
-ppmd_fill_path(pixel **          const pixels, 
-               int               const cols, 
-               int               const rows, 
+ppmd_fill_path(pixel **          const pixels,
+               int               const cols,
+               int               const rows,
                pixval            const maxval,
                const ppmd_path * const pathP,
                pixel             const color) {
diff --git a/lib/pbm.h b/lib/pbm.h
index 27fd1163..57ab3812 100644
--- a/lib/pbm.h
+++ b/lib/pbm.h
@@ -47,6 +47,19 @@ pbm_allocrow(unsigned int const cols);
   ((bit**) pm_allocarray(cols, rows, sizeof(bit)))
 #define pbm_freearray(bits, rows) pm_freearray((char**) bits, rows)
 #define pbm_freerow(bitrow) pm_freerow((char*) bitrow)
+
+/* Beware of arithmetic overflows when using pbm_packed_bytes(),
+   pbm_allocrow_packed() and pbm_allocarray_packed().
+
+   When cols is signed int, pbm_packed_bytes(cols + 8) overflows
+   with large values.   Same with pamP->width which is always signed int.
+
+   Function validateComputableSize() called by pbm_readpbminit()
+   provides a margin of 10, but the "+7" uses much of it.
+
+   To prevent overflows, cast cols or pamP->width to unsigned int
+   like this: pbm_packed_bytes((unsigned int) cols +8))
+*/
 #define pbm_packed_bytes(cols) (((cols)+7)/8)
 #define pbm_allocrow_packed(cols) \
     ((unsigned char *) pm_allocrow(pbm_packed_bytes(cols), \
diff --git a/lib/pm.h b/lib/pm.h
index 3fc92fb4..62ad5355 100644
--- a/lib/pm.h
+++ b/lib/pm.h
@@ -111,13 +111,16 @@ extern int pm_plain_output;
 extern const char * pm_progname;
 
 void
-pm_init(const char * const progname, unsigned int const flags);
+pm_init(const char * const progname,
+        unsigned int const flags);
 
 void
-pm_proginit(int * const argcP, const char * argv[]);
+pm_proginit(int *         const argcP,
+            const char ** const argv);
 
 void
-pm_setMessage(int const newState, int * const oldStateP);
+pm_setMessage(int   const newState,
+              int * const oldStateP);
 
 int
 pm_getMessage(void);
@@ -137,19 +140,23 @@ pm_make_tmpfile_fd(int *         const fdP,
                    const char ** const filenameP);
 
 void
-pm_nextimage(FILE * const file, int * const eofP);
+pm_nextimage(FILE * const file,
+             int *  const eofP);
 
 /* Variable-sized arrays definitions. */
 
 char**
-pm_allocarray (int const cols, int const rows, int const size );
+pm_allocarray (int const cols,
+               int const rows,
+               int const size );
 
 void *
 pm_allocrow(unsigned int const cols,
             unsigned int const size);
 
 void
-pm_freearray (char** const its, int const rows);
+pm_freearray (char ** const its,
+              int     const rows);
 
 void
 pm_freerow(void * const row);
@@ -380,12 +387,25 @@ pm_getline(FILE *   const ifP,
            int *    const eofP,
            size_t * const lineLenP);
 
+void
+pm_readfile(FILE *                 const fileP,
+            const unsigned char ** const bytesP,
+            size_t *               const szP);
+
+void
+pm_writefile(FILE *                const fileP,
+             const unsigned char * const bytes,
+             size_t                const sz);
+
 short
 pm_bs_short(short const s);
 
 long
 pm_bs_long(long const l);
 
+int
+pm_is_seekable(FILE * const fileP);
+
 unsigned int
 pm_tell(FILE * const fileP);
 
@@ -400,7 +420,8 @@ pm_seek2(FILE *             const fileP,
          unsigned int       const fileposSize);
 
 void
-pm_seek(FILE * const fileP, unsigned long filepos);
+pm_seek(FILE *        const fileP,
+        unsigned long const filepos);
 
 enum pm_check_code {
     PM_CHECK_OK,
@@ -437,6 +458,9 @@ pm_parse_width(const char * const arg);
 unsigned int
 pm_parse_height(const char * const arg);
 
+unsigned int
+pm_parse_maxval(const char * const arg);
+
 #ifdef __cplusplus
 }
 #endif
diff --git a/lib/pm_system.h b/lib/pm_system.h
index 58e17f05..5cfc50cf 100644
--- a/lib/pm_system.h
+++ b/lib/pm_system.h
@@ -101,6 +101,18 @@ void
 pm_accept_to_memory(int    const pipetosuckFd,
                     void * const accepterParm);
 
+void
+pm_feed_from_file(int    const pipeToFeedFd,
+                  void * const feederParm);
+
+void
+pm_accept_to_file(int    const pipetosuckFd,
+                  void * const accepterParm);
+
+void
+pm_accept_to_filestream(int    const pipetosuckFd,
+                        void * const accepterParm);
+
 #ifdef __cplusplus
 }
 #endif
diff --git a/lib/pmfileio.c b/lib/pmfileio.c
index 4048e74d..65d61dff 100644
--- a/lib/pmfileio.c
+++ b/lib/pmfileio.c
@@ -452,27 +452,16 @@ pm_tmpfile_fd(void) {
 }
 
 
-
-FILE *
-pm_openr_seekable(const char name[]) {
+static bool
+isSeekable(FILE * const fP) {
 /*----------------------------------------------------------------------------
-  Open the file named by name[] such that it is seekable (i.e. it can be
-  rewound and read in multiple passes with fseek()).
+   The file is seekable -- we can set its read/write position to anything we
+   want.
 
-  If the file is actually seekable, this reduces to the same as
-  pm_openr().  If not, we copy the named file to a temporary file
-  and return that file's stream descriptor.
-
-  We use a file that the operating system recognizes as temporary, so
-  it picks the filename and deletes the file when Caller closes it.
+   If we can't tell if it is seekable, we return false.
 -----------------------------------------------------------------------------*/
-    int stat_rc;
-    int seekable;  /* logical: file is seekable */
+    int statRc;
     struct stat statbuf;
-    FILE * original_file;
-    FILE * seekable_file;
-
-    original_file = pm_openr((char *) name);
 
     /* I would use fseek() to determine if the file is seekable and
        be a little more general than checking the type of file, but I
@@ -486,41 +475,62 @@ pm_openr_seekable(const char name[]) {
        some other file is, it doesn't hurt much to assume it isn't.
     */
 
-    stat_rc = fstat(fileno(original_file), &statbuf);
-    if (stat_rc == 0 && S_ISREG(statbuf.st_mode))
-        seekable = TRUE;
-    else
-        seekable = FALSE;
+    statRc = fstat(fileno(fP), &statbuf);
+
+    return statRc == 0 && S_ISREG(statbuf.st_mode);
+}
+
 
-    if (seekable) {
-        seekable_file = original_file;
+
+FILE *
+pm_openr_seekable(const char name[]) {
+/*----------------------------------------------------------------------------
+  Open the file named by name[] such that it is seekable (i.e. it can be
+  rewound and read in multiple passes with fseek()).
+
+  If the file is actually seekable, this reduces to the same as
+  pm_openr().  If not, we copy the named file to a temporary file
+  and return that file's stream descriptor.
+
+  We use a file that the operating system recognizes as temporary, so
+  it picks the filename and deletes the file when Caller closes it.
+-----------------------------------------------------------------------------*/
+    FILE * originalFileP;
+    FILE * seekableFileP;
+
+    originalFileP = pm_openr((char *) name);
+
+    if (isSeekable(originalFileP)) {
+        seekableFileP = originalFileP;
     } else {
-        seekable_file = pm_tmpfile();
+        seekableFileP = pm_tmpfile();
 
         /* Copy the input into the temporary seekable file */
-        while (!feof(original_file) && !ferror(original_file)
-               && !ferror(seekable_file)) {
+        while (!feof(originalFileP) && !ferror(originalFileP)
+               && !ferror(seekableFileP)) {
             char buffer[4096];
-            int bytes_read;
-            bytes_read = fread(buffer, 1, sizeof(buffer), original_file);
-            fwrite(buffer, 1, bytes_read, seekable_file);
+            size_t nBytesRead;
+
+            nBytesRead = fread(buffer, 1, sizeof(buffer), originalFileP);
+            fwrite(buffer, 1, nBytesRead, seekableFileP);
         }
-        if (ferror(original_file))
+        if (ferror(originalFileP))
             pm_error("Error reading input file into temporary file.  "
                      "Errno = %s (%d)", strerror(errno), errno);
-        if (ferror(seekable_file))
+        if (ferror(seekableFileP))
             pm_error("Error writing input into temporary file.  "
                      "Errno = %s (%d)", strerror(errno), errno);
-        pm_close(original_file);
+        pm_close(originalFileP);
         {
-            int seek_rc;
-            seek_rc = fseek(seekable_file, 0, SEEK_SET);
-            if (seek_rc != 0)
+            int seekRc;
+
+            seekRc = fseek(seekableFileP, 0, SEEK_SET);
+            if (seekRc != 0)
                 pm_error("fseek() failed to rewind temporary file.  "
                          "Errno = %s (%d)", strerror(errno), errno);
         }
     }
-    return seekable_file;
+    return seekableFileP;
 }
 
 
@@ -929,6 +939,72 @@ pm_getline(FILE *   const ifP,
 
 
 
+void
+pm_readfile(FILE *                 const fileP,
+            const unsigned char ** const bytesP,
+            size_t *               const szP) {
+
+    unsigned char * buf;
+    size_t allocatedSz;
+    size_t szSoFar;
+    size_t chunkSz;
+    bool eof;
+
+    for (szSoFar = 0, buf = NULL, allocatedSz = 0, chunkSz = 4096,
+             eof = false;
+         !eof; ) {
+
+        size_t bytesReadCt;
+
+        if (szSoFar + chunkSz > allocatedSz) {
+            allocatedSz = szSoFar + chunkSz;
+            REALLOCARRAY(buf, allocatedSz);
+
+            if (!buf) {
+                pm_error("Failed to get memory for %lu byte input buffer",
+                         allocatedSz);
+            }
+        }
+        bytesReadCt = fread(buf + szSoFar, 1, chunkSz, fileP);
+
+        if (ferror(fileP))
+            pm_error("Failed to read input from file");
+
+        szSoFar += bytesReadCt;
+
+        if (bytesReadCt < chunkSz)
+            eof = true;
+        else {
+            /* Double buffer and read size up to 1 MiB */
+            if (szSoFar <= 1024*1024)
+                chunkSz = szSoFar;
+        }
+    }
+
+    *bytesP = buf;
+    *szP    = szSoFar;
+}
+
+
+
+void
+pm_writefile(FILE *                const fileP,
+             const unsigned char * const bytes,
+             size_t                const sz) {
+
+    size_t bytesWrittenCt;
+
+    bytesWrittenCt = fwrite(bytes, 1, sz, fileP);
+
+    if (bytesWrittenCt != sz) {
+        pm_error("Failed to write %lu bytes to Standard Output.  "
+                 "%lu bytes successfully written",
+                 sz, bytesWrittenCt);
+    }
+}
+
+
+
 union cheat {
     uint32_t l;
     short s;
@@ -968,6 +1044,20 @@ pm_bs_long(long const l) {
 
 
 
+int
+pm_is_seekable(FILE * const fP) {
+
+    return isSeekable(fP) ? 1 : 0;
+}
+
+
+
+#pragma GCC diagnostic push
+#pragma GCC diagnostic ignored "-Wpragmas"
+#pragma GCC diagnostic ignored "-Wduplicated-cond"
+
+
+
 void
 pm_tell2(FILE *       const fileP,
          void *       const fileposP,
@@ -1008,6 +1098,10 @@ pm_tell2(FILE *       const fileP,
 
 
 
+#pragma GCC diagnostic pop
+
+
+
 unsigned int
 pm_tell(FILE * const fileP) {
 
@@ -1020,6 +1114,12 @@ pm_tell(FILE * const fileP) {
 
 
 
+#pragma GCC diagnostic push
+#pragma GCC diagnostic ignored "-Wpragmas"
+#pragma GCC diagnostic ignored "-Wduplicated-cond"
+
+
+
 void
 pm_seek2(FILE *             const fileP,
          const pm_filepos * const fileposP,
@@ -1047,8 +1147,13 @@ pm_seek2(FILE *             const fileP,
 
 
 
+#pragma GCC diagnostic pop
+
+
+
 void
-pm_seek(FILE * const fileP, unsigned long filepos) {
+pm_seek(FILE *        const fileP,
+        unsigned long const filepos) {
 /*----------------------------------------------------------------------------
 -----------------------------------------------------------------------------*/
 
@@ -1062,7 +1167,8 @@ pm_seek(FILE * const fileP, unsigned long filepos) {
 
 
 void
-pm_nextimage(FILE * const file, int * const eofP) {
+pm_nextimage(FILE * const file,
+             int *  const eofP) {
 /*----------------------------------------------------------------------------
    Position the file 'file' to the next image in the stream, assuming it is
    now positioned just after the current image.  I.e. read off any white
diff --git a/lib/pnm.h b/lib/pnm.h
index a8aad161..fd262566 100644
--- a/lib/pnm.h
+++ b/lib/pnm.h
@@ -136,6 +136,9 @@ pnm_invertxel(xel *  const x,
               xelval const maxval,
               int    const format);
 
+const char *
+pnm_formattypenm(int const format);
+
 void
 pnm_promoteformat(xel** xels, int cols, int rows, xelval maxval, int format,
                   xelval newmaxval, int newformat);
diff --git a/lib/ppm.h b/lib/ppm.h
index 9fc90bb3..9fa547fe 100644
--- a/lib/ppm.h
+++ b/lib/ppm.h
@@ -161,6 +161,36 @@ ppm_colorname(const pixel* const colorP,
               pixval       const maxval,
               int          const hexok);
 
+typedef struct {
+    unsigned int version;
+    const char ** name;
+        /* malloced, and each entry malloced.  Has space for at least 'size'
+           entries.  May be null if size == 0
+        */
+    pixel * color;       /* malloced */
+        /* malloced.  Has space for at least 'size' entries.  May be null if
+           size == 0
+        */
+    unsigned int size;
+        /* allocated size of 'name' and 'color'.  At least 'count' */
+    unsigned int count;
+        /* number of entries used.*/
+    colorhash_table cht;
+        /* Hash table mapping name[] to color[] */
+} ppm_ColorDict;
+
+ppm_ColorDict *
+ppm_colorDict_new(const char * const fileName,
+                  int          const mustOpen);
+
+void
+ppm_colorDict_destroy(ppm_ColorDict * colorDictP);
+
+void
+ppm_readcolordict2(const char *     const fileName,
+                   int              const mustOpen,
+                   ppm_ColorDict ** const colorDictP);
+
 void
 ppm_readcolordict(const char *      const fileName,
                   int               const mustOpen,
@@ -185,9 +215,9 @@ ppm_freecolornames(const char ** const colornames);
 
 #define PPM_DEPTH(newp,p,oldmaxval,newmaxval) \
     PPM_ASSIGN( (newp), \
-	( (int) PPM_GETR(p) * (newmaxval) + (oldmaxval) / 2 ) / (oldmaxval), \
-	( (int) PPM_GETG(p) * (newmaxval) + (oldmaxval) / 2 ) / (oldmaxval), \
-	( (int) PPM_GETB(p) * (newmaxval) + (oldmaxval) / 2 ) / (oldmaxval) )
+        ( (int) PPM_GETR(p) * (newmaxval) + (oldmaxval) / 2 ) / (oldmaxval), \
+        ( (int) PPM_GETG(p) * (newmaxval) + (oldmaxval) / 2 ) / (oldmaxval), \
+        ( (int) PPM_GETB(p) * (newmaxval) + (oldmaxval) / 2 ) / (oldmaxval) )
 
 #define PPM_SQR(x) (x)*(x)
 
diff --git a/lib/ppmdfont.c b/lib/ppmdfont.c
index f64cd10f..d2be215d 100644
--- a/lib/ppmdfont.c
+++ b/lib/ppmdfont.c
@@ -63,7 +63,7 @@ readCharacter(FILE *              const ifP,
 static void
 readFontHeader(FILE *                   const ifP,
                struct ppmd_fontHeader * const fontHeaderP) {
-    
+
     size_t rc;
 
     rc = fread(&fontHeaderP->signature, 1, sizeof(fontHeaderP->signature),
@@ -135,7 +135,7 @@ ppmd_free_font(const struct ppmd_font * const fontP) {
     for (relativeCodePoint = 0;
          relativeCodePoint < fontP->header.characterCount;
          ++relativeCodePoint) {
-        
+
         free((void*)fontP->glyphTable[relativeCodePoint].commandList);
     }
     free((void*)fontP->glyphTable);
diff --git a/lib/ppmdfont.h b/lib/ppmdfont.h
index 329386ff..aa220dc0 100644
--- a/lib/ppmdfont.h
+++ b/lib/ppmdfont.h
@@ -10,10 +10,10 @@
         struct ppmd_glyphHeader glyphHeader;
         struct ppmd_glyphCommand glyphCommand[N];
     } glyph[M]
-    
+
     Where:
         M is fontHeader.characterCount
-        N is glyphHeader.commandCount   
+        N is glyphHeader.commandCount
 
     glyph[i] is the glyph for code point Q,
       where i = Q - fontHeader.firstCodePoint
diff --git a/lib/ppmdraw.h b/lib/ppmdraw.h
index 5fd4148c..b2c4b5d5 100644
--- a/lib/ppmdraw.h
+++ b/lib/ppmdraw.h
@@ -69,7 +69,7 @@ typedef struct {
 -----------------------------------------------------------------------------*/
     unsigned int version;
         /* Must be zero.  For future expansion. */
-    ppmd_point   begPoint;  
+    ppmd_point   begPoint;
     unsigned int legCount;
         /* Number of legs in the path; i.e. size of 'legs' array */
     size_t       legSize;
@@ -94,7 +94,7 @@ typedef struct {
         /* User has set path.begPoint.  If this is false, path.begPoint is
            meaningless.
         */
-    
+
     unsigned int legsAllocSize;
         /* How many legs of space is allocated in the leg array path.legs */
 
@@ -103,7 +103,7 @@ typedef struct {
            ppmd_path_addlineline(), as opposed to being supplied by the
            user as part of initializing this structure, never to be altered.
         */
-    
+
 } ppmd_pathbuilder;
 
 ppmd_pathbuilder *
@@ -166,7 +166,7 @@ ppmd_drawproc ppmd_point_drawproc;
 
 /* Outline drawing routines.  Lines, splines, circles, etc. */
 
-int 
+int
 ppmd_setlinetype(int const type);
 
 #define PPMD_LINETYPE_NORMAL 0
@@ -187,10 +187,10 @@ ppmd_setlineclip(int const clip);
 */
 
 void
-ppmd_linep(pixel **       const pixels, 
-           int            const cols, 
-           int            const rows, 
-           pixval         const maxval, 
+ppmd_linep(pixel **       const pixels,
+           int            const cols,
+           int            const rows,
+           pixval         const maxval,
            ppmd_point     const p0,
            ppmd_point     const p1,
            ppmd_drawprocp       drawProc,
@@ -199,23 +199,23 @@ ppmd_linep(pixel **       const pixels,
     /* Draws a line from p0 to p1.  */
 
 void
-ppmd_line(pixel**       const pixels, 
-          int           const cols, 
-          int           const rows, 
-          pixval        const maxval, 
-          int           const x0, 
-          int           const y0, 
-          int           const x1, 
-          int           const y1, 
+ppmd_line(pixel**       const pixels,
+          int           const cols,
+          int           const rows,
+          pixval        const maxval,
+          int           const x0,
+          int           const y0,
+          int           const x1,
+          int           const y1,
           ppmd_drawproc       drawproc,
           const void *  const clientdata);
     /* Draws a line from (x0, y0) to (x1, y1). */
 
 void
-ppmd_spline3p(pixel **       const pixels, 
-              int            const cols, 
-              int            const rows, 
-              pixval         const maxval, 
+ppmd_spline3p(pixel **       const pixels,
+              int            const cols,
+              int            const rows,
+              pixval         const maxval,
               ppmd_point     const p0,
               ppmd_point     const p1,
               ppmd_point     const p2,
@@ -224,28 +224,28 @@ ppmd_spline3p(pixel **       const pixels,
 
     /* Draws a three-point spline from p0 to p2, with p1
        as the control point.  All drawing is done via ppmd_linep(),
-       so the routines that control it control ppmd_spline3p() as well. 
+       so the routines that control it control ppmd_spline3p() as well.
     */
 
 void
-ppmd_spline3(pixel **      const pixels, 
-             int           const cols, 
-             int           const rows, 
-             pixval        const maxval, 
-             int           const x0, 
-             int           const y0, 
-             int           const x1, 
-             int           const y1, 
-             int           const x2, 
-             int           const y2, 
+ppmd_spline3(pixel **      const pixels,
+             int           const cols,
+             int           const rows,
+             pixval        const maxval,
+             int           const x0,
+             int           const y0,
+             int           const x1,
+             int           const y1,
+             int           const x2,
+             int           const y2,
              ppmd_drawproc       drawproc,
              const void *  const clientdata);
 
 void
-ppmd_polysplinep(pixel **       const pixels, 
-                 unsigned int   const cols, 
-                 unsigned int   const rows, 
-                 pixval         const maxval, 
+ppmd_polysplinep(pixel **       const pixels,
+                 unsigned int   const cols,
+                 unsigned int   const rows,
+                 pixval         const maxval,
                  ppmd_point     const p0,
                  unsigned int   const nc,
                  ppmd_point *   const c,
@@ -259,25 +259,25 @@ ppmd_polysplinep(pixel **       const pixels,
     */
 
 void
-ppmd_polyspline(pixel **     const pixels, 
-                int          const cols, 
-                int          const rows, 
-                pixval       const maxval, 
-                int          const x0, 
-                int          const y0, 
-                int          const nc, 
-                int *        const xc, 
-                int *        const yc, 
-                int          const x1, 
-                int          const y1, 
+ppmd_polyspline(pixel **     const pixels,
+                int          const cols,
+                int          const rows,
+                pixval       const maxval,
+                int          const x0,
+                int          const y0,
+                int          const nc,
+                int *        const xc,
+                int *        const yc,
+                int          const x1,
+                int          const y1,
                 ppmd_drawproc      drawProc,
                 const void * const clientdata);
 
 void
-ppmd_spline4p(pixel **       const pixels, 
-              unsigned int   const cols, 
-              unsigned int   const rows, 
-              pixval         const maxval, 
+ppmd_spline4p(pixel **       const pixels,
+              unsigned int   const cols,
+              unsigned int   const rows,
+              pixval         const maxval,
               ppmd_point     const endPt0,
               ppmd_point     const endPt1,
               ppmd_point     const ctlPt0,
@@ -286,24 +286,24 @@ ppmd_spline4p(pixel **       const pixels,
               const void *   const clientdata);
 
 void
-ppmd_circlep(pixel **       const pixels, 
-             unsigned int   const cols, 
-             unsigned int   const rows, 
-             pixval         const maxval, 
+ppmd_circlep(pixel **       const pixels,
+             unsigned int   const cols,
+             unsigned int   const rows,
+             pixval         const maxval,
              ppmd_point     const center,
-             unsigned int   const radius, 
+             unsigned int   const radius,
              ppmd_drawprocp       drawProc,
              const void *   const clientData);
     /* Draws a circle centered at 'center' with radius 'radius' */
 
 void
-ppmd_circle(pixel **     const pixels, 
-            int          const cols, 
-            int          const rows, 
-            pixval       const maxval, 
-            int          const cx, 
-            int          const cy, 
-            int          const radius, 
+ppmd_circle(pixel **     const pixels,
+            int          const cols,
+            int          const rows,
+            pixval       const maxval,
+            int          const cx,
+            int          const cy,
+            int          const radius,
             ppmd_drawproc      drawProc,
             const void * const clientdata);
 
@@ -311,23 +311,23 @@ ppmd_circle(pixel **     const pixels,
 /* Simple filling routines.  */
 
 void
-ppmd_filledrectangle(pixel **      const pixels, 
-                     int           const cols, 
-                     int           const rows, 
-                     pixval        const maxval, 
-                     int           const x, 
-                     int           const y, 
-                     int           const width, 
-                     int           const height, 
+ppmd_filledrectangle(pixel **      const pixels,
+                     int           const cols,
+                     int           const rows,
+                     pixval        const maxval,
+                     int           const x,
+                     int           const y,
+                     int           const width,
+                     int           const height,
                      ppmd_drawproc       drawproc,
                      const void *  const clientdata );
     /* Fills in the rectangle [x, y, width, height]. */
 
 
 void
-ppmd_fill_path(pixel **          const pixels, 
-               int               const cols, 
-               int               const rows, 
+ppmd_fill_path(pixel **          const pixels,
+               int               const cols,
+               int               const rows,
                pixval            const maxval,
                const ppmd_path * const pathP,
                pixel             const color);
@@ -354,10 +354,10 @@ char *
 ppmd_fill_init(void);
 
 void
-ppmd_fill_drawprocp(pixel **     const pixels, 
-                    unsigned int const cols, 
-                    unsigned int const rows, 
-                    pixval       const maxval, 
+ppmd_fill_drawprocp(pixel **     const pixels,
+                    unsigned int const cols,
+                    unsigned int const rows,
+                    pixval       const maxval,
                     ppmd_point   const p,
                     const void * const clientdata);
     /* Use this drawproc to trace the outline you want filled.  Use
@@ -365,19 +365,19 @@ ppmd_fill_drawprocp(pixel **     const pixels,
     */
 
 void
-ppmd_fill_drawproc(pixel **     const pixels, 
-                   int          const cols, 
-                   int          const rows, 
-                   pixval       const maxval, 
-                   int          const x, 
-                   int          const y, 
+ppmd_fill_drawproc(pixel **     const pixels,
+                   int          const cols,
+                   int          const rows,
+                   pixval       const maxval,
+                   int          const x,
+                   int          const y,
                    const void * const clientdata);
 
 void
-ppmd_fill(pixel **         const pixels, 
-          int              const cols, 
-          int              const rows, 
-          pixval           const maxval, 
+ppmd_fill(pixel **         const pixels,
+          int              const cols,
+          int              const rows,
+          pixval           const maxval,
           struct fillobj * const fh,
           ppmd_drawproc          drawProc,
           const void *     const clientdata);
@@ -390,27 +390,27 @@ ppmd_fill(pixel **         const pixels,
 /* Text drawing routines. */
 
 void
-ppmd_textp(pixel**        const pixels, 
-           int            const cols, 
-           int            const rows, 
-           pixval         const maxval, 
+ppmd_textp(pixel**        const pixels,
+           int            const cols,
+           int            const rows,
+           pixval         const maxval,
            ppmd_point     const pos,
-           int            const height, 
-           int            const angle, 
-           const char *   const sArg, 
+           int            const height,
+           int            const angle,
+           const char *   const sArg,
            ppmd_drawprocp       drawProc,
            const void *   const clientdata);
 
 void
-ppmd_text(pixel**       const pixels, 
-          int           const cols, 
-          int           const rows, 
-          pixval        const maxval, 
-          int           const xpos, 
-          int           const ypos, 
-          int           const height, 
-          int           const angle, 
-          const char *  const sArg, 
+ppmd_text(pixel**       const pixels,
+          int           const cols,
+          int           const rows,
+          pixval        const maxval,
+          int           const xpos,
+          int           const ypos,
+          int           const height,
+          int           const angle,
+          const char *  const sArg,
           ppmd_drawproc       drawProc,
           const void *  const clientdata);
 /* Draws the null-terminated string 's' left justified at the point
@@ -421,12 +421,12 @@ ppmd_text(pixel**       const pixels,
 */
 
 void
-ppmd_text_box(int          const height, 
-              int          const angle, 
-              const char * const s, 
-              int *        const leftP, 
-              int *        const topP, 
-              int *        const rightP, 
+ppmd_text_box(int          const height,
+              int          const angle,
+              const char * const s,
+              int *        const leftP,
+              int *        const topP,
+              int *        const rightP,
               int *        const bottomP);
 /* Calculates the extents box for text drawn by ppm_text with the given
    string, size, and orientation.  Most extent box calculations should use
diff --git a/lib/ppmfloyd.h b/lib/ppmfloyd.h
deleted file mode 100644
index 264fc0b6..00000000
--- a/lib/ppmfloyd.h
+++ /dev/null
@@ -1,69 +0,0 @@
-/* These declarations were supposed to be in the libfloyd.h file in the ilbm
-   package, but that file was missing, so I made them up myself.  
-   - Bryan 01.03.10.
-*/
-
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-#if 0
-} /* to fake out automatic code indenters */
-#endif
-
-struct ppm_fs_info {
-    /* thisXerr and nextXerr are dynamically allocated arrays each of whose
-       dimension is the width of the image plus 2
-       */
-    long * thisrederr;
-    long * thisgreenerr;
-    long * thisblueerr;
-    long * nextrederr;
-    long * nextgreenerr;
-    long * nextblueerr;
-    int lefttoright;
-    int cols;
-    pixval maxval;
-    int flags;
-    pixel * pixrow;
-    int col_end;
-    pixval red, green, blue;
-};
-
-typedef struct ppm_fs_info ppm_fs_info;
-
-/* Bitmasks for ppm_fs_info.flags */
-#define FS_RANDOMINIT 0x01
-#define FS_ALTERNATE  0x02
-
-ppm_fs_info *
-ppm_fs_init(unsigned int const cols,
-            pixval       const maxval,
-            unsigned int const flags);
-
-void
-ppm_fs_free(ppm_fs_info *fi);
-
-int
-ppm_fs_startrow(ppm_fs_info *fi, pixel *pixrow);
-
-int
-ppm_fs_next(ppm_fs_info *fi, int col);
-
-void
-ppm_fs_endrow(ppm_fs_info *fi);
-
-void
-ppm_fs_update(    ppm_fs_info *fi, int col, pixel *pP);
-
-
-void
-ppm_fs_update3(ppm_fs_info * const fi, 
-               int           const col, 
-               pixval        const r, 
-               pixval        const g, 
-               pixval        const b);
-
-#ifdef __cplusplus
-}
-#endif
diff --git a/lib/rgb.txt b/lib/rgb.txt
index 28231080..90c73024 100644
--- a/lib/rgb.txt
+++ b/lib/rgb.txt
@@ -2,12 +2,17 @@
 # order.  Some color names are defined multiple times, and sometimes
 # with different colors.  Many colors have multiple names.
 
-# - Netpbm originals
+# When Netpbm interprets this dictionary, it recognizes the first definition
+# of a particular color name and the first definition of a particular color
+# definition.  (That means the function is not reversible).
+
 # - Crayola crayons, as determined by John Thomas at Tektronix
 # - Hollasch at Microsoft Research
 # - HTML 4.0
 # - Some HTML extension that Internet Explorer understands
 # - XFree86 rgb.txt ca. 2001, derived from MIT X11
+# - Netpbm originals
+# - Resene paint colors, 2010
 
 # More details on the sources are above each group.
 
@@ -35,7 +40,7 @@
 255 255   0 Yellow
 255 138   0 Orange
 159 211   0 GreenYellow
-  0 255 159 Spring Green
+  0 255 159 SpringGreen
   0 138 255 SkyBlue
 148   0 211 Violet
 255   0 148 VioletRed
@@ -143,7 +148,7 @@
 128 128 105 WarmGrey
   0   0   0 Black
  41  36  33 IvoryBlack
- 46  71  59 Lamp Black
+ 46  71  59 LampBlack
 227  38  54 AlizarinCrimson
 156 102  31 Brick
 227  23  13 CadmiumRedDeep
@@ -335,7 +340,7 @@
 112 128 144 SlateGray
 119 136 153 LightSlateGray
 119 136 153 LightSlateGrey
-211 211 211 light grey
+211 211 211 LightGrey
 100 149 237 CornflowerBlue
 132 112 255 LightSlateBlue
   0 191 255 DeepSkyBlue
@@ -889,3 +894,1412 @@
 
 # These were more or less invented for use with Netpbm:
 255 255 255  D65
+
+# The following is from
+# http://people.csail.mit.edu/jaffer/Color/Resene-2010-rgb.txt
+# on 24.03.31
+
+# Resene RGB Values List
+# For further information refer to http://www.resene.co.nz
+# Copyright Resene Paints Ltd 2001
+#
+# Permission to copy this dictionary, to modify it, to redistribute it,
+# to distribute modified versions, and to use it for any purpose is
+# granted, subject to the following restrictions and understandings.
+#
+# 1. Any text copy made of this dictionary must include this copyright
+# notice in full.
+#
+# 2. Any redistribution in binary form must reproduce this copyright
+# notice in the documentation or other materials provided with the
+# distribution.
+#
+# 3. Resene Paints Ltd makes no warranty or representation that this
+# dictionary is error-free, and is under no obligation to provide any
+# services, by way of maintenance, update, or otherwise.
+#
+# 4. There shall be no use of the name of Resene or Resene Paints Ltd
+# in any advertising, promotional, or sales literature without prior
+# written consent in each case.
+#
+# 5. These RGB colour formulations may not be used to the detriment of
+# Resene Paints Ltd.
+#
+ 36  83  54		kaitokegreen
+ 27  75  53		countygreen
+ 23  70  46		zuccini
+ 29  57  60		nordic
+  0  73  78		sherpablue
+ 37  72  85		tealblue
+ 53  81  79		bluedianne
+ 49  70  67		firefly
+ 44  70  65		gablegreen
+ 39  63  65		daintree
+ 24  67  67		tiber
+ 15  70  69		cyprus
+ 25  68  60		deepteal
+ 32  72  63		zydeco
+ 27  70  54		sherwoodgreen
+ 39  66  52		englishholly
+ 38  67  52		everglade
+ 37  70  54		bottlegreen
+ 37  70  54		bush
+ 35  69  55		burnham
+ 43  63  54		celtic
+ 50  67  54		timbergreen
+ 51  66  49		forestgreen
+ 43  75  64		tepapagreen
+ 52  83  61		goblin
+ 58  69  49		mallard
+ 54  72  47		palmleaf
+ 55  65  42		seaweed
+ 53  63  42		olivegreen
+ 25  57  37		deepfir
+ 27  52  39		cardingreen
+ 32  57  44		palmgreen
+ 37  52  43		holly
+ 35  46  38		blackbean
+ 41  51  43		gordonsgreen
+ 44  50  39		blackforest
+ 42  47  35		pinetree
+ 47  49  37		huntergreen
+ 45  47  40		eternity
+ 43  46  37		rangoongreen
+ 43  46  38		marshland
+ 44  45  36		greenwaterloo
+ 45  45  36		karaka
+ 52  50  45		banjul
+ 53  49  44		acadia
+ 55  49  43		darkebony
+ 57  50  39		creole
+ 56  52  40		graphite
+ 51  44  34		blackmagic
+ 51  44  34		cannonblack
+ 53  40  30		cocoabrown
+ 60  47  35		cola
+ 59  46  37		sambuca
+ 60  52  46		treehouse
+ 61  50  44		deepoak
+ 58  47  45		sepia
+ 54  45  38		coffeebean
+ 54  45  38		cubantan
+ 54  45  38		marlin
+ 48  38  33		woodbark
+ 42  41  34		asphalt
+ 42  41  34		maire
+ 41  41  36		junglegreen
+ 70  54  35		clinker
+ 70  54  41		woodburn
+ 65  54  40		jackobean
+ 63  55  38		birch
+ 63  54  35		mikado
+ 73  63  47		ashbrown
+ 72  65  43		onion
+ 71  62  35		madras
+ 57  61  42		greenkelp
+ 69  64  43		woodrush
+ 76  78  49		waiouru
+ 79  77  50		camouflage
+ 84  78  49		thatchgreen
+ 83  73  49		punga
+ 81  65  45		deepbronze
+ 75  65  42		tumbleweed
+ 85  74  60		metallicbronze
+ 79  64  55		paco
+ 75  67  59		spaceshuttle
+ 74  75  70		gravel
+ 70  71  62		heavymetal
+ 57  62  46		logcabin
+ 61  64  49		scrub
+ 58  65  51		rangitoto
+ 57  57  44		elpaso
+ 58  55  46		touchwood
+ 60  55  49		blackpepper
+ 63  55  46		blackwood
+ 68  54  45		tobago
+ 66  52  43		slugger
+ 69  54  43		darkrum
+ 73  59  47		bronze
+ 71  59  47		englishwalnut
+ 63  57  57		eclipse
+ 70  61  62		jon
+ 52  54  58		shark
+ 54  56  60		vulcan
+ 60  61  62		balticsea
+ 57  59  60		montana
+ 60  59  60		fuscousgrey
+ 58  53  50		kilamanjaro
+ 55  63  67		mirage
+ 55  62  65		mineshaft
+ 57  64  67		charade
+ 59  60  56		zeus
+ 69  70  66		tuatara
+ 64  77  73		corduroy
+ 72  74  70		armadillo
+ 77  77  75		thunder
+ 82  75  75		matterhorn
+ 80  73  74		emperor
+ 69  70  71		bleachedcedar
+ 67  70  75		steelgrey
+ 70  73  78		tuna
+ 72  71  83		gunpowder
+ 61  70  83		rhino
+ 60  67  84		bluezodiac
+ 58  78  95		cello
+ 61  75  82		atomic
+ 58  78  88		deepcove
+ 51  64  70		bigstone
+ 37  63  78		nileblue
+ 35  65  78		greenvogue
+ 37  60  72		tarawera
+ 46  55  73		licorice
+ 53  62  79		cloudburst
+ 56  55  64		blackmarlin
+ 55  54  63		revolver
+ 65  61  75		grape
+ 44  45  60		blackrock
+ 44  42  53		haiti
+ 49  42  41		lividbrown
+ 50  44  43		diesel
+ 51  46  46		nightrider
+ 55  51  50		gondola
+ 50  49  46		crowshead
+ 45  48  50		codgrey
+ 41  44  47		bunker
+ 38  43  47		bluecharcoal
+ 44  44  50		bastille
+ 51  52  58		woodybay
+ 49  51  55		ebony
+ 50  52  56		ebonyclay
+ 44  53  57		gunmetal
+ 40  53  58		oxfordblue
+ 37  47  47		swamp
+ 49  51  48		oil
+ 43  50  48		woodsmoke
+ 41  52  50		aztec
+ 36  46  40		midnightmoss
+ 35  47  44		racinggreen
+ 30  52  66		bluewhale
+ 41  55  65		mosaic
+ 36  54  64		elephant
+ 33  48  62		midnight
+ 30  47  60		tangaroa
+ 36  42  46		cinder
+ 30  39  44		blackpearl
+ 30  39  44		bluebark
+ 36  37  43		blackrussian
+ 41  41  47		jaguar
+ 37  37  37		nero
+ 42  39  37		bokaragrey
+ 31  38  59		outerspace
+ 33  38  58		midnightexpress
+ 33  38  58		stratos
+ 25  47  65		prussianblue
+ 43  52  73		bunting
+ 42  52  74		downriver
+ 48  67 106		capri
+ 38  65 107		bondiblue
+ 39  60  90		catalinablue
+ 39  60  90		cobalt
+ 52  63  92		covegrey
+ 52  63  92		gulfblue
+ 47  60  83		biscay
+ 45  60  84		madison
+ 33  69  89		astronautblue
+ 32  63  88		regalblue
+ 39  74  93		arapawa
+ 71  88 119		chambray
+ 68  81 114		astronaut
+ 71  82 110		eastbay
+ 37  89 127		bahamablue
+ 54  92 125		matisse
+ 44  87 120		veniceblue
+ 50  84 130		sttropaz
+ 41  89 139		endeavour
+  0  98 111		bluelagoon
+ 48  92 113		blumine
+ 44  89 113		chathamsblue
+ 37  91 119		orient
+ 31 106 125		allports
+ 61 113 136		calypso
+ 68 121 142		jellybean
+ 55 111 137		astral
+ 73 136 154		hippieblue
+ 61 133 184		curiousblue
+ 49 110 160		lochmara
+ 78 108 157		sanmarino
+ 78 105 154		azure
+ 87 132 193		havelockblue
+ 91 110 145		waikawagrey
+ 87 109 142		kashmirblue
+ 76 107 136		wedgewood
+129 124 135		topaz
+122 118 121		monsoon
+119 118 114		dovegrey
+116 120 128		stormgrey
+121 132 136		regentgrey
+124 129 124		boulder
+109 120 118		rollingstone
+119 132 142		pigeonpost
+105 125 137		lynch
+100 125 134		hoki
+ 98 119 126		bluebayoux
+104 118 110		sirocco
+102 111 111		nevada
+ 99 109 112		palesky
+102 106 109		midgrey
+111 116 123		raven
+118 115 111		aluminium
+107 106 108		scarpaflow
+124 113 115		empress
+106 104 115		dolphin
+114 114 130		waterloo
+ 96  93 107		smoky
+ 99  99 115		comet
+ 75  90  98		fiord
+ 68  87  97		sanjuan
+ 63  84  90		casal
+ 87  89  93		brightgrey
+ 88  84  82		tundora
+ 86  80  81		mortar
+ 90  79  81		donjuan
+ 78  78  76		shipgrey
+ 78  85  82		capecod
+ 80  85  85		mako
+ 76  83  86		trout
+ 70  83  82		darkslate
+ 79  90  95		pickledbluewood
+ 85  96  97		riverbed
+ 78  96  94		limedspruce
+ 97 102 107		shuttlegrey
+105  98 104		saltbox
+106 100 102		scorpion
+108  94  83		kabul
+110  95  86		dorado
+105  95  80		makara
+101 100  95		stormdust
+ 91 100  82		pickledaspen
+ 91  93  86		chicago
+ 81  87  79		battleshipgrey
+ 89  86  72		millbrook
+ 76  85  68		cabbagepont
+ 79  78  72		merlin
+ 81  79  74		dune
+ 87  83  75		masala
+ 93  89  82		smokeyash
+ 93  83  70		judgegrey
+ 93  78  70		saddle
+ 90  76  66		cork
+ 90  76  66		mash
+ 90  77  65		rock
+ 91  82  68		iroko
+ 85  77  66		mondo
+ 84  79  58		lisbonbrown
+ 84  79  58		panda
+ 77  80  60		kelp
+ 78  85  65		lunargreen
+105 104  75		hemlock
+111  99  75		soyabean
+108  91  76		domino
+117 101  86		pinecone
+114 103  81		coffee
+118 109  82		peat
+122 113  92		pablo
+129 110  92		donkeybrown
+133 113  88		cement
+143 125 107		squirrel
+130 122 103		arrowtown
+128 118  97		stonewall
+134 118 101		sanddune
+138 125 114		americano
+139 126 119		hurricane
+130 127 121		concord
+120 109  95		sandstone
+112 110 102		ironsidegrey
+113 110  97		flint
+103 109  99		limedash
+122 124 118		gunsmoke
+124 124 114		tapa
+120 133 122		bluesmoke
+136 128 100		olivehaze
+139 130 101		granitegreen
+123 120  90		kokoda
+117 120  90		finch
+112 105  80		crocodile
+104 107  80		siam
+ 91 111  85		cactus
+ 99 119  90		axolotl
+ 97 117  91		finlandia
+105 117  92		willowgrove
+117 135 110		xanadu
+ 92 129 115		cuttysark
+ 98 103  70		woodland
+ 79  99  72		tomthumb
+ 82  86  54		greygreen
+ 55  93  79		spectra
+ 62  89  76		plantation
+ 78  93  78		nandor
+ 80  99  85		mineralgreen
+ 64  99  86		stromboli
+ 75  95  86		viridiangreen
+ 57  85  85		oracle
+ 73 101 105		taxbreak
+ 73  98 103		smaltblue
+ 72 108 122		bismark
+ 64 117 119		ming
+ 64 114 109		jade
+ 81 123 120		breakerbay
+ 83 115 111		william
+ 72 128 132		paradiso
+  0 123 119		surfiegreen
+ 41 123 118		elm
+ 49 121 109		genoa
+ 43 121 122		atoll
+ 31  99  97		seagreen
+ 22 100  97		bluestone
+  0  95  91		mosque
+ 38  98  85		eden
+ 32  89  72		aquamarine
+ 38  96  79		eveningsea
+ 48  93  53		parsley
+ 22  91  49		crusoe
+ 38  98  66		greenpea
+ 36 108  70		greenstone
+ 73 118  79		killarney
+ 76 120  92		como
+ 92 138 100		springgreen
+ 56 123  84		amazon
+ 27 138 107		elfgreen
+ 22 126 101		deepsea
+  0 143 112		observatory
+ 23 123  77		salem
+ 19 104  67		jewel
+ 21  99  61		fungreen
+  0 110  78		watercourse
+  0 135 159		easternblue
+ 37 153 178		pelorous
+ 48 142 160		scooter
+ 77 177 200		viking
+ 91 160 208		pictonblue
+ 67 142 172		bostonblue
+ 96 154 184		shakespeare
+111 140 159		bermudagrey
+121 136 171		shipcove
+ 91 137 192		danube
+122 170 224		jordyblue
+147 162 186		rockblue
+164 175 205		echoblue
+138 167 204		poloblue
+102 183 225		malibu
+119 183 208		seagull
+120 177 191		glacier
+140 206 234		anakiwa
+165 206 236		sail
+174 201 235		tropicalblue
+126 205 221		spray
+182 236 222		waterleaf
+111 210 190		downy
+137 217 200		riptide
+146 211 202		aqua
+134 210 193		bermuda
+151 213 179		vistablue
+180 225 187		fringyflower
+157 211 168		chinook
+214 240 205		snowymint
+239 245 209		riceflower
+223 241 214		hintofgreen
+216 240 210		blueromance
+197 231 205		grannyapple
+192 232 213		aeroblue
+215 231 208		peppermint
+222 241 221		tara
+223 240 226		offgreen
+226 242 228		frostedmint
+198 234 221		minttulip
+194 230 236		onahau
+209 234 234		oysterbay
+208 234 232		foam
+203 232 232		mabel
+202 225 217		iceberg
+202 231 226		jaggedice
+206 239 228		hummingbird
+215 238 228		whiteice
+233 238 235		lilywhite
+221 237 233		tranquil
+223 239 234		clearday
+230 242 234		bubbles
+222 227 227		zircon
+216 221 218		mystic
+211 229 239		pattensblue
+210 218 237		hawkesblue
+230 223 231		selago
+231 229 232		whitelilac
+221 220 219		porcelain
+220 221 221		athensgrey
+227 225 224		seashell
+239 230 230		whisper
+238 223 222		softpeach
+238 232 235		magnolia
+233 236 241		solitude
+245 239 235		hintofred
+251 238 232		rosewhite
+242 240 230		alabaster
+244 240 230		romance
+244 234 228		sauvignon
+249 232 226		wisppink
+242 230 221		fantasy
+248 234 223		chardon
+248 235 221		bridalheath
+241 234 215		halfpearllusta
+241 235 218		butterywhite
+241 235 217		orchidwhite
+244 239 224		bianca
+242 237 221		quarterpearllusta
+248 237 219		islandspice
+252 233 215		serenade
+253 239 211		varden
+248 234 202		ginfizz
+247 240 219		apricotwhite
+251 242 219		earlydawn
+251 240 214		halfdutchwhite
+253 239 219		forgetmenot
+249 247 222		chileanheath
+248 246 223		promenade
+250 243 220		offyellow
+241 237 212		rumswizzle
+251 243 211		chinaivory
+245 243 206		moonglow
+248 246 216		whitenectar
+246 245 215		hintofyellow
+235 247 228		panache
+232 243 232		aquaspring
+238 243 229		saltpan
+244 246 236		twilightblue
+238 239 223		sugarcane
+239 236 222		ricecake
+231 242 233		dew
+229 242 231		polar
+223 230 207		willowbrook
+219 229 210		frostee
+222 234 220		applegreen
+218 230 221		swansdown
+219 228 220		aquasqueeze
+224 228 220		catskillwhite
+229 230 223		blacksqueeze
+227 227 220		snowdrift
+229 228 219		blackwhite
+222 221 203		greenwhite
+217 221 213		aquahaze
+217 223 205		gin
+219 224 208		feta
+225 228 197		frost
+225 218 187		coconutcream
+238 231 200		scotchmist
+237 231 200		halfandhalf
+234 227 205		orangewhite
+226 221 199		travertine
+234 218 194		solitaire
+230 219 199		halfspanishwhite
+234 224 200		pearllusta
+245 230 196		pipi
+233 220 190		doublepearllusta
+249 228 197		eggsour
+249 228 198		derby
+245 222 196		sazerac
+225 218 203		albescentwhite
+235 226 210		quarterspanishwhite
+235 225 206		bleachwhite
+235 229 213		cararra
+243 229 220		fairpink
+234 228 220		pampas
+237 231 224		desertstorm
+238 231 220		whitelinen
+236 229 218		soapstone
+233 230 220		narvik
+231 228 222		wildsand
+228 226 220		wanwhite
+233 225 217		springwood
+227 223 217		vistawhite
+224 222 215		blackhaze
+223 221 214		ceramic
+223 221 214		hintofgrey
+223 221 214		seafog
+220 217 205		milkwhite
+225 219 208		merino
+230 214 205		dawnpink
+230 216 212		ebb
+219 208 202		swisscoffee
+223 215 210		bonjour
+220 215 209		gallery
+218 214 204		whitepointer
+215 206 197		swirl
+212 207 197		westar
+217 208 193		blanc
+222 209 198		pearlbush
+230 214 184		rocksalt
+213 203 178		athsspecial
+222 209 183		janna
+222 209 183		spanishwhite
+223 215 189		wheatfield
+219 217 194		loafer
+212 207 180		whiterock
+210 211 179		orinoco
+211 219 203		ottoman
+209 211 204		greynurse
+214 209 192		ecruwhite
+214 209 192		joanna
+210 210 192		celeste
+206 205 184		moonmist
+203 206 192		harp
+191 205 192		pariswhite
+202 199 183		chromewhite
+197 195 176		kangaroo
+191 192 171		kidnapper
+186 192 180		pumice
+186 192 179		tasman
+188 191 168		berylgreen
+208 200 176		parchment
+210 195 163		doublespanishwhite
+207 190 165		softamber
+210 198 182		starkwhite
+203 201 192		quillgrey
+190 189 182		silversand
+194 188 177		cloud
+191 189 193		frenchgrey
+192 191 199		ghost
+195 190 187		paleslate
+205 198 197		alto
+203 205 205		iron
+210 209 205		concrete
+213 210 209		mercury
+221 214 225		titanwhite
+199 205 216		linkwater
+189 186 206		bluehaze
+179 196 216		spindle
+205 213 213		zumthor
+203 208 207		geyser
+184 198 190		nebula
+176 196 196		junglemist
+185 195 190		tiara
+168 195 188		opal
+187 208 201		jetstream
+164 210 224		frenchpass
+160 205 217		regentstblue
+158 209 211		morningglory
+164 220 230		charlotte
+166 213 208		sinbad
+175 227 214		icecold
+180 226 213		cruise
+173 217 209		scandal
+172 201 178		gumleaf
+178 198 177		zanah
+179 193 177		rainee
+195 214 189		surfcrest
+194 213 196		seamist
+193 216 197		edgewater
+184 212 187		surf
+187 205 165		pixiegreen
+189 202 168		paleleaf
+163 189 156		springrain
+139 165 143		envy
+150 167 147		mantle
+143 182 156		summergreen
+154 192 182		shadowgreen
+138 174 164		seanymph
+119 168 171		neptune
+129 166 170		ziggurat
+140 168 160		cascade
+157 180 170		skeptic
+174 187 193		heather
+179 187 183		loblolly
+172 182 178		periglacialblue
+172 174 169		silverchalice
+170 181 184		casper
+160 177 174		conch
+156 172 165		towergrey
+161 169 168		hitgrey
+164 173 176		gullgrey
+146 172 180		botticelli
+147 170 185		nepal
+162 161 172		spunpearl
+165 169 178		mischka
+159 163 167		greychateau
+169 157 157		nobel
+160 159 156		mountainmist
+179 171 182		chatelle
+174 174 173		bombay
+191 179 178		pinkswan
+190 180 171		tide
+191 186 175		cottonseed
+189 186 174		greynickel
+187 173 161		silk
+202 184 162		grainbrown
+204 182 155		vanilla
+201 181 154		sourdough
+197 186 160		sisal
+192 176 147		coral
+190 178 154		akaroa
+191 181 162		tea
+186 183 162		linen
+186 185 169		mistgrey
+190 186 167		ash
+184 181 161		tana
+169 175 153		greenspring
+158 170 158		robinseggblue
+167 166 157		foggygrey
+160 161 151		stardust
+151 164 154		edward
+165 168 143		bud
+170 165 131		neutralgreen
+176 172 148		eagle
+181 172 148		bisonhide
+183 168 163		martini
+176 169 159		cloudy
+162 149 137		zorba
+165 151 132		malta
+167 151 129		bronco
+161 153 134		nomad
+163 152 129		raincloud
+163 154 135		napa
+152 145 113		gurkha
+161 154 127		greyolive
+153 155 149		delta
+159 157 145		dawn
+153 154 134		lemongrass
+135 135 111		schist
+136 137 108		bitter
+135 132 102		bandicoot
+156 141 114		paleoyster
+141 132 120		schooner
+137 132 120		taupegrey
+148 140 126		heatheredgrey
+134 131 122		friargrey
+139 134 133		suvagrey
+135 135 133		jumbo
+159 155 157		shadylady
+147 145 160		greysuit
+153 152 167		santasgrey
+132 156 169		balihai
+146 159 162		powderblue
+140 156 156		submarine
+133 136 133		stack
+129 137 136		oslogrey
+113 143 138		gumbo
+123 148 140		grannysmith
+116 145 142		juniper
+100 136 148		horizon
+105 136 144		gothic
+ 85 143 147		halfbaked
+ 99 146 131		patina
+123 137 118		spanishgreen
+145 160 146		pewter
+110 141 113		laurel
+109 154 120		oxley
+123 177 141		bayleaf
+126 179 148		padua
+117 170 148		acapulco
+116 178 168		gulfstream
+109 175 167		tradewind
+122 197 180		montecarlo
+101 173 178		fountainblue
+ 64 143 144		bluechill
+ 72 144 132		lochinvar
+ 37 151 151		java
+ 95 182 156		keppel
+ 89 186 163		puertorico
+103 190 144		silvertree
+ 41 169 139		niagara
+ 57 159 134		gossamer
+ 50 151  96		eucalyptus
+ 65 159  89		chateaugreen
+ 76 169 115		oceangreen
+133 202 135		deyork
+127 193  92		mantis
+102 179  72		apple
+ 75 163  81		fruitsalad
+ 95 146  40		vidaloca
+136 169  91		chelseacucumber
+122 148  97		highland
+149 152 107		avocado
+152 159 122		sage
+125 157 114		amulet
+132 145  55		wasabi
+146 140  60		highball
+146 140  60		sycamore
+150 132  40		lemonginger
+169 141  54		reefgold
+173 138  59		alpine
+182 150  66		roti
+178 153  75		husk
+174 144  65		turmeric
+171 141  63		luxorgold
+151 151 111		malachitegreen
+163 153 119		canvas
+163 153 119		tallow
+186 171 135		pavlova
+167 160 126		hillary
+199 184 130		yuma
+187 181 141		coriander
+184 173 138		chino
+205 174 112		putty
+198 169  94		laser
+210 185  96		tacha
+185 173  97		gimblet
+175 193 130		caper
+185 184 128		peasoup
+156 166 100		greensmoke
+162 165 128		locust
+164 184 143		norway
+184 202 157		sprout
+191 194 152		greenmist
+189 192 126		pineglade
+227 212 116		wildrice
+204 207 130		deco
+222 203 129		sandwisp
+222 195 113		chenin
+245 205 130		cherokee
+235 200 129		marzipan
+228 195 133		neworleans
+223 194 129		chalky
+221 194 131		zombie
+218 190 130		straw
+220 198 160		raffia
+199 189 149		thistle
+208 195 131		winterhazel
+224 216 167		mintjulep
+216 204 155		tahunasands
+225 213 166		sapling
+233 215 171		beeswax
+233 215 171		colonialwhite
+237 213 166		astra
+235 212 174		givry
+237 210 164		dairycream
+232 212 162		hampton
+228 207 153		doublecolonialwhite
+230 204 154		chamois
+224 200 141		eggwhite
+241 215 158		splash
+246 224 164		buttermilk
+254 224 165		capehoney
+251 229 194		peach
+243 215 182		pinklady
+238 217 182		champagne
+240 223 187		bajawhite
+240 223 187		dutchwhite
+243 229 192		milkpunch
+247 229 183		barleywhite
+233 217 169		sidecar
+242 229 191		halfcolonialwhite
+248 243 196		cornfield
+241 241 198		springsun
+245 245 204		mimosa
+252 237 197		oasis
+255 227 155		creambrulee
+255 214 123		salomie
+249 215 126		goldenglow
+249 228 150		visvis
+248 234 151		picasso
+251 235 155		drover
+249 245 159		paleprim
+248 246 168		shalimar
+244 240 155		portafino
+228 222 142		primrose
+246 244 147		milan
+240 245 144		tidal
+238 242 147		jonquil
+239 248 170		australianmint
+240 245 187		chiffon
+227 229 177		tusk
+245 249 203		carla
+245 244 193		cumulus
+234 247 201		snowflurry
+183 227 168		madang
+159 211 133		gossip
+165 215 133		feijoa
+198 234 128		sulu
+209 239 159		reef
+218 234 111		mindaro
+177 221  82		conifer
+156 208  59		atlantis
+183 197  44		lime
+183 198  26		riogrande
+198 218  54		laspalmas
+194 214  46		fuego
+210 219  50		bitterlemon
+253 227  54		gorse
+235 222  49		goldenfizz
+226 230  77		canary
+251 235  80		parisdaisy
+245 241 113		dolly
+232 237 105		honeysuckle
+236 230 126		texas
+251 240 115		witchhaze
+249 225 118		sweetcorn
+245 204  35		turbo
+241 204  43		goldendream
+238 204  36		broom
+245 215  82		energyyellow
+234 204  74		festival
+218 192  26		sunflower
+240 196  32		moonyellow
+236 189  44		brightsun
+238 192  81		creamcan
+249 208  84		kournikova
+224 193  97		cremedebanane
+234 206 106		goldensand
+240 213  85		portica
+221 203  70		confetti
+228 219  85		manz
+190 202  96		wildwillow
+214 202  61		wattle
+227 221  57		starship
+208 193  23		birdflower
+210 198  31		barberry
+184 167  34		earlsgreen
+196 170  77		sundance
+217 178  32		lemon
+188 155  27		buddhagold
+183 152  38		sahara
+158 128  34		hacienda
+171 154  28		lucky
+142 154  33		citron
+186 192  14		larioja
+169 192  28		bahia
+159 183  10		citrus
+137 172  39		limerick
+180 192  76		celery
+124 159  47		sushi
+ 95 151  39		limeade
+122 172  33		lima
+113 169  29		christi
+ 32 105  55		camarone
+ 44 110  49		sanfelix
+ 47 117  50		japaneselaurel
+ 62 128  39		bilbao
+ 66 137  41		lapalma
+ 95 129  81		gladegreen
+ 96 138  90		hippiegreen
+ 96 124  71		dingley
+ 72 101  49		dell
+ 82 107  45		greenleaf
+ 62  99  52		greenhouse
+ 54  92  52		fern
+ 72  83  26		verdungreen
+ 87  94  46		fernfrond
+ 71  86  47		clover
+ 85  91  44		saratoga
+ 90 110  65		chaletgreen
+ 99 111  34		fijigreen
+102 112  40		pacifika
+102 112  40		rainforest
+116 112  40		olivetone
+126 132  36		trendygreen
+103 105  39		pistachio
+130 106  33		yukongold
+122 114  41		grasshopper
+122 114  41		pesto
+119 113  43		crete
+124 103  32		mustard
+141 112  42		cornharvest
+141 112  42		stinger
+137 126  89		claycreek
+130 133  98		flax
+120 110  76		goben
+107  91  61		limedgum
+115  99  62		yellowmetal
+117  91  39		kumera
+115  99  48		acorn
+115  99  48		himalaya
+ 98  93  42		costadelsol
+ 98  93  42		planter
+ 98  96  62		verdigris
+109  86  44		horsesneck
+ 92  81  47		westcoast
+ 88  76  37		bronzeolive
+ 67  76  40		bronzetone
+ 54  62  29		turtlegreen
+110  51  38		pueblo
+115  61  31		perutan
+112  65  40		darkrimu
+109  59  36		newamber
+ 91  58  36		carnabytan
+ 83  51  30		brownbramble
+ 80  56  30		saddlebrown
+ 91  61  39		bracken
+ 98  66  43		irishcoffee
+102  74  45		dallas
+109  77  44		ironbark
+106  73  40		caferoyale
+108  70  31		antiquebrass
+117  72  47		capepalliser
+125  78  56		cigar
+121  77  46		walnut
+132  92  64		pottersclay
+136  89  49		natural
+116  89  55		shinglefawn
+140 114  84		limedoak
+140  99  56		mckenzie
+143 111  72		driftwood
+141  95  44		rustynail
+144  94  38		afghantan
+157 112  46		butteredrum
+167 117  44		hottoddy
+129  91  40		brazil
+129  91  40		hotcurry
+153  82  43		hawaiiantan
+178 110  51		renosand
+186 111  63		bamboo
+175 108  62		bourbon
+177 108  57		oregon
+171 107  53		pumpkin
+165 101  49		maitai
+161  82  38		richgold
+157  84  50		piper
+156  91  52		indochine
+161  95  59		desert
+161  98  59		redbeech
+173  98  66		tuscany
+169 106  80		santefe
+149  78  44		alerttan
+149  83  47		chelseagem
+142  89  60		rope
+134  75  54		paarl
+136  79  64		mulefawn
+134  80  64		ironstone
+119  66  44		coppercanyon
+122  68  52		peanut
+120  68  48		cumin
+117  68  43		bullshot
+123  72  43		cinnamon
+128  78  44		korma
+136  60  50		prairiesand
+135  56  47		crabapple
+136  53  49		totempole
+142  58  54		tabasco
+140  63  48		embers
+143  63  42		fire
+142  53  55		wellread
+146  56  48		thunderbird
+155  61  61		mexicanred
+161  71  67		roofterracotta
+151  66  45		tiamaria
+157  68  45		rockspray
+154  70  61		cognac
+151  70  60		mojo
+166  86  72		crail
+169  82  73		appleblossom
+199  97  85		sunglo
+190  92  72		flamepea
+168  83  53		orangeroughy
+168  85  51		vesuvius
+177  89  47		fieryorange
+173  82  46		redstage
+172  81  45		roseofsharon
+201  97  56		ecstasy
+187  95  52		smoketree
+191 101  46		christine
+205  93  52		tangerine
+208  94  52		chileanfire
+193  77  54		grenadier
+197  79  51		trinidad
+193  79  59		clementine
+192  81  74		sunset
+212  87  78		valencia
+205  82  91		mandy
+168  50  57		punch
+158  51  50		milanored
+146  42  49		brightred
+149  46  49		guardsmanred
+134  40  46		flamered
+134  40  46		monza
+213 108  48		golddrop
+220 114  42		tahitigold
+212 111  49		tango
+229 127  61		pizazz
+229 130  58		westside
+226 129  59		treepoppy
+234 134  69		flamenco
+239 142  56		sun
+186 120  42		pirategold
+197 131  46		geebung
+202 129  54		goldenbell
+205 132  49		dixie
+209 144  51		fuelyellow
+187 142  52		hokeypokey
+188 146  41		nugget
+226 178  39		goldtips
+216 167  35		galliano
+223 170  40		corn
+227 172  61		tuliptree
+221 173  86		robroy
+220 159  69		saffron
+224 157  55		candlelight
+244 159  53		yellowsea
+218 148  41		buttercup
+224 152  66		firebush
+250 157  73		sunshade
+239 149  72		seabuckthorn
+233 140  58		california
+247 162  51		lightningyellow
+252 174  96		rajah
+252 176  87		texasrose
+253 174  69		mysin
+254 181  82		koromiko
+255 193  82		goldentainoi
+240 178  83		casablanca
+234 184  82		ronchi
+255 205 115		grandis
+255 180  55		supernova
+255 213 154		caramel
+254 219 183		sandybeach
+255 215 160		frangipani
+244 208 164		tequila
+238 199 162		negroni
+255 198 158		romantic
+223 185 146		pancho
+220 182 138		brandy
+227 185 130		maize
+233 186 129		corvette
+255 200 120		chardonnay
+234 183 106		harvestgold
+246 174 120		tacao
+245 183 153		mandyspink
+238 179 158		waxflower
+254 171 154		rosebud
+231 158 136		tonyspink
+253 164 112		hitpink
+228 143 103		apricot
+223 157  91		porsche
+212 145  93		diserria
+212 145  93		whiskeysour
+210 144  98		whiskey
+211 169  92		apache
+218 177  96		equator
+213 177 133		calico
+226 175 128		manhattan
+204 164 131		cameo
+199 163 132		rodeodust
+182 147  92		barleycorn
+157 127  97		sorrellbrown
+163 135 106		sandal
+165 139 111		mongoose
+158 126  83		muesli
+169 132  79		muddywaters
+171 137  83		teak
+191 145  75		tussock
+191 141  60		pizza
+184 138  61		marigold
+181 123  46		mandalay
+198 142  63		anzac
+193 145  86		twine
+192 124  64		brandypunch
+187 116  49		meteor
+198 114  59		zest
+198 128  89		peachschnapps
+208 131  99		burningsand
+206 114  89		japonica
+231 123 117		geraldine
+221 131 116		newyorkpink
+255 152 137		monalisa
+243 134  83		crusta
+203 111  74		reddamask
+221 107  56		sorbus
+226 121  69		jaffa
+225  99  79		flamingo
+239 115  94		persimmon
+216  98  91		roman
+229 109 117		froly
+227 111 138		deepblush
+205 109 147		hopbush
+232 153 190		shocking
+239 149 174		illusion
+224 147 171		kobi
+230 128 149		carissma
+241 145 154		wewak
+238 145 141		sweetpink
+219 129 126		seapink
+208 116 139		charm
+193 111 104		contessa
+194 142 136		orientalpink
+179 112 132		tapestry
+208 138 155		cancan
+167 129 153		bouquet
+197 143 157		viola
+164 135 139		wisteria
+174 148 171		londonhue
+149 135 156		amethystsmoke
+157 156 180		logan
+152 126 126		opium
+154 134 120		almondfrost
+152 125 115		hemp
+182 133 122		brandyrose
+175 147 125		sandrift
+177 148 143		thatch
+181 153 142		delrio
+195 152 139		quicksand
+211 161 148		rose
+205 165 156		eunry
+209 179 153		cashmere
+210 179 169		clamshell
+202 181 178		coldturkey
+200 177 192		maverick
+172 155 155		dustygrey
+185 172 187		lola
+193 159 179		lily
+201 154 160		careyspink
+218 151 144		petiteorchid
+214 139 128		mypink
+255 171 160		cornflower
+248 175 169		sundown
+255 197 187		yourpink
+249 192 196		azalea
+223 177 182		blossom
+245 178 197		cupid
+222 183 217		frenchlilac
+244 200 219		classicrose
+237 184 199		chantilly
+224 183 194		melanie
+218 192 205		twilight
+246 204 215		pinklace
+226 205 213		prim
+212 181 176		oysterpink
+212 187 177		wafer
+220 191 172		justright
+219 194 171		bone
+230 178 166		shilo
+216 180 182		pinkflare
+224 184 177		cavernpink
+235 185 179		beautybush
+245 208 201		coralcandy
+242 205 187		watusi
+231 210 200		bizarre
+229 202 192		duststorm
+235 210 209		vanillaice
+239 220 212		potpourri
+246 222 218		remy
+246 227 218		provincialpink
+252 219 210		pippin
+251 215 204		cinderella
+254 220 193		karry
+249 211 190		tuftbush
+253 215 216		wepeep
+252 213 207		cosmos
+253 233 224		chablis
+250 230 223		bridesmaid
+248 228 227		tutu
+245 230 234		amour
+248 219 224		carouselpink
+239 214 218		palerose
+228 215 229		snuff
+227 214 233		bluechalk
+245 215 220		cherub
+213 199 232		fog
+195 185 221		melrose
+202 180 212		prelude
+174 153 210		bilobaflower
+194 169 219		perfume
+162 158 205		wistful
+192 178 215		moonraker
+172 185 232		perano
+139 152 216		portage
+157 138 191		coldpurple
+170 140 188		eastside
+159 144 208		lavender
+148 112 196		lilacbush
+123  92 183		fuchsia
+114  74 161		studio
+ 91  62 144		daisybush
+181  75 115		royalheath
+138  45  82		rosebudcherry
+137  45  79		disco
+150  44  84		lipstick
+169  64 100		rouge
+180  56 100		cranberry
+162  61  84		nightshadz
+179  54  84		hibiscus
+205  82 108		cabaret
+181  80 103		blush
+171  73  92		hippiepink
+138  51  53		oldbrick
+133  53  52		tallpoppy
+143  62  63		rosewood
+131  61  62		stiletto
+128  58  75		camelot
+149  82 100		vinrouge
+152  73  97		cadillac
+148 106 129		strikemaster
+105  69  84		finn
+121  77  96		cosmic
+142  81 100		cannonpink
+116  64  66		tosca
+133  73  76		solidpink
+125  65  56		redrobin
+126  74  59		nutmeg
+143  78  69		elsalva
+142  77  69		matrix
+139  80  75		lotus
+149  82  76		copperrust
+165 110 117		turkishrose
+171 110 103		coraltree
+158 103  89		auchico
+139  95  77		spicymix
+144 106  84		leather
+159 113  95		toast
+135 106 104		ferra
+130 102  99		pharlap
+125 101  92		russett
+143 119 119		bazaar
+125 103  87		romancoffee
+109  88  67		tobaccobrown
+115  85  62		pickledbean
+115  80  59		oldcopper
+103  72  52		jambalaya
+108  79  63		spice
+106  84  69		quincy
+101  77  73		congobrown
+110  81  80		buccaneer
+107  90  90		zambezi
+110  90  91		falcon
+ 82  77  91		mulledwine
+ 98  86 101		fedora
+ 96  90 103		mobster
+118 109 124		mamba
+113 102 117		rum
+137 117 120		spicypink
+139 125 130		venus
+130 114 164		deluge
+102 111 180		chetwodeblue
+111  99 160		scampi
+131 120 199		moodyblue
+142 114 199		truev
+106  91 177		bluemarguerite
+146 113 167		cesoir
+128  93 128		trendypink
+116  80 133		affair
+104  87 140		butterflybush
+ 81  85 155		governorbay
+ 86  71 134		gigas
+ 86  73 133		victoria
+ 66  99 159		mariner
+ 55  78 136		toryblue
+ 51  80 131		funblue
+ 63  82 129		sapphire
+105  93 135		kimberly
+ 53  62 100		bayofmany
+ 61  50  93		jacarta
+ 59  67 108		portgore
+ 52  52 103		deepkoamaru
+ 53  61 117		toreabay
+ 50  63 117		resolutionblue
+ 61  63 125		jacksonspurple
+ 62  50 103		minsk
+ 75  60 142		bluegem
+ 57  45 115		bluebell
+ 75  45 114		bluediamond
+ 92  60 109		honeyflower
+ 74  59 106		meteorite
+ 78  46  83		hotpurple
+ 74  45  87		scarletgum
+ 46  24  59		blackcurrant
+ 56  26  56		plum
+ 56  33  97		christalle
+ 49  39  96		parism
+ 46  34  73		violentviolet
+ 42  37  81		paua
+ 55  45  82		cherrypie
+ 41  45  79		luckypoint
+ 42  43  65		valhalla
+ 63  46  76		jagger
+ 45  37  65		tolopea
+ 55  37  40		aubergine
+ 60  33  38		temptress
+ 53  34  53		mardigras
+ 61  35  39		chocolate
+ 62  38  49		toledo
+ 69  46  57		barossa
+ 59  43  44		havana
+ 59  43  44		jarrah
+ 52  41  49		melanzane
+ 54  45  56		jacaranda
+ 56  44  56		valentino
+ 47  38  60		violet
+ 60  55  72		martinique
+ 68  50  64		voodoo
+ 76  51  71		loulou
+ 76  61  78		bossanova
+ 85  69  69		woodybrown
+ 69  52  48		rebel
+ 70  52  48		cedar
+ 68  55  54		cowboy
+ 77  62  60		craterbrown
+ 79  56  53		cocoabean
+ 82  57  54		vancleef
+ 74  53  49		bean
+ 72  50  48		mahogany
+ 74  46  50		cabsav
+ 78  49  45		espresso
+ 78  49  46		cherrywood
+ 89  69  55		brownderby
+ 93  59  46		cioccolato
+ 85  52  43		darkoak
+ 91  52  46		redwood
+ 79  48  31		indiantan
+ 68  45  33		moroccobrown
+ 60  36  27		brownpod
+ 62  47  46		tamarind
+ 64  35  39		maroon
+ 58  24  26		rusticred
+ 72  36  39		bulgarianrose
+ 79  42  44		heath
+ 78  39  40		volcano
+ 82  36  38		lonestar
+ 79  33  42		persianred
+ 76  28  36		bordeaux
+ 88  33  36		burntcrimson
+ 91  31  34		venetianred
+ 93  31  30		redoxide
+101  37  37		burgundy
+102  42  44		reddevil
+ 97  45  45		darktan
+103  47  48		japanesemaple
+ 88  47  43		moccaccino
+ 99  53  40		hairyheath
+107  52  42		meranti
+108  55  54		sanguinebrown
+102  54  45		oiledcedar
+110  61  52		metalliccopper
+118  60  51		crownofthorns
+111  55  45		mocha
+108  50  46		kenyancopper
+104  51  50		persianplum
+115  52  58		merlot
+113  51  60		ribbon
+ 95  44  47		jazz
+ 94  42  64		mulberry
+ 83  41  52		blackrose
+ 82  44  53		wineberry
+100  58  72		tawnyport
+ 68  35  47		castro
+ 67  24  47		blackberry
+122  46  77		flirt
+106  31  68		nightclub
+106  31  68		pompadour
+105  41  59		siren
+110  34  51		claret
+124  45  55		paprika
+117  43  47		tamarillo
+120  46  44		lusty
+130  42  50		sangria
+132  40  51		shiraz
+126  37  48		scarlett
+112  31  40		redberry
+101  28  38		pohutukawa
+107  37  44		hotchile
+107  37  44		monarch
+107  37  44		westernred
+138  36  78		cardinal
+105  50 110		seance
+110  57 116		eminence
+104  59 125		clairvoyant
+ 88  53 128		kingfisherdaisy
+ 70  44 119		windsor
diff --git a/lib/util/LICENSE.txt b/lib/util/LICENSE.txt
index 4baac593..98d7e10e 100644
--- a/lib/util/LICENSE.txt
+++ b/lib/util/LICENSE.txt
@@ -1,7 +1,7 @@
 The Frontier Artistic License Version 1.0
 Derived from the Artistic License at OpenSource.org.
 Submitted to OpenSource.org for Open Source Initiative certification.
-   
+
 Preamble
 
 The intent of this document is to state the conditions under which a
@@ -10,7 +10,7 @@ semblance of artistic control over the development of the package,
 while giving the users of the package the right to use and distribute
 the Package in a more-or-less customary fashion, plus the right to
 make reasonable modifications.
-   
+
 Definitions
 
   "Package" refers to the script, suite, file, or collection of
@@ -37,7 +37,7 @@ Definitions
   itself, though there may be fees involved in handling the item.
   It also means that recipients of the item may redistribute it under
   the same conditions they received it.
-       
+
 
 Terms
 
@@ -45,50 +45,50 @@ Terms
 the Standard Version of this Package without restriction, provided
 that you duplicate all of the original copyright notices and
 associated disclaimers.
-   
+
 2. You may apply bug fixes, portability fixes, and other modifications
 derived from the Public Domain or from the Copyright Holder. A Package
 modified in such a way shall still be considered the Standard Version.
-   
+
 3. You may otherwise modify your copy of this Package in any way,
 provided that you insert a prominent notice in each changed script,
 suite, or file stating how and when you changed that script, suite,
 or file, and provided that you do at least ONE of the following:
-   
+
   a) Use the modified Package only within your corporation or
   organization, or retain the modified Package solely for personal use.
-     
+
   b) Place your modifications in the Public Domain or otherwise make
   them Freely Available, such as by posting said modifications to Usenet
   or an equivalent medium, or placing the modifications on a major archive
   site such as ftp.uu.net, or by allowing the Copyright Holder to include
   your modifications in the Standard Version of the Package.
-     
+
   c) Rename any non-standard executables so the names do not conflict
   with standard executables, which must also be provided, and provide
   a separate manual page (or equivalent) for each non-standard executable
   that clearly documents how it differs from the Standard Version.
-     
+
   d) Make other distribution arrangements with the Copyright Holder.
-     
+
 4. You may distribute the programs of this Package in object code or
 executable form, provided that you do at least ONE of the following:
-   
+
   a) Distribute a Standard Version of the executables and library
   files, together with instructions (in the manual page or
   equivalent) on where to get the Standard Version.
-     
+
   b) Accompany the distribution with the machine-readable source of
   the Package with your modifications.
-     
+
   c) Accompany any non-standard executables with their corresponding
   Standard Version executables, give the non-standard executables
   non-standard names, and clearly document the differences in manual
   pages (or equivalent), together with instructions on where to get
   the Standard Version.
-     
+
   d) Make other distribution arrangements with the Copyright Holder.
-     
+
 5. You may charge a reasonable copying fee for any distribution of
 this Package. You may charge any fee you choose for support of this
 Package. You may not charge a fee for this Package itself. However,
@@ -96,25 +96,25 @@ you may distribute this Package in aggregate with other (possibly
 commercial) programs as part of a larger (possibly commercial)
 software distribution provided that you do not advertise this Package
 as a product of your own.
-   
+
 6. The scripts and library files supplied as input to or produced as
 output from the programs of this Package do not automatically fall
 under the copyright of this Package, but belong to whomever generated
 them, and may be sold commercially, and may be aggregated with this
 Package.
-   
+
 7. Scripts, suites, or programs supplied by you that depend on or
 otherwise make use of this Package shall not be considered part of
 this Package.
-   
+
 8. The name of the Copyright Holder may not be used to endorse or
 promote products derived from this software without specific prior
 written permission.
-   
+
 9. THIS PACKAGE IS PROVIDED "AS IS" AND WITHOUT ANY EXPRESS OR IMPLIED
 WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF
 MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
-   
+
                         The End
 
 
diff --git a/lib/util/Makefile b/lib/util/Makefile
index 02119edf..d8e2d135 100644
--- a/lib/util/Makefile
+++ b/lib/util/Makefile
@@ -19,6 +19,10 @@ UTILOBJECTS = \
   matrix.o \
   nsleep.o \
   nstring.o \
+  rand.o \
+  randsysrand.o \
+  randsysrandom.o \
+  randmersenne.o \
   runlength.o \
   shhopt.o \
   token.o \
diff --git a/lib/util/bitio.c b/lib/util/bitio.c
index ca1b55f9..9d96892c 100644
--- a/lib/util/bitio.c
+++ b/lib/util/bitio.c
@@ -6,7 +6,7 @@
  * Works for (sizeof(unsigned long)-1)*8 bits.
  *
  * Copyright (C) 1992 by David W. Sanderson.
- * 
+ *
  * Permission to use, copy, modify, and distribute this software and its
  * documentation for any purpose and without fee is hereby granted,
  * provided that the above copyright notice appear in all copies and
@@ -89,7 +89,7 @@ pm_bitinit(FILE * const f, const char * const mode) {
  * pm_bitfini() - deallocate the given struct bitstream *.
  *
  * You must call this after you are done with the struct bitstream *.
- * 
+ *
  * It may flush some bits left in the buffer.
  *
  * Returns the number of bytes written, -1 on error.
@@ -137,13 +137,13 @@ pm_bitfini(b)
 
 /*
  * pm_bitread() - read the next nbits into *val from the given file.
- * 
+ *
  * The last pm_bitread() must be followed by a call to pm_bitfini().
- * 
+ *
  * Returns the number of bytes read, -1 on error.
  */
 
-int 
+int
 pm_bitread(b, nbits, val)
     struct bitstream *b;
     unsigned long   nbits;
@@ -172,9 +172,9 @@ pm_bitread(b, nbits, val)
 
 /*
  * pm_bitwrite() - write the low nbits of val to the given file.
- * 
+ *
  * The last pm_bitwrite() must be followed by a call to pm_bitfini().
- * 
+ *
  * Returns the number of bytes written, -1 on error.
  */
 
diff --git a/lib/util/bitio.h b/lib/util/bitio.h
index dfc5a153..d1fbbff2 100644
--- a/lib/util/bitio.h
+++ b/lib/util/bitio.h
@@ -6,7 +6,7 @@
  * Works for (sizeof(unsigned long)-1)*8 bits.
  *
  * Copyright (C) 1992 by David W. Sanderson.
- * 
+ *
  * Permission to use, copy, modify, and distribute this software and its
  * documentation for any purpose and without fee is hereby granted,
  * provided that the above copyright notice appear in all copies and
@@ -41,7 +41,7 @@ extern "C" {
 } /* to fake out automatic code indenters */
 #endif
 
-typedef struct bitstream	*BITSTREAM;
+typedef struct bitstream        *BITSTREAM;
 
 struct bitstream *
 pm_bitinit(FILE * const f, const char * const mode);
@@ -50,7 +50,7 @@ pm_bitinit(FILE * const f, const char * const mode);
  * pm_bitfini() - deallocate the given BITSTREAM.
  *
  * You must call this after you are done with the BITSTREAM.
- * 
+ *
  * It may flush some bits left in the buffer.
  *
  * Returns the number of bytes written, -1 on error.
@@ -61,7 +61,7 @@ pm_bitfini(BITSTREAM b);
 
 /*
  * pm_bitread() - read the next nbits into *val from the given file.
- * 
+ *
  * Returns the number of bytes read, -1 on error.
  */
 
@@ -72,9 +72,9 @@ pm_bitread(BITSTREAM       b,
 
 /*
  * pm_bitwrite() - write the low nbits of val to the given file.
- * 
+ *
  * The last pm_bitwrite() must be followed by a call to pm_bitflush().
- * 
+ *
  * Returns the number of bytes written, -1 on error.
  */
 
diff --git a/lib/util/bitreverse.h b/lib/util/bitreverse.h
index b3f0ea13..9acdc5fe 100644
--- a/lib/util/bitreverse.h
+++ b/lib/util/bitreverse.h
@@ -13,7 +13,7 @@
 **
 **     c = ((c >>  1) & 0x55) | ((c <<  1) & 0xaa);
 **     c = ((c >>  2) & 0x33) | ((c <<  2) & 0xcc);
-**     c = ((c >> 4) & 0x0f) | ((c << 4) & 0xf0); 
+**     c = ((c >> 4) & 0x0f) | ((c << 4) & 0xf0);
 */
 
 #ifndef _BITR_H_
diff --git a/lib/util/floatcode.h b/lib/util/floatcode.h
index dc31d038..07012dad 100644
--- a/lib/util/floatcode.h
+++ b/lib/util/floatcode.h
@@ -33,9 +33,9 @@ pm_floatFromBigendFloat(pm_bigendFloat const arg) {
             pm_bigendFloat bigend;
             float native;
         } converter;
-        
+
         converter.bigend = arg;
-        
+
         retval = converter.native;
     }; break;
     case LITTLE_ENDIAN: {
@@ -68,7 +68,7 @@ pm_bigendFloatFromFloat(float const arg) {
             pm_bigendFloat bigend;
             float native;
         } converter;
-        
+
         converter.native = arg;
 
         retval = converter.bigend;
@@ -117,9 +117,9 @@ pm_doubleFromBigendDouble(pm_bigendDouble const arg) {
             pm_bigendDouble bigend;
             double native;
         } converter;
-        
+
         converter.bigend = arg;
-        
+
         retval = converter.native;
     }; break;
     case LITTLE_ENDIAN: {
@@ -156,7 +156,7 @@ pm_bigendDoubleFromDouble(double const arg) {
             pm_bigendDouble bigend;
             double native;
         } converter;
-        
+
         converter.native = arg;
 
         retval = converter.bigend;
diff --git a/lib/util/intcode.h b/lib/util/intcode.h
index 1066ee9b..6f40a740 100644
--- a/lib/util/intcode.h
+++ b/lib/util/intcode.h
@@ -108,7 +108,7 @@ pm_uintFromBigend32(bigend32 const arg) {
 
 #if HAVE_GCC_BSWAP
     case LITTLE_ENDIAN: {
-        /* Use GCC built-in */  
+        /* Use GCC built-in */
         union {
             bigend32 bigend;
             uint32_t native;
@@ -117,7 +117,7 @@ pm_uintFromBigend32(bigend32 const arg) {
         retval = __builtin_bswap32(converter.native);
     } break;
 #endif
-    
+
     default:
         retval =
             (arg.bytes[0] << 24) |
@@ -146,9 +146,9 @@ pm_bigendFromUint32(uint32_t const arg) {
         retval = converter.bigend;
     } break;
 
-#if HAVE_GCC_BSWAP    
+#if HAVE_GCC_BSWAP
     case LITTLE_ENDIAN: {
-        /* Use GCC built-in */  
+        /* Use GCC built-in */
         union {
             bigend32 bigend;
             uint32_t native;
@@ -156,7 +156,7 @@ pm_bigendFromUint32(uint32_t const arg) {
         converter.native = __builtin_bswap32(arg);
         retval = converter.bigend;
     } break;
-#endif    
+#endif
 
     default: {
         uint32_t shift;
@@ -208,9 +208,9 @@ pm_uintFromBigend64(bigend64 const arg) {
         retval = converter.native;
     } break;
 
-#if HAVE_GCC_BSWAP    
+#if HAVE_GCC_BSWAP
     case LITTLE_ENDIAN: {
-        /* Use GCC built-in */  
+        /* Use GCC built-in */
         union {
             bigend64 bigend;
             uint64_t native;
@@ -249,7 +249,7 @@ pm_bigendFromUint64(uint64_t const arg) {
 #if HAVE_GCC_BSWAP
     case LITTLE_ENDIAN: {
 
-        /* Use GCC built-in */  
+        /* Use GCC built-in */
         union {
             bigend64 bigend;
             uint64_t native;
@@ -258,7 +258,7 @@ pm_bigendFromUint64(uint64_t const arg) {
         retval = converter.bigend;
     } break;
 #endif
-    
+
     default: {
         uint64_t shift;
         shift = arg;
diff --git a/lib/util/io.c b/lib/util/io.c
index 54ecb6a8..ad17f680 100644
--- a/lib/util/io.c
+++ b/lib/util/io.c
@@ -32,7 +32,7 @@ pm_freadline(FILE *        const fileP,
 
     bufferSize = 1024;  /* initial value */
     *errorP = NULL; /* initial value */
-    
+
     MALLOCARRAY(buffer, bufferSize);
 
     for (cursor = 0, gotLine = false, eof = false;
@@ -53,7 +53,7 @@ pm_freadline(FILE *        const fileP,
                         (unsigned int)bufferSize);
         else {
             int const rc = getc(fileP);
-        
+
             if (rc < 0) {
                 if (feof(fileP))
                     eof = true;
diff --git a/lib/util/mallocvar.h b/lib/util/mallocvar.h
index 23b28c40..73498357 100644
--- a/lib/util/mallocvar.h
+++ b/lib/util/mallocvar.h
@@ -67,7 +67,18 @@ static __inline__ void
 reallocProduct(void **      const blockP,
                size_t       const factor1,
                unsigned int const factor2) {
+/*----------------------------------------------------------------------------
+   Reallocate the block at *blockPP to size 'factor1' * 'factor2'.
+   (Reallocate means make *blockPP point to a block of that size that
+   contains the same data as the block to which *blockP points now, with
+   additional space as needed at the end).
+
+   If *blockPP is null, make *blockPP point to a new block of memory of
+   the desired size with no contents.
 
+   If the reallocation fails, release any memory pointed by *blockP and
+   make *blockP null.
+-----------------------------------------------------------------------------*/
     size_t const sizeMax =
 #if defined(SIZE_MAX)
         SIZE_MAX
@@ -109,8 +120,6 @@ reallocProduct(void **      const blockP,
     void * array; \
     array = arrayName; \
     reallocProduct(&array, nElements, sizeof(arrayName[0])); \
-    if (!array && arrayName) \
-        free(arrayName); \
     arrayName = array; \
 } while (0)
 
diff --git a/lib/util/matrix.c b/lib/util/matrix.c
index e9456e93..1849bf49 100644
--- a/lib/util/matrix.c
+++ b/lib/util/matrix.c
@@ -201,7 +201,7 @@ pm_solvelineareq(double **     const aArg,
             /* Work from the bottom up to solve for the unknowns x[], from
                the a and c rows in question and all the x[] below it
             */
-            
+
             unsigned int k;
             for (k = 0; k < n; ++k) {
                 unsigned int const m = n - k - 1;
@@ -210,7 +210,7 @@ pm_solvelineareq(double **     const aArg,
 
                 for (j = m+1, xwork = c[m]; j < n; ++j)
                     xwork -= a[m][j] * x[j];
-                    
+
                 x[m] = xwork / a[m][m];
             }
         }
diff --git a/lib/util/nstring.c b/lib/util/nstring.c
index 6d68af49..29da8fe5 100644
--- a/lib/util/nstring.c
+++ b/lib/util/nstring.c
@@ -1,128 +1,16 @@
-/*
- * snprintf.c - a portable implementation of snprintf
- *
-
-   THIS MODULE WAS ADAPTED FOR NETPBM BY BRYAN HENDERSON ON 2002.03.24.
-   Bryan got the base from
-   http://www.ijs.si/software/snprintf/snprintf-2.2.tar.gz, but made
-   a lot of changes and additions.
-
- * AUTHOR
- *   Mark Martinec <mark.martinec@ijs.si>, April 1999.
- *
- *   Copyright 1999, Mark Martinec. All rights reserved.
- *
- * TERMS AND CONDITIONS
- *   This program is free software; you can redistribute it and/or modify
- *   it under the terms of the "Frontier Artistic License" which comes
- *   with this Kit.
- *
- *   This program is distributed in the hope that it will be useful,
- *   but WITHOUT ANY WARRANTY; without even the implied warranty
- *   of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
- *   See the Frontier Artistic License for more details.
- *
- *   You should have received a copy of the Frontier Artistic License
- *   with this Kit in the file named LICENSE.txt .
- *   If not, I'll be glad to provide one.
- *
- * FEATURES
- * - careful adherence to specs regarding flags, field width and precision;
- * - good performance for large string handling (large format, large
- *   argument or large paddings). Performance is similar to system's sprintf
- *   and in several cases significantly better (make sure you compile with
- *   optimizations turned on, tell the compiler the code is strict ANSI
- *   if necessary to give it more freedom for optimizations);
- * - return value semantics per ISO/IEC 9899:1999 ("ISO C99");
- * - written in standard ISO/ANSI C - requires an ANSI C compiler.
- *
- * IMPLEMENTED CONVERSION SPECIFIERS AND DATA TYPES
- *
- * This snprintf implements only the following conversion specifiers:
- * s, c, d, u, o, x, X, p, f  (and synonyms: i, D, U, O - see below)
- * with flags: '-', '+', ' ', '0' and '#'.
- * An asterisk is acceptable for field width as well as precision.
- *
- * Length modifiers 'h' (short int), 'l' (long int),
- * and 'll' (long long int) are implemented.
- *
- * Conversion of numeric data (conversion specifiers d, u, o, x, X, p)
- * with length modifiers (none or h, l, ll) is left to the system routine
- * sprintf, but all handling of flags, field width and precision as well as
- * c and s conversions is done very carefully by this portable routine.
- * If a string precision (truncation) is specified (e.g. %.8s) it is
- * guaranteed the string beyond the specified precision will not be referenced.
- *
- * Length modifiers h, l and ll are ignored for c and s conversions (you
- * can't use data types wint_t and wchar_t).
- *
- * The following common synonyms for conversion characters are acceptable:
- *   - i is a synonym for d
- *   - D is a synonym for ld, explicit length modifiers are ignored
- *   - U is a synonym for lu, explicit length modifiers are ignored
- *   - O is a synonym for lo, explicit length modifiers are ignored
- * The D, O and U conversion characters are nonstandard, they are accepted
- * for backward compatibility only, and should not be used for new code.
- *
- * The following is specifically NOT implemented:
- *   - flag ' (thousands' grouping character) is recognized but ignored
- *   - numeric conversion specifiers: e, E, g, G and synonym F,
- *     as well as the new a and A conversion specifiers
- *   - length modifier 'L' (long double) and 'q' (quad - use 'll' instead)
- *   - wide character/string conversions: lc, ls, and nonstandard
- *     synonyms C and S
- *   - writeback of converted string length: conversion character n
- *   - the n$ specification for direct reference to n-th argument
- *   - locales
- *
- * It is permitted for str_m to be zero, and it is permitted to specify NULL
- * pointer for resulting string argument if str_m is zero (as per ISO C99).
- *
- * The return value is the number of characters which would be generated
- * for the given input, excluding the trailing null. If this value
- * is greater or equal to str_m, not all characters from the result
- * have been stored in str, output bytes beyond the (str_m-1) -th character
- * are discarded. If str_m is greater than zero it is guaranteed
- * the resulting string will be null-terminated.
- *
- * NOTE that this matches the ISO C99, OpenBSD, and GNU C library 2.1,
- * but is different from some older and vendor implementations,
- * and is also different from XPG, XSH5, SUSv2 specifications.
- * For historical discussion on changes in the semantics and standards
- * of snprintf see printf(3) man page in the Linux programmers manual.
- *
- * Routines asprintf and vasprintf return a pointer (in the ptr argument)
- * to a buffer sufficiently large to hold the resulting string. This pointer
- * should be passed to free(3) to release the allocated storage when it is
- * no longer needed. If sufficient space cannot be allocated, these functions
- * will return -1 and set ptr to be a NULL pointer. These two routines are a
- * GNU C library extensions (glibc).
- *
- * Routines asnprintf and vasnprintf are similar to asprintf and vasprintf,
- * yet, like snprintf and vsnprintf counterparts, will write at most str_m-1
- * characters into the allocated output string, the last character in the
- * allocated buffer then gets the terminating null. If the formatted string
- * length (the return value) is greater than or equal to the str_m argument,
- * the resulting string was truncated and some of the formatted characters
- * were discarded. These routines present a handy way to limit the amount
- * of allocated memory to some sane value.
- *
- * AVAILABILITY
- *   http://www.ijs.si/software/snprintf/
- *
- */
-
-
+/*=============================================================================
+                               nstring.c
+===============================================================================
+  Code in this file is contributed to the public domain by its authors.
+=============================================================================*/
 #define _DEFAULT_SOURCE /* New name for SVID & BSD source defines */
+#define _C99_SOURCE  /* Make sure snprintf() is in stdio.h */
 #define _XOPEN_SOURCE 500  /* Make sure strdup() is in string.h */
 #define _BSD_SOURCE  /* Make sure strdup() is in string.h */
 #define _GNU_SOURCE
    /* Because of conditional compilation, this is GNU source only if the C
       library is GNU.
    */
-#define PORTABLE_SNPRINTF_VERSION_MAJOR 2
-#define PORTABLE_SNPRINTF_VERSION_MINOR 2
-
 #include <sys/types.h>
 #include <limits.h>
 #include <string.h>
@@ -137,64 +25,6 @@
 
 #include "nstring.h"
 
-#ifdef isdigit
-#undef isdigit
-#endif
-#define isdigit(c) ((c) >= '0' && (c) <= '9')
-
-/* For copying strings longer or equal to 'breakeven_point'
- * it is more efficient to call memcpy() than to do it inline.
- * The value depends mostly on the processor architecture,
- * but also on the compiler and its optimization capabilities.
- * The value is not critical, some small value greater than zero
- * will be just fine if you don't care to squeeze every drop
- * of performance out of the code.
- *
- * Small values favor memcpy, large values favor inline code.
- */
-#if defined(__alpha__) || defined(__alpha)
-#  define breakeven_point   2	/* AXP (DEC Alpha)     - gcc or cc or egcs */
-#endif
-#if defined(__i386__)  || defined(__i386)
-#  define breakeven_point  12	/* Intel Pentium/Linux - gcc 2.96 */
-#endif
-#if defined(__hppa)
-#  define breakeven_point  10	/* HP-PA               - gcc */
-#endif
-#if defined(__sparc__) || defined(__sparc)
-#  define breakeven_point  33	/* Sun Sparc 5         - gcc 2.8.1 */
-#endif
-
-/* some other values of possible interest: */
-/* #define breakeven_point  8 */  /* VAX 4000          - vaxc */
-/* #define breakeven_point 19 */  /* VAX 4000          - gcc 2.7.0 */
-
-#ifndef breakeven_point
-#  define breakeven_point   6	/* some reasonable one-size-fits-all value */
-#endif
-
-#define fast_memcpy(d,s,n) \
-  { register size_t nn = (size_t)(n); \
-    if (nn >= breakeven_point) memcpy((d), (s), nn); \
-    else if (nn > 0) { /* proc call overhead is worth only for large strings*/\
-      register char *dd; register const char *ss; \
-      for (ss=(s), dd=(d); nn>0; nn--) *dd++ = *ss++; } }
-
-#define fast_memset(d,c,n) \
-  { register size_t nn = (size_t)(n); \
-    if (nn >= breakeven_point) memset((d), (int)(c), nn); \
-    else if (nn > 0) { /* proc call overhead is worth only for large strings*/\
-      register char *dd; register const int cc=(int)(c); \
-      for (dd=(d); nn>0; nn--) *dd++ = cc; } }
-
-/* declarations */
-
-static char credits[] = "\n\
-@(#)snprintf.c, v2.2: Mark Martinec, <mark.martinec@ijs.si>\n\
-@(#)snprintf.c, v2.2: Copyright 1999, Mark Martinec. Frontier Artistic License applies.\n\
-@(#)snprintf.c, v2.2: http://www.ijs.si/software/snprintf/\n";
-
-
 /* MacOS X before 10.7, for one, does not have strnlen */
 size_t
 pm_strnlen(const char * const s,
@@ -209,577 +39,6 @@ pm_strnlen(const char * const s,
 
 
 
-void
-pm_vsnprintf(char *       const str,
-             size_t       const str_m,
-             const char * const fmt,
-             va_list            ap,
-             size_t *     const sizeP) {
-
-    size_t str_l = 0;
-    const char *p = fmt;
-
-    /* In contrast with POSIX, the ISO C99 now says that str can be
-       NULL and str_m can be 0.  This is more useful than the old:
-       if (str_m < 1) return -1;
-    */
-
-    if (!p) p = "";
-    while (*p) {
-        if (*p != '%') {
-            /* if (str_l < str_m) str[str_l++] = *p++; -- this would
-               be sufficient but the following code achieves better
-               performance for cases * where format string is long and
-               contains few conversions
-            */
-            const char *q = strchr(p + 1,'%');
-            size_t n = !q ? strlen(p) : (q - p);
-            if (str_l < str_m) {
-                size_t const avail = str_m - str_l;
-                fast_memcpy(str + str_l, p, (MIN(n, avail)));
-            }
-            p += n; str_l += n;
-        } else {
-            size_t min_field_width;
-            size_t precision = 0;
-            bool precision_specified;
-            bool justify_left;
-            bool alternate_form;
-            bool force_sign;
-            bool space_for_positive;
-                /* If both the ' ' and '+' flags appear,
-                   the ' ' flag should be ignored.
-                */
-            char length_modifier = '\0';  /* allowed values: \0, h, l, L */
-            char tmp[32];
-                /* temporary buffer for simple numeric->string conversion */
-
-            const char *str_arg;
-                /* string address in case of string argument */
-            size_t str_arg_l;
-                /* natural field width of arg without padding and sign */
-            unsigned char uchar_arg;
-                /* unsigned char argument value - only defined for c
-                   conversion.  N.B. standard explicitly states the char
-                   argument for the c conversion is unsigned.
-                */
-
-            bool zero_padding;
-
-            size_t number_of_zeros_to_pad;
-                /* number of zeros to be inserted for numeric
-                   conversions as required by the precision or minimal
-                   field width
-                */
-
-            size_t zero_padding_insertion_ind;
-                /* index into tmp where zero padding is to be inserted */
-
-            char fmt_spec;
-                /* current conversion specifier character */
-
-            str_arg = credits;
-                /* just to make compiler happy (defined but not used) */
-            str_arg = NULL;
-            ++p;  /* skip '%' */
-
-            /* parse flags */
-            justify_left = false;  /* initial value */
-            alternate_form = false;  /* initial value */
-            force_sign = false;  /* initial value */
-            space_for_positive = false;  /* initial value */
-            zero_padding = false;  /* initial value */
-            number_of_zeros_to_pad = 0;  /* initial value */
-            zero_padding_insertion_ind = 0;  /* initial value */
-            fmt_spec = '\0';  /* initial value */
-
-            while (*p == '0' || *p == '-' || *p == '+' ||
-                   *p == ' ' || *p == '#' || *p == '\'') {
-                switch (*p) {
-                case '0': zero_padding = true; break;
-                case '-': justify_left = true; break;
-                case '+': force_sign = true; space_for_positive = false; break;
-                case ' ': force_sign = true; break;
-                    /* If both the ' ' and '+' flags appear, the ' '
-                       flag should be ignored
-                    */
-                case '#': alternate_form = true; break;
-                case '\'': break;
-                }
-                ++p;
-            }
-            /* If the '0' and '-' flags both appear, the '0' flag
-               should be ignored.
-            */
-
-            /* parse field width */
-            if (*p == '*') {
-                int j;
-                ++p;
-                j = va_arg(ap, int);
-                if (j >= 0) { min_field_width = j; justify_left = false; }
-                else { min_field_width = -j; justify_left = true; }
-            } else if (isdigit((int)(*p))) {
-                /* size_t could be wider than unsigned int; make sure
-                   we treat argument like common implementations do
-                */
-                unsigned int uj = *p++ - '0';
-                while (isdigit((int)(*p)))
-                    uj = 10*uj + (unsigned int)(*p++ - '0');
-                min_field_width = uj;
-            } else
-                min_field_width = 0;
-
-            /* parse precision */
-            if (*p == '.') {
-                ++p;
-                precision_specified = true;
-                if (*p == '*') {
-                    int j = va_arg(ap, int);
-                    p++;
-                    if (j >= 0) precision = j;
-                    else {
-                        precision_specified = false; precision = 0;
-                        /* NOTE: Solaris 2.6 man page claims that in
-                           this case the precision should be set to 0.
-                           Digital Unix 4.0, HPUX 10 and BSD man page
-                           claim that this case should be treated as
-                           unspecified precision, which is what we do
-                           here.
-                        */
-                    }
-                } else if (isdigit((int)(*p))) {
-                    /* size_t could be wider than unsigned int; make
-                       sure we treat argument like common
-                       implementations do
-                    */
-                    unsigned int uj = *p++ - '0';
-                    while (isdigit((int)(*p)))
-                        uj = 10*uj + (unsigned int)(*p++ - '0');
-                    precision = uj;
-                }
-            } else
-                precision_specified = false;
-
-            /* parse 'h', 'l' and 'll' length modifiers */
-            if (*p == 'h' || *p == 'l') {
-                length_modifier = *p; p++;
-                if (length_modifier == 'l' && *p == 'l') {
-                    /* double l = long long */
-                    length_modifier = 'l';  /* treat it as a single 'l' */
-                    p++;
-                }
-            }
-            fmt_spec = *p;
-
-            /* common synonyms: */
-            switch (fmt_spec) {
-            case 'i': fmt_spec = 'd'; break;
-            case 'D': fmt_spec = 'd'; length_modifier = 'l'; break;
-            case 'U': fmt_spec = 'u'; length_modifier = 'l'; break;
-            case 'O': fmt_spec = 'o'; length_modifier = 'l'; break;
-            default: break;
-            }
-            /* get parameter value, do initial processing */
-            switch (fmt_spec) {
-            case '%':
-                /* % behaves similar to 's' regarding flags and field widths */
-            case 'c':
-                /* c behaves similar to 's' regarding flags and field widths */
-            case 's':
-                /* wint_t and wchar_t not handled */
-                length_modifier = '\0';
-                /* the result of zero padding flag with non-numeric
-                    conversion specifier is undefined. Solaris and
-                    HPUX 10 does zero padding in this case, Digital
-                    Unix and Linux does not.
-                */
-
-                zero_padding = false;
-                    /* turn zero padding off for string conversions */
-                str_arg_l = 1;
-                switch (fmt_spec) {
-                case '%':
-                    str_arg = p; break;
-                case 'c': {
-                    int j = va_arg(ap, int);
-                    uchar_arg = (unsigned char) j;
-                        /* standard demands unsigned char */
-                    str_arg = (const char *) &uchar_arg;
-                    break;
-                }
-                case 's':
-                    str_arg = va_arg(ap, const char *);
-                    if (!str_arg)
-                        /* make sure not to address string beyond the
-                           specified precision !!!
-                        */
-                        str_arg_l = 0;
-                    else if (!precision_specified)
-                        /* truncate string if necessary as requested by
-                           precision
-                        */
-                        str_arg_l = strlen(str_arg);
-                    else if (precision == 0)
-                        str_arg_l = 0;
-                    else {
-                        /* memchr on HP does not like n > 2^31  !!! */
-                        const char * q =
-                            memchr(str_arg, '\0', MIN(precision, 0x7fffffff));
-                        str_arg_l = !q ? precision : (q-str_arg);
-                    }
-                    break;
-                default: break;
-                }
-                break;
-            case 'd': case 'u': case 'o': case 'x': case 'X': case 'p': {
-                /* NOTE: the u, o, x, X and p conversion specifiers imply
-                   the value is unsigned;  d implies a signed value
-                */
-                int arg_sign = 0;
-                /* 0  if numeric argument is zero (or if pointer is NULL
-                      for 'p'),
-                   +1 if greater than zero (or nonzero for unsigned arguments),
-                   -1 if negative (unsigned argument is never negative)
-                */
-
-                int int_arg = 0;
-                unsigned int uint_arg = 0;
-                   /* defined only for length modifier h, or for no
-                      length modifiers
-                   */
-
-                long int long_arg = 0;  unsigned long int ulong_arg = 0;
-                /* only defined for length modifier l */
-
-                void *ptr_arg = NULL;
-                /* pointer argument value -only defined for p conversion */
-
-                if (fmt_spec == 'p') {
-                    /* HPUX 10: An l, h, ll or L before any other
-                        conversion character (other than d, i, u, o,
-                        x, or X) is ignored.
-
-                      Digital Unix: not specified, but seems to behave
-                      as HPUX does.
-
-                      Solaris: If an h, l, or L appears before any
-                      other conversion specifier (other than d, i, u,
-                      o, x, or X), the behavior is
-                      undefined. (Actually %hp converts only 16-bits
-                      of address and %llp treats address as 64-bit
-                      data which is incompatible with (void *)
-                      argument on a 32-bit system).
-                    */
-
-                    length_modifier = '\0';
-                    ptr_arg = va_arg(ap, void *);
-                    if (ptr_arg != NULL) arg_sign = 1;
-                } else if (fmt_spec == 'd') {  /* signed */
-                    switch (length_modifier) {
-                    case '\0':
-                    case 'h':
-                        /* It is non-portable to specify a second
-                           argument of char or short to va_arg,
-                           because arguments seen by the called
-                           function are not char or short.  C converts
-                           char and short arguments to int before
-                           passing them to a function.
-                        */
-                        int_arg = va_arg(ap, int);
-                        if      (int_arg > 0) arg_sign =  1;
-                        else if (int_arg < 0) arg_sign = -1;
-                        break;
-                    case 'l':
-                        long_arg = va_arg(ap, long int);
-                        if      (long_arg > 0) arg_sign =  1;
-                        else if (long_arg < 0) arg_sign = -1;
-                        break;
-                    }
-                } else {  /* unsigned */
-                    switch (length_modifier) {
-                    case '\0':
-                    case 'h':
-                        uint_arg = va_arg(ap, unsigned int);
-                        if (uint_arg)
-                            arg_sign = 1;
-                        break;
-                    case 'l':
-                        ulong_arg = va_arg(ap, unsigned long int);
-                        if (ulong_arg)
-                            arg_sign = 1;
-                        break;
-                    }
-                }
-                str_arg = tmp; str_arg_l = 0;
-                /* NOTE: For d, i, u, o, x, and X conversions, if
-                   precision is specified, the '0' flag should be
-                   ignored. This is so with Solaris 2.6, Digital UNIX
-                   4.0, HPUX 10, Linux, FreeBSD, NetBSD; but not with
-                   Perl.
-                */
-                if (precision_specified)
-                    zero_padding = false;
-                if (fmt_spec == 'd') {
-                    if (force_sign && arg_sign >= 0)
-                        tmp[str_arg_l++] = space_for_positive ? ' ' : '+';
-                    /* leave negative numbers for sprintf to handle,
-                       to avoid handling tricky cases like (short
-                       int)(-32768)
-                    */
-                } else if (alternate_form) {
-                    if (arg_sign != 0 && (fmt_spec == 'x' ||
-                                          fmt_spec == 'X')) {
-                        tmp[str_arg_l++] = '0';
-                        tmp[str_arg_l++] = fmt_spec;
-                    }
-                    /* alternate form should have no effect for p
-                       conversion, but ...
-                    */
-                }
-                zero_padding_insertion_ind = str_arg_l;
-                if (!precision_specified)
-                    precision = 1;   /* default precision is 1 */
-                if (precision == 0 && arg_sign == 0) {
-                    /* converted to null string */
-                    /* When zero value is formatted with an explicit
-                       precision 0, the resulting formatted string is
-                       empty (d, i, u, o, x, X, p).
-                    */
-                } else {
-                    char f[5]; int f_l = 0;
-                    f[f_l++] = '%';
-                        /* construct a simple format string for sprintf */
-                    if (!length_modifier) { }
-                    else if (length_modifier=='2') {
-                        f[f_l++] = 'l'; f[f_l++] = 'l';
-                    }
-                    else
-                        f[f_l++] = length_modifier;
-                    f[f_l++] = fmt_spec; f[f_l++] = '\0';
-                    if (fmt_spec == 'p')
-                        str_arg_l += sprintf(tmp+str_arg_l, f, ptr_arg);
-                    else if (fmt_spec == 'd') {  /* signed */
-                        switch (length_modifier) {
-                        case '\0':
-                        case 'h':
-                            str_arg_l+=sprintf(tmp+str_arg_l, f, int_arg);
-                            break;
-                        case 'l':
-                            str_arg_l+=sprintf(tmp+str_arg_l, f, long_arg);
-                            break;
-                        }
-                    } else {  /* unsigned */
-                        switch (length_modifier) {
-                        case '\0':
-                        case 'h':
-                            str_arg_l += sprintf(tmp+str_arg_l, f, uint_arg);
-                            break;
-                        case 'l':
-                            str_arg_l += sprintf(tmp+str_arg_l, f, ulong_arg);
-                            break;
-                        }
-                    }
-                    /* include the optional minus sign and possible "0x"
-                       in the region before the zero padding insertion point
-                    */
-                    if (zero_padding_insertion_ind < str_arg_l &&
-                        tmp[zero_padding_insertion_ind] == '-') {
-                        zero_padding_insertion_ind += 1;
-                    }
-                    if (zero_padding_insertion_ind + 1 < str_arg_l &&
-                        tmp[zero_padding_insertion_ind]   == '0' &&
-                        (tmp[zero_padding_insertion_ind+1] == 'x' ||
-                         tmp[zero_padding_insertion_ind+1] == 'X') ) {
-                        zero_padding_insertion_ind += 2;
-                    }
-                }
-                {
-                    size_t const num_of_digits =
-                        str_arg_l - zero_padding_insertion_ind;
-                    if (alternate_form && fmt_spec == 'o'
-                        /* unless zero is already the first character */
-                        && !(zero_padding_insertion_ind < str_arg_l
-                             && tmp[zero_padding_insertion_ind] == '0')) {
-                        /* assure leading zero for alternate-form
-                           octal numbers
-                        */
-                        if (!precision_specified ||
-                            precision < num_of_digits+1) {
-                            /* precision is increased to force the
-                               first character to be zero, except if a
-                               zero value is formatted with an
-                               explicit precision of zero
-                            */
-                            precision = num_of_digits+1;
-                            precision_specified = true;
-                        }
-                    }
-                    /* zero padding to specified precision? */
-                    if (num_of_digits < precision)
-                        number_of_zeros_to_pad = precision - num_of_digits;
-                }
-                /* zero padding to specified minimal field width? */
-                if (!justify_left && zero_padding) {
-                    int const n =
-                        min_field_width - (str_arg_l+number_of_zeros_to_pad);
-                    if (n > 0)
-                        number_of_zeros_to_pad += n;
-                }
-            } break;
-            case 'f': {
-                char f[10];
-                if (precision_specified)
-                    snprintf(f, ARRAY_SIZE(f), "%%%u.%uf",
-                             (unsigned)min_field_width, (unsigned)precision);
-                else
-                    snprintf(f, ARRAY_SIZE(f), "%%%uf",
-                             (unsigned)min_field_width);
-
-                str_arg_l = sprintf(tmp, f, va_arg(ap, double));
-                str_arg = &tmp[0];
-
-                min_field_width = 0;
-                zero_padding_insertion_ind = 0;
-            } break;
-            default:
-                /* Unrecognized conversion specifier.  Discard the
-                   unrecognized conversion, just keep the unrecognized
-                   conversion character.
-                */
-                zero_padding = false;
-                    /* turn zero padding off for non-numeric convers. */
-                /* reset flags */
-                justify_left = true;
-                min_field_width = 0;
-                str_arg = p;
-                str_arg_l = 0;
-                if (*p)
-                    /* include invalid conversion specifier unchanged
-                       if not at end-of-string
-                    */
-                    ++str_arg_l;
-                break;
-            }
-            if (*p)
-                p++;  /* step over the just processed conversion specifier */
-            /* insert padding to the left as requested by
-               min_field_width; this does not include the zero padding
-               in case of numerical conversions
-            */
-
-            if (!justify_left) {
-                /* left padding with blank or zero */
-                int n = min_field_width - (str_arg_l + number_of_zeros_to_pad);
-                if (n > 0) {
-                    if (str_l < str_m) {
-                        size_t const avail = str_m - str_l;
-                        fast_memset(str + str_l, (zero_padding ? '0' : ' '),
-                                    (MIN(n, avail)));
-                    }
-                    str_l += n;
-                }
-            }
-            /* zero padding as requested by the precision or by the
-               minimal field width for numeric conversions required?
-            */
-            if (number_of_zeros_to_pad <= 0) {
-                /* will not copy first part of numeric right now,
-                   force it to be copied later in its entirety
-                */
-                zero_padding_insertion_ind = 0;
-            } else {
-                {
-                    /* insert first part of numerics (sign or '0x') before
-                       zero padding
-                    */
-                    int const n = zero_padding_insertion_ind;
-                    if (n > 0) {
-                        if (str_l < str_m) {
-                            size_t const avail = str_m - str_l;
-                            fast_memcpy(str + str_l, str_arg, (MIN(n, avail)));
-                        }
-                        str_l += n;
-                    }
-                }
-                {
-                    /* insert zero padding as requested by the precision
-                       or min field width
-                    */
-                    int const n = number_of_zeros_to_pad;
-                    if (n > 0) {
-                        if (str_l < str_m) {
-                            size_t const avail = str_m - str_l;
-                            fast_memset(str + str_l, '0', (MIN(n, avail)));
-                        }
-                        str_l += n;
-                    }
-                }
-            }
-            /* insert formatted string (or as-is conversion specifier
-               for unknown conversions)
-            */
-            {
-                int const n = str_arg_l - zero_padding_insertion_ind;
-                if (n > 0) {
-                    if (str_l < str_m) {
-                        size_t const avail = str_m-str_l;
-                        fast_memcpy(str + str_l,
-                                    str_arg + zero_padding_insertion_ind,
-                                    MIN(n, avail));
-                    }
-                    str_l += n;
-                }
-            }
-            /* insert right padding */
-            if (justify_left) {
-                /* right blank padding to the field width */
-                int const n =
-                    min_field_width - (str_arg_l + number_of_zeros_to_pad);
-                if (n > 0) {
-                    if (str_l < str_m) {
-                        size_t const avail = str_m - str_l;
-                        fast_memset(str+str_l, ' ', (MIN(n, avail)));
-                    }
-                    str_l += n;
-                }
-            }
-        }
-    }
-    if (str_m > 0) {
-        /* make sure the string is null-terminated even at the expense
-           of overwriting the last character (shouldn't happen, but
-           just in case)
-        */
-        str[MIN(str_l, str_m - 1)] = '\0';
-    }
-    *sizeP = str_l;
-}
-
-
-
-int
-pm_snprintf(char *       const dest,
-            size_t       const str_m,
-            const char * const fmt,
-            ...) {
-
-    size_t size;
-    va_list ap;
-
-    va_start(ap, fmt);
-
-    pm_vsnprintf(dest, str_m, fmt, ap, &size);
-
-    va_end(ap);
-
-    assert(size <= INT_MAX);
-
-    return size;
-}
-
-
-
 /* When a function that is supposed to return a malloc'ed string cannot
    get the memory for it, it should return 'pm_strsol'.  That has a much
    better effect on the caller, if the caller doesn't explicitly allow for
@@ -825,7 +84,7 @@ pm_asprintf(const char ** const resultP,
 
     va_start(varargs, fmt);
 
-    pm_vsnprintf(NULL, 0, fmt, varargs, &dryRunLen);
+    dryRunLen = vsnprintf(NULL, 0, fmt, varargs);
 
     va_end(varargs);
 
@@ -842,7 +101,7 @@ pm_asprintf(const char ** const resultP,
 
             va_start(varargs, fmt);
 
-            pm_vsnprintf(buffer, allocSize, fmt, varargs, &realLen);
+            realLen = vsnprintf(buffer, allocSize, fmt, varargs);
 
             assert(realLen == dryRunLen);
             va_end(varargs);
diff --git a/lib/util/nstring.h b/lib/util/nstring.h
index 8829617d..1aa486c6 100644
--- a/lib/util/nstring.h
+++ b/lib/util/nstring.h
@@ -22,17 +22,15 @@ extern "C" {
    array.
 */
 #define STRSCPY(A,B) \
-	(strncpy((A), (B), sizeof(A)), *((A)+sizeof(A)-1) = '\0')
+        (strncpy((A), (B), sizeof(A)), *((A)+sizeof(A)-1) = '\0')
 #define STRSCMP(A,B) \
-	(strncmp((A), (B), sizeof(A)))
+        (strncmp((A), (B), sizeof(A)))
 #define STRSCAT(A,B) \
     (strncpy(A+strlen(A), B, sizeof(A)-strlen(A)), *((A)+sizeof(A)-1) = '\0')
 #define STRSEQ(A, B) \
-	(strneq((A), (B), sizeof(A)))
+        (strneq((A), (B), sizeof(A)))
 
-#define MEMEQ(a,b,c) (memcmp(a, b, c) == 0)
-
-#define MEMSEQ(a,b) (memeq(a, b, sizeof(*(a))) == 0)
+#define MEMSEQ(a,b) (memeq(a, b, sizeof(*(a))))
 
 #define MEMSSET(a,b) (memset(a, b, sizeof(*(a))))
 
@@ -126,15 +124,11 @@ strncaseeq(const char * const comparand,
 #define TOUPPER(C) ((char)toupper((unsigned char)(C)))
 
 
-/* These are all private versions of commonly available standard C
-   library subroutines whose names are the same except with the N at
-   the end.  Because not all standard C libraries have them all,
-   Netpbm must include them in its own libraries, and because some
-   standard C libraries have some of them, Netpbm must use different
-   names for them.
+/* Most of these are private versions of commonly available standard C library
+   subroutines whose names are similar.  They're here because not all standard
+   C libraries have them.
 
-   The GNU C library has all of them.  All but the oldest standard C libraries
-   have snprintf().
+   The GNU C library has all of them.
 
    There are slight differences between the asprintf() family and that
    found in other libraries:
@@ -160,19 +154,6 @@ size_t
 pm_strnlen(const char * const s,
            size_t       const maxlen);
 
-int
-pm_snprintf(char *       const dest,
-            size_t       const str_m,
-            const char * const fmt,
-            ...) PM_GNU_PRINTF_ATTR(3,4);
-
-void
-pm_vsnprintf(char *       const str,
-             size_t       const str_m,
-             const char * const fmt,
-             va_list            ap,
-             size_t *     const sizeP);
-
 const char *
 pm_strdup(const char * const arg);
 
diff --git a/lib/util/pm_c_util.h b/lib/util/pm_c_util.h
index a093adb6..110d7536 100644
--- a/lib/util/pm_c_util.h
+++ b/lib/util/pm_c_util.h
@@ -13,7 +13,7 @@
 #undef ABS
 #define ABS(a) ((a) >= 0 ? (a) : -(a))
 #undef SGN
-#define SGN(a)		(((a)<0) ? -1 : 1)
+#define SGN(a)          (((a)<0) ? -1 : 1)
 #undef ODD
 #define ODD(n) ((n) & 1)
 #undef ROUND
@@ -65,7 +65,7 @@
   */
   #if ( defined(__GNUC__) && (__GNUC__ >= 2) ) || \
       ( defined(__STDC__) && (__STDC__ == 1) && \
-        defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L) ) 
+        defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L) )
     #include <stdbool.h>
   #else
     /* We used to assume that if TRUE was defined, then bool was too.
@@ -76,7 +76,7 @@
        also another library that defines bool, he can either make the
        other library define/respect HAVE_BOOL or just define HAVE_BOOL in
        the file that includes pm_config.h or with a compiler option.  Note
-       that C++ always has bool.  
+       that C++ always has bool.
     */
     #ifndef HAVE_BOOL
       #define HAVE_BOOL 1
diff --git a/lib/util/rand.c b/lib/util/rand.c
new file mode 100644
index 00000000..fd083c3b
--- /dev/null
+++ b/lib/util/rand.c
@@ -0,0 +1,320 @@
+/*
+
+Pseudo-random number generator for Netpbm
+
+The interface provided herein should be flexible enough for anybody
+who wishes to use some other random number generator.
+
+---
+
+If you desire to implement a different generator, or writing an original
+one, first take a look at the random number generator section of the
+GNU Scientific Library package (GSL).
+
+GNU Scientific Library
+https://www.gnu.org/software/gsl/
+
+GSL Random Number Generators
+https://wnww.gnu.org/software/gsl/doc/html/rng.html
+
+*/
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <inttypes.h>
+#include <strings.h>
+#include <time.h>
+#include <float.h>
+#include <math.h>
+
+#include "netpbm/pm_c_util.h"
+#include "netpbm/mallocvar.h"
+#include "netpbm/pm.h"
+#include "netpbm/rand.h"
+
+/*-----------------------------------------------------------------------------
+                              Use
+-------------------------------------------------------------------------------
+  Typical usage:
+
+      #include "rand.h"
+
+      ...
+
+      myfunction( ... , unsigned int const seed , ... ) {
+
+          struct randSt;
+
+          ...
+
+          pm_randinit(&randSt);
+          pm_srand(&randSt, seed);  // pm_srand2() is often more useful
+
+          ...
+
+          pm_rand(&randSt);
+
+          ...
+
+          pm_randterm(&randSt);
+
+      }
+-----------------------------------------------------------------------------*/
+
+
+
+/*-----------------------------------------------------------------------------
+                            Design note
+-------------------------------------------------------------------------------
+
+  Netpbm code contains multiple instances where random numbers are used.
+  Stock Netpbm always uses an internal pseudo-random number generator
+  that implements the Mersenne Twister method and does not rely on any
+  randomness facility of the operating system, but it is easy to compile
+  an alternative version that uses the operating system function, or some
+  other generator.
+
+  The Mersenne Twister method was new to Netpbm in Netpbm 10.94 (March 2021).
+  Before that, Netpbm used standard OS-provided facilities.
+
+  Programs that use random numbers have existed in Netpbm since PBMPlus days.
+  The system rand() function was used where randomness was required;
+  exceptions were rare and all of them appear to be errors on the part of the
+  original author.
+
+  Although the rand() function is available in every system on which Netpbm
+  runs, differences exist in the underlying algorithm, so that Netpbm programs
+  produced different output on different systems even when the user specified
+  the same random number seed.
+
+  This was not considered a problem in the early days.  Deterministic
+  operation was not a feature users requested and it was impossible regardless
+  of the random number generation method on most programs because they did not
+  allow a user to specify a seed for the generator.
+
+  This state of affairs changed as Netpbm got firmly established as a
+  base-level system package.  Security became critical for many users.  A
+  crucial component of quality control is automated regression tests (="make
+  check").  Unpredictable behavior gets in the way of testing.  One by one
+  programs were given the -randomseed (or -seed) option to ensure reproducible
+  results.  Often this was done as new test cases were written.  However,
+  inconsistent output caused by system-level differences in rand()
+  implementation remained a major obstacle.
+
+  In 2020 the decision was made to replace all calls to rand() in the Netpbm
+  source code with an internal random number generator.  We decided to use the
+  Mersenne Twister, which is concise, enjoys a fine reputation and is
+  available under liberal conditions (see below.)
+-----------------------------------------------------------------------------*/
+
+
+void
+pm_srand(struct pm_randSt * const randStP,
+         unsigned int       const seed) {
+/*----------------------------------------------------------------------------
+  Initialize (or "seed") the random number generation sequence with value
+  'seed'.
+-----------------------------------------------------------------------------*/
+    pm_randinit(randStP);
+
+    randStP->vtable.srand(randStP, seed);
+
+    randStP->seed = seed;
+}
+
+
+
+void
+pm_srand2(struct pm_randSt * const randStP,
+          bool               const seedValid,
+          unsigned int       const seed) {
+/*----------------------------------------------------------------------------
+  Seed the random number generator.  If 'seedValid' is true, use 'seed'.
+  Otherwise, use pm_randseed().
+
+  For historical reasons pm_randseed() is defined in libpm.c rather than
+  this source file.
+-----------------------------------------------------------------------------*/
+    pm_srand(randStP, seedValid ? seed : pm_randseed() );
+
+}
+
+
+
+unsigned long int
+pm_rand(struct pm_randSt * const randStP) {
+/*----------------------------------------------------------------------------
+  An integer random number in the interval [0, randStP->max].
+-----------------------------------------------------------------------------*/
+    return randStP->vtable.rand(randStP);
+}
+
+
+
+double
+pm_drand(struct pm_randSt * const randStP) {
+/*----------------------------------------------------------------------------
+  A floating point random number in the interval [0, 1].
+
+  Although the return value is declared as double, the actual value will have
+  no more precision than a single call to pm_rand() provides.  This is 32 bits
+  for Mersenne Twister.
+-----------------------------------------------------------------------------*/
+    return (double) pm_rand(randStP) / randStP->max;
+}
+
+
+
+double
+pm_drand1(struct pm_randSt * const randStP) {
+/*----------------------------------------------------------------------------
+  A floating point random number in the interval [0, 1).
+-----------------------------------------------------------------------------*/
+    return (double) pm_rand(randStP) / ((double) randStP->max + 1.0);
+}
+
+
+
+double
+pm_drand2(struct pm_randSt * const randStP) {
+/*----------------------------------------------------------------------------
+  A floating point random number in the interval (0, 1).
+-----------------------------------------------------------------------------*/
+    return ((double) pm_rand(randStP) + 0.5) / ((double) randStP->max + 1.0);
+}
+
+
+
+void
+pm_gaussrand2(struct pm_randSt * const randStP,
+              double *           const r1P,
+              double *           const r2P) {
+/*----------------------------------------------------------------------------
+  Generate two Gaussian (or normally) distributed random numbers *r1P and
+  *r2P.
+
+  Mean = 0, Standard deviation = 1.
+
+  This is called the Box-Muller method.
+
+  For details of this algorithm and other methods for producing
+  Gaussian random numbers see:
+
+  http://www.doc.ic.ac.uk/~wl/papers/07/csur07dt.pdf
+-----------------------------------------------------------------------------*/
+    double u1, u2;
+
+    u1 = pm_drand2(randStP);
+    u2 = pm_drand1(randStP);
+
+    *r1P = sqrt(-2.0 * log(u1)) * cos(2.0 * M_PI * u2);
+    *r2P = sqrt(-2.0 * log(u1)) * sin(2.0 * M_PI * u2);
+}
+
+
+
+double
+pm_gaussrand(struct pm_randSt * const randStP) {
+/*----------------------------------------------------------------------------
+  A Gaussian (or normally) distributed random number.
+
+  Mean = 0, Standard deviation = 1.
+
+  If a randStP->gaussCache has a value, return that value.  Otherwise call
+  pm_gaussrand2; return one generated value, remember the other.
+-----------------------------------------------------------------------------*/
+    double retval;
+
+    if (!randStP->gaussCacheValid) {
+        pm_gaussrand2(randStP, &retval, &randStP->gaussCache);
+        randStP->gaussCacheValid = true;
+    } else {
+        retval = randStP->gaussCache;
+        randStP->gaussCacheValid = false;
+    }
+
+    return retval;
+}
+
+
+
+uint32_t
+pm_rand32(struct pm_randSt * const randStP) {
+/*-----------------------------------------------------------------------------
+  Generate a 32-bit random number.
+-----------------------------------------------------------------------------*/
+    unsigned int const randMax = randStP->max;
+
+    /* 'randMax is a power of 2 minus 1.  Function pm_randinit() rejects
+       generators which do not satisfy this condition.  It is unlikely that
+       such odd generators actually exist.
+
+       Many system generators are known to return 31 bits (max = 2147483647 or
+       0x7FFFFFFF).  Historically, there were generators that returned only 15
+       bits.
+    */
+
+    uint32_t retval;
+
+    if (randMax >= 0xFFFFFFFF)
+        retval = pm_rand(randStP);
+    else {
+        uint32_t scale;
+
+        retval = 0;  /* Initial value */
+
+        for (scale = 0xFFFFFFFF; scale > 0; scale /= (randMax +1))
+            retval = retval * (randMax + 1) + pm_rand(randStP);
+    }
+
+    return retval;
+}
+
+
+
+void
+pm_randinit(struct pm_randSt * const randStP) {
+/*----------------------------------------------------------------------------
+  Initialize the random number generator.
+-----------------------------------------------------------------------------*/
+    switch (PM_RANDOM_NUMBER_GENERATOR) {
+    case PM_RAND_SYS_RAND:
+        randStP->vtable = pm_randsysrand_vtable;
+        break;
+    case PM_RAND_SYS_RANDOM:
+        randStP->vtable = pm_randsysrandom_vtable;
+        break;
+    case PM_RAND_MERSENNETWISTER:
+        randStP->vtable = pm_randmersenne_vtable;
+        break;
+    default:
+        pm_error("INTERNAL ERROR: Invalid value of "
+                 "PM_RANDOM_NUMBER_GENERATOR (random number generator "
+                 "engine type): %u", PM_RANDOM_NUMBER_GENERATOR);
+    }
+
+    randStP->vtable.init(randStP);
+
+    if (randStP->max == 0)
+        pm_error("Random number generator maximum value must be positive.");
+    else if (((long int) randStP->max & (long int) (randStP->max + 1)) != 0x0L)
+        pm_error("Non-standard random number generator with maximum value "
+                 "%u.  Cannot handle maximum values which are not powers "
+                 "of 2 minus 1", randStP->max);
+
+    randStP->gaussCacheValid = false;
+}
+
+
+
+void
+pm_randterm(struct pm_randSt * const randStP) {
+/*----------------------------------------------------------------------------
+  Tear down the random number generator.
+-----------------------------------------------------------------------------*/
+     if (randStP->stateP)
+         free(randStP->stateP);
+}
+
+
+
diff --git a/lib/util/rand.h b/lib/util/rand.h
new file mode 100644
index 00000000..fedf5aa0
--- /dev/null
+++ b/lib/util/rand.h
@@ -0,0 +1,118 @@
+/* Interface header file for random number generator functions in libnetpbm */
+
+#ifndef RAND_H_INCLUDED
+#define RAND_H_INCLUDED
+
+#include <inttypes.h>
+
+#include "netpbm/pm_c_util.h"
+#include "netpbm/mallocvar.h"
+
+/*
+  Definitions for selecting the random number generator
+
+  The default random number generator is Mersenne Twister.  Here we
+  provide a means to revert to the system rand() generator if need be.
+
+  Glibc provides generators: rand(), random() and drand48().  Each has
+  its own associated functions.  In the Glibc documentation rand() is
+  called "ISO", random() is called "BSD" and drand48() is called "SVID".
+  If your system has the glibc documentation installed "info rand" should
+  get you to the relevant page.  The documentation is available online
+  from:
+
+  https://www.gnu.org/software/libc/manual/html_node/Pseudo_002dRandom-Numbers.html
+  Pseudo-Random Numbers (The GNU C Library)
+
+  Glibc's choice of name is confusing for what it calls "ISO" rand()
+  was available in early BSD systems.
+
+  Functions by these names appear on most Unix systems, but generation
+  formulas and default initial states are known to differ.  On systems
+  which do not use glibc, what is called rand() may have no relation
+  with the formula of the ISO C standard.  Likewise random() may have
+  no relation with the BSD formula.
+*/
+
+enum PmRandEngine {PM_RAND_SYS_RAND,         /* rand()   */
+                   PM_RAND_SYS_RANDOM,       /* random() */
+                   PM_RAND_SYS_DRAND48,      /* drand48()  reserved */
+                   PM_RAND_MERSENNETWISTER   /* default */};
+
+#ifndef PM_RANDOM_NUMBER_GENERATOR
+  #define PM_RANDOM_NUMBER_GENERATOR PM_RAND_MERSENNETWISTER
+#endif
+
+
+/* Structure to hold random number generator profile and internal state */
+
+struct pm_randSt;
+
+struct pm_rand_vtable {
+    void
+    (*init)(struct pm_randSt * const randStP);
+
+    void
+    (*srand)(struct pm_randSt * const randStP,
+              unsigned int       const seed);
+
+    unsigned long int
+    (*rand)(struct pm_randSt * const randStP);
+};
+
+extern struct pm_rand_vtable const pm_randsysrand_vtable;
+extern struct pm_rand_vtable const pm_randsysrandom_vtable;
+extern struct pm_rand_vtable const pm_randmersenne_vtable;
+
+struct pm_randSt {
+    struct pm_rand_vtable vtable;
+    void *                stateP;  /* Internal state */
+    unsigned int          max;
+    unsigned int          seed;
+    bool                  gaussCacheValid;
+    double                gaussCache;
+};
+
+/* Function declarations */
+
+extern void
+pm_randinit(struct pm_randSt * const randStP);
+
+extern void
+pm_randterm(struct pm_randSt * const randStP);
+
+extern void
+pm_srand(struct pm_randSt * const randStP,
+         unsigned int       const seed);
+
+
+extern void
+pm_srand2(struct pm_randSt * const randStP,
+          bool               const withSeed,
+          unsigned int       const seedVal);
+
+extern unsigned long int
+pm_rand(struct pm_randSt * const randStP);
+
+extern double
+pm_drand(struct pm_randSt * const randStP);
+
+extern double
+pm_drand1(struct pm_randSt * const randStP);
+
+extern double
+pm_drand2(struct pm_randSt * const randStP);
+
+extern void
+pm_gaussrand2(struct pm_randSt * const randStP,
+              double *           const r1P,
+              double *           const r2P);
+
+extern double
+pm_gaussrand(struct pm_randSt * const randStP);
+
+extern uint32_t
+pm_rand32(struct pm_randSt * const randStP);
+
+
+#endif
diff --git a/lib/util/randmersenne.c b/lib/util/randmersenne.c
new file mode 100644
index 00000000..34355a23
--- /dev/null
+++ b/lib/util/randmersenne.c
@@ -0,0 +1,192 @@
+#include "netpbm/pm.h"
+#include "netpbm/rand.h"
+
+/* +++++ Start of Mersenne Twister pseudorandom number generator code +++++ */
+
+/*
+   Original source code from:
+   http://www.math.sci.hiroshima-u.ac.jp/m-mat/MT/VERSIONS/C-LANG/c-lang.html
+
+   A C-program for MT19937, with initialization improved 2002/1/26.
+   Coded by Takuji Nishimura and Makoto Matsumoto.
+
+   Copyright (C) 1997 - 2002, Makoto Matsumoto and Takuji Nishimura,
+   All rights reserved.
+
+   Redistribution and use in source and binary forms, with or without
+   modification, are permitted provided that the following conditions
+   are met:
+
+     1. Redistributions of source code must retain the above copyright
+        notice, this list of conditions and the following disclaimer.
+
+     2. Redistributions in binary form must reproduce the above copyright
+        notice, this list of conditions and the following disclaimer in the
+        documentation and/or other materials provided with the distribution.
+
+     3. The names of its contributors may not be used to endorse or promote
+        products derived from this software without specific prior written
+        permission.
+
+   THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+   "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+   LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+   A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT
+   OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+   SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+   LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+   DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+   THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+   (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+   OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+   Any feedback is very welcome.
+   http://www.math.sci.hiroshima-u.ac.jp/~m-mat/MT/emt.html
+   email: m-mat @ math.sci.hiroshima-u.ac.jp (remove space)
+
+   Above conditions apply in the following code to the line which says:
+   +++++ End of Mersenne Twister pseudorandom number generator code +++++
+*/
+
+/* Period parameters */
+
+#define MT_N 624
+#define MT_M 397
+#define MT_MATRIX_A 0x9908b0dfUL   /* constant vector a */
+
+struct MtState {
+    uint32_t mt[MT_N]; /* the array for the state vector  */
+    unsigned int mtIndex;
+};
+
+
+
+static void
+randMtAlloc(struct MtState ** const statePP) {
+
+    struct MtState * stateP;
+
+    MALLOCVAR_NOFAIL(stateP);
+
+    *statePP = stateP;
+}
+
+
+
+/* 32 bit masks */
+
+static uint32_t const FMASK = 0xffffffffUL; /* all bits */
+static uint32_t const UMASK = 0x80000000UL; /* most significant bit */
+static uint32_t const LMASK = 0x7fffffffUL; /* least significant 31 bits */
+
+
+
+static void
+srandMt(struct MtState * const stateP,
+        unsigned int     const seed) {
+/*-----------------------------------------------------------------------------
+  Initialize state array mt[MT_N] with seed
+-----------------------------------------------------------------------------*/
+    unsigned int mtIndex;
+    uint32_t * const mt = stateP->mt;
+
+    mt[0]= seed & FMASK;
+
+    for (mtIndex = 1; mtIndex < MT_N; ++mtIndex) {
+        mt[mtIndex] = (1812433253UL * (mt[mtIndex-1]
+                       ^ (mt[mtIndex-1] >> 30)) + mtIndex);
+
+        /* See Knuth TAOCP Vol2. 3rd Ed. P.106 for multiplier. */
+    }
+
+    stateP->mtIndex = mtIndex;
+}
+
+
+
+static unsigned long int
+randMt32(struct MtState * const stateP) {
+/*----------------------------------------------------------------------------
+  Generate a 32 bit random number   interval: [0, 0xffffffff]
+  ----------------------------------------------------------------------------*/
+    unsigned int mtIndex;
+    uint32_t retval;
+
+    if (stateP->mtIndex >= MT_N) {
+        /* generate N words at one time */
+        uint32_t * const mt = stateP->mt;
+        uint32_t const mag01[2]={0x0UL, MT_MATRIX_A};
+        /* mag01[x] = x * MT_MATRIX_A  for x=0, 1 */
+
+        int k;
+        uint32_t y;
+
+        if (stateP->mtIndex >= MT_N+1) {
+            pm_error("Internal error in Mersenne Twister random number"
+                     "generator");
+        }
+
+        for (k = 0; k < MT_N-MT_M; ++k) {
+            y = (mt[k] & UMASK) | (mt[k+1] & LMASK);
+            mt[k] = mt[k + MT_M] ^ (y >> 1) ^ mag01[y & 0x1UL];
+        }
+        for (; k < MT_N-1; ++k) {
+            y = (mt[k] & UMASK) | (mt[k+1] & LMASK);
+            mt[k] = mt[k+(MT_M-MT_N)] ^ (y >> 1) ^ mag01[y & 0x1UL];
+        }
+        y = (mt[MT_N - 1] & UMASK) | (mt[0] & LMASK);
+        mt[MT_N - 1] = mt[MT_M - 1] ^ (y >> 1) ^ mag01[y & 0x1UL];
+
+        mtIndex = 0;
+    } else
+        mtIndex = stateP->mtIndex;
+
+    retval = stateP->mt[mtIndex];
+
+    /* Tempering */
+    retval ^= (retval >> 11);
+    retval ^= (retval <<  7) & 0x9d2c5680UL;
+    retval ^= (retval << 15) & 0xefc60000UL;
+    retval ^= (retval >> 18);
+
+    stateP->mtIndex = mtIndex + 1;
+
+    return retval;
+}
+
+/* +++++ End of Mersenne Twister pseudorandom number generator code +++++ */
+
+
+static void
+vinit(struct pm_randSt * const randStP) {
+
+    randMtAlloc((struct MtState ** const) &randStP->stateP);
+    randStP->max    = 0xffffffffUL;
+}
+
+
+
+static void
+vsrand(struct pm_randSt * const randStP,
+       unsigned int       const seed) {
+
+    srandMt(randStP->stateP, seed);
+}
+
+
+
+static unsigned long int
+vrand(struct pm_randSt * const randStP) {
+
+    return randMt32(randStP->stateP);
+}
+
+
+
+struct pm_rand_vtable const pm_randmersenne_vtable = {
+    &vinit,
+    &vsrand,
+    &vrand
+};
+
+
diff --git a/lib/util/randsysrand.c b/lib/util/randsysrand.c
new file mode 100644
index 00000000..f97a5d3c
--- /dev/null
+++ b/lib/util/randsysrand.c
@@ -0,0 +1,39 @@
+#include <stdlib.h>
+
+#include "netpbm/rand.h"
+
+
+
+static void
+vinit(struct pm_randSt * const randStP) {
+
+    randStP->max    = RAND_MAX;
+    randStP->stateP = NULL;
+}
+
+
+
+static void
+vsrand(struct pm_randSt * const randStP,
+       unsigned int       const seed) {
+
+    srand(seed);
+}
+
+
+
+static unsigned long int
+vrand(struct pm_randSt * const randStP) {
+
+    return rand();
+}
+
+
+
+struct pm_rand_vtable const pm_randsysrand_vtable = {
+    &vinit,
+    &vsrand,
+    &vrand
+};
+
+
diff --git a/lib/util/randsysrandom.c b/lib/util/randsysrandom.c
new file mode 100644
index 00000000..f26bb18d
--- /dev/null
+++ b/lib/util/randsysrandom.c
@@ -0,0 +1,45 @@
+/* Implementation note: Mingw/Windows does not provide POSIX 'random', so
+   netpbm/pm_config.h makes that a macro for POSIX 'rand' on that platform
+*/
+
+#define _DEFAULT_SOURCE /* New name for SVID & BSD source defines */
+#define _XOPEN_SOURCE 500  /* Make sure random() is in stdlib.h */
+#define _BSD_SOURCE  /* Make sure random() is in stdlib.h */
+
+#include <stdlib.h>
+
+#include "netpbm/pm_config.h"
+#include "netpbm/rand.h"
+
+static void
+vinit(struct pm_randSt * const randStP) {
+
+    randStP->max    = RAND_MAX;
+    randStP->stateP = NULL;
+}
+
+
+
+static void
+vsrand(struct pm_randSt * const randStP,
+       unsigned int       const seed) {
+
+    srandom(seed);
+}
+
+
+
+static unsigned long int
+vrand(struct pm_randSt * const randStP) {
+
+    return random();
+}
+
+
+struct pm_rand_vtable const pm_randsysrandom_vtable = {
+    &vinit,
+    &vsrand,
+    &vrand
+};
+
+
diff --git a/lib/util/runlength.h b/lib/util/runlength.h
index de921650..f984267b 100644
--- a/lib/util/runlength.h
+++ b/lib/util/runlength.h
@@ -14,12 +14,12 @@ extern "C" {
 
 
 enum pm_RleMode { PM_RLE_PACKBITS,          /* most common mode */
-                  PM_RLE_GRAPHON,           /* reserved */ 
+                  PM_RLE_GRAPHON,           /* reserved */
                   PM_RLE_PPA,               /* reserved */
                   PM_RLE_SGI8,              /* reserved */
                   PM_RLE_SGI16,
                   PM_RLE_PALM16,
-                  PM_RLE_PALMPDB  
+                  PM_RLE_PALMPDB
                 };
 
 size_t
diff --git a/lib/util/shhopt.README b/lib/util/shhopt.README
index 2d241edf..f34f9a39 100644
--- a/lib/util/shhopt.README
+++ b/lib/util/shhopt.README
@@ -7,19 +7,20 @@ The file LICENSE.TXT in this directory contains the license (the
 Artistic License) under which Bryan took and redistributed Shhopt and
 the license under which Bryan offers the modified Shhopt to others.
 
-Bryan made the following changes to shhopt for Netpbm.  It is fully
-backward compatible with the original.
+Bryan made the following changes to shhopt for Netpbm.  
 
 - OPT_FLOAT (floating point number) data type added
 
-- optParseOptions2() added.  Advantages over optParseOptions(): You
+- symbols prefixed with "pm_".
+
+- pm_optParseOptions2() added.  Advantages over pm_optParseOptions(): You
   can have a syntax where there is no such thing as a short option
   (e.g. -a.  Maybe stacked like -tanp).  Then the long options can
   have either 1 or 2 dashes (e.g. -width or --width).  Of course, -w
   could be an abbreviation of -width; that's not the same thing as a
   short option.
 
-- optParseOptions3() added.  Advantages over optParseOptions2(): 
+- pm_optParseOptions3() added.  Advantages over pm_optParseOptions2(): 
   Tells you whether (how many times, actually) an option was
   specified - no need to play games with defaults.  Also, no need
   to initialize an option value variable.
@@ -34,6 +35,15 @@ backward compatible with the original.
 - replace isdigit() with ISDIGIT() from Netpbm nstring.h so weird 
   8-bit characters don't cause incorrect results.
 
+- OPT_NAMELIST and OPT_STRINGLIST added.
+
+WARNING: pm_optParseOptionsX modify their argv argument (the array of
+pointers, not the the things to which they point).
+
+WARNING: The option values returned by pm_optParseOptionsX for options of type
+OPT_STRING reside in the program's argument space (the memory addressed by the
+program's argv array).
+
 ------------------------------------------------------------------------------
 
 
diff --git a/lib/util/shhopt.c b/lib/util/shhopt.c
index cc8f165e..5c74efdb 100644
--- a/lib/util/shhopt.c
+++ b/lib/util/shhopt.c
@@ -34,30 +34,22 @@
 #include "token.h"
 #include "shhopt.h"
 
-/*-----------------------------------------------------------------------+
-|  PRIVATE DATA                                                          |
-+-----------------------------------------------------------------------*/
+
 
 static void optFatalFunc(const char *, ...);
 static void (*optFatal)(const char *format, ...) = optFatalFunc;
 
-/*-----------------------------------------------------------------------+
-|  PRIVATE FUNCTIONS                                                     |
-+-----------------------------------------------------------------------*/
 
-/*------------------------------------------------------------------------
- |  NAME          optFatalFunc
- |
- |  FUNCTION      Show given message and abort the program.
- |
- |  INPUT         format, ...
- |                        Arguments used as with printf().
- |
- |  RETURNS       Never returns. The program is aborted.
- */
+
 static void
-optFatalFunc(const char *format, ...)
-{
+optFatalFunc(const char * const format, ...) {
+/*----------------------------------------------------------------------------
+  FUNCTION      Show given message and abort the program.
+
+  INPUT         Arguments used as with printf().
+
+  RETURNS       Never returns. The program is aborted.
+-----------------------------------------------------------------------------*/
     va_list ap;
 
     fflush(stdout);
@@ -68,21 +60,20 @@ optFatalFunc(const char *format, ...)
     exit(99);
 }
 
-/*------------------------------------------------------------------------
- |  NAME          optStructCount
- |
- |  FUNCTION      Get number of options in a optStruct.
- |
- |  INPUT         opt     array of possible options.
- |
- |  RETURNS       Number of options in the given array.
- |
- |  DESCRIPTION   Count elements in an optStruct-array. The structure must
- |                be ended using an element of type OPT_END.
- */
+
+
 static int
-optStructCount(const optEntry opt[])
-{
+optStructCount(const optEntry * const opt) {
+/*--------------------------------------------------------------------------
+  FUNCTION      Get number of options in a optStruct.
+
+  INPUT         opt     array of possible options.
+
+  RETURNS       Number of options in the given array.
+
+  DESCRIPTION   Count elements in an optStruct-array. The structure must
+                 be ended using an element of type OPT_END.
+----------------------------------------------------------------------------*/
     int ret = 0;
 
     while (opt[ret].type != OPT_END && ret < 500)
@@ -92,68 +83,84 @@ optStructCount(const optEntry opt[])
 
 
 
-static int
-optMatch(optEntry     const opt[],
-         const char * const s,
-         int          const lng) {
+enum Shortlong {SL_SHORT, SL_LONG};
+
+static void
+optMatch(optEntry       const opt[],
+         const char *   const targetOpt,
+         enum Shortlong const shortLong,
+         bool *         const foundP,
+         unsigned int * const optIndexP) {
 /*------------------------------------------------------------------------
- |  FUNCTION      Find a matching option.
- |
- |  INPUT         opt     array of possible options.
- |                s       string to match, without `-' or `--'.
- |                lng     match long option, otherwise short.
- |
- |  RETURNS       Index to the option if found, -1 if not found.
- |
- |  DESCRIPTION   Short options are matched from the first character in
- |                the given string.
- */
+   FUNCTION      Find a matching option.
+
+   INPUT         opt        array of valid option names.
+                 targetOpt  option string to match, without `-' or `--'.
+                            e.g. "verbose" or "height=5"
+                 shortLong  whether to match short option or long
+
+   RETURNS       *foundP     there is a matching option class the table
+                 *optIndexP  index in the option class table
+                             meaningless if *foundP is false
 
-    unsigned int const nopt = optStructCount(opt);
+   DESCRIPTION   Short options are matched from the first character in
+                 the given string.
+
+                 Where multiple entries in opt[] match, return the first.
+--------------------------------------------------------------------------*/
+    unsigned int const optCt = optStructCount(opt);
 
     unsigned int q;
     unsigned int matchlen;
-    const char * p;
-
-    matchlen = 0;  /* initial value */
+    bool found;
+    unsigned int optIndex;
 
-    if (lng) {
-        if ((p = strchr(s, '=')) != NULL)
-            matchlen = p - s;
+    if (shortLong == SL_LONG) {
+        const char * const equalPos = strchr(targetOpt, '=');
+        if (equalPos)
+            matchlen = equalPos - &targetOpt[0];
         else
-            matchlen = strlen(s);
-    }
-    for (q = 0; q < nopt; ++q) {
-        if (lng) {
+            matchlen = strlen(targetOpt);
+    } else
+        matchlen = 0;
+
+    for (q = 0, found = false; q < optCt && !found; ++q) {
+        switch (shortLong) {
+        case SL_LONG: {
             if (opt[q].longName) {
-                if (strncmp(s, opt[q].longName, matchlen) == 0)
-                    return q;
+                if (strneq(targetOpt, opt[q].longName, matchlen)) {
+                    found = true;
+                    optIndex = q;
+                }
             }
-        } else {
+        }
+        case SL_SHORT: {
             if (opt[q].shortName) {
-                if (s[0] == opt[q].shortName)
-                    return q;
+                if (targetOpt[0] == opt[q].shortName) {
+                    found = true;
+                    optIndex = q;
+                }
             }
         }
+        }
     }
-    return -1;
+    *foundP    = found;
+    *optIndexP = optIndex;
 }
 
 
 
-/*------------------------------------------------------------------------
- |  NAME          optString
- |
- |  FUNCTION      Return a (static) string with the option name.
- |
- |  INPUT         opt     the option to stringify.
- |                lng     is it a long option?
- |
- |  RETURNS       Pointer to static string.
- */
 static char *
-optString(const optEntry opte, int lng)
-{
+optString(optEntry const opte,
+          int      const lng) {
+/*--------------------------------------------------------------------------
+   FUNCTION      Return a (static) string with the option name.
+
+   INPUT         opt     the option to stringify.
+                 lng     is it a long option?
+
+   RETURNS       Pointer to static string.
+--------------------------------------------------------------------------*/
     static char ret[31];
 
     if (lng) {
@@ -170,7 +177,7 @@ optString(const optEntry opte, int lng)
 
 
 static optEntry
-optStructToEntry(const optStruct opt) {
+optStructToEntry(optStruct const opt) {
 /*----------------------------------------------------------------------------
    Return the information in 'opt' (an optStruct type) as an optEntry type.
    optEntry is newer and has an additional field.
@@ -184,13 +191,13 @@ optStructToEntry(const optStruct opt) {
     opte.specified = NULL;
     opte.flags     = opt.flags;
 
-    return(opte);
+    return opte;
 }
 
 
 
 static optEntry *
-optStructTblToEntryTbl(const optStruct optStructTable[]) {
+optStructTblToEntryTbl(const optStruct * const optStructTable) {
 /*----------------------------------------------------------------------------
    Return a table of optEntry types containing the information in the
    input table of optStruct types.
@@ -219,49 +226,48 @@ optStructTblToEntryTbl(const optStruct optStructTable[]) {
 
 
 
-/*------------------------------------------------------------------------
- |  NAME          optNeedsArgument
- |
- |  FUNCTION      Check if an option requires an argument.
- |
- |  INPUT         opt     the option to check.
- |
- |  RETURNS       Boolean value.
- */
 static int
-optNeedsArgument(const optEntry opt)
-{
+optNeedsArgument(const optEntry opt) {
+/*--------------------------------------------------------------------------
+   FUNCTION      Check if an option requires an argument.
+
+   INPUT         opt     the option to check.
+
+   RETURNS       Boolean value.
+---------------------------------------------------------------------------*/
     return opt.type == OPT_STRING
-	|| opt.type == OPT_INT
-	|| opt.type == OPT_UINT
-	|| opt.type == OPT_LONG
-	|| opt.type == OPT_ULONG
+        || opt.type == OPT_INT
+        || opt.type == OPT_UINT
+        || opt.type == OPT_LONG
+        || opt.type == OPT_ULONG
     || opt.type == OPT_FLOAT
     || opt.type == OPT_NAMELIST
     || opt.type == OPT_STRINGLIST
         ;
 }
 
-/*------------------------------------------------------------------------
- |  NAME          argvRemove
- |
- |  FUNCTION      Remove an entry from an argv-array.
- |
- |  INPUT         argc    pointer to number of options.
- |                argv    array of option-/argument-strings.
- |                i       index of option to remove.
- |
- |  OUTPUT        argc    new argument count.
- |                argv    array with given argument removed.
- */
+
+
 static void
-argvRemove(int *argc, char *argv[], int i)
-{
-    if (i >= *argc)
-        return;
-    while (i++ < *argc)
-        argv[i - 1] = argv[i];
-    --*argc;
+argvRemove(int *         const argcP,
+           const char ** const argv,
+           unsigned int  const n) {
+/*------------------------------------------------------------------------
+   INPUT         argc    pointer to number of options.
+                 argv    array of option-/argument-strings.
+                 n       index of option to remove.
+
+   OUTPUT        argc    new argument count.
+                 argv    array with given argument removed.
+--------------------------------------------------------------------------*/
+    if (n < *argcP) {
+        unsigned int i;
+
+        for (i = n; i++ < *argcP; )
+            argv[i - 1] = argv[i];
+
+        --*argcP;
+    }
 }
 
 
@@ -378,21 +384,20 @@ parseStringList(const char *   const listText,
 
 
 
-/*------------------------------------------------------------------------
- |  NAME          optExecute
- |
- |  FUNCTION      Perform the action of an option.
- |
- |  INPUT         opt     element in array of defined options that
- |                        applies to this option
- |                arg     argument to option, if it applies.
- |                lng     was the option given as a long option?
- |
- |  RETURNS       Nothing. Aborts in case of error.
- */
 static void
-optExecute(optEntry  const opt, char *arg, int lng)
-{
+optExecute(optEntry     const opt,
+           const char * const arg,
+           int          const lng) {
+/*--------------------------------------------------------------------------
+   FUNCTION      Perform the action of an option.
+
+   INPUT         opt     element in array of defined options that
+                         applies to this option
+                 arg     argument to option, if it applies.
+                 lng     was the option given as a long option?
+
+   RETURNS       Nothing. Aborts in case of error.
+----------------------------------------------------------------------------*/
     if (opt.specified)
         *opt.specified = 1;
 
@@ -404,7 +409,7 @@ optExecute(optEntry  const opt, char *arg, int lng)
 
     case OPT_STRING:
         if (opt.arg)
-            *((char **) opt.arg) = arg;
+            *((const char **) opt.arg) = arg;
         break;
 
     case OPT_INT:
@@ -498,99 +503,87 @@ optExecute(optEntry  const opt, char *arg, int lng)
 
 
 
-/*-----------------------------------------------------------------------+
-|  PUBLIC FUNCTIONS                                                      |
-+-----------------------------------------------------------------------*/
-
-/*------------------------------------------------------------------------
- |  NAME          optSetFatalFunc
- |
+void
+pm_optSetFatalFunc(void (*f)(const char *, ...)) {
+/*--------------------------------------------------------------------------
  |  FUNCTION      Set function used to display error message and exit.
  |
- |  SYNOPSIS      #include "shhopt.h"
- |                void optSetFatalFunc(void (*f)(const char *, ...));
- |
  |  INPUT         f       function accepting printf()'like parameters,
  |                        that _must_ abort the program.
- */
-void
-pm_optSetFatalFunc(void (*f)(const char *, ...)) {
-
+----------------------------------------------------------------------------*/
     optFatal = f;
 }
 
 
 
-/*------------------------------------------------------------------------
- |  NAME          pm_optParseOptions
- |
- |  FUNCTION      Parse commandline options.
- |
- |  SYNOPSIS      #include "shhopt.h"
- |                void pm_optParseOptions(int *argc, char *argv[],
- |                                     optStruct opt[], int allowNegNum);
- |
- |  INPUT         argc    Pointer to number of options.
- |                argv    Array of option-/argument-strings.
- |                opt     Array of possible options.
- |                allowNegNum
- |                        a negative number is not to be taken as
- |                        an option.
- |
- |  OUTPUT        argc    new argument count.
- |                argv    array with arguments removed.
- |
- |  RETURNS       Nothing. Aborts in case of error.
- |
- |  DESCRIPTION   This function checks each option in the argv-array
- |                against strings in the opt-array, and `executes' any
- |                matching action. Any arguments to the options are
- |                extracted and stored in the variables or passed to
- |                functions pointed to by entries in opt.
- |
- |                Options and arguments used are removed from the argv-
- |                array, and argc is decreased accordingly.
- |
- |                Any error leads to program abortion.
- */
 void
-pm_optParseOptions(int *argc, char *argv[], optStruct opt[], int allowNegNum)
-{
-    int  ai,        /* argv index. */
-         optarg,    /* argv index of option argument, or -1 if none. */
-         mi,        /* Match index in opt. */
-         done;
-    char *arg,      /* Pointer to argument to an option. */
-         *o,        /* pointer to an option character */
-         *p;
-
-    optEntry *opt_table;  /* malloc'ed array */
-
-    opt_table = optStructTblToEntryTbl(opt);
-    if (opt_table == NULL)
+pm_optParseOptions(int *       const argcP,
+                   char **     const argv,
+                   optStruct * const opt,
+                   int         const allowNegNum) {
+/*------------------------------------------------------------------------
+   FUNCTION      Parse commandline options.
+
+   INPUT         argc    Pointer to number of options.
+                 argv    Array of option-/argument-strings.
+                 opt     Array of possible options.
+                 allowNegNum
+                         a negative number is not to be taken as
+                         an option.
+
+   OUTPUT        argc    new argument count.
+                 argv    array with arguments removed.
+
+   RETURNS       Nothing. Aborts in case of error.
+
+   DESCRIPTION   This function checks each option in the argv-array
+                 against strings in the opt-array, and `executes' any
+                 matching action. Any arguments to the options are
+                 extracted and stored in the variables or passed to
+                 functions pointed to by entries in opt.
+
+                 Options and arguments used are removed from the argv-
+                 array, and argc is decreased accordingly.
+
+                 Any error leads to program abortion.
+----------------------------------------------------------------------------*/
+    int ai;        /* argv index. */
+    int optarg;    /* argv index of option argument, or -1 if none. */
+    int done;
+    char * arg;      /* Pointer to argument to an option. */
+    char * o;        /* pointer to an option character */
+    char * p;
+
+    optEntry * optTable;  /* malloc'ed array */
+
+    optTable = optStructTblToEntryTbl(opt);
+    if (optTable == NULL)
         optFatal("Memory allocation failed (trying to allocate space for "
                  "new-format option table)");
 
     /*
      *  Loop through all arguments.
      */
-    for (ai = 0; ai < *argc; ) {
+    for (ai = 0; ai < *argcP; ) {
         /*
          *  "--" indicates that the rest of the argv-array does not
          *  contain options.
          */
-        if (strcmp(argv[ai], "--") == 0) {
-            argvRemove(argc, argv, ai);
+        if (streq(argv[ai], "--")) {
+            argvRemove(argcP, (const char **)argv, ai);
             break;
         }
 
         if (allowNegNum && argv[ai][0] == '-' && ISDIGIT(argv[ai][1])) {
             ++ai;
             continue;
-        } else if (strncmp(argv[ai], "--", 2) == 0) {
+        } else if (strneq(argv[ai], "--", 2)) {
+            bool found;
+            unsigned int mi;
             /* long option */
             /* find matching option */
-            if ((mi = optMatch(opt_table, argv[ai] + 2, 1)) < 0)
+            optMatch(optTable, argv[ai] + 2, SL_LONG, &found, &mi);
+            if (!found)
                 optFatal("unrecognized option `%s'", argv[ai]);
 
             /* possibly locate the argument to this option. */
@@ -600,24 +593,24 @@ pm_optParseOptions(int *argc, char *argv[], optStruct opt[], int allowNegNum)
 
             /* does this option take an argument? */
             optarg = -1;
-            if (optNeedsArgument(opt_table[mi])) {
+            if (optNeedsArgument(optTable[mi])) {
                 /* option needs an argument. find it. */
                 if (!arg) {
-                    if ((optarg = ai + 1) == *argc)
+                    if ((optarg = ai + 1) == *argcP)
                         optFatal("option `%s' requires an argument",
-                                 optString(opt_table[mi], 1));
+                                 optString(optTable[mi], 1));
                     arg = argv[optarg];
                 }
             } else {
                 if (arg)
                     optFatal("option `%s' doesn't allow an argument",
-                             optString(opt_table[mi], 1));
+                             optString(optTable[mi], 1));
             }
-            optExecute(opt_table[mi], arg, 1);
+            optExecute(optTable[mi], arg, 1);
             /* remove option and any argument from the argv-array. */
             if (optarg >= 0)
-                argvRemove(argc, argv, ai);
-            argvRemove(argc, argv, ai);
+                argvRemove(argcP, (const char **)argv, ai);
+            argvRemove(argcP, (const char **)argv, ai);
         } else if (*argv[ai] == '-') {
             /* A dash by itself is not considered an option. */
             if (argv[ai][1] == '\0') {
@@ -629,45 +622,50 @@ pm_optParseOptions(int *argc, char *argv[], optStruct opt[], int allowNegNum)
             done = 0;
             optarg = -1;
             while (*o && !done) {
+                bool found;
+                unsigned int mi;
                 /* find matching option */
-                if ((mi = optMatch(opt_table, o, 0)) < 0)
+                optMatch(optTable, o, SL_SHORT, &found, &mi);
+                if (!found)
                     optFatal("unrecognized option `-%c'", *o);
 
                 /* does this option take an argument? */
                 optarg = -1;
                 arg = NULL;
-                if (optNeedsArgument(opt_table[mi])) {
+                if (optNeedsArgument(optTable[mi])) {
                     /* option needs an argument. find it. */
                     arg = o + 1;
                     if (!*arg) {
-                        if ((optarg = ai + 1) == *argc)
+                        if ((optarg = ai + 1) == *argcP)
                             optFatal("option `%s' requires an argument",
-                                     optString(opt_table[mi], 0));
+                                     optString(optTable[mi], 0));
                         arg = argv[optarg];
                     }
                     done = 1;
                 }
                 /* perform the action of this option. */
-                optExecute(opt_table[mi], arg, 0);
+                optExecute(optTable[mi], arg, 0);
                 ++o;
             }
             /* remove option and any argument from the argv-array. */
             if (optarg >= 0)
-                argvRemove(argc, argv, ai);
-            argvRemove(argc, argv, ai);
+                argvRemove(argcP, (const char **)argv, ai);
+            argvRemove(argcP, (const char **)argv, ai);
         } else {
             /* a non-option argument */
             ++ai;
         }
     }
-    free(opt_table);
+    free(optTable);
 }
 
 
 static void
-parse_short_option_token(char *argv[], const int argc, const int ai,
-                         const optEntry opt_table[],
-                         int * const tokens_consumed_p) {
+parseShortOptionToken(const char **    const argv,
+                      int              const argc,
+                      int              const ai,
+                      const optEntry * const optTable,
+                      unsigned int *   const tokensConsumedP) {
 /*----------------------------------------------------------------------------
    Parse a cluster of short options, e.g. -walne .
 
@@ -677,41 +675,43 @@ parse_short_option_token(char *argv[], const int argc, const int ai,
    argv[] and argc describe the whole program argument set.  'ai' is the
    index of the argument that is the short option cluster.
 -----------------------------------------------------------------------------*/
-    char *o;  /* A short option character */
-    char *arg;
-    int mi;   /* index into option table */
-    unsigned char processed_arg;  /* boolean */
+    const char * optP;  /* A short option character */
+    const char * arg;   /* The argument of the short option */
+    bool processedArg;
         /* We processed an argument to one of the one-character options.
            This necessarily means there are no more options in this token
            to process.
            */
 
-    *tokens_consumed_p = 1;  /* initial assumption */
+    *tokensConsumedP = 1;  /* initial assumption */
 
-    o = argv[ai] + 1;
-    processed_arg = 0;  /* initial value */
-    while (*o && !processed_arg) {
-		/* find matching option */
-		if ((mi = optMatch(opt_table, o, 0)) < 0)
-		    optFatal("unrecognized option `-%c'", *o);
+    for (optP = argv[ai] + 1, processedArg = false;
+         *optP && !processedArg; ) {
 
-		/* does this option take an argument? */
-		if (optNeedsArgument(opt_table[mi])) {
-		    /* option needs an argument. find it. */
-		    arg = o + 1;
-		    if (!*arg) {
+        bool found;
+        unsigned int mi;   /* index into option table */
+        /* find matching option */
+        optMatch(optTable, optP, SL_SHORT, &found, &mi);
+        if (!found)
+            optFatal("unrecognized option `-%c'", *optP);
+
+        /* does this option take an argument? */
+        if (optNeedsArgument(optTable[mi])) {
+            /* option needs an argument. find it. */
+            arg = optP + 1;
+            if (!*arg) {
                 if (ai + 1 >= argc)
-			    optFatal("option `%s' requires an argument",
-				     optString(opt_table[mi], 0));
-			arg = argv[ai+1];
-            (*tokens_consumed_p)++;
-		    }
-		    processed_arg = 1;
-		} else
+                    optFatal("option `%s' requires an argument",
+                             optString(optTable[mi], 0));
+                arg = argv[ai+1];
+                ++*tokensConsumedP;
+            }
+            processedArg = 1;
+        } else
             arg = NULL;
-		/* perform the action of this option. */
-		optExecute(opt_table[mi], arg, 0);
-		++o;
+        /* perform the action of this option. */
+        optExecute(optTable[mi], arg, 0);
+        ++optP;
     }
 }
 
@@ -721,7 +721,7 @@ static void
 fatalUnrecognizedLongOption(const char * const optionName,
                             optEntry     const optTable[]) {
 
-    unsigned int const nopt = optStructCount(optTable);
+    unsigned int const optCt = optStructCount(optTable);
 
     unsigned int q;
 
@@ -730,7 +730,7 @@ fatalUnrecognizedLongOption(const char * const optionName,
     optList[0] = '\0';  /* initial value */
 
     for (q = 0;
-         q < nopt && strlen(optList) + 1 <= sizeof(optList);
+         q < optCt && strlen(optList) + 1 <= sizeof(optList);
          ++q) {
 
         const optEntry * const optEntryP = &optTable[q];
@@ -757,12 +757,12 @@ fatalUnrecognizedLongOption(const char * const optionName,
 
 
 static void
-parse_long_option(char *   const argv[],
-                  int      const argc,
-                  int      const ai,
-                  int      const namepos,
-                  optEntry const opt_table[],
-                  int *    const tokens_consumed_p) {
+parseLongOption(const char **    const argv,
+                int              const argc,
+                int              const ai,
+                int              const namepos,
+                const optEntry * const optTable,
+                unsigned int *   const tokensConsumedP) {
 /*----------------------------------------------------------------------------
    Parse a long option, e.g. -verbose or --verbose.
 
@@ -772,102 +772,68 @@ parse_long_option(char *   const argv[],
    argv[] and argc describe the whole program argument set.  'ai' is the
    index of the argument that is the long option.
 -----------------------------------------------------------------------------*/
-    char *equals_arg;
+    char * equalsArg;
       /* The argument of an option, included in the same token, after a
          "=".  NULL if no "=" in the token.
          */
-    char *arg;     /* The argument of an option; NULL if none */
-    int mi;    /* index into option table */
+    const char * arg;     /* The argument of an option; NULL if none */
+    bool found;
+    unsigned int mi;    /* index into option table */
 
     /* The current token is an option, and its name starts at
        Index 'namepos' in the argument.
     */
-    *tokens_consumed_p = 1;  /* initial assumption */
+    *tokensConsumedP = 1;  /* initial assumption */
     /* find matching option */
-    if ((mi = optMatch(opt_table, &argv[ai][namepos], 1)) < 0)
-        fatalUnrecognizedLongOption(argv[ai], opt_table);
+    optMatch(optTable, &argv[ai][namepos], SL_LONG, &found, &mi);
+    if (!found)
+        fatalUnrecognizedLongOption(argv[ai], optTable);
 
     /* possibly locate the argument to this option. */
     {
-        char *p;
+        char * p;
         if ((p = strchr(argv[ai], '=')) != NULL)
-            equals_arg = p + 1;
+            equalsArg = p + 1;
         else
-            equals_arg = NULL;
+            equalsArg = NULL;
     }
     /* does this option take an argument? */
-    if (optNeedsArgument(opt_table[mi])) {
+    if (optNeedsArgument(optTable[mi])) {
         /* option needs an argument. find it. */
-        if (equals_arg)
-            arg = equals_arg;
+        if (equalsArg)
+            arg = equalsArg;
         else {
             if (ai + 1 == argc)
                 optFatal("option `%s' requires an argument",
-                         optString(opt_table[mi], 1));
+                         optString(optTable[mi], 1));
             arg = argv[ai+1];
-            (*tokens_consumed_p)++;
+            ++*tokensConsumedP;
         }
     } else {
-        if (equals_arg)
+        if (equalsArg)
             optFatal("option `%s' doesn't allow an argument, but you "
                      "have specified it in the form name=value",
-                     optString(opt_table[mi], 1));
+                     optString(optTable[mi], 1));
         else
             arg = NULL;
     }
     /* perform the action of this option. */
-    optExecute(opt_table[mi], arg, 1);
+    optExecute(optTable[mi], arg, 1);
 }
 
 
 
-/*------------------------------------------------------------------------
- |  NAME          pm_optParseOptions2
- |
- |  FUNCTION      Parse commandline options.
- |
- |  SYNOPSIS      #include "shhopt.h"
- |                void pm_optParseOptions2(int *argc, char *argv[],
- |                                      optStruct2 opt, unsigned long flags);
- |
- |  INPUT         argc    Pointer to number of options.
- |                argv    Array of option-/argument-strings.
- |                opt     Structure describing option syntax.
- |                flags   Result is undefined if not zero.
- |                        For future expansion.
- |
- |  OUTPUT        argc    new argument count.
- |                argv    array with arguments removed.
- |
- |  RETURNS       Nothing. Aborts in case of error.
- |
- |  DESCRIPTION   This function checks each option in the argv-array
- |                against strings in the opt-array, and `executes' any
- |                matching action. Any arguments to the options are
- |                extracted and stored in the variables or passed to
- |                functions pointed to by entries in opt.
- |
- |                This differs from pm_optParseOptions in that it accepts
- |                long options with just one hyphen and doesn't accept
- |                any short options.  It also has accommodations for
- |                future expansion.
- |
- |                Options and arguments used are removed from the argv-
- |                array, and argc is decreased accordingly.
- |
- |                Any error leads to program abortion.
- */
 void
-pm_optParseOptions2(int * const argc_p, char *argv[], const optStruct2 opt,
-                 const unsigned long flags)
+pm_optParseOptions2(int *         const argcP,
+                    char **       const argv,
+                    optStruct2    const opt,
+                    unsigned long const flags) {
 /*----------------------------------------------------------------------------
    This does the same thing as pm_optParseOptions3(), except that there is no
    "specified" return value.
 
    This function exists for backward compatibility.
 -----------------------------------------------------------------------------*/
-
-{
     optStruct3 opt3;
 
     opt3.short_allowed = opt.short_allowed;
@@ -878,7 +844,7 @@ pm_optParseOptions2(int * const argc_p, char *argv[], const optStruct2 opt,
         optFatal("Memory allocation failed (trying to allocate space for "
                  "new-format option table)");
 
-    pm_optParseOptions3(argc_p, argv, opt3, sizeof(opt3), flags);
+    pm_optParseOptions3(argcP, argv, opt3, sizeof(opt3), flags);
 
     free(opt3.opt_table);
 }
@@ -887,120 +853,132 @@ pm_optParseOptions2(int * const argc_p, char *argv[], const optStruct2 opt,
 
 
 static void
-zero_specified(optEntry opt_table[]) {
+zeroSpecified(const optEntry * const optTable) {
 /*----------------------------------------------------------------------------
    Set all the "number of times specified" return values identified in the
-   option table opt_table[] to zero.
+   option table opttable[] to zero.
 -----------------------------------------------------------------------------*/
     unsigned int i;
 
-    for (i = 0; opt_table[i].type != OPT_END; i++) {
-        if (opt_table[i].specified)
-            *(opt_table[i].specified) = 0;
+    for (i = 0; optTable[i].type != OPT_END; ++i) {
+        if (optTable[i].specified)
+            *(optTable[i].specified) = 0;
     }
 }
 
 
 
-/*------------------------------------------------------------------------
- |  NAME          pm_optParseOptions3
- |
- |  FUNCTION      Parse commandline options.
- |
- |  INPUT         argc    Pointer to number of options.
- |                argv    Array of option-/argument-strings.
- |                opt     Structure describing option syntax.
- |                optStructSize
- |                        Size of "opt" (since the caller may be older
- |                        than this function, it may be using a structure
- |                        with fewer fields than exist today.  We use this
- |                        parameter to handle those older callers).
- |                flags   Result is undefined if not zero.
- |                        For future expansion.
- |
- |  OUTPUT        argc    new argument count.
- |                argv    array with arguments removed.
- |
- |                Areas pointed to by pointers in 'opt' get updated with
- |                option values and counts.
- |
- |  RETURNS       Nothing. Aborts in case of error.
- |
- |  DESCRIPTION   This function checks each option in the argv-array
- |                against strings in the opt-array, and `executes' any
- |                matching action. Any arguments to the options are
- |                extracted and stored in the variables or passed to
- |                functions pointed to by entries in opt.
- |
- |                This differs from pm_optParseOptions in that it accepts
- |                long options with just one hyphen and doesn't accept
- |                any short options.  It also has accommodations for
- |                future expansion.
- |
- |                Options and arguments used are removed from the argv-
- |                array, and argc is decreased accordingly.
- |
- |                Any error leads to program abortion.
- */
 void
-pm_optParseOptions3(int * const argc_p, char *argv[], const optStruct3 opt,
-                 const unsigned int optStructSize, const unsigned long flags)
-{
-    int  ai;        /* argv index. */
-    int tokens_consumed;
-    unsigned char no_more_options;  /* boolean */
+pm_optParseOptions3(int *         const argcP,
+                    char **       const argv,
+                    optStruct3    const opt,
+                    unsigned int  const optStructSz,
+                    unsigned long const flags) {
+/*----------------------------------------------------------------------------
+  Same as 'pm_optParseOptions4', except argv has type char ** instead of const
+  char **.  This function does not modify the argv[] strings; it exists for
+  backward compatibility with programs that pass an argv of type char ** .
+-----------------------------------------------------------------------------*/
+    pm_optParseOptions4(argcP, (const char **)argv, opt, optStructSz, flags);
+}
+
+
+
+void
+pm_optParseOptions4(int *         const argcP,
+                    const char ** const argv,
+                    optStruct3    const opt,
+                    unsigned int  const optStructSize,
+                    unsigned long const flags) {
+/*---------------------------------------------------------------------------
+   FUNCTION      Parse commandline options.
+
+   INPUT         argc    Pointer to number of options.
+                 argv    Array of option-/argument-strings.
+                 opt     Structure describing option syntax.
+                 optStructSize
+                         Size of "opt" (since the caller may be older
+                         than this function, it may be using a structure
+                         with fewer fields than exist today.  We use this
+                         parameter to handle those older callers).
+                 flags   Result is undefined if not zero.
+                         For future expansion.
+
+   OUTPUT        argc    new argument count.
+                 argv    array with arguments removed.
+
+                 Areas pointed to by pointers in 'opt' get updated with
+                 option values and counts.
+
+   RETURNS       Nothing. Aborts in case of error.
+
+   DESCRIPTION   This function checks each option in the argv-array
+                 against strings in the opt-array, and `executes' any
+                 matching action. Any arguments to the options are
+                 extracted and stored in the variables or passed to
+                 functions pointed to by entries in opt.
+
+                 This differs from pm_optParseOptions in that it accepts
+                 long options with just one hyphen and doesn't accept
+                 any short options.  It also has accommodations for
+                 future expansion.
+
+                 Options and arguments used are removed from the argv-
+                 array, and argc is decreased accordingly.
+
+                 Any error leads to program abortion.
+----------------------------------------------------------------------------*/
+    unsigned int ai;        /* argv index. */
+    unsigned int tokensConsumed;
+    bool noMoreOptions;
         /* We've encountered the "no more options" token */
 
-    zero_specified(opt.opt_table);
+    zeroSpecified(opt.opt_table);
 
-    /*
-     *  Loop through all arguments.
-     */
-    no_more_options = 0;  /* initial value */
-    for (ai = 0; ai < *argc_p; ) {
-        if (no_more_options)
+    for (ai = 0, noMoreOptions = false; ai < *argcP; ) {
+        if (noMoreOptions)
             /* Can't be an option -- there aren't any more */
-            ai++;
+            ++ai;
         else if (argv[ai][0] != '-')
             /* Can't be an option -- doesn't start with a dash */
-            ai++;
+            ++ai;
         else {
             /* It starts with a dash -- could be an option */
             if (argv[ai][1] == '\0') {
                 /* A dash by itself is not considered an option. */
                 ++ai;
-                tokens_consumed = 0;
+                tokensConsumed = 0;
             } else if (opt.allowNegNum && ISDIGIT(argv[ai][1])) {
                 /* It's a negative number parameter, not an option */
                 ++ai;
-                tokens_consumed = 0;
+                tokensConsumed = 0;
             } else if (argv[ai][1] == '-') {
                 /* It starts with -- */
                 if (argv[ai][2] == '\0') {
                     /* The entire thing is "--".  That means no more options */
-                    tokens_consumed = 1;
-                    no_more_options = 1;
+                    tokensConsumed = 1;
+                    noMoreOptions  = true;
                 } else
                     /* It's an option that starts with "--" */
-                    parse_long_option(argv, *argc_p, ai, 2,
-                                      opt.opt_table, &tokens_consumed);
+                    parseLongOption(argv, *argcP, ai, 2,
+                                    opt.opt_table, &tokensConsumed);
             } else {
                 if (opt.short_allowed) {
                     /* It's a cluster of (one or more) short options */
-                    parse_short_option_token(argv, *argc_p, ai,
-                                             opt.opt_table, &tokens_consumed);
+                    parseShortOptionToken(argv, *argcP, ai,
+                                          opt.opt_table, &tokensConsumed);
                 } else {
                     /* It's a long option that starts with "-" */
-                    parse_long_option(argv, *argc_p, ai, 1,
-                                      opt.opt_table, &tokens_consumed);
+                    parseLongOption(argv, *argcP, ai, 1,
+                                    opt.opt_table, &tokensConsumed);
                 }
 
             }
             /* remove option and any argument from the argv-array. */
             {
-                int i;
-                for (i = 0; i < tokens_consumed; i++)
-                    argvRemove(argc_p, argv, ai);
+                unsigned int i;
+                for (i = 0; i < tokensConsumed; ++i)
+                    argvRemove(argcP, argv, ai);
             }
         }
     }
@@ -1020,3 +998,5 @@ pm_optDestroyNameValueList(struct optNameValue * const list) {
 
     free(list);
 }
+
+
diff --git a/lib/util/shhopt.h b/lib/util/shhopt.h
index b6d4cdfd..26d375e4 100644
--- a/lib/util/shhopt.h
+++ b/lib/util/shhopt.h
@@ -10,14 +10,12 @@ main ( int argc, char **argv ) {
     /* initial values here are just to demonstrate what gets set and
        what doesn't by the code below.
     */
-    int help_flag = 7;
-    unsigned int help_spec =7;
-    unsigned int height_spec =7;
-    unsigned int name_spec= 7;
+    unsigned int heightSpec =7;
+    unsigned int nameSpec= 7;
     char *name= "initial";
     int height=7;
-    int verbose_flag=7;
-    int debug_flag=7;
+    int verboseFlag=7;
+    int debugFlag=7;
     char ** methodlist;
     struct optNameValue * optlist;
 
@@ -26,12 +24,12 @@ main ( int argc, char **argv ) {
     optEntry * option_def;
     MALLOCARRAY(option_def, 100);
 
-    OPTENT3(0,   "height",   OPT_INT,        &height,       &height_spec, 0);
-    OPTENT3('n', "name",     OPT_STRING,     &name,         &name_spec,   0);
-    OPTENT3('v', "verbose",  OPT_FLAG,       &verbose_flag, NULL,         0);
-    OPTENT3('g', "debug",    OPT_FLAG,       &debug_flag,   NULL,         0);
-    OPTENT3(0,   "methods",  OPT_STRINGLIST, &methodlist,   NULL,         0);
-    OPTENT3(0,   "options",  OPT_NAMELIST,   &optlist,      NULL,         0);
+    OPTENT3(0,   "height",   OPT_INT,        &height,       &heightSpec,  0);
+    OPTENT3('n', "name",     OPT_STRING,     &name,         &nameSpec,    0);
+    OPTENT3('v', "verbose",  OPT_FLAG,       &verboseFlag,  NULL,         0);
+    OPTENT3('g', "debug",    OPT_FLAG,       &debugFlag,    NULL,         0);
+    OPTENT3(0,   "methods",  OPT_STRINGLIST, &methodlist,   &methodSpec,  0);
+    OPTENT3(0,   "options",  OPT_NAMELIST,   &optlist,      &optSpec,     0);
 
     opt.opt_table = option_def;
     opt.short_allowed = 1;
@@ -43,13 +41,13 @@ main ( int argc, char **argv ) {
 
     printf("argc=%d\n", argc);
     printf("height=%d\n", height);
-    printf("height_spec=%d\n", height_spec);
+    printf("height_spec=%d\n", heightSpec);
     printf("name='%s'\n", name);
-    printf("name_spec=%d\n", name_spec);
-    printf("verbose_flag=%d\n", verbose_flag);
-    printf("debug_flag=%d\n", verbose_flag);
+    printf("name_spec=%d\n", nameSpec);
+    printf("verbose_flag=%d\n", verboseFlag);
+    printf("debug_flag=%d\n", verboseFlag);
 
-    if (methodlist) {
+    if (methodSpec) {
         unsigned int i;
         printf("methods: ");
         while (methodlist[i]) {
@@ -60,7 +58,7 @@ main ( int argc, char **argv ) {
     } else
         printf("No -options\n");
 
-    if (optlist) {
+    if (optSpec) {
         unsigned int i;
         while (optlist[i].name) {
             printf("option '%s' = '%s'\n", optlist[i].name, optlist[i].value);
@@ -84,6 +82,7 @@ Now run this program with something like
   you need an OPTENTINIT call to establish the empty option table:
 
     optEntry * option_def;
+    unsigned int option_def_index;
     MALLOCARRAY(option_def, 1);
     OPTENTINIT;
 
@@ -210,7 +209,7 @@ typedef struct {
 /* OPTENT3 is the same as OPTENTRY except that it also sets the "specified"
    element of the table entry (so it assumes OPTION_DEF is a table of optEntry
    instead of optStruct).  This is a pointer to a variable that the parser
-   will set to and indication of whether the option appears in the command
+   will set to an indication of whether the option appears in the command
    line.  1 for yes; 0 for no.
 
    HISTORICAL NOTE: Until 2019, this was the number of times the option was
@@ -225,8 +224,8 @@ typedef struct {
        const char * alpha_filename
        unsigned int alpha_spec;
        MALLOCARRAY_NOFAIL(option_def, 100);
-       OPTENT3('h', "verbose",  OPT_FLAG,   &verbose_flag    NULL);
-       OPTENT3(0,   "alphaout", OPT_STRING, &alpha_filename, &alpha_spec);
+       OPTENT3('h', "verbose",  OPT_FLAG,   &verbose_flag,   NULL,        0);
+       OPTENT3(0,   "alphaout", OPT_STRING, &alpha_filename, &alpha_spec, 0);
 */
 
 #define OPTENT3(shortvalue,longvalue,typevalue,outputvalue,specifiedvalue, \
@@ -262,6 +261,13 @@ pm_optParseOptions3(int * const argc_p, char *argv[], const optStruct3 opt,
                  const unsigned int optStructSize, const unsigned long flags);
 
 void
+pm_optParseOptions4(int *         const argcP,
+                    const char ** const argv,
+                    optStruct3    const opt,
+                    unsigned int  const optStructSize,
+                    unsigned long const flags);
+
+void
 pm_optDestroyNameValueList(struct optNameValue * const list);
 
 #ifdef __cplusplus
diff --git a/lib/util/testnstring.c b/lib/util/testnstring.c
index 87e6139e..0952f04c 100644
--- a/lib/util/testnstring.c
+++ b/lib/util/testnstring.c
@@ -12,7 +12,7 @@ int
 main(int argc, char **argv) {
 
     char snprintfNResult[80];
-    const char * asprintfNResult; 
+    const char * asprintfNResult;
 
     printf("Hello world.\n");
 
@@ -20,7 +20,7 @@ main(int argc, char **argv) {
 
     printf("snprintfN result='%s'\n", snprintfNResult);
 
-    asprintfN(&asprintfNResult, "asprintf'ed string %d %u %s", 
+    asprintfN(&asprintfNResult, "asprintf'ed string %d %u %s",
               5, 89, "substring");
 
     printf("asprintfN result='%s'\n", asprintfNResult);
diff --git a/lib/util/token.c b/lib/util/token.c
index a68a4821..c81432f7 100644
--- a/lib/util/token.c
+++ b/lib/util/token.c
@@ -65,7 +65,7 @@ pm_gettoken(const char *  const tokenStart,
                 token[charCount++] = *cursor++;
             }
             token[charCount] = '\0';
-            
+
             *tokenP = token;
             *nextP = cursor;
         }
diff --git a/lib/util/vasprintf.c b/lib/util/vasprintf.c
index a947f763..fbca457a 100644
--- a/lib/util/vasprintf.c
+++ b/lib/util/vasprintf.c
@@ -1,9 +1,11 @@
+#define _C99_SOURCE  /* Make sure snprintf() is in stdio.h */
 #define _GNU_SOURCE
    /* Because of conditional compilation, this is GNU source only if the C
       library is GNU.
    */
 #include <stdlib.h>
 #include <string.h>
+#include <stdio.h>
 
 #include "pm_config.h"
 #include "pm_c_util.h"
@@ -36,7 +38,7 @@ pm_vasprintf(const char ** const resultP,
        simply make two copies of the va_list variable in normal C
        fashion, but on others you need va_copy, which is a relatively
        recent invention.  In particular, the simple va_list copy
-       failed on an AMD64 Gcc Linux system in March 2006.  
+       failed on an AMD64 Gcc Linux system in March 2006.
 
        So instead, we just allocate 4K and truncate or waste as
        necessary.
@@ -49,14 +51,14 @@ pm_vasprintf(const char ** const resultP,
     */
     size_t const allocSize = 4096;
     result = malloc(allocSize);
-    
+
     if (result == NULL)
         *resultP = pm_strsol;
     else {
         size_t realLen;
 
-        pm_vsnprintf(result, allocSize, format, varargs, &realLen);
-        
+        realLen = vsnprintf(result, allocSize, format, varargs);
+
         if (realLen >= allocSize)
             strcpy(result + allocSize - 15, "<<<TRUNCATED");
 
@@ -75,3 +77,6 @@ pm_vasprintf_knows_float(void) {
     return false;
 #endif
 }
+
+
+
diff --git a/other/Makefile b/other/Makefile
index aa0d75bb..b3884666 100644
--- a/other/Makefile
+++ b/other/Makefile
@@ -24,10 +24,14 @@ endif
 # build.
 
 PORTBINARIES = pamarith pambayer pamchannel pamdepth \
-	pamendian pamexec pamfix pamlookup pampick pamsplit \
+	pamendian pamfix pamlookup pampick pamsplit \
 	pamstack pamsummcol pamunlookup pamvalidate pnmcolormap \
 	ppmdcfont ppmddumpfont ppmdmkfont 
 
+ifneq ($(DONT_HAVE_PROCESS_MGMT),Y)
+  PORTBINARIES += pamexec
+endif
+
 ifneq ($(LINUXSVGALIB),NONE)
   PORTBINARIES += ppmsvgalib
 endif
diff --git a/other/pamarith.c b/other/pamarith.c
index 31f52a59..05ba5327 100644
--- a/other/pamarith.c
+++ b/other/pamarith.c
@@ -112,7 +112,7 @@ parseCommandLine(int argc, const char ** const argv,
     opt.short_allowed = FALSE;  /* We have no short (old-fashioned) options */
     opt.allowNegNum = FALSE;  /* We have no parms that are negative numbers */
 
-    pm_optParseOptions3(&argc, (char **)argv, opt, sizeof(opt), 0);
+    pm_optParseOptions4(&argc, argv, opt, sizeof(opt), 0);
         /* Uses and sets argc, argv, and some of *cmdlineP and others. */
 
     if (addSpec + subtractSpec + multiplySpec + divideSpec + differenceSpec +
diff --git a/other/pambayer.c b/other/pambayer.c
index 7fc1f809..1d5522f9 100644
--- a/other/pambayer.c
+++ b/other/pambayer.c
@@ -18,7 +18,7 @@
   USA
 
   Copyright Alexandre Becoulet <diaxen AT free DOT fr>
-  
+
   Completely rewritten for Netpbm by Bryan Henderson August 2005.
 */
 
@@ -32,31 +32,29 @@
 #include "nstring.h"
 
 
-enum bayerType {
+enum BayerType {
     BAYER1,
     BAYER2,
     BAYER3,
     BAYER4
 };
 
-struct cmdlineInfo {
-    const char * inputFilespec;
-    enum bayerType bayerType;
-    unsigned int nointerpolate;
+struct CmdlineInfo {
+    const char *   inputFilespec;
+    enum BayerType bayerType;
+    unsigned int   nointerpolate;
 };
 
 
 
 static void
 parseCommandLine(int argc, const char ** argv,
-                 struct cmdlineInfo * const cmdlineP) {
+                 struct CmdlineInfo * const cmdlineP) {
 /*----------------------------------------------------------------------------
    Note that the file spec array we return is stored in the storage that
    was passed to us as the argv array.
 -----------------------------------------------------------------------------*/
     optEntry * option_def;
-        /* Instructions to pm_optParseOptions3 on how to parse our options.
-         */
     optStruct3 opt;
 
     unsigned int option_def_index;
@@ -66,18 +64,20 @@ parseCommandLine(int argc, const char ** argv,
     MALLOCARRAY_NOFAIL(option_def, 100);
 
     option_def_index = 0;   /* incremented by OPTENT3 */
-    OPTENT3(0, "type",     OPT_UINT, &type,
-            &typeSpec, 0);
+    OPTENT3(0, "type",          OPT_UINT, &type,
+            &typeSpec,                      0);
     OPTENT3(0, "nointerpolate", OPT_FLAG, NULL,
-            &cmdlineP->nointerpolate, 0);
+            &cmdlineP->nointerpolate,       0);
 
     opt.opt_table = option_def;
     opt.short_allowed = FALSE;  /* We have no short (old-fashioned) options */
     opt.allowNegNum = FALSE;  /* We may have parms that are negative numbers */
 
-    pm_optParseOptions3(&argc, (char **)argv, opt, sizeof(opt), 0);
+    pm_optParseOptions4(&argc, argv, opt, sizeof(opt), 0);
         /* Uses and sets argc, argv, and some of *cmdlineP and others. */
 
+    free(option_def);
+
     if (argc-1 < 1)
         cmdlineP->inputFilespec = "-";
     else if (argc-1 > 1)
@@ -101,13 +101,61 @@ parseCommandLine(int argc, const char ** argv,
 
 
 static void
-calc_4(const struct pam * const pamP,
-       tuple **           const intuples,
-       tuple **           const outtuples,
-       unsigned int       const plane,
-       bool               const noInterpolation,
-       unsigned int       const xoffset,
-       unsigned int       const yoffset) {
+clearTuples(const struct pam * const pamP,
+            tuple **           const outtuples) {
+/*----------------------------------------------------------------------------
+  Make tuples at the edge that may not get set to anything by the normal
+  computation of the bayer pattern black.
+-----------------------------------------------------------------------------*/
+    if (pamP->height <= 4 || pamP->width <= 4) {
+        unsigned int row;
+
+        for (row = 0; row < pamP->height; ++row) {
+            unsigned int col;
+            for (col = 0; col < pamP->width; ++col) {
+                unsigned int plane;
+                for (plane = 0; plane < pamP->depth; ++plane)
+                    outtuples[row][col][plane] = 0;
+            }
+        }
+    } else {
+        unsigned int col;
+        unsigned int row;
+
+        for (col = 0; col < pamP->width; ++col) {
+            unsigned int plane;
+
+            for (plane = 0; plane < pamP->depth; ++plane) {
+                outtuples[0][col][plane] = 0;
+                outtuples[1][col][plane] = 0;
+                outtuples[pamP->height-2][col][plane] = 0;
+                outtuples[pamP->height-1][col][plane] = 0;
+            }
+
+            for (row = 2; row < pamP->height - 2; ++row) {
+                unsigned int plane;
+
+                for (plane = 0; plane < pamP->depth; ++plane) {
+                    outtuples[row][0][plane] = 0;
+                    outtuples[row][1][plane] = 0;
+                    outtuples[row][pamP->width-2][plane] = 0;
+                    outtuples[row][pamP->width-1][plane] = 0;
+                }
+            }
+        }
+    }
+}
+
+
+
+static void
+calc4(const struct pam * const pamP,
+      tuple **           const intuples,
+      tuple **           const outtuples,
+      unsigned int       const plane,
+      bool               const noInterpolation,
+      unsigned int       const xoffset,
+      unsigned int       const yoffset) {
 /*----------------------------------------------------------------------------
     X . X
     . . .
@@ -121,7 +169,7 @@ calc_4(const struct pam * const pamP,
   (even/odd is with respect to ('xoffset', 'yoffset')).
 -----------------------------------------------------------------------------*/
     unsigned int row;
-    
+
     /* Do the even rows -- the even column pixels get copied from the input,
        while the odd column pixels get the mean of adjacent even ones
     */
@@ -140,7 +188,7 @@ calc_4(const struct pam * const pamP,
     for (row = yoffset; row + 2 < pamP->height; row += 2) {
         unsigned int col;
         for (col = xoffset; col < pamP->width; ++col) {
-            outtuples[row + 1][col][plane] = 
+            outtuples[row + 1][col][plane] =
                 noInterpolation ?
                 0 :
                 (outtuples[row][col][plane] +
@@ -152,13 +200,13 @@ calc_4(const struct pam * const pamP,
 
 
 static void
-calc_5(const struct pam * const pamP,
-       tuple **           const intuples,
-       tuple **           const outtuples,
-       unsigned int       const plane,
-       bool               const noInterpolation,
-       unsigned int       const xoffset,
-       unsigned int       const yoffset) {
+calc5(const struct pam * const pamP,
+      tuple **           const intuples,
+      tuple **           const outtuples,
+      unsigned int       const plane,
+      bool               const noInterpolation,
+      unsigned int       const xoffset,
+      unsigned int       const yoffset) {
 /*----------------------------------------------------------------------------
    . X .
    X . X
@@ -194,7 +242,7 @@ calc_5(const struct pam * const pamP,
 
 
 
-struct compAction {
+struct CompAction {
     unsigned int xoffset;
     unsigned int yoffset;
     void (*calc)(const struct pam * const pamP,
@@ -207,54 +255,68 @@ struct compAction {
 };
 
 
+struct BayerPattern {
 
-static struct compAction const comp_1[3] = {
+    struct CompAction compAction[3];
+        /* compAction[n] tells how to compute Plane 'n' */
+};
+
+
+
+static struct BayerPattern const bayer1 = {
 /*----------------------------------------------------------------------------
   G B G B
   R G R G
   G B G B
   R G R G
 -----------------------------------------------------------------------------*/
-
-    { 0, 1, calc_4 },
-    { 0, 1, calc_5 },
-    { 1, 0, calc_4 }
+    {  /* compAction */
+        { 0, 1, calc4 },
+        { 0, 1, calc5 },
+        { 1, 0, calc4 }
+    }
 };
 
-static struct compAction const comp_2[3] = {
+static struct BayerPattern const bayer2 = {
 /*----------------------------------------------------------------------------
   R G R G
   G B G B
   R G R G
   G B G B
 -----------------------------------------------------------------------------*/
-    { 0, 0, calc_4 },
-    { 0, 0, calc_5 },
-    { 1, 1, calc_4 }
+    {  /* compAction */
+        { 0, 0, calc4 },
+        { 0, 0, calc5 },
+        { 1, 1, calc4 }
+    }
 };
 
-static struct compAction const comp_3[3] = {
+static struct BayerPattern const bayer3 = {
 /*----------------------------------------------------------------------------
   B G B G
   G R G R
   B G B G
   G R G R
 -----------------------------------------------------------------------------*/
-    { 1, 1, calc_4 },
-    { 0, 0, calc_5 },
-    { 0, 0, calc_4 }
+    {  /* compAction */
+        { 1, 1, calc4 },
+        { 0, 0, calc5 },
+        { 0, 0, calc4 }
+    }
 };
 
-static struct compAction const comp_4[3] = {
+static struct BayerPattern const bayer4 = {
 /*----------------------------------------------------------------------------
   G R G R
   B G B G
   G R G R
   B G B G
 -----------------------------------------------------------------------------*/
-    { 1, 0, calc_4 },
-    { 0, 1, calc_5 },
-    { 0, 1, calc_4 }
+    {  /* compAction */
+        { 1, 0, calc4 },
+        { 0, 1, calc5 },
+        { 0, 1, calc4 }
+    }
 };
 
 
@@ -278,55 +340,83 @@ makeOutputPam(const struct pam * const inpamP,
 
 
 
-static const struct compAction *
-actionTableForType(enum bayerType const bayerType) {
+struct XyOffset {
+/*----------------------------------------------------------------------------
+   A two-dimensional offset within a matrix.
+-----------------------------------------------------------------------------*/
+    unsigned int row;
+    unsigned int col;
+};
+
 
-    const struct compAction * retval;
+
+static const struct CompAction *
+actionTableForType(enum BayerType const bayerType) {
+
+    const struct CompAction * retval;
 
     switch (bayerType) {
-    case BAYER1: retval = comp_1; break;
-    case BAYER2: retval = comp_2; break;
-    case BAYER3: retval = comp_3; break;
-    case BAYER4: retval = comp_4; break;
+    case BAYER1: retval = bayer1.compAction; break;
+    case BAYER2: retval = bayer2.compAction; break;
+    case BAYER3: retval = bayer3.compAction; break;
+    case BAYER4: retval = bayer4.compAction; break;
     }
     return retval;
 }
 
 
 
-int
+static void
+calcImage(struct pam *   const inpamP,
+          tuple **       const intuples,
+          struct pam *   const outpamP,
+          tuple **       const outtuples,
+          enum BayerType const bayerType,
+          bool           const wantNoInterpolate) {
+
+    const struct CompAction * const compActionTable =
+        actionTableForType(bayerType);
+
+    unsigned int plane;
+
+    clearTuples(outpamP, outtuples);
+
+    for (plane = 0; plane < 3; ++plane) {
+
+        struct CompAction const compAction = compActionTable[plane];
+
+        compAction.calc(inpamP, intuples, outtuples, plane,
+                        wantNoInterpolate,
+                        compAction.xoffset, compAction.yoffset);
+    }
+}
+
+
+            int
 main(int argc, const char **argv) {
 
-    struct cmdlineInfo cmdline;
+    struct CmdlineInfo cmdline;
     FILE * ifP;
     struct pam inpam;
     struct pam outpam;
     tuple ** intuples;
     tuple ** outtuples;
-    const struct compAction * compActionTable;
-    unsigned int plane;
 
     pm_proginit(&argc, argv);
-    
+
     parseCommandLine(argc, argv, &cmdline);
-    
+
     ifP = pm_openr(cmdline.inputFilespec);
-    
-    intuples = pnm_readpam(ifP, &inpam, PAM_STRUCT_SIZE(tuple_type));
 
-    compActionTable = actionTableForType(cmdline.bayerType);
+    intuples = pnm_readpam(ifP, &inpam, PAM_STRUCT_SIZE(tuple_type));
 
     makeOutputPam(&inpam, &outpam);
 
     outtuples = pnm_allocpamarray(&outpam);
 
-    for (plane = 0; plane < 3; ++plane) {
-        struct compAction const compAction = compActionTable[plane];
+    calcImage(&inpam, intuples, &outpam, outtuples,cmdline.bayerType,
+              !!cmdline.nointerpolate);
 
-        compAction.calc(&inpam, intuples, outtuples, plane,
-                        cmdline.nointerpolate,
-                        compAction.xoffset, compAction.yoffset);
-    }
     pnm_writepam(&outpam, outtuples);
 
     pnm_freepamarray(outtuples, &outpam);
@@ -334,3 +424,6 @@ main(int argc, const char **argv) {
 
     return 0;
 }
+
+
+
diff --git a/other/pamchannel.c b/other/pamchannel.c
index e89a979b..95fdc088 100644
--- a/other/pamchannel.c
+++ b/other/pamchannel.c
@@ -43,8 +43,6 @@ parseCommandLine(int argc, const char ** argv,
    was passed to us as the argv array.
 -----------------------------------------------------------------------------*/
     optEntry *option_def;
-        /* Instructions to pm_optParseOptions3 on how to parse our options.
-         */
     optStruct3 opt;
     extern struct pam pam;  /* Just so we can look at field sizes */
 
@@ -54,16 +52,16 @@ parseCommandLine(int argc, const char ** argv,
     MALLOCARRAY_NOFAIL(option_def, 100);
 
     option_def_index = 0;   /* incremented by OPTENT3 */
-    OPTENT3(0, "infile",     OPT_STRING, &cmdlineP->inputFileName, 
+    OPTENT3(0, "infile",     OPT_STRING, &cmdlineP->inputFileName,
             &infileSpec, 0);
-    OPTENT3(0, "tupletype",  OPT_STRING, &cmdlineP->tupletype, 
+    OPTENT3(0, "tupletype",  OPT_STRING, &cmdlineP->tupletype,
             &tupletypeSpec, 0);
 
     opt.opt_table = option_def;
     opt.short_allowed = FALSE;  /* We have no short (old-fashioned) options */
     opt.allowNegNum = FALSE;  /* We have no parms that are negative numbers */
 
-    pm_optParseOptions3(&argc, (char **)argv, opt, sizeof(opt), 0);
+    pm_optParseOptions4(&argc, argv, opt, sizeof(opt), 0);
         /* Uses and sets argc, argv, and some of *cmdlineP and others. */
 
     if (!infileSpec)
@@ -78,16 +76,16 @@ parseCommandLine(int argc, const char ** argv,
                      (unsigned)sizeof(pam.tuple_type));
 
     cmdlineP->n_channel = 0;  /* initial value */
-    { 
+    {
         int argn;
         for (argn = 1; argn < argc; argn++) {
             int n;
             char *endptr;
 
-            if (cmdlineP->n_channel >= MAX_CHANNELS) 
+            if (cmdlineP->n_channel >= MAX_CHANNELS)
                 pm_error("You may not specify more than %d channels.",
                          MAX_CHANNELS);
-            
+
             n = strtol(argv[argn], &endptr, 10);
             if (n < 0)
                 pm_error("Channel numbers cannot be negative.  "
@@ -95,7 +93,7 @@ parseCommandLine(int argc, const char ** argv,
             if (endptr == NULL)
                 pm_error("non-numeric channel number argument: '%s'",
                          argv[argn]);
-            
+
             cmdlineP->channel_to_extract[cmdlineP->n_channel++] = n;
         }
     }
@@ -106,13 +104,13 @@ parseCommandLine(int argc, const char ** argv,
 
 
 static void
-validateChannels(int          const n_channel, 
-                 unsigned int const channels[], 
+validateChannels(int          const n_channel,
+                 unsigned int const channels[],
                  int          const depth) {
 
     int i;
 
-    for (i = 0; i < n_channel; i++) 
+    for (i = 0; i < n_channel; i++)
         if (channels[i] > depth-1)
             pm_error("You specified channel number %d.  The highest numbered\n"
                      "channel in the input image is %d.",
@@ -140,18 +138,18 @@ doOneImage(FILE *       const ifP,
     outpam.depth  = nChannel;
     outpam.format = PAM_FORMAT;
     strcpy(outpam.tuple_type, tupletype);
-    
+
     pnm_writepaminit(&outpam);
 
     {
         tuple * inrow;
         tuple * outrow;
-        
-        inrow  = pnm_allocpamrow(&inpam);      
+
+        inrow  = pnm_allocpamrow(&inpam);
         outrow = pnm_allocpamrow(&outpam);
-        { 
+        {
             unsigned int row;
-            
+
             for (row = 0; row < inpam.height; ++row) {
                 unsigned int col;
 
@@ -159,15 +157,15 @@ doOneImage(FILE *       const ifP,
 
                 for (col = 0; col < inpam.width; ++col) {
                     unsigned int plane;
-                    for (plane = 0; plane < nChannel; ++plane) 
-                        outrow[col][plane] = 
+                    for (plane = 0; plane < nChannel; ++plane)
+                        outrow[col][plane] =
                             inrow[col][channelToExtract[plane]];
                 }
                 pnm_writepamrow(&outpam, outrow);
             }
         }
         pnm_freepamrow(outrow);
-        pnm_freepamrow(inrow);        
+        pnm_freepamrow(inrow);
     }
 }
 
@@ -183,7 +181,7 @@ main(int argc, const char *argv[]) {
     pm_proginit(&argc, argv);
 
     parseCommandLine(argc, argv, &cmdline);
-    
+
     ifP = pm_openr(cmdline.inputFileName);
 
     eof = FALSE;
diff --git a/other/pamdepth.c b/other/pamdepth.c
index 46601864..4425fcf2 100644
--- a/other/pamdepth.c
+++ b/other/pamdepth.c
@@ -36,8 +36,6 @@ parseCommandLine(int argc, const char ** argv,
    was passed to us as the argv array.
 -----------------------------------------------------------------------------*/
     optEntry * option_def;
-        /* Instructions to pm_optParseOptions3 on how to parse our options.
-         */
     optStruct3 opt;
 
     unsigned int option_def_index;
@@ -52,7 +50,7 @@ parseCommandLine(int argc, const char ** argv,
     opt.short_allowed = FALSE;  /* We have no short (old-fashioned) options */
     opt.allowNegNum = FALSE;  /* We may have parms that are negative numbers */
 
-    pm_optParseOptions3(&argc, (char **)argv, opt, sizeof(opt), 0);
+    pm_optParseOptions4(&argc, argv, opt, sizeof(opt), 0);
         /* Uses and sets argc, argv, and some of *cmdlineP and others. */
 
     if (argc-1 < 1)
@@ -124,7 +122,7 @@ transformRaster(struct pam * const inpamP,
                 tuplerow[col][plane] = sampleMap[tuplerow[col][plane]];
         }
         pnm_writepamrow(outpamP, tuplerow);
-	}
+        }
 
     pnm_freepamrow(tuplerow);
 
diff --git a/other/pamendian.c b/other/pamendian.c
index d82ebd38..8826b06f 100644
--- a/other/pamendian.c
+++ b/other/pamendian.c
@@ -1,20 +1,21 @@
-/******************************************************************************
+/*=============================================================================
                               pamendian
-*******************************************************************************
+===============================================================================
 
   Reverse the endianness of multi-byte samples in a Netpbm stream.
   I.e. convert between the true format and the little endian variation of
   it.
-******************************************************************************/
-  
+=============================================================================*/
+
 #include "pam.h"
 
 
 static sample
-reverseSample(sample const insample, unsigned int const bytesPerSample) {
+reverseSample(sample       const insample,
+              unsigned int const bytesPerSample) {
 /*----------------------------------------------------------------------------
   Return a sample whose value is the least significant
-  'bytes_per_sample' bytes, in reverse order.
+  'bytesPerSample' bytes, in reverse order.
 -----------------------------------------------------------------------------*/
     unsigned int bytePos;
     sample shiftedInsample;
@@ -30,14 +31,14 @@ reverseSample(sample const insample, unsigned int const bytesPerSample) {
 
 
 
-int main(int argc, char *argv[]) {
+int main(int argc, const char ** argv) {
 
     struct pam inpam, outpam;
     tuple * intuplerow;
     tuple * outtuplerow;
     unsigned int row;
 
-    pnm_init(&argc, argv);
+    pm_proginit(&argc, argv);
 
     pnm_readpaminit(stdin, &inpam, PAM_STRUCT_SIZE(tuple_type));
 
@@ -46,25 +47,39 @@ int main(int argc, char *argv[]) {
 
     pnm_writepaminit(&outpam);
 
-    intuplerow = pnm_allocpamrow(&inpam);      
+    /* We read the samples as if the maxval is 65535 so pnm_readpamrow, which
+       assumes big-endian samples, doesn't choke on a little-endian sample,
+       finding it to exceed the maxval.  (The pure way to do this would be not
+       to use libnetpbm row reading and writing facilities on little-endian
+       pseudo-Netpbm images, but this program isn't important enough to
+       justify that effort).
+    */
+    inpam.maxval = 65535;
+
+    intuplerow  = pnm_allocpamrow(&inpam);
     outtuplerow = pnm_allocpamrow(&outpam);
 
-    for (row = 0; row < inpam.height; row++) {
+    for (row = 0; row < inpam.height; ++row) {
         unsigned int col;
+
         pnm_readpamrow(&inpam, intuplerow);
-        for (col = 0; col < inpam.width; col++) {
+        for (col = 0; col < inpam.width; ++col) {
             unsigned int plane;
-            for (plane = 0; plane < inpam.depth; plane++) 
-                outtuplerow[col][plane] = 
-                    reverseSample(intuplerow[col][plane], 
+
+            for (plane = 0; plane < inpam.depth; ++plane) {
+                outtuplerow[col][plane] =
+                    reverseSample(intuplerow[col][plane],
                                   inpam.bytes_per_sample);
+            }
         }
         pnm_writepamrow(&outpam, outtuplerow);
     }
 
-    pnm_freepamrow(outtuplerow);        
-    pnm_freepamrow(intuplerow);        
+    pnm_freepamrow(outtuplerow);
+    pnm_freepamrow(intuplerow);
 
-    exit(0);
+    return 0;
 }
 
+
+
diff --git a/other/pamexec.c b/other/pamexec.c
index c3a1ee78..b615790c 100644
--- a/other/pamexec.c
+++ b/other/pamexec.c
@@ -15,8 +15,11 @@
 #define _BSD_SOURCE 1      /* Make sure strdup() is in string.h */
 #define _XOPEN_SOURCE 500  /* Make sure strdup() is in string.h */
 
+#include <stdbool.h>
 #include <string.h>
 #include <stdio.h>
+#include <signal.h>
+#include <setjmp.h>
 #include <errno.h>
 
 #include "pm_c_util.h"
@@ -25,7 +28,27 @@
 #include "mallocvar.h"
 #include "pam.h"
 
-struct cmdlineInfo {
+
+/* About SIGPIPE:
+
+   Unix has a strange function where by default, if you write into a pipe when
+   the reading side of the pipe has been closed, it generates a signal (of
+   class SIGPIPE), but if you tell the OS to ignore signals of class SIGPIPE,
+   then instead of generating that signal, the system call to write to the
+   pipe just fails.
+
+   Pamexec writes to a pipe when it feeds an image to the user's program's
+   Standard Input.  Should the user's program close its end of the pipe (such
+   as by exiting) before reading the whole image, that would, if we did
+   nothing to deal with it, cause Pamexec to receive a SIGPIPE signal, which
+   would make the OS terminate Pamexec.
+
+   We don't want that, so we tell the OS to ignore SIGPIPE signals, so that
+   instead our attempt to write to the pipe just fails and we fail with a
+   meaningful error message.
+*/
+
+struct CmdlineInfo {
     /* All the information the user supplied in the command line,
        in a form easy for the program to use.
     */
@@ -40,14 +63,12 @@ struct cmdlineInfo {
 
 static void
 parseCommandLine(int argc, const char ** argv,
-                 struct cmdlineInfo * const cmdlineP) {
+                 struct CmdlineInfo * const cmdlineP) {
 /*----------------------------------------------------------------------------
    Note that the pointers we place into *cmdlineP are sometimes to storage
    in the argv array.
 -----------------------------------------------------------------------------*/
-    optEntry *option_def;
-        /* Instructions to OptParseOptions3 on how to parse our options.
-         */
+    optEntry * option_def;
     optStruct3 opt;
 
     unsigned int option_def_index;
@@ -59,13 +80,13 @@ parseCommandLine(int argc, const char ** argv,
     OPTENT3(0,   "check",   OPT_FLAG,   NULL,         &cmdlineP->check, 0);
 
     opt.opt_table = option_def;
-    opt.short_allowed = FALSE; /* We have no short (old-fashioned) options */
-    opt.allowNegNum = FALSE;   /* We have no parms that are negative numbers */
+    opt.short_allowed = false; /* We have no short (old-fashioned) options */
+    opt.allowNegNum = false;   /* We have no parms that are negative numbers */
 
-    pm_optParseOptions3(&argc, (char **)argv, opt, sizeof(opt), 0);
+    pm_optParseOptions4(&argc, argv, opt, sizeof(opt), 0);
         /* Uses and sets argc, argv, and some of *cmdlineP and others. */
 
-    if (argc-1 < 1) 
+    if (argc-1 < 1)
         pm_error("You must specify at least one argument: the shell command "
                  "to execute");
     else {
@@ -92,7 +113,7 @@ pipeOneImage(FILE * const infileP,
     struct pam inpam;
     struct pam outpam;
     enum pm_check_code checkRetval;
-    
+
     unsigned int row;
     tuple * tuplerow;
 
@@ -107,9 +128,25 @@ pipeOneImage(FILE * const infileP,
 
     tuplerow = pnm_allocpamrow(&inpam);
 
-    for (row = 0; row < inpam.height; ++row) {
-        pnm_readpamrow(&inpam, tuplerow);
-        pnm_writepamrow(&outpam, tuplerow);
+    {
+        jmp_buf jmpbuf;
+        int rc;
+        rc = setjmp(jmpbuf);
+        if (rc == 0) {
+            pm_setjmpbuf(&jmpbuf);
+
+            for (row = 0; row < inpam.height; ++row) {
+                pnm_readpamrow(&inpam, tuplerow);
+                pnm_writepamrow(&outpam, tuplerow);
+            }
+        } else {
+            pm_setjmpbuf(NULL);
+            pm_error("Failed to read image and pipe it to program's "
+                     "Standard Input.  If previous messages indicate "
+                     "a broken pipe error, that means the program closed "
+                     "its Standard Error (possibly by exiting) before "
+                     "it had read the entire image>");
+        }
     }
 
     pnm_freepamrow(tuplerow);
@@ -133,7 +170,7 @@ doOneImage(FILE *        const ifP,
     ofP = popen(command, "w");
 
     if (ofP == NULL)
-        pm_asprintf(errorP, 
+        pm_asprintf(errorP,
                     "Failed to start shell to run command '%s'.  "
                     "errno = %d (%s)",
                     command, errno, strerror(errno));
@@ -141,7 +178,7 @@ doOneImage(FILE *        const ifP,
         int rc;
 
         pipeOneImage(ifP, ofP);
-            
+
         rc = pclose(ofP);
 
         if (check && rc != 0)
@@ -157,7 +194,7 @@ doOneImage(FILE *        const ifP,
 int
 main(int argc, const char *argv[]) {
 
-    struct cmdlineInfo cmdline;
+    struct CmdlineInfo cmdline;
 
     FILE *       ifP;         /* Input file pointer */
     int          eof;         /* No more images in input */
@@ -169,12 +206,17 @@ main(int argc, const char *argv[]) {
     pm_proginit(&argc, argv);
 
     parseCommandLine(argc, argv, &cmdline);
-    
+
+    /* Make write to closed pipe fail rather than generate a signal.
+       See comments at top of program.
+    */
+    signal(SIGPIPE, SIG_IGN);
+
     ifP = pm_openr(cmdline.inputFileName);
 
-    for (eof = FALSE, imageSeq = 0; !eof; ++imageSeq) {
+    for (eof = false, imageSeq = 0; !eof; ++imageSeq) {
         const char * error;
-        
+
         doOneImage(ifP, cmdline.command, cmdline.check, &error);
 
         if (error) {
@@ -185,9 +227,8 @@ main(int argc, const char *argv[]) {
         pnm_nextimage(ifP, &eof);
     }
     pm_close(ifP);
-    
+
     return 0;
 }
 
 
-
diff --git a/other/pamlookup.c b/other/pamlookup.c
index d57546d9..9682a65e 100644
--- a/other/pamlookup.c
+++ b/other/pamlookup.c
@@ -4,7 +4,7 @@
 
   Look up integers or ordered pairs from an index image in a lookup table and
   produce a corresponding image containing the results of the lookups.
-  
+
   The index image and lookup table are PAM images.  The output image is
   a PAM image with the width and height of the index image and tuples of
   the kind in the lookup table.
@@ -26,7 +26,7 @@ struct CmdlineInfo {
     /* All the information the user supplied in the command line,
        in a form easy for the program to use.
     */
-    const char * indexFilespec;  
+    const char * indexFilespec;
     char *       lookupFilespec;
     char *       missingcolor;  /* null if not specified */
     unsigned int fit;
@@ -48,26 +48,26 @@ parseCommandLine(int argc, const char ** const argv,
     optStruct3 opt;
 
     unsigned int option_def_index;
-    
+
     unsigned int lookupfileSpec, missingcolorSpec;
 
     MALLOCARRAY_NOFAIL(option_def, 100);
 
     option_def_index = 0;   /* incremented by OPTENTRY */
-    OPTENT3(0, "lookupfile",     OPT_STRING, &cmdlineP->lookupFilespec,  
+    OPTENT3(0, "lookupfile",     OPT_STRING, &cmdlineP->lookupFilespec,
             &lookupfileSpec, 0);
-    OPTENT3(0,   "missingcolor", OPT_STRING, 
+    OPTENT3(0,   "missingcolor", OPT_STRING,
             &cmdlineP->missingcolor,   &missingcolorSpec, 0);
-    OPTENT3(0,   "fit", OPT_FLAG, 
+    OPTENT3(0,   "fit", OPT_FLAG,
             NULL,   &cmdlineP->fit, 0);
-    OPTENT3(0,   "byplane", OPT_FLAG, 
+    OPTENT3(0,   "byplane", OPT_FLAG,
             NULL,   &cmdlineP->byplane, 0);
 
     opt.opt_table = option_def;
     opt.short_allowed = FALSE;  /* We have no short (old-fashioned) options */
     opt.allowNegNum = FALSE;  /* We may have parms that are negative numbers */
 
-    pm_optParseOptions3(&argc, (char **)argv, opt, sizeof(opt), 0);
+    pm_optParseOptions4(&argc,argv, opt, sizeof(opt), 0);
         /* Uses and sets argc, argv, and some of *cmdlineP and others. */
 
     if (!lookupfileSpec)
@@ -85,12 +85,12 @@ parseCommandLine(int argc, const char ** const argv,
         cmdlineP->indexFilespec = argv[1];
 
     free(option_def);
-}        
+}
 
 
 
 static void
-fitLookup(tuple **     const inputLookup, 
+fitLookup(tuple **     const inputLookup,
           struct pam   const inputLookuppam,
           tuple ***    const fitLookupP,
           struct pam * const fitLookuppamP,
@@ -115,7 +115,7 @@ fitLookup(tuple **     const inputLookup,
     inPamtuples.tuplesP = (tuple ***) &inputLookup;
     outPamtuples.pamP = fitLookuppamP;
     outPamtuples.tuplesP = fitLookupP;
-    
+
     pm_system_lp("pamscale",
                  &pm_feed_from_pamtuples, &inPamtuples,
                  &pm_accept_to_pamtuples, &outPamtuples,
@@ -128,7 +128,7 @@ fitLookup(tuple **     const inputLookup,
 
 
 static void
-getLookup(const char * const lookupFileName, 
+getLookup(const char * const lookupFileName,
           unsigned int const indexDegree,
           unsigned int const indexMaxval,
           tuple ***    const lookupP,
@@ -136,7 +136,7 @@ getLookup(const char * const lookupFileName,
           bool         const fit) {
 /*----------------------------------------------------------------------------
    Get the lookup image (the one that maps integers to tuples, e.g. a
-   color index / color map / palette) from the file named 
+   color index / color map / palette) from the file named
    'lookupFileName'.
 
    Interpret the lookup image for use with indices that are ntuples of size
@@ -154,25 +154,25 @@ getLookup(const char * const lookupFileName,
     tuple ** inputLookup;
 
     lookupfileP = pm_openr(lookupFileName);
-    inputLookup = pnm_readpam(lookupfileP, 
+    inputLookup = pnm_readpam(lookupfileP,
                               &inputLookuppam, PAM_STRUCT_SIZE(tuple_type));
 
     pm_close(lookupfileP);
-    
+
     if (fit) {
         fitLookup(inputLookup, inputLookuppam, lookupP, lookuppamP,
-                  indexMaxval + 1, 
+                  indexMaxval + 1,
                   indexDegree > 1 ? indexMaxval + 1 : 1);
         pnm_freepamarray(inputLookup, &inputLookuppam);
     } else {
         *lookupP = inputLookup;
         *lookuppamP = inputLookuppam;
     }
-        
+
     if (indexDegree == 1 && lookuppamP->height != 1)
         pm_error("Your index image has integer indices, "
                  "so the lookup table image must be one row.  "
-                 "Yours is %d rows.", 
+                 "Yours is %d rows.",
                  lookuppamP->height);
 
     if (lookuppamP->width - 1 > indexMaxval)
@@ -190,9 +190,9 @@ getLookup(const char * const lookupFileName,
 
 
 static void
-computeDefaultTuple(struct CmdlineInfo const cmdline, 
+computeDefaultTuple(struct CmdlineInfo const cmdline,
                     tuple **           const lookup,
-                    struct pam *       const lookuppamP, 
+                    struct pam *       const lookuppamP,
                     tuple *            const defaultTupleP) {
 
     tuple retval;
@@ -204,10 +204,10 @@ computeDefaultTuple(struct CmdlineInfo const cmdline,
        lookup table.  We should probably check here for a lookup file
        that has a visual image tuple type, but we don't out of
        laziness.  The program probably ought to have a generic
-       "missing tuple type" option too.  
+       "missing tuple type" option too.
     */
     if (cmdline.missingcolor) {
-        pixel const color = 
+        pixel const color =
             ppm_parsecolor(cmdline.missingcolor, lookuppamP->maxval);
 
         if (lookuppamP->depth >= 3) {
@@ -224,7 +224,7 @@ computeDefaultTuple(struct CmdlineInfo const cmdline,
             else
                 retval[0] = PPM_GETR(color);
         }
-    } else 
+    } else
         pnm_assigntuple(lookuppamP, retval, lookup[0][0]);
 
     *defaultTupleP = retval;
@@ -261,7 +261,7 @@ doLookupByPlane(struct pam const indexpam,
     outpam = indexpam;  /* initial value */
     outpam.maxval = lookuppam.maxval;
     outpam.file = ofP;
-    
+
     tuplerowIndex = pnm_allocpamrow(&indexpam);
     tuplerowOut = pnm_allocpamrow(&outpam);
 
@@ -273,7 +273,7 @@ doLookupByPlane(struct pam const indexpam,
     for (row = 0; row < indexpam.height; ++row) {
         unsigned int col;
         pnm_readpamrow(&indexpam, tuplerowIndex);
-        
+
         for (col = 0; col < indexpam.width; ++col) {
             unsigned int plane;
 
@@ -320,7 +320,7 @@ doLookupWholeTuple(struct pam const indexpam,
     outpam.height = indexpam.height;
     outpam.width = indexpam.width;
     outpam.file = ofP;
-    
+
     tuplerowIndex = pnm_allocpamrow(&indexpam);
     tuplerowOut = pnm_allocpamrow(&outpam);
 
@@ -329,11 +329,11 @@ doLookupWholeTuple(struct pam const indexpam,
     for (row = 0; row < outpam.height; ++row) {
         unsigned int col;
         pnm_readpamrow(&indexpam, tuplerowIndex);
-        
+
         for (col = 0; col < outpam.width; ++col) {
             unsigned int indexRow, indexCol;
             tuple v;
-            
+
             if (indexpam.depth < 2) {
                 indexRow = 0;
                 indexCol = tuplerowIndex[col][0];
@@ -368,7 +368,7 @@ main(int argc, const char ** const argv) {
     tuple ** lookup;
 
     tuple defaultTuple;
-    
+
     pm_proginit(&argc, argv);
 
     parseCommandLine(argc, argv, &cmdline);
@@ -385,7 +385,7 @@ main(int argc, const char ** const argv) {
 
     indexDegree = cmdline.byplane ? 1 : indexpam.depth;
 
-    getLookup(cmdline.lookupFilespec, indexDegree, indexpam.maxval, 
+    getLookup(cmdline.lookupFilespec, indexDegree, indexpam.maxval,
               &lookup, &lookuppam, cmdline.fit || cmdline.byplane);
 
     computeDefaultTuple(cmdline, lookup, &lookuppam, &defaultTuple);
@@ -399,7 +399,7 @@ main(int argc, const char ** const argv) {
 
     pnm_freepamtuple(defaultTuple);
     pnm_freepamarray(lookup, &lookuppam);
-    
+
     return 0;
 }
 
diff --git a/other/pampick.c b/other/pampick.c
index 67d42fc5..d831fcbb 100644
--- a/other/pampick.c
+++ b/other/pampick.c
@@ -98,9 +98,7 @@ parseCommandLine(int argc, const char ** argv,
    Note that the pointers we place into *cmdlineP are sometimes to storage
    in the argv array.
 -----------------------------------------------------------------------------*/
-    optEntry *option_def;
-        /* Instructions to OptParseOptions3 on how to parse our options.
-         */
+    optEntry * option_def;
     optStruct3 opt;
 
     unsigned int option_def_index;
@@ -119,7 +117,7 @@ parseCommandLine(int argc, const char ** argv,
     opt.short_allowed = FALSE;  /* We have no short (old-fashioned) options */
     opt.allowNegNum = FALSE;  /* We have no parms that are negative numbers */
 
-    pm_optParseOptions3(&argc, (char **)argv, opt, sizeof(opt), 0);
+    pm_optParseOptions4(&argc, argv, opt, sizeof(opt), 0);
         /* Uses and sets argc, argv, and some of *cmdlineP and others. */
 
     initUintSet(&cmdlineP->imageSeqList, argc-1);
diff --git a/other/pamsplit.c b/other/pamsplit.c
index 93c1726a..1c1ab3d4 100644
--- a/other/pamsplit.c
+++ b/other/pamsplit.c
@@ -41,9 +41,7 @@ parseCommandLine(int argc, const char ** argv,
    Note that the pointers we place into *cmdlineP are sometimes to storage
    in the argv array.
 -----------------------------------------------------------------------------*/
-    optEntry *option_def;
-        /* Instructions to OptParseOptions3 on how to parse our options.
-         */
+    optEntry * option_def;
     optStruct3 opt;
 
     unsigned int padnameSpec;
@@ -60,13 +58,13 @@ parseCommandLine(int argc, const char ** argv,
     opt.short_allowed = FALSE;  /* We have no short (old-fashioned) options */
     opt.allowNegNum = FALSE;  /* We have no parms that are negative numbers */
 
-    pm_optParseOptions3(&argc, (char **)argv, opt, sizeof(opt), 0);
+    pm_optParseOptions4(&argc, argv, opt, sizeof(opt), 0);
         /* Uses and sets argc, argv, and some of *cmdlineP and others. */
 
     if (!padnameSpec)
         cmdlineP->padname = 0;
 
-    if (argc - 1 < 1) 
+    if (argc - 1 < 1)
         cmdlineP->inputFileName = "-";
     else
         cmdlineP->inputFileName = argv[1];
@@ -91,7 +89,7 @@ extractOneImage(FILE * const infileP,
     struct pam inpam;
     struct pam outpam;
     enum pm_check_code checkRetval;
-    
+
     unsigned int row;
     tuple * tuplerow;
 
@@ -115,7 +113,7 @@ extractOneImage(FILE * const infileP,
 
 
 static void
-computeOutputName(char          const outputFilePattern[], 
+computeOutputName(char          const outputFilePattern[],
                   unsigned int  const padCount,
                   unsigned int  const imageSeq,
                   const char ** const outputNameP) {
@@ -157,13 +155,13 @@ main(int argc, const char *argv[]) {
 
     FILE * ifP;
     int eof;  /* No more images in input */
-    unsigned int imageSeq;  
+    unsigned int imageSeq;
         /* Sequence of current image in input file.  First = 0 */
 
     pm_proginit(&argc, argv);
 
     parseCommandLine(argc, argv, &cmdline);
-    
+
     ifP = pm_openr(cmdline.inputFileName);
 
     eof = FALSE;
@@ -171,7 +169,7 @@ main(int argc, const char *argv[]) {
         FILE * ofP;
         const char * outputFileName;  /* malloc'ed */
 
-        computeOutputName(cmdline.outputFilePattern, cmdline.padname, 
+        computeOutputName(cmdline.outputFilePattern, cmdline.padname,
                           imageSeq,
                           &outputFileName);
         pm_message("WRITING %s", outputFileName);
@@ -185,7 +183,7 @@ main(int argc, const char *argv[]) {
         pnm_nextimage(ifP, &eof);
     }
     pm_close(ifP);
-    
+
     return 0;
 }
 
diff --git a/other/pamstack.c b/other/pamstack.c
index 308852c8..1c005f4c 100644
--- a/other/pamstack.c
+++ b/other/pamstack.c
@@ -13,6 +13,7 @@
 -----------------------------------------------------------------------------*/
 
 #include <string.h>
+#include <assert.h>
 
 #include "pm_c_util.h"
 #include "mallocvar.h"
@@ -23,46 +24,54 @@
 #define MAX_INPUTS 16
     /* The most input PAMs we allow user to specify */
 
-struct cmdlineInfo {
+enum MaxvalScaling {
+    /* How to scale maxvals if the inputs don't all have the same maxval */
+    MAXVALSCALE_NONE,  /* Don't scale -- fail program */
+    MAXVALSCALE_FIRST, /* Scale everything to maxval of first input */
+    MAXVALSCALE_LCM    /* Scale everything to least common multiple */
+};
+
+struct CmdlineInfo {
     /* All the information the user supplied in the command line,
        in a form easy for the program to use.
     */
-    const char *tupletype;       /* Tuple type for output PAM */
     unsigned int nInput;
         /* The number of input PAMs.  At least 1, at most 16. */
     const char * inputFileName[MAX_INPUTS];
         /* The PAM files to combine, in order. */
+    const char * tupletype;
+    enum MaxvalScaling maxvalScaling;
 };
 
 
 
 static void
-parseCommandLine(int argc, char ** argv,
-                 struct cmdlineInfo * const cmdlineP) {
+parseCommandLine(int argc, const char ** argv,
+                 struct CmdlineInfo * const cmdlineP) {
 /*----------------------------------------------------------------------------
    Note that the file spec strings we return are stored in the storage that
    was passed to us as the argv array.
 -----------------------------------------------------------------------------*/
     optEntry * option_def;
-        /* Instructions to pm_optParseOptions3 on how to parse our options.
-         */
     optStruct3 opt;
     extern struct pam pam;  /* Just so we can look at field sizes */
 
     unsigned int option_def_index;
-    unsigned int tupletypeSpec;
+    unsigned int tupletypeSpec, firstmaxvalSpec, lcmmaxvalSpec;
 
     MALLOCARRAY_NOFAIL(option_def, 100);
-    
+
     option_def_index = 0;   /* incremented by OPTENTRY */
-    OPTENT3(0, "tupletype",  OPT_STRING, &cmdlineP->tupletype, 
+    OPTENT3(0, "tupletype",   OPT_STRING, &cmdlineP->tupletype,
             &tupletypeSpec, 0);
+    OPTENT3(0, "firstmaxval", OPT_FLAG, NULL, &firstmaxvalSpec, 0);
+    OPTENT3(0, "lcmmaxval",   OPT_FLAG, NULL, &lcmmaxvalSpec,   0);
 
     opt.opt_table = option_def;
     opt.short_allowed = FALSE;  /* We have no short (old-fashioned) options */
     opt.allowNegNum = FALSE;  /* We may have parms that are negative numbers */
 
-    pm_optParseOptions3(&argc, argv, opt, sizeof(opt), 0);
+    pm_optParseOptions4(&argc, argv, opt, sizeof(opt), 0);
         /* Uses and sets argc, argv, and some of *cmdlineP and others. */
 
     if (!tupletypeSpec)
@@ -73,12 +82,25 @@ parseCommandLine(int argc, char ** argv,
                      "%u characters allowed.",
                      (unsigned)sizeof(pam.tuple_type));
 
+    if (firstmaxvalSpec) {
+        if (lcmmaxvalSpec)
+            pm_error("Cannot specify both -lcmmaxval and -firstmaxval");
+        else
+            cmdlineP->maxvalScaling = MAXVALSCALE_FIRST;
+    } else if (lcmmaxvalSpec) {
+        if (firstmaxvalSpec)
+            pm_error("Cannot specify both -lcmmaxval and -firstmaxval");
+        else
+            cmdlineP->maxvalScaling = MAXVALSCALE_LCM;
+    } else
+        cmdlineP->maxvalScaling = MAXVALSCALE_NONE;
+
     cmdlineP->nInput = 0;  /* initial value */
-    { 
+    {
         unsigned int argn;
         bool stdinUsed;
         for (argn = 1, stdinUsed = false; argn < argc; ++argn) {
-            if (cmdlineP->nInput >= MAX_INPUTS) 
+            if (cmdlineP->nInput >= MAX_INPUTS)
                 pm_error("You may not specify more than %u input images.",
                          MAX_INPUTS);
             cmdlineP->inputFileName[cmdlineP->nInput++] = argv[argn];
@@ -110,51 +132,71 @@ openAllStreams(unsigned int  const nInput,
 
 
 static void
-outputRaster(const struct pam       inpam[], 
-             unsigned int     const nInput,
-             struct pam             outpam) {
+outputRaster(const struct pam * const inpam,  /* array */
+             unsigned int       const nInput,
+             struct pam         const outpam) {
+/*----------------------------------------------------------------------------
+   Write the raster of the output image according to 'outpam'.  Compose it
+   from the 'nInput' input images described by 'inpam'.
+
+   'outpam' may indicate a different maxval from some or all of the input
+   images.
+-----------------------------------------------------------------------------*/
+    tuple * inrow;
+    tuple * outrow;
 
-    tuple *inrow;
-    tuple *outrow;
-        
     outrow = pnm_allocpamrow(&outpam);
-    inrow = pnm_allocpamrow(&outpam);      
+    inrow  = pnm_allocpamrow(&outpam);
+
+    {
+        unsigned int row;
 
-    { 
-        int row;
-        
-        for (row = 0; row < outpam.height; row++) {
+        for (row = 0; row < outpam.height; ++row) {
             unsigned int inputSeq;
-            int outplane;
-            outplane = 0;  /* initial value */
-            for (inputSeq = 0; inputSeq < nInput; ++inputSeq) {
+            unsigned int outPlane;
+
+            for (inputSeq = 0, outPlane = 0; inputSeq < nInput; ++inputSeq) {
                 struct pam thisInpam = inpam[inputSeq];
-                int col;
+                unsigned int col;
 
                 pnm_readpamrow(&thisInpam, inrow);
 
-                for (col = 0; col < outpam.width; col ++) {
-                    int inplane;
-                    for (inplane = 0; inplane < thisInpam.depth; ++inplane) 
-                        outrow[col][outplane+inplane] = inrow[col][inplane];
+                pnm_scaletuplerow(&thisInpam, inrow, inrow, outpam.maxval);
+
+                for (col = 0; col < outpam.width; ++col) {
+                    unsigned int inPlane;
+                    for (inPlane = 0; inPlane < thisInpam.depth; ++inPlane) {
+                        outrow[col][outPlane+inPlane] = inrow[col][inPlane];
+                    }
                 }
-                outplane += thisInpam.depth;
+                outPlane += thisInpam.depth;
             }
             pnm_writepamrow(&outpam, outrow);
         }
     }
     pnm_freepamrow(outrow);
-    pnm_freepamrow(inrow);        
+    pnm_freepamrow(inrow);
 }
 
 
 
 static void
-processOneImageInAllStreams(unsigned int const nInput,
-                            FILE *       const ifP[],
-                            FILE *       const ofP,
-                            const char * const tupletype) {
+processOneImageInAllStreams(unsigned int       const nInput,
+                            FILE *             const ifP[],
+                            FILE *             const ofP,
+                            const char *       const tupletype,
+                            enum MaxvalScaling const maxvalScaling) {
+/*----------------------------------------------------------------------------
+   Take one image from each of the 'nInput' open input streams ifP[]
+   and stack them into one output image on *ofP.
+
+   Take the images from the current positions of those streams and leave
+   the streams positioned after them.
 
+   Make the output image have tuple type 'tupletype'.
+
+   Scale input samples for output according to 'maxvalScaling'.
+-----------------------------------------------------------------------------*/
     struct pam inpam[MAX_INPUTS];   /* Input PAM images */
     struct pam outpam;  /* Output PAM image */
 
@@ -166,30 +208,67 @@ processOneImageInAllStreams(unsigned int const nInput,
 
     unsigned int outputDepth;
     outputDepth = 0;  /* initial value */
-    
-    for (inputSeq = 0; inputSeq < nInput; ++inputSeq) {
+    sample maxvalLcm;
+        /* Least common multiple of all maxvals or PNM_OVERALLMAXVAL if the
+           LCM is greater than that.
+        */
+    bool allImagesSameMaxval;
+        /* The images all have the same maxval */
+
+    for (inputSeq = 0, allImagesSameMaxval = true, maxvalLcm = 1;
+         inputSeq < nInput;
+         ++inputSeq) {
 
-        pnm_readpaminit(ifP[inputSeq], &inpam[inputSeq], 
+        pnm_readpaminit(ifP[inputSeq], &inpam[inputSeq],
                         PAM_STRUCT_SIZE(tuple_type));
 
-        if (inputSeq > 0) {
-            /* All images, including this one, must be compatible with the 
-               first image.
-            */
-            if (inpam[inputSeq].width != inpam[0].width)
-                pm_error("Image no. %u does not have the same width as "
-                         "Image 0.", inputSeq);
-            if (inpam[inputSeq].height != inpam[0].height)
-                pm_error("Image no. %u does not have the same height as "
-                         "Image 0.", inputSeq);
-            if (inpam[inputSeq].maxval != inpam[0].maxval)
-                pm_error("Image no. %u does not have the same maxval as "
-                         "Image 0.", inputSeq);
-        }
+        /* All images, including this one, must have same dimensions as
+           the first image.
+        */
+        if (inpam[inputSeq].width != inpam[0].width)
+            pm_error("Image no. %u does not have the same width as "
+                     "Image 0.", inputSeq);
+        if (inpam[inputSeq].height != inpam[0].height)
+            pm_error("Image no. %u does not have the same height as "
+                     "Image 0.", inputSeq);
+
+        if (inpam[inputSeq].maxval != inpam[0].maxval)
+            allImagesSameMaxval = false;
+
+        assert(PAM_OVERALL_MAXVAL <= UINT_MAX-1);
+
+        maxvalLcm = pm_lcm(maxvalLcm + 1, inpam[inputSeq].maxval + 1, 1,
+                           PAM_OVERALL_MAXVAL + 1) - 1;
+
+        if (inpam[inputSeq].depth > UINT_MAX - outputDepth)
+            pm_error("Total number of planes is too large to compute "
+                     "(at least %u plus %u)",
+                     outputDepth, inpam[inputSeq].depth);
+
         outputDepth += inpam[inputSeq].depth;
     }
 
     outpam        = inpam[0];     /* Initial value */
+
+    switch (maxvalScaling) {
+    case MAXVALSCALE_NONE:
+        if (!allImagesSameMaxval)
+            pm_error("Inputs do not all have same maxval.  "
+                     "Consider -firstmaxval or -lcmmaxval");
+        break;
+    case MAXVALSCALE_FIRST:
+        outpam.maxval = inpam[0].maxval;
+        if (!allImagesSameMaxval)
+            pm_message("Input maxvals vary; making output maxval %lu "
+                       "per -firstmaxval", outpam.maxval);
+        break;
+    case MAXVALSCALE_LCM:
+        outpam.maxval = maxvalLcm;
+        if (!allImagesSameMaxval)
+            pm_message("Input maxvals vary; making output maxval %lu "
+                       "per -lcmmaxval", outpam.maxval);
+        break;
+    }
     outpam.depth  = outputDepth;
     outpam.file   = ofP;
     outpam.format = PAM_FORMAT;
@@ -226,13 +305,13 @@ nextImageAllStreams(unsigned int const nInput,
 
 
 int
-main(int argc, char *argv[]) {
+main(int argc, const char *argv[]) {
 
-    struct cmdlineInfo cmdline;
+    struct CmdlineInfo cmdline;
     FILE * ifP[MAX_INPUTS];
     bool eof;
 
-    pnm_init(&argc, argv);
+    pm_proginit(&argc, argv);
 
     parseCommandLine(argc, argv, &cmdline);
 
@@ -241,10 +320,13 @@ main(int argc, char *argv[]) {
     eof = FALSE;
     while (!eof) {
         processOneImageInAllStreams(cmdline.nInput, ifP, stdout,
-                                    cmdline.tupletype);
+                                    cmdline.tupletype, cmdline.maxvalScaling);
 
         nextImageAllStreams(cmdline.nInput, ifP, &eof);
     }
 
     return 0;
 }
+
+
+
diff --git a/other/pamsummcol.c b/other/pamsummcol.c
index c84f38ad..ec0d2085 100644
--- a/other/pamsummcol.c
+++ b/other/pamsummcol.c
@@ -21,7 +21,7 @@ struct cmdlineInfo {
     /* All the information the user supplied in the command line,
        in a form easy for the program to use.
     */
-    const char *inputFilespec;  /* Filespec of input file */
+    const char * inputFilespec;  /* Filespec of input file */
     enum function function;
     unsigned int verbose;
 };
@@ -68,18 +68,18 @@ parseCommandLine(int argc, char ** const argv,
         cmdlineP->function = FN_MIN;
     } else if (maxSpec) {
         cmdlineP->function = FN_MAX;
-    } else 
+    } else
         pm_error("You must specify one of -sum, -min, or -max");
-        
+
     if (argc-1 > 1)
         pm_error("Too many arguments (%d).  File spec is the only argument.",
                  argc-1);
 
     if (argc-1 < 1)
         cmdlineP->inputFilespec = "-";
-    else 
+    else
         cmdlineP->inputFilespec = argv[1];
-    
+
 }
 
 
@@ -98,7 +98,7 @@ createAccumulator(enum function    const function,
                   unsigned int     const cols,
                   unsigned int     const planes,
                   struct accum *** const accumulatorP) {
-    
+
     struct accum ** accumulator;
     unsigned int col;
 
@@ -115,7 +115,7 @@ createAccumulator(enum function    const function,
             case FN_MEAN: accumulator[col][plane].u.sum = 0;        break;
             case FN_MIN:  accumulator[col][plane].u.min = UINT_MAX; break;
             case FN_MAX:  accumulator[col][plane].u.max = 0;        break;
-            } 
+            }
         }
     }
     *accumulatorP = accumulator;
@@ -148,14 +148,14 @@ aggregate(struct pam *    const inpamP,
         unsigned int plane;
         for (plane = 0; plane < inpamP->depth; ++plane) {
             switch(function) {
-            case FN_ADD:  
-            case FN_MEAN: 
-                if (accumulator[col][plane].u.sum > 
+            case FN_ADD:
+            case FN_MEAN:
+                if (accumulator[col][plane].u.sum >
                     UINT_MAX - tupleRow[col][plane])
                     pm_error("Numerical overflow in Column %u", col);
                 accumulator[col][plane].u.sum += tupleRow[col][plane];
             break;
-            case FN_MIN:  
+            case FN_MIN:
                 if (tupleRow[col][plane] < accumulator[col][plane].u.min)
                     accumulator[col][plane].u.min = tupleRow[col][plane];
                 break;
@@ -163,7 +163,7 @@ aggregate(struct pam *    const inpamP,
                 if (tupleRow[col][plane] > accumulator[col][plane].u.min)
                     accumulator[col][plane].u.min = tupleRow[col][plane];
                 break;
-            } 
+            }
         }
     }
 }
@@ -176,31 +176,31 @@ makeSummaryRow(struct accum ** const accumulator,
                struct pam *  const   pamP,
                enum function const   function,
                tuple *       const   tupleRow) {
-    
+
     unsigned int col;
 
     for (col = 0; col < pamP->width; ++col) {
         unsigned int plane;
         for (plane = 0; plane < pamP->depth; ++plane) {
             switch(function) {
-            case FN_ADD:  
-                tupleRow[col][plane] = 
+            case FN_ADD:
+                tupleRow[col][plane] =
                     MIN(accumulator[col][plane].u.sum, pamP->maxval);
                 break;
-            case FN_MEAN: 
-                tupleRow[col][plane] = 
+            case FN_MEAN:
+                tupleRow[col][plane] =
                     ROUNDU((double)accumulator[col][plane].u.sum / count);
                 break;
-            case FN_MIN:  
-                tupleRow[col][plane] = 
+            case FN_MIN:
+                tupleRow[col][plane] =
                     accumulator[col][plane].u.min;
                 break;
             case FN_MAX:
-                tupleRow[col][plane] = 
+                tupleRow[col][plane] =
                     accumulator[col][plane].u.max;
                 break;
             }
-        } 
+        }
     }
 }
 
@@ -226,7 +226,7 @@ main(int argc, char *argv[]) {
 
     pnm_readpaminit(ifP, &inpam, PAM_STRUCT_SIZE(tuple_type));
 
-    createAccumulator(cmdline.function, inpam.width, inpam.depth, 
+    createAccumulator(cmdline.function, inpam.width, inpam.depth,
                       &accumulator);
 
     inputRow = pnm_allocpamrow(&inpam);
@@ -244,7 +244,7 @@ main(int argc, char *argv[]) {
 
         aggregate(&inpam, inputRow, cmdline.function, accumulator);
     }
-    makeSummaryRow(accumulator, inpam.height, &outpam, cmdline.function, 
+    makeSummaryRow(accumulator, inpam.height, &outpam, cmdline.function,
                    outputRow);
     pnm_writepamrow(&outpam, outputRow);
 
@@ -253,6 +253,6 @@ main(int argc, char *argv[]) {
     destroyAccumulator(accumulator, inpam.width);
     pm_close(inpam.file);
     pm_close(outpam.file);
-    
+
     return 0;
 }
diff --git a/other/pamunlookup.c b/other/pamunlookup.c
index 624951df..a835ebd8 100644
--- a/other/pamunlookup.c
+++ b/other/pamunlookup.c
@@ -19,7 +19,6 @@
 #include "pm_c_util.h"
 #include "mallocvar.h"
 #include "shhopt.h"
-#include "pm_system.h"
 #include "nstring.h"
 #include "pam.h"
 #include "pammap.h"
@@ -62,7 +61,7 @@ parseCommandLine(int argc, const char ** const argv,
     opt.short_allowed = FALSE;  /* We have no short (old-fashioned) options */
     opt.allowNegNum = FALSE;  /* We may have parms that are negative numbers */
 
-    pm_optParseOptions3(&argc, (char **)argv, opt, sizeof(opt), 0);
+    pm_optParseOptions4(&argc, argv, opt, sizeof(opt), 0);
         /* Uses and sets argc, argv, and some of *cmdlineP and others. */
 
     if (!lookupfileSpec)
diff --git a/other/pamvalidate.c b/other/pamvalidate.c
index a7b08b8e..613df736 100644
--- a/other/pamvalidate.c
+++ b/other/pamvalidate.c
@@ -74,7 +74,7 @@ main(int argc, const char * argv[]) {
 
         if (ferror(tmpfile))
             pm_error("Error reading from temporary file.  "
-                     "Incomplete output.  "    
+                     "Incomplete output.  "
                      "Errno = %s (%d)", strerror(errno), errno);
         else
             fwrite(buffer, 1, bytesReadCt, stdout);
diff --git a/other/pamx/fill.c b/other/pamx/fill.c
index 13a2b21e..dc61ce33 100644
--- a/other/pamx/fill.c
+++ b/other/pamx/fill.c
@@ -1,8 +1,8 @@
-/* 
+/*
    fill an image area with a particular pixel value
- 
+
    By Jim Frost 1989.10.02, Bryan Henderson 2006.03.25.
- 
+
    See COPYRIGHT file for copyright information.
 */
 
@@ -52,7 +52,7 @@ fill(Image * const imageP,
             }
         }
     } break;
-        
+
   case IRGB:
     case ITRUE: {
         unsigned int const linelen= imageP->width * imageP->pixlen;
diff --git a/other/pamx/image.c b/other/pamx/image.c
index 0e719438..fc256ae1 100644
--- a/other/pamx/image.c
+++ b/other/pamx/image.c
@@ -1,8 +1,8 @@
 /*
    Functions to allocate and deallocate structures and structure data
- 
+
    By Jim Frost 1989.09.29, Bryan Henderson 2006.03.25.
- 
+
    See COPYRIGHT file for copyright information.
 */
 
@@ -156,7 +156,7 @@ Image *
 newRGBImage(unsigned int const width,
             unsigned int const height,
             unsigned int const depth) {
-    
+
     unsigned int const pixlen = depth > 0 ? (depth + 7) / 8 : 1;
         /* Special case for "zero" depth image, which is sometimes
            interpreted as "one color"
@@ -164,7 +164,7 @@ newRGBImage(unsigned int const width,
     unsigned int const numcolors = depthToColors(depth);
 
     Image * imageP;
-    
+
     MALLOCVAR_NOFAIL(imageP);
     imageP->type   = IRGB;
     newRGBMapData(&imageP->rgb, numcolors);
@@ -191,7 +191,7 @@ newTrueImage(unsigned int const width,
              unsigned int const height) {
 
     unsigned int const pixlen = 3;
-    
+
     Image * imageP;
 
     MALLOCVAR_NOFAIL(imageP);
diff --git a/other/pamx/pamx.c b/other/pamx/pamx.c
index 35900f82..cc2a70ae 100644
--- a/other/pamx/pamx.c
+++ b/other/pamx/pamx.c
@@ -1,4 +1,4 @@
-/* By Bryan Henderson 2006.03.25 
+/* By Bryan Henderson 2006.03.25
 
    Copyright information is in the file COPYRIGHT
 */
@@ -52,13 +52,13 @@ struct cmdlineInfo {
 
 
 
-static void 
-parseCommandLine(int argc, 
-                 char ** argv, 
+static void
+parseCommandLine(int argc,
+                 char ** argv,
                  struct cmdlineInfo  * const cmdlineP) {
 /* --------------------------------------------------------------------------
    Parse program command line described in Unix standard form by argc
-   and argv.  Return the information in the options as *cmdlineP.  
+   and argv.  Return the information in the options as *cmdlineP.
 
    If command line is internally inconsistent (invalid options, etc.),
    issue error message to stderr and abort program.
@@ -69,7 +69,7 @@ parseCommandLine(int argc,
     optEntry *option_def;
         /* Instructions to pm_optParseOptions3 on how to parse our options. */
     optStruct3 opt;
-  
+
     unsigned int option_def_index;
 
     unsigned int displaySpec, titleSpec, foregroundSpec, backgroundSpec,
@@ -111,7 +111,7 @@ parseCommandLine(int argc,
     opt.opt_table = option_def;
     opt.short_allowed = FALSE;  /* We have no short (old-fashioned) options */
     opt.allowNegNum = FALSE;   /* We have no parms that are negative numbers */
-    
+
     pm_optParseOptions3(&argc, argv, opt, sizeof(opt), 0);
         /* Uses and sets argc, argv, and some of *cmdlineP and others. */
 
@@ -194,7 +194,7 @@ fillRow(struct pam *     const pamP,
    for its contents, according to 'depth'.
 -----------------------------------------------------------------------------*/
     unsigned int col;
-    
+
     for (col = 0; col < pamP->width; ++col) {
         /* Truecolor image data has 3 bytes per pixel, one each for
            red, green, and blue.
@@ -238,7 +238,7 @@ loadPamImage(FILE *   const ifP,
 
     for (row = 0; row < pam.height; ++row) {
         pnm_readpamrow(&pam, tuplerow);
-        
+
         /* This semantically wasteful code allows a dumb compiler
            optimizer to recognize that the depth is constant and
            therefore not generate code that checks the depth every
@@ -288,7 +288,7 @@ processImage(Image *            const imageP,
             imageP->rgb.grn[FOREGROUND_IDX] = color.green;
             imageP->rgb.blu[FOREGROUND_IDX] = color.blue;
         }
-    }    
+    }
 }
 
 
@@ -296,9 +296,9 @@ processImage(Image *            const imageP,
 static void
 determineTitle(struct cmdlineInfo const cmdline,
                const char **      const titleP) {
-    
+
     const char * title;
-    
+
     if (cmdline.title)
         title = strdup(cmdline.title);
     else {
@@ -332,7 +332,7 @@ main(int     argc,
     parseCommandLine(argc, argv, &cmdline);
 
     ifP = pm_openr(cmdline.inputFileName);
-    
+
     dispP = XOpenDisplay(cmdline.display);
     if (!dispP)
         pm_error("Cannot open display '%s'", XDisplayName(cmdline.display));
diff --git a/other/pamx/send.c b/other/pamx/send.c
index 3c3852e2..c33c5c06 100644
--- a/other/pamx/send.c
+++ b/other/pamx/send.c
@@ -1,10 +1,10 @@
 /*
- 
+
   Send an Image to an X pixmap
 
 
   By Jim Frost 1989.10.02, Bryan Henderson 2006.03.25.
- 
+
   Copyright 1989, 1990, 1991 Jim Frost.
   See COPYRIGHT file for copyright information.
 */
@@ -59,7 +59,7 @@ ximageToPixmap(Display *    const disp,
 
     XErrorHandler old_handler;
     Pixmap        pixmap;
-  
+
     GotError = FALSE;
     old_handler = XSetErrorHandler(pixmapErrorTrap);
     XSync(disp, False);
@@ -114,7 +114,7 @@ bitsPerPixelAtDepth(Display *    const disp,
   fprintf(stderr, "bitsPerPixelAtDepth: Can't find pixmap depth info!\n");
   exit(1);
 }
-     
+
 
 
 static void
@@ -130,7 +130,7 @@ findColors(const Image *   const imageP,
 
     for (color = 0; color < 32768; ++color)
         pixelCt[color] = 0;  /* initial value */
-  
+
     for (y = 0, pixel = imageP->data; y < imageP->height; ++y) {
         unsigned int x;
         for (x = 0; x < imageP->width; ++x) {
@@ -184,7 +184,7 @@ pseudoColorImageFromItrue(Image *      const imageP,
 
             /* Put the color in the color map */
             newImageP->rgb.red[colorCt] = red<<11;
-            newImageP->rgb.grn[colorCt] = grn<<11; 
+            newImageP->rgb.grn[colorCt] = grn<<11;
             newImageP->rgb.blu[colorCt] = blu<<11;
 
             /* Reverse-index it */
@@ -192,9 +192,9 @@ pseudoColorImageFromItrue(Image *      const imageP,
 
             ++colorCt;
         }
-    }    
+    }
     newImageP->rgb.used = colorCt;
-    
+
     for (y = 0, pixel  = imageP->data, dpixel = newImageP->data;
          y < imageP->height;
          ++y) {
@@ -241,7 +241,7 @@ makeUsableVisual(Image *      const origImageP,
                      visualP->class);
         }
         break;
-        
+
     case IRGB:
         switch(visualP->class) {
         case TrueColor:
@@ -253,13 +253,13 @@ makeUsableVisual(Image *      const origImageP,
             pm_error("INTERNAL ERROR: impossible visual class %u",
                      visualP->class);
         }
-        
+
     case IBITMAP:
         /* no processing ever needs to be done for bitmaps */
         *newImagePP = origImageP;
         break;
     }
-}    
+}
 
 
 
@@ -271,7 +271,7 @@ makeColorMap1(Display *  const disp,
               Pixel **   const redvalueP,
               Pixel **   const grnvalueP,
               Pixel **   const bluvalueP) {
-    
+
     Pixel * redvalue;
     Pixel * grnvalue;
     Pixel * bluvalue;
@@ -281,22 +281,22 @@ makeColorMap1(Display *  const disp,
     unsigned int redbottom, grnbottom, blubottom;
     unsigned int redtop, grntop, blutop;
     unsigned int a;
-            
+
     MALLOCARRAY_NOFAIL(redvalue, 256);
     MALLOCARRAY_NOFAIL(grnvalue, 256);
     MALLOCARRAY_NOFAIL(bluvalue, 256);
-            
+
     if (visualP == DefaultVisual(disp, scrn))
         *cmapP = DefaultColormap(disp, scrn);
     else
         *cmapP = XCreateColormap(disp, RootWindow(disp, scrn),
                                  visualP, AllocNone);
-            
+
  retry_direct: /* tag we hit if a DirectColor allocation fails on
                 * default colormap */
-            
+
     /* calculate number of distinct colors in each band */
-            
+
     redcolors = grncolors = blucolors = 1;
     for (pixval = 1; pixval; pixval <<= 1) {
         if (pixval & visualP->red_mask)
@@ -306,16 +306,16 @@ makeColorMap1(Display *  const disp,
         if (pixval & visualP->blue_mask)
             blucolors <<= 1;
     }
-            
+
     /* sanity check */
-            
+
     if ((redcolors > visualP->map_entries) ||
         (grncolors > visualP->map_entries) ||
         (blucolors > visualP->map_entries)) {
         pm_message("Warning: inconsistency in color information "
                    "(this may be ugly)");
     }
-            
+
     redstep= 256 / redcolors;
     grnstep= 256 / grncolors;
     blustep= 256 / blucolors;
@@ -329,7 +329,7 @@ makeColorMap1(Display *  const disp,
             grntop = grnbottom + grnstep;
         if (blubottom < 256)
             blutop = blubottom + blustep;
-                
+
         xcolor.flags = DoRed | DoGreen | DoBlue;
         xcolor.red   = (redtop - 1) << 8;
         xcolor.green = (grntop - 1) << 8;
@@ -347,15 +347,15 @@ makeColorMap1(Display *  const disp,
                                          visualP, AllocNone);
                 goto retry_direct;
             }
-                    
+
             /* something completely unexpected happened */
-                    
+
             pm_error("INTERNAL ERROR: XAllocColor failed on a "
                      "TrueColor/Directcolor visual");
         }
-                
+
         /* fill in pixel values for each band at this intensity */
-                
+
         while ((redbottom < 256) && (redbottom < redtop))
             redvalue[redbottom++] = xcolor.pixel & visualP->red_mask;
         while ((grnbottom < 256) && (grnbottom < grntop))
@@ -369,7 +369,7 @@ makeColorMap1(Display *  const disp,
 }
 
 
- 
+
 static void
 allocColorCells(Display *      const disp,
                 Colormap       const cmap,
@@ -379,7 +379,7 @@ allocColorCells(Display *      const disp,
 
     bool outOfCells;
     unsigned int cellCount;
-    
+
     outOfCells = false;  /* initial value */
     cellCount = 0;       /* initial value */
     while (cellCount < colorCount && !outOfCells) {
@@ -392,7 +392,7 @@ allocColorCells(Display *      const disp,
     *cellCountP = cellCount;
 }
 
-    
+
 
 
 static void
@@ -412,9 +412,9 @@ makeColorMap2(Display *  const disp,
     Pixel * colorIndex;
 
     MALLOCARRAY_NOFAIL(colorIndex, rgb.used);
-        
+
     /* 'privateCmap' is invalid if not a dynamic visual */
-        
+
     switch (visualP->class) {
     case StaticColor:
     case StaticGray:
@@ -422,9 +422,9 @@ makeColorMap2(Display *  const disp,
     default:
         privateCmap = userWantsPrivateCmap;
     }
-        
+
     /* get the colormap to use. */
-        
+
     if (privateCmap) { /* user asked us to use a private cmap */
         newmap = TRUE;
         fit = FALSE;
@@ -433,7 +433,7 @@ makeColorMap2(Display *  const disp,
                (visualP->class == StaticColor) ||
                (visualP->class == TrueColor) ||
                (visualP->class == DirectColor)) {
-            
+
         unsigned int a;
 
         fit = userWantsFit;
@@ -442,16 +442,16 @@ makeColorMap2(Display *  const disp,
            shareable.  otherwise we're using a static visual and
            should treat it accordingly.
         */
-            
+
         if (visualP == DefaultVisual(disp, scrn))
             *cmapP = DefaultColormap(disp, scrn);
         else
             *cmapP = XCreateColormap(disp, RootWindow(disp, scrn),
                                      visualP, AllocNone);
         newmap = FALSE;
-            
+
         /* allocate colors shareable (if we can) */
-            
+
         for (a = 0; a < rgb.used; ++a) {
             Status rc;
             XColor  xcolor;
@@ -484,7 +484,7 @@ makeColorMap2(Display *  const disp,
         newmap = TRUE;
         fit    = FALSE;
     }
-        
+
     if (newmap) {
         /* Either create a new colormap or fit the image into the
            one we have.  To create a new one, we create a private
@@ -497,10 +497,10 @@ makeColorMap2(Display *  const disp,
            4. reduce the depth of the image to fit.
            5. allocate the colors again shareable.
            6. ungrab the server and continue on our way.
-               
+
            Someone should shoot the people who designed X color allocation.
         */
-            
+
         unsigned int a;
 
         if (fit) {
@@ -510,13 +510,13 @@ makeColorMap2(Display *  const disp,
         } else {
             if (verbose)
                 pm_message("Using private colormap");
-                
+
             /* create new colormap */
-                
+
             *cmapP = XCreateColormap(disp, RootWindow(disp, scrn),
                                      visualP, AllocNone);
         }
-            
+
         allocColorCells(disp, *cmapP, colorIndex, rgb.used, &a);
 
         if (fit) {
@@ -525,10 +525,10 @@ makeColorMap2(Display *  const disp,
             if (a <= 2)
                 pm_error("Cannot fit into default colormap");
         }
-            
+
         if (a == 0)
             pm_error("Color allocation failed!");
-            
+
         if (fit) {
             unsigned int a;
             for (a = 0; a < rgb.used; ++a) {
@@ -537,7 +537,7 @@ makeColorMap2(Display *  const disp,
                 xcolor.red   = rgb.red[a];
                 xcolor.green = rgb.grn[a];
                 xcolor.blue  = rgb.blu[a];
-                
+
                 if (!XAllocColor(disp, *cmapP, &xcolor))
                     pm_error("XAllocColor failed while fitting colormap!");
                 colorIndex[a] = xcolor.pixel;
@@ -574,7 +574,7 @@ doColorAllocation(XImageInfo * const ximageinfoP,
                   Pixel **     const redvalP,
                   Pixel **     const grnvalP,
                   Pixel **     const bluvalP) {
-    
+
     if ((visualP->class == TrueColor || visualP->class == DirectColor) &&
         !BITMAPP(imageP)) {
         makeColorMap1(disp, scrn, visualP, &ximageinfoP->cmap,
@@ -584,11 +584,11 @@ doColorAllocation(XImageInfo * const ximageinfoP,
         makeColorMap2(disp, scrn, visualP, imageP->rgb,
                       userWantsPrivateCmap, userWantsFit, verbose,
                       &ximageinfoP->cmap, colorIndexP);
-        
+
         *redvalP = *grnvalP = *bluvalP = NULL;
     }
 }
-    
+
 
 
 
@@ -637,19 +637,19 @@ makeXImage(XImageInfo * const ximageinfoP,
     case IRGB:
     case ITRUE: {
         /* Modify image data to match visual and colormap */
-        
+
         unsigned int const dbits = bitsPerPixelAtDepth(disp, scrn, ddepth);
         unsigned int const dpixlen = (dbits + 7) / 8;
 
         ximageinfoP->depth = ddepth;
-        
+
         switch (visualP->class) {
         case DirectColor:
         case TrueColor: {
             unsigned char * data;
             unsigned char * destptr;
             unsigned char * srcptr;
-        
+
             ximageinfoP->ximageP =
                 XCreateImage(disp, visualP, ddepth, ZPixmap, 0,
                              NULL, imageP->width, imageP->height, 8, 0);
@@ -702,7 +702,7 @@ makeXImage(XImageInfo * const ximageinfoP,
         } break;
 
         default: {
-            
+
             /* only IRGB images make it this far. */
 
             /* If our XImage doesn't have modulus 8 bits per pixel,
@@ -734,7 +734,7 @@ makeXImage(XImageInfo * const ximageinfoP,
                 ximageinfoP->ximageP->byte_order = MSBFirst;
                 for (a= 0; a < dbits; ++a) {
                     Pixel const pixmask = 1 << a;
-                    unsigned char * const destdata = 
+                    unsigned char * const destdata =
                         data + ((ddepth - a - 1) * imageP->height * linelen);
 
                     unsigned int y;
@@ -792,7 +792,7 @@ makeXImage(XImageInfo * const ximageinfoP,
                 }
             }
         } break;
-        }   
+        }
     } break;
     }
     if (verbose)
@@ -819,7 +819,7 @@ imageToXImage(Display *    const disp,
     Pixel * bluvalue;
 
     assertGoodImage(origImageP);
-  
+
     MALLOCVAR_NOFAIL(ximageinfoP);
     ximageinfoP->disp = disp;
     ximageinfoP->scrn = scrn;
@@ -828,7 +828,7 @@ imageToXImage(Display *    const disp,
     ximageinfoP->foreground = ximageinfoP->background = 0;
     ximageinfoP->gc = NULL;
     ximageinfoP->ximageP = NULL;
-  
+
     makeUsableVisual(origImageP, visualP, ddepth, &imageP);
 
     assertGoodImage(imageP);
@@ -849,7 +849,7 @@ imageToXImage(Display *    const disp,
     }
     if (imageP != origImageP)
         freeImage(imageP);
-    
+
     return ximageinfoP;
 }
 
@@ -870,7 +870,7 @@ sendXImage(XImageInfo * const ximageinfoP,
     XGCValues gcv;
 
     /* build and cache the GC */
-    
+
     if (!ximageinfoP->gc) {
         gcv.function = GXcopy;
         if (ximageinfoP->ximageP->depth == 1) {
@@ -885,7 +885,7 @@ sendXImage(XImageInfo * const ximageinfoP,
                 XCreateGC(ximageinfoP->disp, ximageinfoP->drawable,
                           GCFunction, &gcv);
     }
-    
+
     XPutImage(ximageinfoP->disp, ximageinfoP->drawable, ximageinfoP->gc,
               ximageinfoP->ximageP, src_x, src_y, dst_x, dst_y, w, h);
 }
diff --git a/other/pamx/window.c b/other/pamx/window.c
index d907163b..61089ea5 100644
--- a/other/pamx/window.c
+++ b/other/pamx/window.c
@@ -1,8 +1,8 @@
 /*
    Functions to allocate and deallocate structures and structure data
- 
+
    By Jim Frost 1989.10.03, Bryan Henderson 2006.03.25.
- 
+
    See COPYRIGHT file for copyright information.
 */
 
@@ -80,10 +80,10 @@ static void
 setDeleteWindow(viewer * const viewerP) {
 
     Atom const protoAtom = XInternAtom(viewerP->dispP, "WM_PROTOCOLS", False);
-    
+
     viewerP->deleteAtom = XInternAtom(viewerP->dispP,
                                       "WM_DELETE_WINDOW", False);
-    
+
     if ((protoAtom != None) && (viewerP->deleteAtom != None))
         XChangeProperty(viewerP->dispP, viewerP->viewportWin,
                         protoAtom, XA_ATOM, 32, PropModeReplace,
@@ -139,7 +139,7 @@ createViewer(viewer **     const viewerPP,
              bool          const fullscreen) {
 
     viewer * viewerP;
-    
+
     XSetWindowAttributes  swa_view;
 
     MALLOCVAR_NOFAIL(viewerP);
@@ -164,7 +164,7 @@ createViewer(viewer **     const viewerPP,
         ButtonPressMask | Button1MotionMask | KeyPressMask |
         StructureNotifyMask | EnterWindowMask | LeaveWindowMask;
     swa_view.save_under       = FALSE;
-    
+
     viewerP->viewportWin =
         XCreateWindow(dispP, RootWindow(dispP, scrn),
                       viewerP->xpos, viewerP->ypos,
@@ -176,7 +176,7 @@ createViewer(viewer **     const viewerPP,
                       &swa_view);
 
     setXloadimageClassHint(viewerP->dispP, viewerP->viewportWin);
-    
+
     setDeleteWindow(viewerP);
 
     viewerP->blank = TRUE;
@@ -192,7 +192,7 @@ determineRepaintStrategy(viewer  *    const viewerP,
                          bool         const verbose,
                          XImageInfo * const ximageinfoP,
                          Pixmap *     const pixmapP) {
-                        
+
     /* Decide how we're going to handle repaints.  We have three modes:
        use backing-store, use background pixmap, and use exposures.
        If the server allows backing-store, we enable it and use it.
@@ -200,7 +200,7 @@ determineRepaintStrategy(viewer  *    const viewerP,
        server does not have backing-store, we try to send the image to
        a pixmap and use that as backing-store.  If that fails, we use
        exposures to blit the image (which is ugly but it works).
-       
+
        'use_pixmap' forces background pixmap mode, which may improve
        performance.
     */
@@ -303,7 +303,7 @@ createImageWindow(viewer *      const viewerP,
 
 static void
 destroyImageWindow(viewer * const viewerP) {
-    
+
     if (viewerP->imageWin) {
         if (viewerP->imageColormap &&
             (viewerP->imageColormap != DefaultColormap(viewerP->dispP, viewerP->scrn)))
@@ -311,7 +311,7 @@ destroyImageWindow(viewer * const viewerP) {
         XDestroyWindow(viewerP->dispP, viewerP->imageWin);
     }
 }
-                       
+
 
 
 static void
@@ -348,12 +348,32 @@ placeImage(viewer * const viewerP,
            int      const height,
            int *    const rxP,     /* input and output */
            int *    const ryP) {   /* input and output */
+/*----------------------------------------------------------------------------
+   Move the X window of *viewerP on the right place on the display to contain
+   an image whose dimensions are 'width' by 'height'.
+
+   As input *rxP and *ryP are the current location of the window (offset from
+   the top left corner of the display of the top left corner of the window).
+   We update them with the new location.
+
+   If the image is narrower than the display, center it.
+
+   Otherwise, either left-justify it or right-justify it depending upon the
+   current position of the window:
+
+      If in the current position, the right edge of the image is within the
+      display, right-justify.
 
+      Otherwise left-justify.
+
+
+   Do the analogous thing for vertical placement.
+-----------------------------------------------------------------------------*/
     int pixx, pixy;
-    
+
     pixx = *rxP;
     pixy = *ryP;
-    
+
     if (viewerP->width > width)
         pixx = (viewerP->width - width) / 2;
     else {
@@ -366,7 +386,7 @@ placeImage(viewer * const viewerP,
         pixy = (viewerP->height - height) / 2;
     else {
         if ((pixy < 0) && (pixy + height < viewerP->height))
-            pixy = viewerP->height - viewerP->height;
+            pixy = viewerP->height - height;
         if (pixy > 0)
             pixy = 0;
     }
@@ -434,10 +454,10 @@ destroyViewer(viewer * const viewerP) {
     if (viewerP->imageWin)
         XDestroyWindow(viewerP->dispP, viewerP->imageWin);
     viewerP->imageWin = 0;
-    
+
     if (viewerP->viewportWin)
         XDestroyWindow(viewerP->dispP, viewerP->viewportWin);
-    
+
     viewerP->viewportWin = 0;
 
     XFreeCursor(viewerP->dispP, viewerP->cursor);
@@ -459,12 +479,12 @@ setViewportColormap(viewer *  const viewerP,
 
     if (cmap_atom == None)
         cmap_atom = XInternAtom(viewerP->dispP, "WM_COLORMAP_WINDOWS", False);
-    
+
     /* If the visual we're using is the same as the default visual (used by
        the viewport window) then we can set the viewport window to use the
        image's colormap.  This keeps most window managers happy.
     */
-    
+
     if (visualP == DefaultVisual(viewerP->dispP, viewerP->scrn)) {
         swa.colormap = viewerP->imageColormap;
         XChangeWindowAttributes(viewerP->dispP, viewerP->viewportWin,
@@ -507,11 +527,11 @@ iconName(const char * const s) {
         t = strchr(buf, ' ');
         if (t)
             *t = '\0';
-    
+
         /* Strip off leading path.  if you don't use unix-style paths,
            You might want to change this.
         */
-    
+
         t= strrchr(buf, '/');
         if (t) {
             char * p;
@@ -557,7 +577,7 @@ visualClassFromName(const char * const name) {
     unsigned int a;
     int class;
     bool found;
-    
+
     for (a = 0, found = FALSE; VisualClassName[a].name; ++a) {
         if (strcaseeq(VisualClassName[a].name, name)) {
             /* Check for uniqueness.  We special-case StaticGray
@@ -674,10 +694,10 @@ bestVisual(Display *      const disp,
         pm_message("bestVisual: didn't find any depths?!?");
         depth = DefaultDepth(disp, scrn);
     }
-    
+
     /* given this depth, find the best possible visual
      */
-    
+
     default_visualP = DefaultVisual(disp, scrn);
     switch (imageP->type) {
     case ITRUE: {
@@ -697,7 +717,7 @@ bestVisual(Display *      const disp,
                 visualP = bestVisualOfClassAndDepth(disp, scrn, TrueColor,
                                                     depth);
         }
-        
+
         if (!visualP || ((depth <= 8) &&
                          bestVisualOfClassAndDepth(disp, scrn, PseudoColor,
                                                    depth)))
@@ -711,7 +731,7 @@ bestVisual(Display *      const disp,
         if (!visualP)
             visualP = bestVisualOfClassAndDepth(disp, scrn, StaticGray, depth);
     } break;
-        
+
     case IRGB: {
         /* if it's an RGB image, we want PseudoColor if we can get it */
 
@@ -814,7 +834,7 @@ getImageDispDimensions(viewer *       const viewerP,
         *widthP  = viewerP->width;
         *heightP = viewerP->height;
     } else {
-        unsigned int const displayWidth = 
+        unsigned int const displayWidth =
             DisplayWidth(viewerP->dispP, viewerP->scrn);
         unsigned int const displayHeight =
             DisplayHeight(viewerP->dispP, viewerP->scrn);
@@ -878,9 +898,9 @@ getVisualAndDepth(Image *        const imageP,
 static void
 setNormalSizeHints(viewer *     const viewerP,
                    Image *      const imageP) {
-    
+
     XSizeHints sh;
-    
+
     sh.width  = viewerP->width;
     sh.height = viewerP->height;
     if (viewerP->fullscreen) {
@@ -984,7 +1004,7 @@ run(viewer *     const viewerP,
             KeySym ks;
             XComposeStatus status;
             Status rc;
-            
+
             rc = XLookupString(&event.key, buf, 128, &ks, &status);
             if (rc == 1) {
                 char const ret = buf[0];
@@ -1093,7 +1113,7 @@ static void
 resizeViewer(viewer *     const viewerP,
              unsigned int const newWidth,
              unsigned int const newHeight) {
-    
+
     if (viewerP->width != newWidth || viewerP->height != newHeight) {
         XResizeWindow(viewerP->dispP, viewerP->viewportWin,
                       newWidth, newHeight);
@@ -1116,7 +1136,7 @@ displayInViewer(viewer *       const viewerP,
                 const char *   const title,
                 bool           const verbose,
                 int *          const retvalP) {
-    
+
     XImageInfo *     ximageInfoP;
     Visual *         visual;
     unsigned int     depth;
@@ -1134,7 +1154,7 @@ displayInViewer(viewer *       const viewerP,
     getVisualAndDepth(imageP, viewerP->dispP, viewerP->scrn,
                       fit, visualSpec, visualClass,
                       &visual, &depth);
-    
+
     if (verbose && (visual != DefaultVisual(viewerP->dispP, viewerP->scrn)))
         pm_message("Using %s visual", nameOfVisualClass(visual->class));
 
@@ -1211,3 +1231,6 @@ displayInViewer(viewer *       const viewerP,
 
     *retvalP = retvalueFromExitReason(exitReason);
 }
+
+
+
diff --git a/other/pnmcolormap.c b/other/pnmcolormap.c
index 7da3122b..f59a1a0d 100644
--- a/other/pnmcolormap.c
+++ b/other/pnmcolormap.c
@@ -1,7 +1,6 @@
-/******************************************************************************
-                               pnmcolormap.c
-*******************************************************************************
-
+/*=============================================================================
+                               pnmcolormap
+===============================================================================
   Create a colormap file (a PPM image containing one pixel of each of a set
   of colors).  Base the set of colors on an input image.
 
@@ -20,9 +19,8 @@
   copyright notice and this permission notice appear in supporting
   documentation.  This software is provided "as is" without express or
   implied warranty.
-
-******************************************************************************/
-
+=============================================================================*/
+#include <stdbool.h>
 #include <assert.h>
 #include <math.h>
 
@@ -41,19 +39,41 @@ enum MethodForRep {REP_CENTER_BOX, REP_AVERAGE_COLORS, REP_AVERAGE_PIXELS};
 enum MethodForSplit {SPLIT_MAX_PIXELS, SPLIT_MAX_COLORS, SPLIT_MAX_SPREAD};
 
 struct Box {
-    unsigned int index;
+/*----------------------------------------------------------------------------
+   A box contains an extent of a color frequency table, i.e. the colors
+   with some consecutive index values in the color frequency table.
+-----------------------------------------------------------------------------*/
+    unsigned int serialNum;
+        /* Unique identifier of this box; sequence number of creation. */
+    unsigned int startIndex;
+        /* First index in the extent */
     unsigned int colorCt;
+        /* Size of the extent (Number of colors in it -- at least 1) */
     unsigned int sum;
+        /* Number of pixels of all colors in the extent */
     unsigned int maxdim;
-        /* which dimension has the largest spread.  RGB plane number. */
+        /* Which dimension has the largest spread.  RGB plane number. */
+        /* Meaningless if box contains only 1 color */
     sample       spread;
         /* spread in dimension 'maxdim' */
+        /* Meaningless if box contains only 1 color */
 };
 
 struct BoxVector {
+    tupletable2 colorFreqTable;
+        /* The colors and their frequencies (number of pixels in the image of
+           that color), ordered into consecutive boxes, as defined by 'box'.
+        */
+    unsigned int colorDepth;
+        /* Number of planes in the tuples of 'colorFreqTable' */
     struct Box * box;  /* malloc'ed array */
+        /* An array of boxes that contain consecutive extents of
+           'colorFreqTable'.  The list covers the entire table.
+        */
     unsigned int boxCt;
+        /* Number of boxes in the above list */
     unsigned int capacity;
+        /* Number of boxes the array is capable of containing */
 };
 
 struct CmdlineInfo {
@@ -62,7 +82,7 @@ struct CmdlineInfo {
     */
     const char * inputFileNm;  /* Name of input file */
     unsigned int allcolors;  /* boolean: select all colors from the input */
-    unsigned int newcolors;
+    unsigned int newColorCt;
         /* Number of colors argument; meaningless if allcolors true */
     enum MethodForLargest methodForLargest;
         /* -spreadintensity/-spreadluminosity options */
@@ -73,13 +93,14 @@ struct CmdlineInfo {
     unsigned int sort;
     unsigned int square;
     unsigned int verbose;
+    unsigned int debug;
 };
 
 
 
 static void
 parseCommandLine (int argc, const char ** argv,
-                  struct CmdlineInfo *cmdlineP) {
+                  struct CmdlineInfo * const cmdlineP) {
 /*----------------------------------------------------------------------------
    parse program command line described in Unix standard form by argc
    and argv.  Return the information in the options as *cmdlineP.
@@ -90,9 +111,7 @@ parseCommandLine (int argc, const char ** argv,
    Note that the strings we return are stored in the storage that
    was passed to us as the argv array.  We also trash *argv.
 -----------------------------------------------------------------------------*/
-    optEntry *option_def;
-        /* Instructions to pm_optParseOptions3 on how to parse our options.
-         */
+    optEntry * option_def;
     optStruct3 opt;
 
     unsigned int option_def_index;
@@ -120,18 +139,20 @@ parseCommandLine (int argc, const char ** argv,
             NULL,                       &splitcolorct,     0);
     OPTENT3(0,   "splitspread",      OPT_FLAG,
             NULL,                       &splitspread,      0);
-    OPTENT3(0, "sort",     OPT_FLAG,   NULL,
-            &cmdlineP->sort,       0 );
-    OPTENT3(0, "square",   OPT_FLAG,   NULL,
-            &cmdlineP->square,       0 );
-    OPTENT3(0, "verbose",   OPT_FLAG,   NULL,
-            &cmdlineP->verbose,       0 );
+    OPTENT3(0, "sort",               OPT_FLAG,   NULL,
+            &cmdlineP->sort,                               0);
+    OPTENT3(0, "square",             OPT_FLAG,   NULL,
+            &cmdlineP->square,                             0);
+    OPTENT3(0, "verbose",            OPT_FLAG,   NULL,
+            &cmdlineP->verbose,                            0);
+    OPTENT3(0, "debug",              OPT_FLAG,   NULL,
+            &cmdlineP->debug,                              0);
 
     opt.opt_table = option_def;
-    opt.short_allowed = FALSE;  /* We have no short (old-fashioned) options */
-    opt.allowNegNum = FALSE;  /* We have no parms that are negative numbers */
+    opt.short_allowed = false;  /* We have no short (old-fashioned) options */
+    opt.allowNegNum = false;  /* We have no parms that are negative numbers */
 
-    pm_optParseOptions3( &argc, (char **)argv, opt, sizeof(opt), 0 );
+    pm_optParseOptions4( &argc, argv, opt, sizeof(opt), 0 );
         /* Uses and sets argc, argv, and some of *cmdline_p and others. */
 
 
@@ -177,21 +198,18 @@ parseCommandLine (int argc, const char ** argv,
                      "output as an argument.");
         else {
             if (strcmp(argv[1], "all") == 0)
-                cmdlineP->allcolors = TRUE;
+                cmdlineP->allcolors = true;
             else {
-                char * tail;
-                long int const newcolors = strtol(argv[1], &tail, 10);
-                if (*tail != '\0')
+                const char * error;
+                cmdlineP->allcolors = false;
+                pm_string_to_uint(argv[1], &cmdlineP->newColorCt, &error);
+
+                if (error) {
                     pm_error("The number of colors argument '%s' is not "
-                             "a number or 'all'", argv[1]);
-                else if (newcolors < 1)
+                             "an unsigned number or 'all'.  %s",
+                             argv[1], error);
+                } else if (cmdlineP->newColorCt == 0)
                     pm_error("The number of colors must be positive");
-                else if (newcolors == 1)
-                    pm_error("The number of colors must be greater than 1.");
-                else {
-                    cmdlineP->newcolors = newcolors;
-                    cmdlineP->allcolors = FALSE;
-                }
             }
         }
     }
@@ -200,28 +218,63 @@ parseCommandLine (int argc, const char ** argv,
 
 
 #ifndef LITERAL_FN_DEF_MATCH
-static qsort_comparison_fn compareplane;
+static qsort_comparison_fn compareColor;
 #endif
 
-static unsigned int compareplanePlane;
-    /* This is a parameter to compareplane().  We use this global variable
-       so that compareplane() can be called by qsort(), to compare two
-       tuples.  qsort() doesn't pass any arguments except the two tuples.
-    */
+static struct {
+/*----------------------------------------------------------------------------
+  This is a parameter to compareColor().  We use this global variable
+  so that compareColor() can be called by qsort(), to compare two
+  tuples.  qsort() doesn't pass any arguments except the two tuples.
+-----------------------------------------------------------------------------*/
+    unsigned int comparePlane;
+        /* The number of the plane to compare between the tuples */
+    unsigned int colorDepth;
+        /* Depth (number of planes) of the tuples */
+} compareColorParm;
+
 static int
-compareplane(const void * const arg1,
+compareColor(const void * const arg1,
              const void * const arg2) {
 
     const struct tupleint * const * const comparandPP  = arg1;
     const struct tupleint * const * const comparatorPP = arg2;
 
-    sample const comparandSample  = (*comparandPP) ->tuple[compareplanePlane];
-    sample const comparatorSample = (*comparatorPP)->tuple[compareplanePlane];
+    sample const comparandSample  =
+        (*comparandPP) ->tuple[compareColorParm.comparePlane];
+    sample const comparatorSample =
+        (*comparatorPP)->tuple[compareColorParm.comparePlane];
 
-    return
-        comparandSample < comparatorSample ? -1 :
-        comparandSample > comparatorSample ? 1 :
-        0;
+    int retval;
+
+    if (comparandSample < comparatorSample)
+        retval = -1;
+    else if (comparandSample > comparatorSample)
+        retval = +1;
+    else {
+        /* In the plane that matters, samples are equal, but we're going to
+           try to differentiate the colors anyway so as to make qsort put the
+           colors in a deterministic order so the boxes are deterministic.
+        */
+        unsigned int plane;
+        int bestDiffSoFar;  /* -1, 0, or 1, like our return value */
+        for (plane = 0, bestDiffSoFar = 0;
+             plane < compareColorParm.colorDepth && bestDiffSoFar == 0;
+             ++plane) {
+
+            sample const comparandSample  =
+                (*comparandPP) ->tuple[compareColorParm.comparePlane];
+            sample const comparatorSample =
+                (*comparatorPP)->tuple[compareColorParm.comparePlane];
+
+            if (comparandSample < comparatorSample)
+                bestDiffSoFar = -1;
+            else if (comparandSample > comparatorSample)
+                bestDiffSoFar = +1;
+        }
+        retval = bestDiffSoFar;
+    }
+    return retval;
 }
 
 
@@ -239,7 +292,9 @@ sumcompare(const void * const arg1,
 
     return
         comparatorP->sum < comparandP->sum ? -1 :
-        comparatorP->sum > comparandP->sum ? 1 :
+        comparatorP->sum > comparandP->sum ? +1 :
+        comparatorP->serialNum < comparandP->serialNum ? -1 :
+        comparatorP->serialNum > comparandP->serialNum ? +1 :
         0;
 }
 
@@ -259,6 +314,8 @@ colcompare(const void * const arg1,
     return
         comparatorP->colorCt < comparandP->colorCt ? -1 :
         comparatorP->colorCt > comparandP->colorCt ? 1 :
+        comparatorP->serialNum < comparandP->serialNum ? -1 :
+        comparatorP->serialNum > comparandP->serialNum ? +1 :
         0;
 }
 
@@ -278,6 +335,8 @@ spreadcompare(const void * const arg1,
     return
         comparatorP->spread < comparandP->spread ? -1 :
         comparatorP->spread > comparandP->spread ? 1 :
+        comparatorP->serialNum < comparandP->serialNum ? -1 :
+        comparatorP->serialNum > comparandP->serialNum ? +1 :
         0;
 }
 
@@ -308,7 +367,7 @@ sortBoxes(struct BoxVector *  const boxVectorP,
 */
 
 static void
-findBoxBoundaries(tupletable2  const colorfreqtable,
+findBoxBoundaries(tupletable2  const colorFreqTable,
                   unsigned int const depth,
                   unsigned int const boxStart,
                   unsigned int const boxSize,
@@ -322,14 +381,14 @@ findBoxBoundaries(tupletable2  const colorfreqtable,
     unsigned int i;
 
     for (plane = 0; plane < depth; ++plane) {
-        minval[plane] = colorfreqtable.table[boxStart]->tuple[plane];
+        minval[plane] = colorFreqTable.table[boxStart]->tuple[plane];
         maxval[plane] = minval[plane];
     }
 
     for (i = 1; i < boxSize; ++i) {
         unsigned int plane;
         for (plane = 0; plane < depth; ++plane) {
-            sample const v = colorfreqtable.table[boxStart + i]->tuple[plane];
+            sample const v = colorFreqTable.table[boxStart + i]->tuple[plane];
             if (v < minval[plane]) minval[plane] = v;
             if (v > maxval[plane]) maxval[plane] = v;
         }
@@ -402,7 +461,7 @@ findPlaneWithLargestSpreadByLuminosity(sample         const minval[],
 
 static void
 computeBoxSpread(const struct Box *    const boxP,
-                 tupletable2           const colorfreqtable,
+                 tupletable2           const colorFreqTable,
                  unsigned int          const depth,
                  enum MethodForLargest const methodForLargest,
                  unsigned int *        const planeWithLargestP,
@@ -420,7 +479,7 @@ computeBoxSpread(const struct Box *    const boxP,
     MALLOCARRAY_NOFAIL(minval, depth);
     MALLOCARRAY_NOFAIL(maxval, depth);
 
-    findBoxBoundaries(colorfreqtable, depth, boxP->index, boxP->colorCt,
+    findBoxBoundaries(colorFreqTable, depth, boxP->startIndex, boxP->colorCt,
                       minval, maxval);
 
     switch (methodForLargest) {
@@ -439,13 +498,13 @@ computeBoxSpread(const struct Box *    const boxP,
 
 
 static unsigned int
-freqTotal(tupletable2 const freqtable) {
+freqTotal(tupletable2 const freqTable) {
 
     unsigned int i;
     unsigned int sum;
 
-    for (i = 0, sum = 0; i < freqtable.size; ++i)
-        sum += freqtable.table[i]->value;
+    for (i = 0, sum = 0; i < freqTable.size; ++i)
+        sum += freqTable.table[i]->value;
 
     return sum;
 }
@@ -453,27 +512,30 @@ freqTotal(tupletable2 const freqtable) {
 
 
 static struct BoxVector
-newBoxVector(tupletable2           const colorfreqtable,
+newBoxVector(tupletable2           const colorFreqTable,
              unsigned int          const capacity,
              unsigned int          const depth,
              enum MethodForLargest const methodForLargest) {
 
-    unsigned int const colorCt = colorfreqtable.size;
-    unsigned int const sum     = freqTotal(colorfreqtable);
+    unsigned int const colorCt = colorFreqTable.size;
+    unsigned int const sum     = freqTotal(colorFreqTable);
 
     struct BoxVector boxVector;
 
+    boxVector.colorFreqTable = colorFreqTable;
+    boxVector.colorDepth     = depth;
+
     MALLOCARRAY(boxVector.box, capacity);
 
     if (!boxVector.box)
         pm_error("out of memory allocating box vector table");
 
     /* Set up the initial box. */
-    boxVector.box[0].index   = 0;
-    boxVector.box[0].colorCt = colorCt;
-    boxVector.box[0].sum     = sum;
+    boxVector.box[0].startIndex = 0;
+    boxVector.box[0].colorCt    = colorCt;
+    boxVector.box[0].sum        = sum;
 
-    computeBoxSpread(&boxVector.box[0], colorfreqtable, depth,
+    computeBoxSpread(&boxVector.box[0], colorFreqTable, depth,
                      methodForLargest,
                      &boxVector.box[0].maxdim,
                      &boxVector.box[0].spread);
@@ -497,7 +559,7 @@ destroyBoxVector(struct BoxVector const boxVector) {
 static void
 centerBox(int          const boxStart,
           int          const boxSize,
-          tupletable2  const colorfreqtable,
+          tupletable2  const colorFreqTable,
           unsigned int const depth,
           tuple        const newTuple) {
 
@@ -507,10 +569,10 @@ centerBox(int          const boxStart,
         int minval, maxval;
         unsigned int i;
 
-        minval = maxval = colorfreqtable.table[boxStart]->tuple[plane];
+        minval = maxval = colorFreqTable.table[boxStart]->tuple[plane];
 
         for (i = 1; i < boxSize; ++i) {
-            int const v = colorfreqtable.table[boxStart + i]->tuple[plane];
+            int const v = colorFreqTable.table[boxStart + i]->tuple[plane];
             minval = MIN( minval, v);
             maxval = MAX( maxval, v);
         }
@@ -547,7 +609,7 @@ newColorMap(unsigned int const colorCt,
 static void
 averageColors(int          const boxStart,
               int          const boxSize,
-              tupletable2  const colorfreqtable,
+              tupletable2  const colorFreqTable,
               unsigned int const depth,
               tuple        const newTuple) {
 
@@ -560,7 +622,7 @@ averageColors(int          const boxStart,
         sum = 0;
 
         for (i = 0; i < boxSize; ++i)
-            sum += colorfreqtable.table[boxStart+i]->tuple[plane];
+            sum += colorFreqTable.table[boxStart+i]->tuple[plane];
 
         newTuple[plane] = ROUNDDIV(sum, boxSize);
     }
@@ -571,7 +633,7 @@ averageColors(int          const boxStart,
 static void
 averagePixels(int          const boxStart,
               int          const boxSize,
-              tupletable2  const colorfreqtable,
+              tupletable2  const colorFreqTable,
               unsigned int const depth,
               tuple        const newTuple) {
 
@@ -583,7 +645,7 @@ averagePixels(int          const boxStart,
     /* Count the tuples in question */
     n = 0;  /* initial value */
     for (i = 0; i < boxSize; ++i)
-        n += colorfreqtable.table[boxStart + i]->value;
+        n += colorFreqTable.table[boxStart + i]->value;
 
 
     for (plane = 0; plane < depth; ++plane) {
@@ -593,8 +655,8 @@ averagePixels(int          const boxStart,
         sum = 0;
 
         for (i = 0; i < boxSize; ++i)
-            sum += colorfreqtable.table[boxStart+i]->tuple[plane]
-                * colorfreqtable.table[boxStart+i]->value;
+            sum += colorFreqTable.table[boxStart+i]->tuple[plane]
+                * colorFreqTable.table[boxStart+i]->value;
 
         newTuple[plane] = ROUNDDIV(sum, n);
     }
@@ -605,8 +667,6 @@ averagePixels(int          const boxStart,
 static tupletable2
 colormapFromBv(unsigned int      const colorCt,
                struct BoxVector  const boxVector,
-               tupletable2       const colorfreqtable,
-               unsigned int      const depth,
                enum MethodForRep const methodForRep) {
     /*
     ** Ok, we've got enough boxes.  Now choose a representative color for
@@ -619,26 +679,26 @@ colormapFromBv(unsigned int      const colorCt,
     tupletable2 colormap;
     unsigned int boxIdx;
 
-    colormap = newColorMap(colorCt, depth);
+    colormap = newColorMap(colorCt, boxVector.colorDepth);
 
     for (boxIdx = 0; boxIdx < boxVector.boxCt; ++boxIdx) {
         switch (methodForRep) {
         case REP_CENTER_BOX:
-            centerBox(boxVector.box[boxIdx].index,
+            centerBox(boxVector.box[boxIdx].startIndex,
                       boxVector.box[boxIdx].colorCt,
-                      colorfreqtable, depth,
+                      boxVector.colorFreqTable, boxVector.colorDepth,
                       colormap.table[boxIdx]->tuple);
             break;
         case REP_AVERAGE_COLORS:
-            averageColors(boxVector.box[boxIdx].index,
+            averageColors(boxVector.box[boxIdx].startIndex,
                           boxVector.box[boxIdx].colorCt,
-                          colorfreqtable, depth,
+                          boxVector.colorFreqTable, boxVector.colorDepth,
                           colormap.table[boxIdx]->tuple);
             break;
         case REP_AVERAGE_PIXELS:
-            averagePixels(boxVector.box[boxIdx].index,
+            averagePixels(boxVector.box[boxIdx].startIndex,
                           boxVector.box[boxIdx].colorCt,
-                          colorfreqtable, depth,
+                          boxVector.colorFreqTable, boxVector.colorDepth,
                           colormap.table[boxIdx]->tuple);
             break;
         default:
@@ -652,42 +712,72 @@ colormapFromBv(unsigned int      const colorCt,
 
 
 static void
+setBox(struct Box *          const boxP,
+       unsigned int          const startIndex,
+       unsigned int          const colorCt,
+       unsigned int          const sum,
+       struct BoxVector *    const boxVectorP,
+       enum MethodForLargest const methodForLargest
+    ) {
+
+    boxP->startIndex = startIndex;
+    boxP->colorCt    = colorCt;
+    boxP->sum        = sum;
+
+    computeBoxSpread(boxP, boxVectorP->colorFreqTable,
+                     boxVectorP->colorDepth, methodForLargest,
+                     &boxP->maxdim, &boxP->spread);
+}
+
+
+
+static void
+makeNewBox(struct BoxVector *    const boxVectorP,
+           unsigned int          const startIndex,
+           unsigned int          const colorCt,
+           unsigned int          const sum,
+           enum MethodForLargest const methodForLargest) {
+
+    struct Box * const boxP = &boxVectorP->box[boxVectorP->boxCt++];
+
+    assert(boxVectorP->boxCt <= boxVectorP->capacity);
+
+    boxP->serialNum = boxVectorP->boxCt;
+
+    setBox(boxP, startIndex, colorCt, sum, boxVectorP, methodForLargest);
+}
+
+
+
+static void
 splitBox(struct BoxVector *    const boxVectorP,
          unsigned int          const boxIdx,
-         tupletable2           const colorfreqtable,
-         unsigned int          const depth,
          enum MethodForLargest const methodForLargest,
          enum MethodForSplit   const methodForSplit) {
 /*----------------------------------------------------------------------------
-   Split Box 'boxIdx' in the box vector 'boxVector' (so that bv contains one
-   more box than it did as input).  Split it so that each new box represents
-   about half of the pixels in the distribution given by 'colorfreqtable' for
-   the colors in the original box, but with distinct colors in each of the two
-   new boxes.
+   Split Box 'boxIdx' in the box vector 'boxVector' (so that 'boxVector'
+   contains one more box than it did as input).  Split it so that each new box
+   represents about half of the pixels in the image for the colors in the
+   original box, but with distinct colors in each of the two new boxes.
 
    Assume the box contains at least two colors.
 -----------------------------------------------------------------------------*/
-    unsigned int const boxStart = boxVectorP->box[boxIdx].index;
+    unsigned int const boxStart = boxVectorP->box[boxIdx].startIndex;
     unsigned int const boxSize  = boxVectorP->box[boxIdx].colorCt;
     unsigned int const sum      = boxVectorP->box[boxIdx].sum;
 
     unsigned int medianIndex;
-    int lowersum;
+    unsigned int lowerSum;
         /* Number of pixels whose value is "less than" the median */
 
-
-    /* Perhaps this sort should go after creating a box, not before splitting.
-       Because you need the sort to use the REP_CENTER_BOX method of choosing
-       a color to represent the final boxes
-    */
-
-    /* Set the gross global variable 'compareplanePlane' as a
-       parameter to compareplane(), which is called by qsort().
+    /* Set the gross global variable 'compareColorParm' as a
+       parameter to compareColor(), which is called by qsort().
     */
-    compareplanePlane = boxVectorP->box[boxIdx].maxdim;
-    qsort((char*) &colorfreqtable.table[boxStart], boxSize,
-          sizeof(colorfreqtable.table[boxStart]),
-          compareplane);
+    compareColorParm.comparePlane    = boxVectorP->box[boxIdx].maxdim;
+    compareColorParm.colorDepth      = boxVectorP->colorDepth;
+    qsort((char*) &boxVectorP->colorFreqTable.table[boxStart], boxSize,
+          sizeof(boxVectorP->colorFreqTable.table[boxStart]),
+          compareColor);
 
     {
         /* Find the median based on the counts, so that about half the pixels
@@ -695,31 +785,25 @@ splitBox(struct BoxVector *    const boxVectorP,
         */
         unsigned int i;
 
-        lowersum = colorfreqtable.table[boxStart]->value; /* initial value */
-        for (i = 1; i < boxSize - 1 && lowersum < sum/2; ++i) {
-            lowersum += colorfreqtable.table[boxStart + i]->value;
+        lowerSum = boxVectorP->colorFreqTable.table[boxStart]->value;
+            /* initial value */
+        for (i = 1; i < boxSize - 1 && lowerSum < sum/2; ++i) {
+            lowerSum += boxVectorP->colorFreqTable.table[boxStart + i]->value;
         }
         medianIndex = i;
     }
-    /* Split the box, and sort to bring the biggest boxes to the top.  */
-    {
-        struct Box * const oldBoxP = &boxVectorP->box[boxIdx];
+    /* Split the box, and sort to bring the biggest boxes to the top.  The old
+       box becomes the lower half; we make a new box for the upper half.
+    */
+    setBox(&boxVectorP->box[boxIdx],
+           boxStart, medianIndex,
+           lowerSum,
+           boxVectorP, methodForLargest);
 
-        oldBoxP->colorCt = medianIndex;
-        oldBoxP->sum     = lowersum;
-        computeBoxSpread(oldBoxP, colorfreqtable, depth, methodForLargest,
-                         &oldBoxP->maxdim, &oldBoxP->spread);
-    }
-    {
-        struct Box * const newBoxP = &boxVectorP->box[boxVectorP->boxCt];
-
-        newBoxP->index   = boxStart + medianIndex;
-        newBoxP->colorCt = boxSize - medianIndex;
-        newBoxP->sum     = sum - lowersum;
-        computeBoxSpread(newBoxP, colorfreqtable, depth, methodForLargest,
-                         &newBoxP->maxdim, &newBoxP->spread);
-        ++boxVectorP->boxCt;
-    }
+    makeNewBox(boxVectorP,
+               boxStart + medianIndex, boxSize - medianIndex,
+               sum - lowerSum,
+               methodForLargest);
 
     sortBoxes(boxVectorP, methodForSplit);
 }
@@ -727,21 +811,58 @@ splitBox(struct BoxVector *    const boxVectorP,
 
 
 static void
-mediancut(tupletable2           const colorfreqtable,
+reportBoxVector(struct BoxVector const boxVector) {
+
+    unsigned int i;
+
+    pm_message("All colors of image, sorted into %u boxes:", boxVector.boxCt);
+
+    for (i = 0; i < boxVector.boxCt; ++i) {
+        const struct Box * const boxP = &boxVector.box[i];
+
+        unsigned int j;
+
+        pm_message("Box %u, %u colors starting with index %u (%u pixels):",
+                   i, boxP->colorCt, boxP->startIndex, boxP->sum);
+        if (boxP->colorCt > 1)
+            pm_message("Largest spread is %lu, in plane %u",
+                       boxP->spread, boxP->maxdim);
+
+        for (j = 0; j < boxP->colorCt; ++j) {
+            unsigned int colorIdx = boxP->startIndex + j;
+
+            assert(colorIdx < boxVector.colorFreqTable.size);
+
+            tuple const color =
+                boxVector.colorFreqTable.table[colorIdx]->tuple;
+
+            pm_message("(%lu, %lu, %lu)",
+                       color[PAM_RED_PLANE],
+                       color[PAM_GRN_PLANE],
+                       color[PAM_BLU_PLANE]);
+        }
+    }
+}
+
+
+
+static void
+mediancut(tupletable2           const colorFreqTable,
           unsigned int          const depth,
-          int                   const newcolorCt,
+          unsigned int          const newColorCt,
           enum MethodForLargest const methodForLargest,
           enum MethodForRep     const methodForRep,
           enum MethodForSplit   const methodForSplit,
+          bool                  const wantBvReport,
           tupletable2 *         const colormapP) {
 /*----------------------------------------------------------------------------
-   Compute a set of only 'newcolorCt' colors that best represent an
+   Compute a set of only 'newColorCt' colors that best represent an
    image whose pixels are summarized by the histogram
-   'colorfreqtable'.  Each tuple in that table has depth 'depth'.
-   colorfreqtable.table[i] tells the number of pixels in the subject image
-   have a particular color.
+   'colorFreqTable'.  Each tuple in that table has depth 'depth'.
+   colorFreqTable.table[i] tells the number of pixels in the subject image
+   that have a particular color.
 
-   As a side effect, sort 'colorfreqtable'.
+   As a side effect, sort 'colorFreqTable'.
 -----------------------------------------------------------------------------*/
     struct BoxVector boxVector;
     bool multicolorBoxesExist;
@@ -749,13 +870,13 @@ mediancut(tupletable2           const colorfreqtable,
            there is more splitting we can do.
         */
 
-    boxVector = newBoxVector(colorfreqtable, newcolorCt, depth,
+    boxVector = newBoxVector(colorFreqTable, newColorCt, depth,
                              methodForLargest);
 
-    multicolorBoxesExist = (colorfreqtable.size > 1);
+    multicolorBoxesExist = (colorFreqTable.size > 1);
 
     /* Split boxes until we have enough. */
-    while (boxVector.boxCt < newcolorCt && multicolorBoxesExist) {
+    while (boxVector.boxCt < newColorCt && multicolorBoxesExist) {
         unsigned int boxIdx;
 
         for (boxIdx = 0;
@@ -764,13 +885,18 @@ mediancut(tupletable2           const colorfreqtable,
             /* Find the first splittable box. */
 
         if (boxIdx >= boxVector.boxCt)
-            multicolorBoxesExist = FALSE;
+            multicolorBoxesExist = false;
         else
-            splitBox(&boxVector, boxIdx, colorfreqtable, depth,
-                     methodForLargest, methodForSplit);
+            splitBox(&boxVector, boxIdx, methodForLargest, methodForSplit);
+                /* Side effect: sorts the extent of 'colorfreqTable' that is
+                   in the box
+                */
     }
-    *colormapP = colormapFromBv(newcolorCt, boxVector, colorfreqtable,
-                                depth, methodForRep);
+
+    if (wantBvReport)
+        reportBoxVector(boxVector);
+
+    *colormapP = colormapFromBv(newColorCt, boxVector, methodForRep);
 
     destroyBoxVector(boxVector);
 }
@@ -834,7 +960,7 @@ static void
 computeHistogram(FILE *         const ifP,
                  int *          const formatP,
                  struct pam *   const freqPamP,
-                 tupletable2 *  const colorfreqtableP) {
+                 tupletable2 *  const colorFreqTableP) {
 /*----------------------------------------------------------------------------
   Make a histogram of the colors in the image stream in the file '*ifP'.
 
@@ -856,7 +982,7 @@ computeHistogram(FILE *         const ifP,
     tuplehash = pnm_createtuplehash();
     colorCount = 0;
 
-    eof = FALSE;
+    eof = false;
 
     for (imageSeq = 0; !eof; ++imageSeq) {
         struct pam inpam;
@@ -876,13 +1002,13 @@ computeHistogram(FILE *         const ifP,
 
         pnm_nextimage(ifP, &eof);
     }
-    colorfreqtableP->table =
+    colorFreqTableP->table =
         pnm_tuplehashtotable(&firstPam, tuplehash, colorCount);
-    colorfreqtableP->size = colorCount;
+    colorFreqTableP->size = colorCount;
 
     pnm_destroytuplehash(tuplehash);
 
-    pm_message("%u colors found", colorfreqtableP->size);
+    pm_message("%u colors found", colorFreqTableP->size);
 
     freqPamP->size   = sizeof(*freqPamP);
     freqPamP->len    = PAM_STRUCT_SIZE(tuple_type);
@@ -899,10 +1025,11 @@ computeHistogram(FILE *         const ifP,
 static void
 computeColorMapFromInput(FILE *                const ifP,
                          bool                  const allColors,
-                         int                   const reqColors,
+                         unsigned int          const reqColorCt,
                          enum MethodForLargest const methodForLargest,
                          enum MethodForRep     const methodForRep,
                          enum MethodForSplit   const methodForSplit,
+                         bool                  const wantBvReport,
                          int *                 const formatP,
                          struct pam *          const freqPamP,
                          tupletable2 *         const colormapP) {
@@ -911,7 +1038,7 @@ computeColorMapFromInput(FILE *                const ifP,
    image stream in file 'ifP'.  Figure it out using the median cut
    technique.
 
-   The colormap will have 'reqcolors' or fewer colors in it, unless
+   The colormap will have 'reqcolorCt' or fewer colors in it, unless
    'allcolors' is true, in which case it will have all the colors that
    are in the input.
 
@@ -925,23 +1052,26 @@ computeColorMapFromInput(FILE *                const ifP,
    *formatP and *freqPamP.  (This information is not really
    relevant to our colormap mission; just a fringe benefit).
 -----------------------------------------------------------------------------*/
-    tupletable2 colorfreqtable;
+    tupletable2 colorFreqTable;
+        /* Table of all colors in the image, with the number of pixels of
+           each color.
+        */
 
-    computeHistogram(ifP, formatP, freqPamP, &colorfreqtable);
+    computeHistogram(ifP, formatP, freqPamP, &colorFreqTable);
 
     if (allColors) {
-        *colormapP = colorfreqtable;
+        *colormapP = colorFreqTable;
     } else {
-        if (colorfreqtable.size <= reqColors) {
-            pm_message("Image already has few enough colors (<=%d).  "
-                       "Keeping same colors.", reqColors);
-            *colormapP = colorfreqtable;
+        if (colorFreqTable.size <= reqColorCt) {
+            pm_message("Image already has few enough colors (<=%u).  "
+                       "Keeping same colors.", reqColorCt);
+            *colormapP = colorFreqTable;
         } else {
-            pm_message("choosing %d colors...", reqColors);
-            mediancut(colorfreqtable, freqPamP->depth,
-                      reqColors, methodForLargest, methodForRep,
-                      methodForSplit, colormapP);
-            pnm_freetupletable2(freqPamP, colorfreqtable);
+            pm_message("choosing %u colors...", reqColorCt);
+            mediancut(colorFreqTable, freqPamP->depth,
+                      reqColorCt, methodForLargest, methodForRep,
+                      methodForSplit, wantBvReport, colormapP);
+            pnm_freetupletable2(freqPamP, colorFreqTable);
         }
     }
 }
@@ -967,16 +1097,16 @@ sortColormap(tupletable2  const colormap,
             unsigned int plane;
             bool iIsGreater, iIsLess;
 
-            iIsGreater = FALSE; iIsLess = FALSE;
+            iIsGreater = false; iIsLess = false;
             for (plane = 0;
                  plane < depth && !iIsGreater && !iIsLess;
                  ++plane) {
                 if (colormap.table[i]->tuple[plane] >
                     colormap.table[j]->tuple[plane])
-                    iIsGreater = TRUE;
+                    iIsGreater = true;
                 else if (colormap.table[i]->tuple[plane] <
                          colormap.table[j]->tuple[plane])
-                    iIsLess = TRUE;
+                    iIsLess = true;
             }
             if (iIsGreater) {
                 for (plane = 0; plane < depth; ++plane) {
@@ -1077,7 +1207,7 @@ colormapToImage(int                const format,
     outpamP->size             = sizeof(*outpamP);
     outpamP->len              = PAM_STRUCT_SIZE(tuple_type);
     outpamP->format           = format,
-    outpamP->plainformat      = FALSE;
+    outpamP->plainformat      = false;
     outpamP->depth            = colormapPamP->depth;
     outpamP->maxval           = colormapPamP->maxval;
     outpamP->bytes_per_sample = pnm_bytespersample(outpamP->maxval);
@@ -1112,10 +1242,11 @@ main(int argc, const char * argv[] ) {
     ifP = pm_openr(cmdline.inputFileNm);
 
     computeColorMapFromInput(ifP,
-                             cmdline.allcolors, cmdline.newcolors,
+                             cmdline.allcolors, cmdline.newColorCt,
                              cmdline.methodForLargest,
                              cmdline.methodForRep,
                              cmdline.methodForSplit,
+                             !!cmdline.debug,
                              &format, &colormapPam, &colormap);
 
     pm_close(ifP);
diff --git a/other/ppmdcfont.c b/other/ppmdcfont.c
index 130b6383..a8bcbcd8 100644
--- a/other/ppmdcfont.c
+++ b/other/ppmdcfont.c
@@ -30,10 +30,10 @@ generateGlyphCommand(struct ppmd_glyphCommand const glyphCommand) {
     case CMD_DRAWLINE: verb = "CMD_DRAWLINE"; break;
     case CMD_MOVEPEN:  verb = "CMD_MOVEPEN";  break;
     }
-    
+
     fprintf(stdout, "  {/* glyphCommand */ %s, %u, %u }\n",
             verb, glyphCommand.x, glyphCommand.y);
-    
+
 }
 
 
@@ -76,7 +76,7 @@ generateCommandTables(const struct ppmd_font * const fontP,
             pm_asprintf(&commandTableVariableName, "%s_cmd_%u",
                         glyphTableVariableName,
                         fontP->header.firstCodePoint + relativeCodePoint);
-            
+
             generateCommandTable(fontP->glyphTable[relativeCodePoint],
                                  commandTableVariableName);
 
@@ -133,7 +133,7 @@ generateGlyphTable(const struct ppmd_font * const fontP,
         pm_asprintf(&commandTableVariableName, "%s_cmd_%u",
                     variableName,
                     fontP->header.firstCodePoint + relativeCodePoint);
-        
+
         generateGlyph(fontP->glyphTable[relativeCodePoint],
                       commandTableVariableName);
 
@@ -154,7 +154,7 @@ generateFont(const struct ppmd_font * const fontP,
              const char *             const glyphTableVariableName) {
 
     fprintf(stdout, "struct ppmd_font const %s = {\n", fontVariableName);
-    
+
     generateHeader(fontP->header);
 
     fprintf(stdout, "  ,\n");
@@ -189,12 +189,12 @@ main(int argc, char **argv) {
     generateGlyphTable(fontP, glyphTableVariableName);
 
     fprintf(stdout, "\n");
-        
+
     generateFont(fontP, fontVariableName, glyphTableVariableName);
 
     pm_strfree(glyphTableVariableName);
 
     ppmd_free_font(fontP);
-    
+
     return 0;
 }
diff --git a/other/ppmddumpfont.c b/other/ppmddumpfont.c
index 3ab477ab..1c3474e8 100644
--- a/other/ppmddumpfont.c
+++ b/other/ppmddumpfont.c
@@ -19,7 +19,7 @@ untwos(unsigned char const arg) {
 
 static void
 dumpHeader(struct ppmd_fontHeader const fontHeader) {
-    
+
     pm_message("Font has %u characters", fontHeader.characterCount);
     pm_message("Font has code points %u through %u",
                fontHeader.firstCodePoint,
@@ -34,7 +34,7 @@ dumpGlyph(struct ppmd_glyph const glyph) {
     unsigned int commandNum;
 
     pm_message("  skip before: %u pixels; skip after: %u pixels; "
-               "%u commands:", 
+               "%u commands:",
                glyph.header.skipBefore,
                glyph.header.skipAfter,
                glyph.header.commandCount);
@@ -42,10 +42,10 @@ dumpGlyph(struct ppmd_glyph const glyph) {
     for (commandNum = 0;
          commandNum < glyph.header.commandCount;
          ++commandNum) {
-         
+
         struct ppmd_glyphCommand const glyphCommand =
             glyph.commandList[commandNum];
-        
+
         const char * verbDisp;
 
         switch (glyphCommand.verb) {
@@ -84,6 +84,6 @@ main(int argc, char **argv) {
     }
 
     ppmd_free_font(fontP);
-    
+
     return 0;
 }
diff --git a/other/ppmdmkfont.c b/other/ppmdmkfont.c
index 7cf1256f..f340e4f4 100644
--- a/other/ppmdmkfont.c
+++ b/other/ppmdmkfont.c
@@ -63,7 +63,7 @@ static unsigned char char37[] =
   250, 244, 252, 244, 254, 245, 1, 246, 4, 246, 7, 245, 9, 244,
   192, 0, 5, 2, 3, 3, 2, 5, 2, 7, 4, 9, 6, 9, 8, 8, 9, 6, 9, 4, 7,
   2, 5, 2 };
-  
+
 static unsigned char char38[] =
 { 34, 243, 13,
   10, 253, 10, 252, 9, 251, 8, 251, 7, 252, 6, 254, 4,
@@ -155,7 +155,7 @@ static unsigned char char54[] =
 static unsigned char char55[] =
 { 5, 246, 10,
   7, 244, 253, 9, 192, 0, 249, 244, 7, 244 };
-    
+
 static unsigned char char56[] =
 { 29, 246, 10,
   254, 244, 251, 245, 250, 247, 250, 249, 251, 251,
@@ -169,12 +169,12 @@ static unsigned char char57[] =
   254, 249, 251, 249, 250, 250, 247, 252, 245, 255, 244, 0, 244, 3,
   245, 5, 247, 6, 251, 6, 0, 5, 5, 3, 8, 0, 9, 254, 9, 251, 8, 250,
   6 };
-      
+
 static unsigned char char58[] =
 { 11, 251, 5,
   0, 251, 255, 252, 0, 253, 1, 252, 0, 251, 192, 0, 0,
   7, 255, 8, 0, 9, 1, 8, 0, 7 };
-                                
+
 static unsigned char char59[] =
 { 14, 251, 5,
   0, 251, 255, 252, 0, 253, 1, 252, 0, 251, 192, 0, 1,
@@ -208,7 +208,7 @@ static unsigned char char64[] =
   248, 247, 250, 246, 253, 246, 0, 247, 3, 248, 5, 250, 7, 252, 8,
   255, 9, 2, 9, 5, 8, 7, 7, 8, 6, 192, 0, 6, 249, 5, 1, 5, 3, 6, 4
 };
-  
+
 static unsigned char char65[] =
 { 8, 247, 9,
   0, 244, 248, 9, 192, 0, 0, 244, 8, 9, 192, 0, 251, 2,
@@ -266,7 +266,7 @@ static unsigned char char75[] =
   249, 244, 249, 9, 192, 0, 7, 244, 249, 2, 192, 0,
   254, 253, 7, 9 };
 
-static unsigned char char76[] = 
+static unsigned char char76[] =
 { 3, 246, 7,
   250, 244, 250, 9, 6, 9 };
 
@@ -274,12 +274,12 @@ static unsigned char char77[] =
 { 11, 244, 12,
   248, 244, 248, 9, 192, 0, 248, 244, 0, 9, 192, 0, 8,
   244, 0, 9, 192, 0, 8, 244, 8, 9 };
-                                               
+
 static unsigned char char78[] =
 { 8, 245, 11,
   249, 244, 249, 9, 192, 0, 249, 244, 7, 9, 192, 0, 7,
   244, 7, 9 };
-                         
+
 static unsigned char char79[] =
 { 21, 245, 11,
   254, 244, 252, 245, 250, 247, 249, 249, 248, 252,
@@ -297,7 +297,7 @@ static unsigned char char81[] =
   248, 1, 249, 4, 250, 6, 252, 8, 254, 9, 2, 9, 4, 8, 6, 6, 7, 4,
   8, 1, 8, 252, 7, 249, 6, 247, 4, 245, 2, 244, 254, 244, 192, 0,
   1, 5, 7, 11 };
-                           
+
 static unsigned char char82[] =
 { 16, 245, 10,
   249, 244, 249, 9, 192, 0, 249, 244, 2, 244, 5, 245,
@@ -372,13 +372,13 @@ static unsigned char char97[] =
   6, 251, 6, 9, 192, 0, 6, 254, 4, 252, 2, 251, 255,
   251, 253, 252, 251, 254, 250, 1, 250, 3, 251, 6, 253, 8, 255, 9,
   2, 9, 4, 8, 6, 6 };
-                                
+
 static unsigned char char98[] =
 { 17, 246, 9,
   250, 244, 250, 9, 192, 0, 250, 254, 252, 252, 254,
   251, 1, 251, 3, 252, 5, 254, 6, 1, 6, 3, 5, 6, 3, 8, 1, 9, 254,
   9, 252, 8, 250, 6 };
-                                 
+
 static unsigned char char99[] =
 { 14, 247, 9,
   6, 254, 4, 252, 2, 251, 255, 251, 253, 252, 251, 254,
@@ -389,7 +389,7 @@ static unsigned char char100[] =
   6, 244, 6, 9, 192, 0, 6, 254, 4, 252, 2, 251, 255,
   251, 253, 252, 251, 254, 250, 1, 250, 3, 251, 6, 253, 8, 255, 9,
   2, 9, 4, 8, 6, 6 };
-                                 
+
 static unsigned char char101[] =
 { 17, 247, 9,
   250, 1, 6, 1, 6, 255, 5, 253, 4, 252, 2, 251, 255,
@@ -429,7 +429,7 @@ static unsigned char char107[] =
 static unsigned char char108[] =
 { 2, 252, 4,
   0, 244, 0, 9 };
-                                        
+
 static unsigned char char109[] =
 { 18, 241, 15,
   245, 251, 245, 9, 192, 0, 245, 255, 248, 252, 250,
@@ -458,12 +458,12 @@ static unsigned char char113[] =
   6, 251, 6, 16, 192, 0, 6, 254, 4, 252, 2, 251, 255,
   251, 253, 252, 251, 254, 250, 1, 250, 3, 251, 6, 253, 8, 255, 9,
   2, 9, 4, 8, 6, 6 };
-                                 
+
 static unsigned char char114[] =
 { 8, 249, 6,
   253, 251, 253, 9, 192, 0, 253, 1, 254, 254, 0, 252,
   2, 251, 5, 251 };
-                               
+
 static unsigned char char115[] =
 { 17, 248, 9,
   6, 254, 5, 252, 2, 251, 255, 251, 252, 252, 251,
@@ -482,7 +482,7 @@ static unsigned char char117[] =
 static unsigned char char118[] =
 { 5, 248, 8,
   250, 251, 0, 9, 192, 0, 6, 251, 0, 9 };
-                                                                
+
 static unsigned char char119[] =
 { 11, 245, 11,
   248, 251, 252, 9, 192, 0, 0, 251, 252, 9, 192, 0,
@@ -496,7 +496,7 @@ static unsigned char char121[] =
 { 9, 248, 8,
   250, 251, 0, 9, 192, 0, 6, 251, 0, 9, 254, 13, 252,
   15, 250, 16, 249, 16 };
-                                     
+
 static unsigned char char122[] =
 { 8, 248, 9,
   6, 251, 251, 9, 192, 0, 251, 251, 6, 251, 192, 0,
@@ -554,7 +554,7 @@ writeGlyphCommand(FILE *                   const ofP,
     fputc(glyphCommand.verb, ofP);
     fputc(glyphCommand.x, ofP);
     fputc(glyphCommand.y, ofP);
-}    
+}
 
 
 
@@ -563,11 +563,11 @@ writeMovePen(FILE *                const ofP,
              const unsigned char * const glyphData) {
 
     struct ppmd_glyphCommand glyphCommand;
-            
+
     glyphCommand.verb = CMD_MOVEPEN;
     glyphCommand.x = glyphData[0];
     glyphCommand.y = glyphData[1];
-    
+
     writeGlyphCommand(ofP, glyphCommand);
 }
 
@@ -578,13 +578,13 @@ writeMovePenNoop(FILE *                const ofP,
                  const unsigned char * const glyphData) {
 
     struct ppmd_glyphCommand glyphCommand;
-            
+
     glyphCommand.verb = CMD_MOVEPEN;
     glyphCommand.x = glyphData[0];
     glyphCommand.y = glyphData[1];
-    
+
     writeGlyphCommand(ofP, glyphCommand);
-                
+
     glyphCommand.verb = CMD_NOOP;
     glyphCommand.x = 0;
     glyphCommand.y = 0;
@@ -603,10 +603,10 @@ writeDrawLine(FILE *                const ofP,
     glyphCommand.verb = CMD_DRAWLINE;
     glyphCommand.x = glyphData[0];
     glyphCommand.y = glyphData[1];
-    
+
     writeGlyphCommand(ofP, glyphCommand);
 }
-            
+
 
 
 static void
@@ -616,7 +616,7 @@ writeGlyphHeader(FILE *                  const ofP,
     fputc(glyphHeader.commandCount, ofP);
     fputc(glyphHeader.skipBefore, ofP);
     fputc(glyphHeader.skipAfter, ofP);
-}    
+}
 
 
 
@@ -638,7 +638,7 @@ writeBuiltinCharacter(FILE *       const ofP,
     commandNum = 0;
 
     while (commandNum < glyphHeader.commandCount) {
-            
+
         if (commandNum == 0) {
             writeMovePen(ofP, &glyphData[3 + commandNum * 2]);
             commandNum += 1;
@@ -700,6 +700,6 @@ main(int argc, char **argv) {
     ppm_init(&argc, argv);
 
     writeBuiltinFont(stdout);
-    
+
     return 0;
 }
diff --git a/other/ppmsvgalib.c b/other/ppmsvgalib.c
index c5700992..e106280b 100644
--- a/other/ppmsvgalib.c
+++ b/other/ppmsvgalib.c
@@ -6,7 +6,7 @@
    By Bryan Henderson, San Jose CA 2002.01.06.
 
    Contributed to the public domain.
-   
+
 ******************************************************************************/
 
 #define _XOPEN_SOURCE    /* Make sure modern signal stuff is in signal.h */
@@ -20,6 +20,7 @@
 #include "pm_c_util.h"
 #include "ppm.h"
 #include "shhopt.h"
+#include "mallocvar.h"
 
 struct cmdlineInfo {
     /* All the information the user supplied in the command line,
@@ -37,7 +38,7 @@ parseCommandLine (int argc, char ** argv,
                   struct cmdlineInfo *cmdlineP) {
 /*----------------------------------------------------------------------------
    parse program command line described in Unix standard form by argc
-   and argv.  Return the information in the options as *cmdlineP.  
+   and argv.  Return the information in the options as *cmdlineP.
 
    If command line is internally inconsistent (invalid options, etc.),
    issue error message to stderr and abort program.
@@ -45,15 +46,15 @@ parseCommandLine (int argc, char ** argv,
    Note that the strings we return are stored in the storage that
    was passed to us as the argv array.  We also trash *argv.
 -----------------------------------------------------------------------------*/
-    optEntry *option_def = malloc( 100*sizeof( optEntry ) );
-        /* Instructions to pm_optParseOptions3 on how to parse our options.
-         */
+    optEntry * option_def;
     optStruct3 opt;
 
     unsigned int option_def_index;
 
     unsigned int modeSpec;
 
+    MALLOCARRAY(option_def, 100);
+
     option_def_index = 0;   /* incremented by OPTENT3 */
     OPTENT3(0,   "mode",         OPT_UINT,
             &cmdlineP->mode,   &modeSpec, 0);
@@ -83,10 +84,10 @@ parseCommandLine (int argc, char ** argv,
 
 
 static void
-displayImage(FILE * const ifP, 
-             int    const cols, 
+displayImage(FILE * const ifP,
+             int    const cols,
              int    const rows,
-             pixval const maxval, 
+             pixval const maxval,
              int    const format,
              int    const originCol,
              int    const originRow) {
@@ -107,7 +108,7 @@ displayImage(FILE * const ifP,
 
     pixelrow = ppm_allocrow(cols);
 
-    /* Implementation note:  It might be faster to use 
+    /* Implementation note:  It might be faster to use
        vga_drawscansegment() instead of vga_drawpixel()
     */
 
@@ -143,13 +144,13 @@ sigintHandler(int const signal) {
 
 
 
-static void 
+static void
 waitforSigint(void) {
 
     struct sigaction oldsigaction;
     struct sigaction newsigaction;
     int rc;
-    
+
     newsigaction.sa_handler = &sigintHandler;
     sigemptyset(&newsigaction.sa_mask);
     newsigaction.sa_flags = 0;
@@ -166,19 +167,19 @@ waitforSigint(void) {
 
 
 static void
-display(FILE * const ifP, 
-        int    const cols, 
-        int    const rows, 
-        pixval const maxval, 
-        int    const format, 
-        int    const videoMode, 
+display(FILE * const ifP,
+        int    const cols,
+        int    const rows,
+        pixval const maxval,
+        int    const format,
+        int    const videoMode,
         bool   const verbose) {
 
     int xmax, ymax;
     vga_modeinfo *modeinfo;
 
     modeinfo = vga_getmodeinfo(videoMode);
-    
+
     if (verbose) {
         pm_message("Screen Width: %d  Height: %d  Colors: %d",
                    modeinfo->width,
@@ -193,18 +194,18 @@ display(FILE * const ifP,
     if (modeinfo->colors <= 256)
         pm_error("This video mode has %d or fewer colors, which means "
                  "it is colormapped (aka paletted, aka pseudocolor).  "
-                 "This program cannot drive colormapped modes.", 
+                 "This program cannot drive colormapped modes.",
                  modeinfo->colors);
 
     if (cols > modeinfo->width)
         pm_error("Image is too wide (%d columns) for screen (%d columns).  "
-                 "Use Pamcut to select part to display.", 
+                 "Use Pamcut to select part to display.",
                  cols, modeinfo->width);
     if (rows > modeinfo->height)
         pm_error("Image is too tall (%d rows) for screen (%d rows).  "
                  "Use Pamcut to select part to display.",
                  rows, modeinfo->height);
-    
+
     /* The program must not terminate after we set the video mode and before
        we reset it to text mode.  Note that vga_setmode() sets up handlers
        for signals such as SIGINT that attempt to restore modes and then exit
@@ -241,7 +242,7 @@ display(FILE * const ifP,
 
 
 
-int 
+int
 main(int argc, char *argv[]) {
 
     FILE * ifP;
@@ -261,7 +262,7 @@ main(int argc, char *argv[]) {
 
     {
         enum pm_check_code checkResult;
-        ppm_check(ifP, PM_CHECK_BASIC, format, cols, rows, maxval, 
+        ppm_check(ifP, PM_CHECK_BASIC, format, cols, rows, maxval,
                   &checkResult);
     }
 
@@ -274,7 +275,7 @@ main(int argc, char *argv[]) {
         pm_error("Svgalib unable to allocate a virtual console.");
 
     if (vga_hasmode(cmdline.mode))
-        display(ifP, cols, rows, maxval, format, 
+        display(ifP, cols, rows, maxval, format,
                 cmdline.mode, cmdline.verbose);
     else {
         pm_error("Svgalib video mode #%d not available.  Either the "
diff --git a/pm_config.in.h b/pm_config.in.h
index b30bccfe..7ba51454 100644
--- a/pm_config.in.h
+++ b/pm_config.in.h
@@ -167,6 +167,16 @@
 #define lstat stat
 #endif
 
+/* Mingw provides much of POSIX, but does not provide 'random' (and a
+   discussion on the Mingw mailing list in March 2021 shows that the
+   developers want it that way).  MSVCRT itself has a sufficient 'rand',
+   though, so we use that for 'random'.
+*/
+#if MSVCRT
+#define random rand
+#define srandom srand
+#endif
+
 /*  CONFIGURE: Netpbm uses __inline__ to declare functions that should
     be compiled as inline code.  GNU C recognizes the __inline__ keyword.
     If your compiler recognizes any other keyword for this, you can set
diff --git a/test/411toppm.test b/test/411toppm.test
index 98170c67..7a9e533c 100755
--- a/test/411toppm.test
+++ b/test/411toppm.test
@@ -1,4 +1,4 @@
-#! /bin/bash
+#! /bin/sh
 # This script tests: 411toppm
 # Also requires:
 
diff --git a/test/Execute-Tests b/test/Execute-Tests
index 3530d978..c86121dc 100755
--- a/test/Execute-Tests
+++ b/test/Execute-Tests
@@ -50,7 +50,7 @@ esac
 # invoke, the list of tests to run ('Test-Order'), and *.ok files that
 # indicate the expected results of tests.
 
-srcdir=$(dirname $0)
+export srcdir=$(dirname $0)
 
 # Set tmpdir, which is used in some of the test scripts.  By default
 # this is created by mktemp.  The user can override and specify tmpdir,
@@ -103,6 +103,10 @@ if [ ! -f ./testgrid.pbm ]
   then cp -v ${srcdir}/testgrid.pbm ./testgrid.pbm
 fi
 
+if [ ! -f ./maze.pbm ]
+  then cp -v ${srcdir}/maze.pbm ./maze.pbm
+fi
+
 if [ ! -f ./testimg.ppm ]
   then cp -v ${srcdir}/testimg.ppm  ./testimg.ppm 
 fi
@@ -178,13 +182,15 @@ elif [ $VALGRIND_TESTS = "on" ]
   mkdir $valdir
  
   vg_command_base="valgrind --trace-children=yes";
+  # You may want to add --track-origins=yes to the above.
 
   for i in awk basename cat cksum cmp comm cp cut date dirname \
-           egrep fgrep file grep gs head iconv mkdir mktemp perl rm \
-           sed seq sh sort tee tr uniq wc \
+           egrep fgrep file grep gs head iconv ls mkdir mktemp perl \
+           printf rm sed seq sh sort tail tee tr uniq wc \
            testrandom Available-Testprog
 
     # Tell valgrind not to probe execution of the above programs.
+    # You may add programs in Netpbm to the above to speed up tests.
 
     do vg_skip=$vg_skip"/*/"$i","; done;
 
@@ -238,13 +244,15 @@ if [ $VALGRIND_TESTS = "on" ]
 fi
 
 # Execute a single test and test its result.
-# But first check if the .ok file exists.  (Some .ok files are
-# dynamically created.)  Then see if target programs and requirements
-# are in place.  If either of these conditions are not met, do
-# not execute the test and report "Not Testable".
+# But first check if the .ok file exists.
+# (In past versions certain .ok files were dynamically created.)
+# Then see if target programs and requirements are in place.  If
+# either of these conditions are not met, do not execute the test and
+# report "Not Testable".
 
 if [ ! -s ${srcdir}/${tname%.test}.ok ]
 then
+  echo "${tname%.test}.ok does not exist"
   let result=4;
 else
   ${srcdir}/Available-Testprog \
@@ -296,7 +304,7 @@ fi
 # (Do not erase them if we are working from the source directory.)
 
 if [ ! $PWD -ef ${srcdir} ]
-    then rm ./testimg.ppm ./testgrid.pbm
+    then rm ./testimg.ppm ./testgrid.pbm ./maze.pbm
 fi
 
 
diff --git a/test/Makefile b/test/Makefile
index c640dfff..732113f3 100644
--- a/test/Makefile
+++ b/test/Makefile
@@ -8,27 +8,14 @@ include $(BUILDDIR)/config.mk
 
 MERGE_OBJECTS =
 
-PROGS = testrandom
-
-OKSTOGENERATE = $(patsubst %.rand-ok, %.ok, $(wildcard *.rand-ok))
-
-all: $(PROGS) $(OKSTOGENERATE)
-
-testrandom.o: testrandom.c
-	$(CC_FOR_BUILD) -c -o $@ $(CFLAGS_FOR_BUILD) $<
-
-testrandom: testrandom.o
-	$(LD_FOR_BUILD) -o $@ $(LDFLAGS_FOR_BUILD) $<
-
-RAND_VARIETY ?= $(shell ./testrandom -x)
-
-$(OKSTOGENERATE): %.ok: %.rand-ok testrandom
-	sed -n "/^$(RAND_VARIETY)|/s/^$(RAND_VARIETY)|//p" $< > $@
+PROGS =
 
 OMIT_TEST_RULE = 1
 include $(SRCDIR)/common.mk
 
+all:
+
 distclean clean: cleanlocal
 .PHONY: cleanlocal
 cleanlocal:
-	rm -f $(PROGS) $(patsubst %.rand-ok,%.ok,$(wildcard *.rand-ok))
+
diff --git a/test/Test-Order b/test/Test-Order
index aaf46985..6c21c759 100644
--- a/test/Test-Order
+++ b/test/Test-Order
@@ -2,6 +2,7 @@
 
 all-in-place.test
 legacy-names.test
+random-generator.test
 
 # Generator tests
 
@@ -15,6 +16,8 @@ pbmtext.test
 pbmtext-bdf.test
 pbmtext-iso88591.test
 pbmtext-utf8.test
+pbmtextps-dump.test
+pbmtextps.test
 pbmupc.test
 pgmramp.test
 pamgauss.test
@@ -24,13 +27,19 @@ pamcrater.test
 ppmpat.test
 ppmforge-parameters.test
 
+pamstereogram.test
+
 # Generators with random components
 
+pbmnoise1.test
+pbmnoise2.test
+pbmnoise-parameters.test
 pgmnoise.test
 pgmnoise-parameters.test
 ppmpat-random.test
 ppmforge.test
 ppmrough.test
+ppmrough-parameters.test
 
 # Analyzer tests
 
@@ -45,6 +54,7 @@ pbmminkowski.test
 pgmminkowski.test
 
 pnmcolormap.test
+pnmcolormap2.test
 
 # Basic (internal) converter tests
 
@@ -61,10 +71,14 @@ pnmtopnm-plain.test
 pamdepth.test
 
 pamditherbw.test
+pamditherbw-random.test
 pamhue.test
 
 pbmclean.test
 pamcut.test
+pamcat1.test
+pamcat2.test
+pamcat3.test
 pnmcat.test
 pamdice.test
 pamundice.test
@@ -75,9 +89,21 @@ pnminvert.test
 pamchannel.test
 ppmchange.test
 pambackground.test
-pnmpaste-pbm.test
+
+pnmpad-reportonly.test
+pnmpad-flip.test
+pnmpad-extend-enlarge.test
+pnmpad-pnmmargin.test
+pnmpad-format.test
+pnmpad-color.test
+
+pamrestack.test
+pamshuffle.test
+ppmshift.test
+ppmspread.test
 
 pbmpscale.test
+pamrecolor.test
 pnmremap1.test
 pnmremap2.test
 pnmquant.test
@@ -92,6 +118,8 @@ ppmdim.test
 pnmshear.test
 pgmbentley.test
 
+pnmindex.test
+
 pamfunc.test
 pamarith.test
 pamarith-compare-equal.test
@@ -116,19 +144,45 @@ pnmcrop-blank.test
 ppmmix.test
 pammixmulti-identity.test
 
+pamaddnoise-parameters.test
+
+pamstack.test
+
 # Symmetry test
 
 symmetry.test
 
+# Standard input tests
+
+stdin-pbm1.test
+stdin-pbm2.test
+stdin-pgm1.test
+stdin-pgm2.test
+stdin-ppm1.test
+stdin-ppm2.test
+stdin-ppm3.test
+stdin-pnm1.test
+stdin-pnm2.test
+stdin-pam1.test
+stdin-pam2.test
+stdin-pam3.test
+
+pbm-misc-converters.test
+
 # Format converter tests
 
 pamtopdbimg.test
+pamtosvg.test
 pbmtog3.test
+ppmtoapplevol.test
+ppmtomitsu.test
 411toppm.test
 eyuvtoppm.test
 rawtoppm.test
 
-pbm-misc-converters.test
+gif-transparent1.test
+
+pnmtojpeg-scans.test
 
 # Miscellaneous utility tests
 
@@ -136,6 +190,7 @@ ppmdfont.test
 pamfix.test
 pamvalidate.test
 pamexec.test
+pbmlife.test
 
 # Round-trip tests : editors
 
@@ -143,8 +198,10 @@ pnm-plain-roundtrip.test
 pnm-pam-roundtrip.test
 pnminvert-roundtrip.test
 pamflip-roundtrip.test
+pamflip-pbm-roundtrip.test
 pamdepth-roundtrip.test
 pad-crop-roundtrip.test
+pbm-ppm-roundtrip.test
 cut-paste-roundtrip.test
 rgb3-roundtrip.test
 ppmchange-roundtrip.test
@@ -157,6 +214,7 @@ pamhue-roundtrip.test
 
 # Round-trip tests: miscellaneous utilities
 
+pamendian-roundtrip.test
 pamexec-roundtrip.test
 channel-stack-roundtrip.test
 
@@ -198,6 +256,7 @@ pj-roundtrip.test
 ps-roundtrip.test
 ps-flate-roundtrip.test
 ps-alt-roundtrip.test
+qoi-roundtrip.test
 sgi-roundtrip.test
 sbig-roundtrip.test
 st4-roundtrip.test
@@ -214,6 +273,7 @@ xbm-roundtrip.test
 xpm-roundtrip.test
 xv-roundtrip.test
 xwd-roundtrip.test
+ybm-roundtrip.test
 
 # Round-trip tests : lossy converters
 
@@ -222,3 +282,4 @@ jpeg-roundtrip.test
 lps-roundtrip.test
 tiffcmyk-roundtrip.test
 yuv-roundtrip.test
+
diff --git a/test/all-in-place.ok b/test/all-in-place.ok
index 4d840102..31854728 100644
--- a/test/all-in-place.ok
+++ b/test/all-in-place.ok
@@ -41,6 +41,7 @@ pamarith: ok
 pambackground: ok
 pambayer: ok
 pambrighten: ok
+pamcat: ok
 pamchannel: ok
 pamcomp: ok
 pamcrater: ok
@@ -61,6 +62,7 @@ pamfunc: ok
 pamgauss: ok
 pamgetcolor: ok
 pamgradient: ok
+pamhomography: ok
 pamhue: ok
 pamlevels: ok
 pamlookup: ok
@@ -74,12 +76,14 @@ pamperspective: ok
 pampick: ok
 pampop9: ok
 pamrecolor: ok
+pamrestack: ok
 pamrubber: ok
 pamscale: ok
 pamseq: ok
 pamshadedrelief: ok
 pamsharpmap: ok
 pamsharpness: ok
+pamshuffle: ok
 pamsistoaglyph: ok
 pamslice: ok
 pamsplit: ok
@@ -106,6 +110,7 @@ pamtopdbimg: ok
 pamtopfm: ok
 pamtopng: ok
 pamtopnm: ok
+pamtoqoi: ok
 pamtosrf: ok
 pamtosvg: ok
 pamtotga: ok
@@ -124,6 +129,7 @@ pbmlife: ok
 pbmmake: ok
 pbmmask: ok
 pbmminkowski: ok
+pbmnoise: ok
 pbmpage: ok
 pbmpscale: ok
 pbmreduce: ok
@@ -197,7 +203,6 @@ pjtoppm: ok
 pktopbm: ok
 pngtopam: ok
 pnmalias: ok
-pnmcat: ok
 pnmcolormap: ok
 pnmconvol: ok
 pnmcrop: ok
@@ -298,6 +303,7 @@ ppmtv: ok
 ppmwheel: ok
 psidtopgm: ok
 pstopnm: ok
+qoitopam: ok
 qrttoppm: ok
 rasttopnm: ok
 rawtopgm: ok
diff --git a/test/all-in-place.test b/test/all-in-place.test
index 78a9346a..386d2872 100755
--- a/test/all-in-place.test
+++ b/test/all-in-place.test
@@ -83,6 +83,7 @@ ordinary_testprogs="\
   pambackground \
   pambayer \
   pambrighten \
+  pamcat \
   pamchannel \
   pamcomp \
   pamcrater \
@@ -103,6 +104,7 @@ ordinary_testprogs="\
   pamgauss \
   pamgetcolor \
   pamgradient \
+  pamhomography \
   pamhue \
   pamlevels \
   pamlookup \
@@ -116,12 +118,14 @@ ordinary_testprogs="\
   pampick \
   pampop9 \
   pamrecolor \
+  pamrestack \
   pamrubber \
   pamscale \
   pamseq \
   pamshadedrelief \
   pamsharpmap \
   pamsharpness \
+  pamshuffle \
   pamsistoaglyph \
   pamslice \
   pamsplit \
@@ -148,6 +152,7 @@ ordinary_testprogs="\
   pamtopfm \
   pamtopng \
   pamtopnm \
+  pamtoqoi \
   pamtosrf \
   pamtosvg \
   pamtotga \
@@ -166,6 +171,7 @@ ordinary_testprogs="\
   pbmmake \
   pbmmask \
   pbmminkowski \
+  pbmnoise \
   pbmpage \
   pbmpscale \
   pbmreduce \
@@ -239,7 +245,6 @@ ordinary_testprogs="\
   pktopbm \
   pngtopam \
   pnmalias \
-  pnmcat \
   pnmcolormap \
   pnmconvol \
   pnmcrop \
@@ -340,6 +345,7 @@ ordinary_testprogs="\
   ppmwheel \
   psidtopgm \
   pstopnm \
+  qoitopam \
   qrttoppm \
   rasttopnm \
   rawtopgm \
@@ -432,4 +438,4 @@ testExitStatus anytopnm 0 $?
 manweb --help > /dev/null
     testExitStatus manweb 0 $?
 
-# We do not test vidtoppm.
\ No newline at end of file
+# We do not test vidtoppm.
diff --git a/test/atari-roundtrip.test b/test/atari-roundtrip.test
index 413438a1..809cbdb2 100755
--- a/test/atari-roundtrip.test
+++ b/test/atari-roundtrip.test
@@ -1,4 +1,4 @@
-#! /bin/bash
+#! /bin/sh
 # This script tests: ppmtopi1 pi1toppm ppmtoneo neotoppm
 # Also requires: pgmramp pamscale pbmmake pamenlarge rgb3toppm pamdepth
 
diff --git a/test/atk-roundtrip.ok b/test/atk-roundtrip.ok
index 845be5fb..b9437e7d 100644
--- a/test/atk-roundtrip.ok
+++ b/test/atk-roundtrip.ok
@@ -1 +1,7 @@
-2425386270 41
+Test 1. Should print 281226646 481
+281226646 481
+Test 2. Should print 1824220442 125013 twice, then 2146497872 1000013 twice
+241513515 125013
+241513515 125013
+2146497872 1000013
+2146497872 1000013
diff --git a/test/atk-roundtrip.test b/test/atk-roundtrip.test
index 6db3df6d..97ac1be7 100755
--- a/test/atk-roundtrip.test
+++ b/test/atk-roundtrip.test
@@ -1,7 +1,23 @@
-#! /bin/bash
+#! /bin/sh
 # This script tests: pbmtoatk atktopbm
-# Also requires:
+# Also requires: pbmmake
 
+echo "Test 1. Should print 281226646 481"
+# cksum of maze.pbm
 
-# Should print 2425386270 41, cksum of testgrid.pbm
-pbmtoatk testgrid.pbm | atktopbm | cksum
+pbmtoatk maze.pbm | atktopbm | cksum
+
+tmpdir=${tmpdir:-/tmp}
+maxwidth_pbm=${tmpdir}/maxwidth.pbm
+maxheight_pbm=${tmpdir}/maxheight.pbm
+
+echo \
+ "Test 2. Should print 1824220442 125013 twice, then 2146497872 1000013 twice"
+
+pbmmake -g 1000000 1 | tee ${maxwidth_pbm} | cksum
+pbmtoatk ${maxwidth_pbm} | atktopbm | cksum
+
+pbmmake -b 1 1000000 | tee ${maxheight_pbm} | cksum
+pbmtoatk ${maxheight_pbm} | atktopbm | cksum
+
+rm ${maxwidth_pbm} ${maxheight_pbm}
diff --git a/test/avs-roundtrip.test b/test/avs-roundtrip.test
index 042ce91e..255226db 100755
--- a/test/avs-roundtrip.test
+++ b/test/avs-roundtrip.test
@@ -1,4 +1,4 @@
-#! /bin/bash
+#! /bin/sh
 # This script tests: pamtoavs avstopam
 # Also requires: pamtopnm
 
diff --git a/test/bmp-roundtrip.ok b/test/bmp-roundtrip.ok
index 4f4f8367..217a54aa 100644
--- a/test/bmp-roundtrip.ok
+++ b/test/bmp-roundtrip.ok
@@ -1,14 +1,14 @@
-PBM
-2425386270 41
-2425386270 41
-2425386270 41
-2425386270 41
-PPM
+Test 1 PBM.  Should print 281226646 481 four times
+281226646 481
+281226646 481
+281226646 481
+281226646 481
+Test 2 PPM.  Should print 1926073387 101484 four times
 1926073387 101484
 1926073387 101484
 1926073387 101484
 1926073387 101484
-PGM
+Test 3 PGM.  Should print 1571496937 33838 nine times
 1571496937 33838
 1571496937 33838
 1571496937 33838
diff --git a/test/bmp-roundtrip.test b/test/bmp-roundtrip.test
index c9ef363a..340eee66 100755
--- a/test/bmp-roundtrip.test
+++ b/test/bmp-roundtrip.test
@@ -1,30 +1,24 @@
-#! /bin/bash
+#! /bin/sh
 # This script tests: bmptopnm ppmtobmp
 # Also requires: pamchannel pamtopnm pamseq
 
 tmpdir=${tmpdir:-/tmp}
 
-# Test 1.  Should print 2425386270 41 four times
-
-echo PBM
+echo "Test 1 PBM.  Should print 281226646 481 four times"
 
 for mode in "" "-bpp=1" "-windows" "-os2"
   do
-  ppmtobmp ${mode} testgrid.pbm | bmptopnm | cksum
+  ppmtobmp ${mode} maze.pbm | bmptopnm | cksum
   done
 
-# Test 2.  Should print 1926073387 101484 four times
-
-echo PPM
+echo "Test 2 PPM.  Should print 1926073387 101484 four times"
 
 for mode in "" "-bpp=24" "-windows" "-os2"
   do
   ppmtobmp ${mode} testimg.ppm | bmptopnm | cksum
   done
 
-# Test 3.  Should print 1571496937 33838 nine times
-
-echo PGM
+echo "Test 3 PGM.  Should print 1571496937 33838 nine times"
 
 red_pgm=${tmpdir}/red.pgm
 mapfile_pgm=${tmpdir}/mapfile.pgm
diff --git a/test/channel-stack-roundtrip.test b/test/channel-stack-roundtrip.test
index dae64605..14ac0d2e 100755
--- a/test/channel-stack-roundtrip.test
+++ b/test/channel-stack-roundtrip.test
@@ -1,6 +1,6 @@
-#! /bin/bash
-# This script tests: pamchanel pamstack
-# Also requires: pamtopam pamstack pamtopnm
+#! /bin/sh
+# This script tests: pamchannel pamstack
+# Also requires: pamtopam pamtopnm
 
 tmpdir=${tmpdir:-/tmp}
 r_pam=${tmpdir}/testimg_r.pam
diff --git a/test/cis-roundtrip.ok b/test/cis-roundtrip.ok
index da90078b..8cac8da6 100644
--- a/test/cis-roundtrip.ok
+++ b/test/cis-roundtrip.ok
@@ -1,2 +1,8 @@
+Test 1. Should print 2631579683 1546 twice
 2631579683 1546
-2425386270 41
+2631579683 1546
+Test 2. Should print 281226646 481, cksum of maze.pbm four times
+281226646 481
+281226646 481
+281226646 481
+281226646 481
diff --git a/test/cis-roundtrip.test b/test/cis-roundtrip.test
index 62fcc3b9..3316868c 100755
--- a/test/cis-roundtrip.test
+++ b/test/cis-roundtrip.test
@@ -1,14 +1,23 @@
-#! /bin/bash
+#! /bin/sh
 # This script tests: pbmtocis cistopbm
-# Also requires: pbmmake pamcut
+# Also requires: pbmmake pamcut pamfile pnmcrop
 
+tmpdir=${tmpdir:-/tmp}
+test_pbm=${tmpdir}/test.pbm
 
 # Output images produced by pbmtocis are of fixed size,
 # either 128x96 or 256x192.
 # Smaller input images are padded, larger ones are cropped.
 
-# Test 1. Should print 2631579683 1546
-pbmmake -g 128 96 | pbmtocis | cistopbm | cksum
+echo "Test 1. Should print 2631579683 1546 twice"
+pbmmake -g 128 96 | tee ${test_pbm} | cksum
+pbmtocis ${test_pbm} | cistopbm | cksum
 
-# Test 2. Should print 2425386270 41
-pbmtocis testgrid.pbm | cistopbm | pamcut 0 0 14 16 | cksum
+rm ${test_pbm}
+
+echo "Test 2. Should print 281226646 481, cksum of maze.pbm four times"
+size=$(pamfile -size maze.pbm | awk '{print "-width="$1,"-height="$2}')
+pbmtocis    maze.pbm | cistopbm    | pamcut -left=0 -top=0 ${size} | cksum
+pbmtocis -i maze.pbm | cistopbm -i | pamcut -left=0 -top=0 ${size} | cksum
+pbmtocis    maze.pbm | cistopbm    | pnmcrop -black -right -bottom | cksum
+pbmtocis -w maze.pbm | cistopbm    | pnmcrop -white -right -bottom | cksum
diff --git a/test/cmuw-roundtrip.ok b/test/cmuw-roundtrip.ok
index 845be5fb..4ec1a381 100644
--- a/test/cmuw-roundtrip.ok
+++ b/test/cmuw-roundtrip.ok
@@ -1 +1,2 @@
-2425386270 41
+Should print 281226646 481, cksum of maze.pbm
+281226646 481
diff --git a/test/cmuw-roundtrip.test b/test/cmuw-roundtrip.test
index e52adb70..8664a1e6 100755
--- a/test/cmuw-roundtrip.test
+++ b/test/cmuw-roundtrip.test
@@ -1,7 +1,6 @@
-#! /bin/bash
+#! /bin/sh
 # This script tests: pbmtocmuwm cmuwmtopbm
 # Also requires:
 
-
-# Should print 2425386270 41, cksum of testgrid.pbm
-pbmtocmuwm testgrid.pbm | cmuwmtopbm | cksum
+echo "Should print 281226646 481, cksum of maze.pbm"
+pbmtocmuwm maze.pbm | cmuwmtopbm | cksum
diff --git a/test/cut-cat-roundtrip.ok b/test/cut-cat-roundtrip.ok
index bc9b8cb4..edf1de67 100644
--- a/test/cut-cat-roundtrip.ok
+++ b/test/cut-cat-roundtrip.ok
@@ -1,92 +1,54 @@
-Test 1.
-1926073387 101484
-1926073387 101484
-1926073387 101484
-1926073387 101484
-1926073387 101484
-1926073387 101484
-Test 2.
-3891261972 202953
-3891261972 202953
-3891261972 202953
-3891261972 202953
-3891261972 202953
-3891261972 202953
-Test 3.
-1926073387 101484
-1926073387 101484
-1926073387 101484
-1926073387 101484
-1926073387 101484
-Test 4.
-26789469 202953
-26789469 202953
-26789469 202953
-26789469 202953
-26789469 202953
-Test 5.
-2425386270 41
-2425386270 41
-2425386270 41
-2425386270 41
-2425386270 41
-2425386270 41
-2425386270 41
-2425386270 41
-2425386270 41
-2425386270 41
-2425386270 41
-2425386270 41
-2425386270 41
-2425386270 41
-Test 6.
-1887700557 73
-1887700557 73
-1887700557 73
-1887700557 73
-1887700557 73
-1887700557 73
-1887700557 73
-1887700557 73
-1887700557 73
-1887700557 73
-1887700557 73
-1887700557 73
-1887700557 73
-1887700557 73
-1887700557 73
-Test 7.
-2425386270 41
-2425386270 41
-2425386270 41
-2425386270 41
-2425386270 41
-2425386270 41
-2425386270 41
-2425386270 41
-2425386270 41
-2425386270 41
-2425386270 41
-2425386270 41
-2425386270 41
-2425386270 41
-2425386270 41
-2425386270 41
-Test 8.
-3221289196 73
-3221289196 73
-3221289196 73
-3221289196 73
-3221289196 73
-3221289196 73
-3221289196 73
-3221289196 73
-3221289196 73
-3221289196 73
-3221289196 73
-3221289196 73
-3221289196 73
-3221289196 73
-3221289196 73
-3221289196 73
-3221289196 73
+Test 1.  Should print 1926073387 101484 six times
+1926073387 101484
+1926073387 101484
+1926073387 101484
+1926073387 101484
+1926073387 101484
+1926073387 101484
+Test 2.  Should print 3891261972 202953 1926073387 101484 six times
+3891261972 202953 1926073387 101484
+3891261972 202953 1926073387 101484
+3891261972 202953 1926073387 101484
+3891261972 202953 1926073387 101484
+3891261972 202953 1926073387 101484
+3891261972 202953 1926073387 101484
+Test 3.  Should print 1926073387 101484 five times
+1926073387 101484
+1926073387 101484
+1926073387 101484
+1926073387 101484
+1926073387 101484
+Test 4.  Should print 26789469 202953 1926073387 101484 five times
+26789469 202953 1926073387 101484
+26789469 202953 1926073387 101484
+26789469 202953 1926073387 101484
+26789469 202953 1926073387 101484
+26789469 202953 1926073387 101484
+Test 5.  Should print 281226646 481 six times
+281226646 481
+281226646 481
+281226646 481
+281226646 481
+281226646 481
+281226646 481
+Test 6.  Should print 1748767123 895 281226646 481 six times
+1748767123 895 281226646 481
+1748767123 895 281226646 481
+1748767123 895 281226646 481
+1748767123 895 281226646 481
+1748767123 895 281226646 481
+1748767123 895 281226646 481
+Test 7.  Should print 281226646 481 seven times
+281226646 481
+281226646 481
+281226646 481
+281226646 481
+281226646 481
+281226646 481
+281226646 481
+Test 8.  Should print 1346655680 954 281226646 481 five times
+1346655680 954 281226646 481
+1346655680 954 281226646 481
+1346655680 954 281226646 481
+1346655680 954 281226646 481
+1346655680 954 281226646 481
diff --git a/test/cut-cat-roundtrip.test b/test/cut-cat-roundtrip.test
index 95ee5279..274cb865 100755
--- a/test/cut-cat-roundtrip.test
+++ b/test/cut-cat-roundtrip.test
@@ -1,128 +1,147 @@
-#! /bin/bash
+#! /bin/sh
 # This script tests: pamcut
-# Also requires: pnmcat pnmpad
+# Also requires: pamfile pamcat pnmpad pnmcrop
 
 tmpdir=${tmpdir:-/tmp}
-quant_ppm=${tmpdir}/quant.ppm
 
-right_pbm=${tmpdir}/right.pbm
-left_pbm=${tmpdir}/left.pbm
-right_ppm=${tmpdir}/right.ppm
 left_ppm=${tmpdir}/left.ppm
-bottom_pbm=${tmpdir}/bottom.pbm
-top_pbm=${tmpdir}/top.pbm
-bottom_ppm=${tmpdir}/bottom.ppm
+right_ppm=${tmpdir}/right.ppm
 top_ppm=${tmpdir}/top.ppm
+bottom_ppm=${tmpdir}/bottom.ppm
+padded_ppm=${tmpdir}/padded.ppm
+
+echo "Test 1.  Should print 1926073387 101484 six times"
 
+testimg_ppm_sum=`cksum < testimg.ppm`
+echo ${testimg_ppm_sum}
 
-# Test 1.  Should print 1926073387 101484 six times
-echo Test 1.
+imgsize=$(pamfile -size testimg.ppm)
+width=$(echo ${imgsize} | cut -d " " -f 1)
+height=$(echo ${imgsize} | cut -d " " -f 2)
 
-cat testimg.ppm | cksum
 for i in 0 1 128 224 225
   do
   pamcut -left=$((i+1)) testimg.ppm > ${right_ppm}
   pamcut -right=$i      testimg.ppm > ${left_ppm}
-  pnmcat -lr ${left_ppm} ${right_ppm} | \
-    pamcut -left=0 -width=227| cksum
+  pamcat -lr ${left_ppm} ${right_ppm} | \
+    pamcut -left=0 -width=${width} | cksum
   rm ${left_ppm} ${right_ppm}
   done
 
+echo "Test 2.  Should print 3891261972 202953 1926073387 101484 six times"
+# Padding added to right.
 
-# Test 2.  Should print 3891261972 202953 six times
-# Not roundtrip.  Padding added to right.
-echo Test 2.
+pnmpad -right=${width} -black testimg.ppm | cksum | tr '\n' ' '
+echo ${testimg_ppm_sum}
 
-pnmpad -right=227 -black testimg.ppm | cksum
-for i in  0 1 128 224 225
+for border in 0 1 128 224 225
   do
-  pamcut -left=$((i+1)) -width=227 -pad testimg.ppm > ${right_ppm}
-  pamcut -right=$i      -width=227 -pad testimg.ppm > ${left_ppm}
-  pnmcat -lr ${left_ppm} ${right_ppm} ${left_ppm} | \
-    pamcut -left=$((227-i-1))  -width=$((227*2)) | cksum
-  rm ${left_ppm} ${right_ppm}
+  pamcut -left=$((${border}+1)) -width=${width} -pad testimg.ppm > ${right_ppm}
+  pamcut -right=${border} -width=${width} -pad testimg.ppm > ${left_ppm}
+  pamcat -lr ${left_ppm} ${right_ppm} ${left_ppm} | \
+    pamcut -left=$((${width}-${border}-1))  -width=$((${width}*2)) | \
+    tee ${padded_ppm} | cksum | tr '\n' ' '
+  pnmcrop -black -right ${padded_ppm} | cksum
+  rm ${left_ppm} ${right_ppm} ${padded_ppm}
   done
 
 
-# Test 3.  Should print 1926073387 101484 five times
-echo Test 3.
+echo "Test 3.  Should print 1926073387 101484 five times"
 
-cat testimg.ppm | cksum
-for i in 0 1 70 147
+echo ${testimg_ppm_sum}
+for border in 0 1 70 147
   do
-  pamcut -top=$((i+1)) testimg.ppm > ${bottom_ppm}
-  pamcut -bottom=$i    testimg.ppm > ${top_ppm}
-  pnmcat -tb ${top_ppm} ${bottom_ppm} | \
-    pamcut -top=0 -height=149 | cksum
+  pamcut -top=$((${border}+1)) testimg.ppm > ${bottom_ppm}
+  pamcut -bottom=${border}     testimg.ppm > ${top_ppm}
+  pamcat -tb ${top_ppm} ${bottom_ppm} | \
+    pamcut -top=0 -height=${height} | cksum
   rm ${top_ppm} ${bottom_ppm}
   done
 
-# Test 4.  Should print 26789469 202953 five times
-# Not roundtrip.  Padding added to bottom.
-echo Test 4.
+echo "Test 4.  Should print 26789469 202953 1926073387 101484 five times"
+# Padding added to bottom.
 
-pnmpad -bottom=149 -black testimg.ppm | cksum
-for i in 0 1 70 147
+pnmpad -bottom=${height} -black testimg.ppm | cksum | tr '\n' ' '
+echo ${testimg_ppm_sum}
+for border in 0 1 70 147
   do
-  pamcut -top=$((i+1)) -height=149 -pad testimg.ppm > ${bottom_ppm}
-  pamcut -bottom=$i    -height=149 -pad testimg.ppm > ${top_ppm}
-  pnmcat -tb ${top_ppm} ${bottom_ppm} ${top_ppm} | \
-    pamcut -top=$((149-i-1))  -height=$((149*2)) | cksum
-  rm ${top_ppm} ${bottom_ppm}
+  pamcut -top=$((${border}+1)) -height=${height} -pad testimg.ppm \
+    > ${bottom_ppm}
+  pamcut -bottom=${border}     -height=${height} -pad testimg.ppm > ${top_ppm}
+  pamcat -tb ${top_ppm} ${bottom_ppm} ${top_ppm} | \
+    pamcut -top=$((${height}-${border}-1))  -height=$((${height}*2)) | \
+    tee ${padded_ppm} | cksum | tr '\n' ' 'cksum
+  pnmcrop -black -bottom ${padded_ppm} | cksum
+  rm ${top_ppm} ${bottom_ppm} ${padded_ppm}
   done
 
-# Test 5.  Should print 2425386270 41 fourteen times
-echo Test 5.
+left_pbm=${tmpdir}/left.pbm
+right_pbm=${tmpdir}/right.pbm
+top_pbm=${tmpdir}/top.pbm
+bottom_pbm=${tmpdir}/bottom.pbm
+padded_pbm=${tmpdir}/padded.pbm
+
+echo "Test 5.  Should print 281226646 481 six times"
+
+maze_pbm_sum=`cksum < maze.pbm`
+echo ${maze_pbm_sum}
+
+imgsize=$(pamfile -size maze.pbm)
+width=$(echo ${imgsize} | cut -d " " -f 1)
+height=$(echo ${imgsize} | cut -d " " -f 2)
 
-cat testgrid.pbm | cksum
-for i in `seq 0 12`
+for i in 0 1 10 30 50
   do
-  pamcut -left=$((i+1)) testgrid.pbm > ${right_pbm}
-  pamcut -right=$i      testgrid.pbm > ${left_pbm}
-  pnmcat -lr ${left_pbm} ${right_pbm} | \
-    pamcut -left=0 -width=14 | cksum
-  rm ${left_pbm} ${right_pbm}
+  pamcut -left=$((i+1)) maze.pbm > ${right_ppm}
+  pamcut -right=$i      maze.pbm > ${left_ppm}
+  pamcat -lr ${left_ppm} ${right_ppm} | \
+    pamcut -left=0 -width=${width} | cksum
+  rm ${left_ppm} ${right_ppm}
   done
 
 
-# Test 6.  Should print 1887700557 73 fifteen times
-# Not roundtrip.  Padding added to right.
-echo Test 6.
+echo "Test 6.  Should print 1748767123 895 281226646 481 six times"
+# Padding added to right.
+
+pnmpad -right=${width} -black maze.pbm | cksum | tr '\n' ' '
+echo ${maze_pbm_sum}
 
-pnmpad -right=14 -black testgrid.pbm | cksum
-for i in `seq 0 13`
+for border in 0 1 10 30 50
   do
-  pamcut -left=$((i+1)) -width=14 -pad testgrid.pbm > ${right_pbm}
-  pamcut -right=$i      -width=14 -pad testgrid.pbm > ${left_pbm}
-  pnmcat -lr ${left_pbm} ${right_pbm} ${left_pbm} | \
-    pamcut -left=$((14-i-1)) -width=28 | cksum
-  rm ${left_pbm} ${right_pbm}
+  pamcut -left=$((${border}+1)) -width=${width} -pad maze.pbm > ${right_ppm}
+  pamcut -right=${border} -width=${width} -pad maze.pbm > ${left_ppm}
+  pamcat -lr ${left_ppm} ${right_ppm} ${left_ppm} | \
+    pamcut -left=$((${width}-${border}-1))  -width=$((${width}*2)) | \
+    tee ${padded_ppm} | cksum | tr '\n' ' '
+  pnmcrop -black -right ${padded_ppm} | cksum
+  rm ${left_ppm} ${right_ppm} ${padded_ppm}
   done
 
-# Test 7.  Should print 2425386270 41 sixteen times
-echo Test 7.
 
-cat testgrid.pbm | cksum
-for i in `seq 0 14`
+echo "Test 7.  Should print 281226646 481 seven times"
+
+echo ${maze_pbm_sum}
+for border in 0 1 12 21 31 44
   do
-  pamcut -top=$((i+1)) testgrid.pbm > ${bottom_pbm}
-  pamcut -bottom=$i    testgrid.pbm > ${top_pbm}
-  pnmcat -tb ${top_pbm} ${bottom_pbm} | \
-    pamcut -top=0 -height=16 | cksum
-  rm ${top_pbm} ${bottom_pbm}
+  pamcut -top=$((${border}+1)) maze.pbm > ${bottom_ppm}
+  pamcut -bottom=${border}     maze.pbm > ${top_ppm}
+  pamcat -tb ${top_ppm} ${bottom_ppm} | \
+    pamcut -top=0 -height=${height} | cksum
+  rm ${top_ppm} ${bottom_ppm}
   done
 
-# Test 8.  Should print 3221289196 73 seventeen times
-# Not roundtrip.  Padding added to bottom.
-echo Test 8.
+echo "Test 8.  Should print 1346655680 954 281226646 481 five times"
+# Padding added to bottom.
 
-pnmpad -bottom=16 -black testgrid.pbm | cksum
-for i in `seq 0 15`
+pnmpad -bottom=${height} -black maze.pbm | cksum | tr '\n' ' '
+echo ${maze_pbm_sum}
+for border in 0 1 10 50
   do
-  pamcut -top=$((i+1)) -height=16 -pad testgrid.pbm > ${bottom_pbm}
-  pamcut -bottom=$i    -height=16 -pad testgrid.pbm > ${top_pbm}
-  pnmcat -tb ${top_pbm} ${bottom_pbm} ${top_pbm} | \
-    pamcut -top=$((16-i-1)) -height=32 | cksum
-  rm ${top_pbm} ${bottom_pbm}
+  pamcut -top=$((${border}+1)) -height=${height} -pad maze.pbm > ${bottom_ppm}
+  pamcut -bottom=${border}     -height=${height} -pad maze.pbm > ${top_ppm}
+  pamcat -tb ${top_ppm} ${bottom_ppm} ${top_ppm} | \
+    pamcut -top=$((${height}-${border}-1))  -height=$((${height}*2)) | \
+    tee ${padded_ppm} | cksum | tr '\n' ' 'cksum
+  pnmcrop -black -bottom ${padded_ppm} | cksum
+  rm ${top_ppm} ${bottom_ppm} ${padded_ppm}
   done
-
diff --git a/test/cut-paste-roundtrip.test b/test/cut-paste-roundtrip.test
index 1bb3a7c2..bec8baf5 100755
--- a/test/cut-paste-roundtrip.test
+++ b/test/cut-paste-roundtrip.test
@@ -1,7 +1,8 @@
-#! /bin/bash
+#! /bin/sh
 # This script tests: pamcut pnmpaste
 # Also requires: pbmmake pnmpad
 
+tmpdir=${tmpdir:-/tmp}
 base_ppm=${tmpdir}/base.ppm
 
 # Test 1. Should produce 2999529086 101484
diff --git a/test/enlarge-reduce-roundtrip.test b/test/enlarge-reduce-roundtrip.test
index 54b52c60..5d223cf1 100755
--- a/test/enlarge-reduce-roundtrip.test
+++ b/test/enlarge-reduce-roundtrip.test
@@ -1,4 +1,4 @@
-#! /bin/bash
+#! /bin/sh
 # This script tests: pamenlarge pbmpscale pbmreduce
 # Also requires: pbmtext
 
diff --git a/test/eyuvtoppm.test b/test/eyuvtoppm.test
index b28b4539..6bbc2e7e 100755
--- a/test/eyuvtoppm.test
+++ b/test/eyuvtoppm.test
@@ -1,4 +1,4 @@
-#! /bin/bash
+#! /bin/sh
 # This script tests: eyuvtoppm
 # Also requires:
 
diff --git a/test/facesaver-roundtrip.test b/test/facesaver-roundtrip.test
index f4b8f069..75fcf662 100755
--- a/test/facesaver-roundtrip.test
+++ b/test/facesaver-roundtrip.test
@@ -1,4 +1,4 @@
-#! /bin/bash
+#! /bin/sh
 # This script tests: pgmtofs fstopgm
 # Also requires: pamchannel pamtopnm
 
diff --git a/test/fiasco-roundtrip.test b/test/fiasco-roundtrip.test
index 8325a37d..8d5fdaa6 100755
--- a/test/fiasco-roundtrip.test
+++ b/test/fiasco-roundtrip.test
@@ -1,4 +1,4 @@
-#! /bin/bash
+#! /bin/sh
 # This script tests: pnmtofiasco fiascotopnm
 # Also requires: pnmpad pnmpsnr
 
diff --git a/test/fits-roundtrip.test b/test/fits-roundtrip.test
index e793df9a..030a519e 100755
--- a/test/fits-roundtrip.test
+++ b/test/fits-roundtrip.test
@@ -1,4 +1,4 @@
-#! /bin/bash
+#! /bin/sh
 # This script tests: pamtofits fitstopnm
 # Also requires:
 
diff --git a/test/g3-roundtrip.ok b/test/g3-roundtrip.ok
index 603c9457..7140cc8b 100644
--- a/test/g3-roundtrip.ok
+++ b/test/g3-roundtrip.ok
@@ -1,6 +1,9 @@
+Test 1.  Should print 0 0 0 : 0 or 0 0 0 0 : 0 total three times
 0 0 0 : 0
 0 0 0 : 0
 0 0 0 0 : 0
+Test 2.  Should print 0 0 0 : 0 or 0 0 0 0 : 0 total seven times
+then 1777627284 265, 2985378006 3135, 3651878552 3135
 0 0 0 : 0
 0 0 0 : 0
 0 0 0 0 : 0
@@ -11,3 +14,9 @@
 1777627284 265
 2985378006 3135
 3651878552 3135
+Test 3.  Should print 0 0 0 : 0 twice
+then 356688157 17399694 twice
+0 0 0 : 0
+0 0 0 : 0
+356688157 17399694
+356688157 17399694
diff --git a/test/g3-roundtrip.test b/test/g3-roundtrip.test
index d18e4466..2736c09a 100755
--- a/test/g3-roundtrip.test
+++ b/test/g3-roundtrip.test
@@ -1,23 +1,33 @@
 #! /bin/bash
 # This script tests: g3topbm pbmtog3
-# Also requires: pnmcrop pbmmake
+# Also requires: pamfile pnmcrop pbmmake pbmpage pnmpad pamenlarge
 
 tmpdir=${tmpdir:-/tmp}
 complete256_pbm=${tmpdir}/complete256.pbm
 widew_pbm=${tmpdir}/widew.pbm
 wideb_pbm=${tmpdir}/wideb.pbm
+page_pbm=${tmpdir}/page.pbm
+pagemax_pbm=${tmpdir}/pagemax.pbm
 
-pbmtog3 -nofixedwidth testgrid.pbm | \
-g3topbm -width=14 | cmp -s - testgrid.pbm
+echo "Test 1.  Should print 0 0 0 : 0 or 0 0 0 0 : 0 total three times"
+
+width=$(pamfile -size maze.pbm | cut -d " " -f 1) 
+
+pbmtog3 -nofixedwidth maze.pbm | \
+g3topbm -width=${width} | cmp -s - maze.pbm
 echo ${PIPESTATUS[@]} ":" $?
 
-pbmtog3 -nofixedwidth -reversebits testgrid.pbm | \
-g3topbm -width=14 -reversebits | cmp -s - testgrid.pbm
+pbmtog3 -nofixedwidth -reversebits maze.pbm | \
+g3topbm -width=${width} -reversebits | cmp -s - maze.pbm
 echo ${PIPESTATUS[@]} ":" $?
 
-pbmtog3 testgrid.pbm | \
+pbmtog3 maze.pbm | \
 g3topbm  | pnmcrop -white -right -bottom | \
- cmp -s - testgrid.pbm ; echo ${PIPESTATUS[@]} ":" $?
+ cmp -s - maze.pbm ; echo ${PIPESTATUS[@]} ":" $?
+
+
+echo "Test 2.  Should print 0 0 0 : 0 or 0 0 0 0 : 0 total seven times"
+echo "then 1777627284 265, 2985378006 3135, 3651878552 3135"
 
 # works with gawk and mawk
 # produce all possible 8-bit patterns
@@ -27,7 +37,7 @@ LC_ALL=C awk 'BEGIN { print "P4";         # header
                       for (i=0;i<256;++i) # raster
                            printf("%c",i) }' > ${complete256_pbm}
 
-pbmtog3 -nofixedwidth  ${complete256_pbm} |  g3topbm -width=8 | \
+pbmtog3 -nofixedwidth  ${complete256_pbm} | g3topbm -width=8 | \
  cmp -s - ${complete256_pbm} ; echo ${PIPESTATUS[@]} ":" $?
 
 pbmtog3 -reverse -nofixedwidth ${complete256_pbm} | \
@@ -59,3 +69,20 @@ cat ${wideb_pbm} | cksum
 cat ${widew_pbm} | cksum
 
 rm ${complete256_pbm} ${wideb_pbm} ${widew_pbm}
+
+
+echo "Test 3.  Should print 0 0 0 : 0 twice"
+echo "then 356688157 17399694 twice"
+
+pbmpage 3 -a4 | pamenlarge 2 > ${page_pbm}
+pbmtog3 -nofixedwidth  ${page_pbm} | g3topbm | \
+ cmp -s - ${page_pbm} ; echo ${PIPESTATUS[@]} ":" $?
+
+pnmpad -width=1000 -height=1400 ${page_pbm} > ${pagemax_pbm}
+pbmtog3 -nofixedwidth  ${pagemax_pbm} | g3topbm  | \
+ cmp -s - ${pagemax_pbm} ; echo ${PIPESTATUS[@]} ":" $?
+
+cat ${page_pbm} | cksum
+cat ${pagemax_pbm} | cksum
+
+rm ${page_pbm} ${pagemax_pbm} 
\ No newline at end of file
diff --git a/test/gem-roundtrip.ok b/test/gem-roundtrip.ok
index 845be5fb..5168378d 100644
--- a/test/gem-roundtrip.ok
+++ b/test/gem-roundtrip.ok
@@ -1 +1 @@
-2425386270 41
+281226646 481
diff --git a/test/gem-roundtrip.test b/test/gem-roundtrip.test
index 0fce59db..d97a5cb9 100755
--- a/test/gem-roundtrip.test
+++ b/test/gem-roundtrip.test
@@ -1,7 +1,7 @@
-#! /bin/bash
+#! /bin/sh
 # This script tests: pbmtogem gemtopnm
 # Also requires:
 
 
-# Should print 2425386270 41, cksum of testgrid.pbm
-pbmtogem testgrid.pbm | gemtopnm | cksum
+# Should print 281226646 481, cksum of maze.pbm
+pbmtogem maze.pbm | gemtopnm | cksum
diff --git a/test/gif-roundtrip.ok b/test/gif-roundtrip.ok
index 607ebd5c..27d1bb47 100644
--- a/test/gif-roundtrip.ok
+++ b/test/gif-roundtrip.ok
@@ -1,18 +1,23 @@
+Test 1. Should print 1926073387 101484
 1926073387 101484
+Test 2. Should produce 1571496937 33838 six times
 1571496937 33838
 1571496937 33838
 1571496937 33838
 1571496937 33838
 1571496937 33838
-2425386270 41
-2425386270 41
-2425386270 41
-2425386270 41
-2425386270 41
+1571496937 33838
+Test 3. Should produce 281226646 481 six times
+281226646 481
+281226646 481
+281226646 481
+281226646 481
+281226646 481
+281226646 481
+Test 4. Should produce P1 4 1 0101
 P1 4 1 0101 
-4030 : 0 0 0 0 : 0 , 4030 : 0 0 0 0 : 0
-4031 : 0 0 0 0 : 0 , 4031 : 0 0 0 0 : 0
-4097 : 0 0 0 0 : 0 , 4097 : 0 0 0 0 : 0
+Test 5. Should produce: N : 0 0 0 0 : 0 , N : 0 0 0 0 : 0
+(N=238, 239, 240, 241, 255, 256, 257, 4030, 4031, 4097)
 238 : 0 0 0 0 : 0 , 238 : 0 0 0 0 : 0
 239 : 0 0 0 0 : 0 , 239 : 0 0 0 0 : 0
 240 : 0 0 0 0 : 0 , 240 : 0 0 0 0 : 0
@@ -20,3 +25,6 @@ P1 4 1 0101
 255 : 0 0 0 0 : 0 , 255 : 0 0 0 0 : 0
 256 : 0 0 0 0 : 0 , 256 : 0 0 0 0 : 0
 257 : 0 0 0 0 : 0 , 257 : 0 0 0 0 : 0
+4030 : 0 0 0 0 : 0 , 4030 : 0 0 0 0 : 0
+4031 : 0 0 0 0 : 0 , 4031 : 0 0 0 0 : 0
+4097 : 0 0 0 0 : 0 , 4097 : 0 0 0 0 : 0
diff --git a/test/gif-roundtrip.test b/test/gif-roundtrip.test
index 1e6c7760..13ff595e 100755
--- a/test/gif-roundtrip.test
+++ b/test/gif-roundtrip.test
@@ -7,7 +7,8 @@ tmpdir=${tmpdir:-/tmp}
 # Test 1. Break up input image into three monochrome planes,
 # maxval 255.  Transform each plane to gif and back to pgm.
 # Reassemble the planes.  Result should be identical to input.
-# Should print 1926073387 101484
+
+echo "Test 1. Should print 1926073387 101484"
 
 test_ppm=${tmpdir}/testimg.ppm
 
@@ -29,13 +30,11 @@ pamtogif ${test_blu} | giftopnm | \
 
 rm ${test_ppm} ${test_grn} ${test_blu} ${out_red} ${out_grn}
 
-
-# Test 2. Should produce 1571496937 33838
-# which is the result of cksum testimg.red
-# five times
+echo "Test 2. Should produce 1571496937 33838 six times"
 
 test_gif=${tmpdir}/testimg.gif
 
+cat ${test_red} | cksum
 pamtogif ${test_red} | giftopnm | cksum
 pamtogif -interlace ${test_red} | giftopnm | cksum
 pamtogif -noclear ${test_red} | giftopnm | cksum
@@ -46,22 +45,23 @@ echo "junk" >> ${test_gif} && \
 
 rm  ${test_gif} ${test_red}
 
+echo "Test 3. Should produce 281226646 481 six times"
+# maze.pbm is too small for -noclear to take effect 
 
-# Test 3. Should produce 2425386270 41 five times.
-# testgrid.pbm is too small for -noclear to take effect 
-
-pamtogif testgrid.pbm | giftopnm | cksum
-pamtogif -nolzw testgrid.pbm | giftopnm | cksum
-pamtogif -transparent=black testgrid.pbm | giftopnm | cksum
-pamtogif -alpha=testgrid.pbm testgrid.pbm | giftopnm | cksum
-pamtogif -transparent=white testgrid.pbm | giftopnm -alpha=- | \
+cat maze.pbm | cksum
+pamtogif maze.pbm | giftopnm | cksum
+pamtogif -nolzw maze.pbm | giftopnm | cksum
+pamtogif -transparent=black maze.pbm | giftopnm | cksum
+pamtogif -alpha=maze.pbm maze.pbm | giftopnm | cksum
+pamtogif -transparent=white maze.pbm | giftopnm -alpha=- | \
   pnminvert | cksum
 
 
 # Test 4.
 # In this gif file the code length changes after the last image data.
 # Image data: 3 bits, end code 4 bits.
-# Should produce P1 4 1 0 1 0 1
+
+echo "Test 4. Should produce P1 4 1 0101"
 
 pbmmake -g 4 1 | \
   pamtogif -verbose | giftopnm -plain | \
@@ -71,25 +71,18 @@ echo ""
 
 # Test 5.
 # Test whether saturated code tables are handled correctly.
-# Test input images which most use up the string code table or
+# Test input images which use up the string code table or
 # come close to doing so.
 
-# Should produce:
-# 4030 0 , 4030 0
-# 4031 0 , 4031 0
-# 4097 0 , 4097 0
-# 238 0 , 238 0
-# 239 0 , 239 0
-# 240 0 , 240 0
-# 241 0 , 241 0
-# 255 0 , 255 0
-# 256 0 , 256 0
-# 257 0 , 257 0
 
-test4097_pgm=${tmpdir}/testimg4097.pgm
+echo "Test 5. Should produce: N : 0 0 0 0 : 0 , N : 0 0 0 0 : 0"
+echo "(N=238, 239, 240, 241, 255, 256, 257, 4030, 4031, 4097)"
+
 test_pgm=${tmpdir}/testimg.pgm
 
-# The following awk script produces a PGM file with no repeated sequences.
+# The following awk scripts produce a PGM file with no repeated
+# sequences.  Obviously this cannot be compressed at all; the codes
+# are consumed without ever being used.  
 # Here is a smaller example with the same property:
 # P2
 # 8 8
@@ -103,7 +96,9 @@ test_pgm=${tmpdir}/testimg.pgm
 # 3 6 3 7 4 5 4 6
 # 4 7 5 6 5 7 6 7
 
-maxval=63
+test257_pgm=${tmpdir}/testimg257.pgm
+
+maxval=15
 awk -v maxval=${maxval} 'BEGIN \
 { print "P2"
          print "1 "(maxval+1) * (maxval+1) +1
@@ -115,26 +110,25 @@ awk -v maxval=${maxval} 'BEGIN \
              for (j=i+1; j<=maxval; ++j)
                  {print i; print j }
          print 0
-}' > ${test4097_pgm}
+}' >  ${test257_pgm}
 
-for size in 4030 4031 4097
+for size in 238 239 240 241 255 256 257
   do
-  pamcut -height ${size} ${test4097_pgm} > ${test_pgm} &&
+  pamcut -height=${size} ${test257_pgm} > ${test_pgm} &&
   pamtogif -verbose ${test_pgm} | giftopnm | pamdepth ${maxval} | \
     cmp - ${test_pgm}
-  # pamdepth ${maxval} is necessary because
-  # giftopnm output is maxval 255
-  echo -n ${size} ":" ${PIPESTATUS[@]} ":" $? ", "
-  pamtogif -nolzw ${test_pgm} | giftopnm | pamdepth ${maxval} | \
+  printf "${size} : ${PIPESTATUS[*]} : $? , "
+  pamtogif -nolzw -verbose ${test_pgm} | giftopnm | pamdepth ${maxval} | \
     cmp - ${test_pgm}
-  echo ${size} ":" ${PIPESTATUS[@]} ":" $?
+  printf "${size} : ${PIPESTATUS[*]} : $?\n"
   rm ${test_pgm}
   done 
 
-rm ${test4097_pgm}
-test257_pgm=${tmpdir}/testimg257.pgm
+rm ${test257_pgm}
 
-maxval=15
+test4097_pgm=${tmpdir}/testimg4097.pgm
+
+maxval=63
 awk -v maxval=${maxval} 'BEGIN \
 { print "P2"
          print "1 "(maxval+1) * (maxval+1) +1
@@ -146,18 +140,20 @@ awk -v maxval=${maxval} 'BEGIN \
              for (j=i+1; j<=maxval; ++j)
                  {print i; print j }
          print 0
-}' >  ${test257_pgm}
+}' > ${test4097_pgm}
 
-for size in 238 239 240 241 255 256 257
+for size in 4030 4031 4097
   do
-  pamcut -height=${size} ${test257_pgm} > ${test_pgm} &&
+  pamcut -height ${size} ${test4097_pgm} > ${test_pgm} &&
   pamtogif -verbose ${test_pgm} | giftopnm | pamdepth ${maxval} | \
     cmp - ${test_pgm}
-  echo -n ${size} ":" ${PIPESTATUS[@]} ":" $? ", "
-  pamtogif -nolzw -verbose ${test_pgm} | giftopnm | pamdepth ${maxval} | \
+  # pamdepth ${maxval} is necessary because
+  # giftopnm output is maxval 255
+  printf "${size} : ${PIPESTATUS[*]} : $? , "
+  pamtogif -nolzw ${test_pgm} | giftopnm | pamdepth ${maxval} | \
     cmp - ${test_pgm}
-  echo ${size} ":" ${PIPESTATUS[@]} ":" $?
+  printf "${size} : ${PIPESTATUS[*]} : $?\n"
   rm ${test_pgm}
   done 
 
-rm ${test257_pgm}
+rm ${test4097_pgm}
diff --git a/test/gif-transparent1.ok b/test/gif-transparent1.ok
new file mode 100644
index 00000000..a531329a
--- /dev/null
+++ b/test/gif-transparent1.ok
@@ -0,0 +1,99 @@
+Test 0.
+Should print 0 or 1 0.
+Image 1: 1 0
+Image 2: 1 0
+Image 3: 0
+Image 4: 0
+Image 5: 0
+Test 1.
+Should print 0 unless otherwise stated.
+Image 1
+a1: 1 (should print 1)
+a2: 0
+a3: 0
+b1: 1 (should print 1)
+b2: 0
+b3: 0
+c1: 0
+c2: 0
+c3: 0
+c4: 0
+d1: 0
+d2: 0
+Image 2
+a1: 1 (should print 1)
+a2: 0
+a3: 0
+b1: 1 (should print 1)
+b2: 0
+b3: 0
+c1: 0
+c2: 0
+c3: 0
+c4: 0
+d1: 0
+d2: 0
+Image 3
+a1: 1 (should print 1)
+a2: 0
+a3: 0
+b1: 1 (should print 1)
+b2: 0
+b3: 0
+c1: 0
+c2: 0
+c3: 0
+c4: 0
+d1: 0
+d2: 0
+Test 2.
+Should print 0 unless otherwise stated.
+Image 1
+cl1: 0
+cl2: 0
+op1: 1 (should print 1)
+op2: 0
+Image 2
+cl1: 0
+cl2: 0
+op1: 1 (should print 1)
+op2: 0
+Image 3
+cl1: 0
+cl2: 0
+op1: 1 (should print 1)
+op2: 0
+Test 3.
+Should print 0 in all cases.
+Image 1
+a2: 0
+a3: 0
+b2: 0
+b3: 0
+c4: 0
+Image 2
+a2: 0
+a3: 0
+b2: 0
+b3: 0
+c4: 0
+Image 3
+a2: 0
+a3: 0
+b2: 0
+b3: 0
+c4: 0
+Test 4.
+Should print 0 in all cases.
+color=rgb:0f/0f/0f
+0
+0
+0
+color=rgb:ff/00/00
+0
+0
+0
+color=rgb:00/ff/00
+0
+0
+0
diff --git a/test/gif-transparent1.test b/test/gif-transparent1.test
new file mode 100755
index 00000000..74496787
--- /dev/null
+++ b/test/gif-transparent1.test
@@ -0,0 +1,224 @@
+#! /bin/sh
+# This script tests: giftopnm pamtogif ppmtogif
+# Also requires: pamarith pamcomp pamdepth pamenlarge pamstack pbmmake
+# Also requires: pnminvert ppmchange ppmpat ppmtopgm ppmtoppm 
+
+tmpdir=${tmpdir:-/tmp}
+
+madras_ppm=${tmpdir}/madras.ppm
+gingham_ppm=${tmpdir}/gingham.ppm
+argyle_ppm=${tmpdir}/argyle.ppm
+
+alpha0_pbm=${tmpdir}/alpha0.pbm
+alpha1_pbm=${tmpdir}/alpha1.pbm
+clear_pbm=${tmpdir}/clear.pbm
+opaque_pbm=${tmpdir}/opaque.pbm
+alpha0_pam=${tmpdir}/alpha0.pam
+alpha1_pam=${tmpdir}/alpha1.pam
+clear_pam=${tmpdir}/clear.pam
+opaque_pam=${tmpdir}/opaque.pam
+
+image0_alpha_pam=${tmpdir}/image0.alpha.pam
+image1_alpha_pam=${tmpdir}/image1.alpha.pam
+
+out_pnm=${tmpdir}/out.pnm
+out0_ppm=${tmpdir}/out0.ppm
+out1_ppm=${tmpdir}/out1.ppm
+out2_ppm=${tmpdir}/out2.ppm
+a0_out_pbm=${tmpdir}/a0.out.pbm
+a1_out_pbm=${tmpdir}/a1.out.pbm
+
+# Make test images & alpha masks
+
+ppmpat -argyle2 \
+  -color=rgb:00/00/00,rgb:ff/ff/ff,rgb:ff/ff/ff 40 24 > ${argyle_ppm}
+ppmpat -gingham3 \
+  -color=rgb:3f/3f/3f,rgb:7f/7f/7f,rgb:ef/ef/ef 40 24 > ${gingham_ppm}
+ppmpat -madras \
+       -color=rgb:0f/0f/0f,rgb:ff/00/00,rgb:00/ff/00 40 24 > ${madras_ppm}
+
+pbmmake -g 5 3 | pamenlarge 8 | tee ${alpha0_pbm} | \
+  pamdepth 255 > ${alpha0_pam}
+pnminvert ${alpha0_pbm} | tee ${alpha1_pbm} | \
+  pamdepth 255 > ${alpha1_pam}
+
+pbmmake -w 40 24 | tee ${clear_pbm} | pamdepth 255 > ${clear_pam}
+pbmmake -b 40 24 | tee ${opaque_pbm} | pamdepth 255 > ${opaque_pam}
+
+
+echo "Test 0."
+echo "Should print 0 or 1 0."
+i=1
+for test_pnm in ${argyle_ppm} ${gingham_ppm} ${madras_ppm} \
+			      ${alpha0_pbm} ${alpha1_pbm}
+  do
+  printf "Image $i: "; i=$((i+1));
+  pamtogif ${test_pnm} | giftopnm | tee ${out_pnm} | \
+    cmp -s - ${test_pnm}; result=$?
+
+  if [ $result -eq 0 ];
+    then echo $?;
+  else
+    ppmtoppm < ${out_pnm} | cmp -s - ${test_pnm}; echo $result $?
+  fi
+  # madras, alpha, alpha1 : should match
+  # argyle: giftopnm produces PBM, gingham: giftopnm produces PGM
+  rm ${out_pnm}
+  done
+
+
+echo "Test 1."  # Color + alpha channel
+echo "Should print 0 unless otherwise stated."
+
+i=1
+for test_pnm in  ${argyle_ppm} ${gingham_ppm} ${madras_ppm}
+  do
+  echo "Image $i"; i=$((i+1));
+
+  pamstack -tupletype="RGB_ALPHA" ${test_pnm} ${alpha0_pam} > \
+    ${image0_alpha_pam}
+  pamstack -tupletype="RGB_ALPHA" ${test_pnm} ${alpha1_pam} > \
+    ${image1_alpha_pam}
+
+  pamtogif ${image0_alpha_pam} | giftopnm -alphaout=${a0_out_pbm} | \
+    ppmtoppm | tee ${out0_ppm} | \
+    cmp -s - ${test_pnm}; echo "a1:" $? "(should print 1)"
+  cmp -s ${alpha0_pbm} ${a0_out_pbm}; echo "a2:" $?  # Should match
+
+  pamarith -multiply ${test_pnm} ${alpha0_pbm} | \
+    cmp -s - ${out0_ppm}; echo "a3:" $? # Should match
+
+  pamtogif ${image1_alpha_pam} | giftopnm -alphaout=${a1_out_pbm} | \
+    ppmtoppm | tee ${out1_ppm} | \
+    cmp -s - ${test_pnm}; echo "b1:" $? "(should print 1)"
+
+  cmp -s ${alpha1_pbm} ${a1_out_pbm}; echo "b2:" $?  # Should match
+
+  pamarith -multiply ${test_pnm} ${alpha1_pam} | \
+    cmp -s - ${out1_ppm}; echo "b3:" $?    # Should match
+
+  pamarith -multiply ${test_pnm} ${alpha0_pbm} | \
+    cmp -s - ${out0_ppm}; echo "c1:" $?    # Should match
+
+  pamarith -multiply ${test_pnm} ${alpha1_pbm} | \
+    cmp -s - ${out1_ppm}; echo "c2:" $?    # Should match
+
+  pamcomp -alpha=${alpha0_pbm} ${out0_ppm} ${out1_ppm} | \
+    cmp -s - ${test_pnm}; echo "c3:" $?    # Should match
+
+  pamcomp -alpha=${alpha1_pbm} ${out1_ppm} ${out0_ppm} | \
+    cmp -s - ${test_pnm}; echo "c4:" $?    # Should match
+
+  pamtogif ${image0_alpha_pam} -alphacolor=rgb:00/00/80 | \
+    giftopnm  -alphaout=${a0_out_pbm} > /dev/null
+    cmp -s ${a0_out_pbm} ${alpha0_pbm}; echo "d1:" $?    # Should match
+
+  pamtogif ${image0_alpha_pam} -alphacolor=rgb:00/00/80 | \
+    giftopnm | ppmtoppm | \
+    ppmchange rgb:00/00/80 rgb:00/00/00 -remainder=rgb:ff/ff/ff | \
+    ppmtopgm | \
+    cmp -s - ${alpha0_pam}; echo "d2:" $?    # Should match
+
+  rm ${image0_alpha_pam} ${image1_alpha_pam}
+  rm ${out0_ppm} ${out1_ppm} # ${out0_pnm} ${out1_pnm}
+  rm ${a0_out_pbm} ${a1_out_pbm}
+
+  done
+
+echo "Test 2."  # clear/opaque alpha channel
+echo "Should print 0 unless otherwise stated."
+
+i=1
+for test_pnm in  ${argyle_ppm} ${gingham_ppm} ${madras_ppm}
+  do
+  echo "Image $i"; i=$((i+1));
+
+  pamstack -tupletype="RGB_ALPHA" ${test_pnm} ${clear_pam} > \
+    ${image0_alpha_pam}
+  pamstack -tupletype="RGB_ALPHA" ${test_pnm} ${opaque_pam} > \
+    ${image1_alpha_pam}
+
+  # clear
+  pamtogif ${image0_alpha_pam} | giftopnm -alphaout=${a0_out_pbm} | \
+    ppmtoppm | tee ${out0_ppm} | \
+    cmp -s - ${test_pnm}; echo "cl1:" $? # Should match
+  cmp -s ${clear_pbm} ${a0_out_pbm}; echo "cl2:" $?  # Should match
+
+  # opaque
+  pamtogif ${image1_alpha_pam} | giftopnm -alphaout=${a1_out_pbm} | \
+    tee ${out1_ppm} | \
+    cmp -s - ${test_pnm}; echo "op1:" $? "(should print 1)"
+
+  cmp -s ${opaque_pbm} ${a1_out_pbm}; echo "op2:" $?  # Should match
+
+  rm ${image0_alpha_pam} ${image1_alpha_pam}
+  rm ${out0_ppm} ${out1_ppm}
+  rm ${a0_out_pbm} ${a1_out_pbm}
+
+  done
+
+rm ${clear_pbm} ${clear_pam} ${opaque_pbm} ${opaque_pam}
+
+
+echo "Test 3."  # ppmtogif
+echo "Should print 0 in all cases."
+
+i=1
+for test_pnm in  ${argyle_ppm} ${gingham_ppm} ${madras_ppm}
+  do
+  echo "Image $i"; i=$((i+1));
+
+  ppmtogif -alpha=${alpha0_pbm} ${test_pnm} | \
+    giftopnm -alphaout=${a0_out_pbm} | \
+    ppmtoppm > ${out0_ppm}
+    cmp -s ${alpha0_pbm} ${a0_out_pbm}; echo "a2:" $?  # Should match
+  pamarith -multiply ${test_pnm} ${alpha0_pbm} | \
+    cmp -s - ${out0_ppm}; echo "a3:" $? # Should match
+
+  ppmtogif -alpha=${alpha1_pbm} ${test_pnm} | \
+    giftopnm -alphaout=${a1_out_pbm} | \
+    ppmtoppm > ${out1_ppm}
+    cmp -s ${alpha1_pbm} ${a1_out_pbm}; echo "b2:" $?  # Should match
+  pamarith -multiply ${test_pnm} ${alpha1_pam} | \
+    cmp -s - ${out1_ppm}; echo "b3:" $?    # Should match
+
+  pamcomp -alpha=${alpha1_pbm} ${out1_ppm} ${out0_ppm} | \
+    cmp -s - ${test_pnm}; echo "c4:" $?    # Should match
+
+  rm ${out0_ppm} ${out1_ppm}
+  rm ${a0_out_pbm} ${a1_out_pbm}
+
+  done
+
+rm ${alpha0_pbm} ${alpha1_pbm}
+rm ${alpha0_pam} ${alpha1_pam}
+rm ${argyle_ppm} ${gingham_ppm}
+
+
+echo "Test 4."
+echo "Should print 0 in all cases."
+# no separate alpha channel
+# designate colors which appear in madras as transparent 
+
+for color in "0f/0f/0f" "ff/00/00" "00/ff/00"
+  do
+  echo "color=rgb:"${color}
+  pamtogif -transparent=rgb:${color} ${madras_ppm} | \
+    giftopnm -alphaout=${a0_out_pbm} > ${out0_ppm}
+    cmp -s ${madras_ppm} ${out0_ppm}; echo $?   # Should match 
+
+  pbmmake -g 40 24 | pamdepth 255 | pamstack ${madras_ppm} - | 
+  pamtogif -transparent=rgb:${color} - | \
+    giftopnm -alphaout=${a1_out_pbm} > ${out1_ppm}
+    cmp -s ${madras_ppm} ${out1_ppm}; echo $?   # Should match 
+
+  ppmchange rgb:${color} rgb:00/00/00 \
+    -remainder=rgb:ff/ff/ff ${madras_ppm} > ${out2_ppm}
+
+  ppmtoppm < ${a0_out_pbm} | \
+    cmp -s ${out2_ppm} -; echo $?   # Should match 
+
+  rm ${out0_ppm} ${out1_ppm} ${out2_ppm} ${a0_out_pbm} ${a1_out_pbm}
+  done
+
+rm ${madras_ppm} 
diff --git a/test/hdiff-roundtrip.test b/test/hdiff-roundtrip.test
index a4a4a906..ec7afc2c 100755
--- a/test/hdiff-roundtrip.test
+++ b/test/hdiff-roundtrip.test
@@ -1,4 +1,4 @@
-#! /bin/bash
+#! /bin/sh
 # This script tests: hdifftopam pamtohdiff
 # Also requires:
 
diff --git a/test/ilbm-roundtrip.ok b/test/ilbm-roundtrip.ok
index 54574a18..2d6fcff0 100644
--- a/test/ilbm-roundtrip.ok
+++ b/test/ilbm-roundtrip.ok
@@ -1,10 +1,18 @@
-829921912 685
-829921912 685
-829921912 685
-829921912 685
+Test 1.  Should produce 669206373 10102 four times
+669206373 10102
+669206373 10102
+669206373 10102
+669206373 10102
+Test 2.  Should produce 1926073387 101484 three times
 1926073387 101484
 1926073387 101484
 1926073387 101484
+Test 3.  Should print 984199586 101484
 984199586 101484
+Test 4.  Should print 2059976475 661 three times
 2059976475 661
 2059976475 661
+2059976475 661
+Test 5.  Should print 482756572 101484 twice
+482756572 101484
+482756572 101484
diff --git a/test/ilbm-roundtrip.test b/test/ilbm-roundtrip.test
index f62368ff..3d7d63ef 100755
--- a/test/ilbm-roundtrip.test
+++ b/test/ilbm-roundtrip.test
@@ -1,28 +1,58 @@
-#! /bin/bash
+#! /bin/sh
 # This script tests: ppmtoilbm ilbmtoppm
-# Also requires: pamseq pamdepth pamtopnm pnmremap
+# Also requires: pamseq pamdepth pamtopnm pnmremap pnmcolormap
 
-#Test. 1  Should produce 829921912 685 four times
-#Output is PPM raw, 14 by 16  maxval 255
-ppmtoilbm testgrid.pbm | ilbmtoppm | cksum
-ppmtoilbm -aga testgrid.pbm | ilbmtoppm | cksum
-ppmtoilbm -ham6 testgrid.pbm | ilbmtoppm | cksum
-ppmtoilbm -ham8 testgrid.pbm | ilbmtoppm | cksum
+echo "Test 1.  Should produce 669206373 10102 four times"
+#Output is PPM raw, 57 by 59  maxval 255
 
+ppmtoilbm maze.pbm | ilbmtoppm | cksum
+ppmtoilbm -aga maze.pbm | ilbmtoppm | cksum
+ppmtoilbm -ham6 maze.pbm | ilbmtoppm | cksum
+ppmtoilbm -ham8 maze.pbm | ilbmtoppm | cksum
 
-#Test. 2  Should produce 1926073387 101484 three times
+
+echo "Test 2.  Should produce 1926073387 101484 three times"
 ppmtoilbm testimg.ppm | ilbmtoppm | cksum
 ppmtoilbm -24force testimg.ppm | ilbmtoppm | cksum
 ppmtoilbm -dcbits 8 8 8 -nocompress testimg.ppm | ilbmtoppm | cksum
 
+tmpdir=${tmpdir:-/tmp}
 
-#Test. 3  Should print 984199586 101484
-pamseq 3 5 -tupletype=RGB | pamdepth 255 | pamtopnm | \
+echo "Test 3.  Should print 984199586 101484"
+test_ppm=${tmpdir}/test.ppm
+pamseq 3 5 -tupletype=RGB | pamdepth 255 | pamtopnm | tee ${test_ppm} | \
   pnmremap -mapfile=- testimg.ppm | ppmtoilbm | ilbmtoppm | cksum
 
 
-#Test. 4 Should print 2059976475 661 twice
-pamseq 3 5 -tupletype=RGB | pamtopnm | \
-  ppmtoilbm -compress | ilbmtoppm | cksum
-pamseq 3 5 -tupletype=RGB | pamtopnm | \
-  ppmtoilbm -nocompress | ilbmtoppm | cksum
+echo "Test 4.  Should print 2059976475 661 three times"
+cat ${test_ppm} | cksum
+ppmtoilbm -compress ${test_ppm} | ilbmtoppm | cksum
+ppmtoilbm -nocompress ${test_ppm} | ilbmtoppm | cksum
+
+rm ${test_ppm}
+
+echo "Test 5.  Should print 482756572 101484 twice"
+mapfile=${tmpdir}/mapfile
+
+# The following was produced by running "pnmcolormap -plain 32 testimg.ppm"
+# We use a prefabricated mapfile because pnmcolormap is known to
+# produce slightly different output on different systems.
+
+cat > ${mapfile} << EOF
+P3
+32 1
+255
+106 82 80 46 43 34 128 62 46 189 68 63 209 41 43 209 65 46 241 62 72
+ 240 189 195 
+122 142 103 92 131 68 159 129 188 177 205 195 96 132 107 193 150 107
+ 242 253 238 241 73 108 
+121 75 67 182 67 47 98 88 48 237 36 47 66 45 42 68 84 43 182 45 41
+ 70 77 67 
+96 45 45 237 62 47 150 59 41 189 76 103 48 69 31 52 68 52 48 45 51
+ 105 80 130 
+EOF
+
+ppmtoilbm -map ${mapfile} testimg.ppm | ilbmtoppm | tee ${test_ppm} | cksum
+ppmtoilbm -map ${mapfile} ${test_ppm} | ilbmtoppm | cksum
+
+rm ${mapfile} ${test_ppm}
diff --git a/test/jbig-roundtrip.ok b/test/jbig-roundtrip.ok
index b98a694b..c9164120 100644
--- a/test/jbig-roundtrip.ok
+++ b/test/jbig-roundtrip.ok
@@ -1,2 +1,2 @@
-2425386270 41
+281226646 481
 1571496937 33838
diff --git a/test/jbig-roundtrip.test b/test/jbig-roundtrip.test
index 570d7336..11cd1778 100755
--- a/test/jbig-roundtrip.test
+++ b/test/jbig-roundtrip.test
@@ -1,9 +1,9 @@
-#! /bin/bash
+#! /bin/sh
 # This script tests: pnmtojbig jbigtopnm
 # Also requires: pamchannel pamtopnm
 
-# Test 1.  Should print 2425386270 41
-pnmtojbig testgrid.pbm | jbigtopnm | cksum
+# Test 1.  Should print 281226646 481
+pnmtojbig maze.pbm | jbigtopnm | cksum
 
 # Test 2.  Should print 1571496937 33838
 pamchannel -infile=testimg.ppm -tupletype="GRAYSCALE" 0 | pamtopnm | \
diff --git a/test/jpeg-roundtrip.test b/test/jpeg-roundtrip.test
index 7cc0fc20..834c02e5 100755
--- a/test/jpeg-roundtrip.test
+++ b/test/jpeg-roundtrip.test
@@ -1,4 +1,4 @@
-#! /bin/bash
+#! /bin/sh
 # This script tests: pnmtojpeg jpegtopnm
 # Also requires: pnmpsnr
 
diff --git a/test/jpeg2k-roundtrip.test b/test/jpeg2k-roundtrip.test
index 0995849d..4a09201d 100755
--- a/test/jpeg2k-roundtrip.test
+++ b/test/jpeg2k-roundtrip.test
@@ -1,4 +1,4 @@
-#! /bin/bash
+#! /bin/sh
 # This script tests: pamtojpeg2k jpeg2ktopam
 # Also requires:
 
diff --git a/test/leaf-roundtrip.test b/test/leaf-roundtrip.test
index 5628ed01..94b31092 100755
--- a/test/leaf-roundtrip.test
+++ b/test/leaf-roundtrip.test
@@ -1,4 +1,4 @@
-#! /bin/bash
+#! /bin/sh
 # This script tests: ppmtoleaf leaftoppm
 # Also requires:
 
diff --git a/test/legacy-names.ok b/test/legacy-names.ok
index 27baf672..f491a1ff 100644
--- a/test/legacy-names.ok
+++ b/test/legacy-names.ok
@@ -12,6 +12,7 @@ pgmoil: ok
 pgmslice: ok
 pngtopnm: ok
 pnmarith: ok
+pnmcat: ok
 pnmcomp: ok
 pnmcut: ok
 pnmdepth: ok
diff --git a/test/legacy-names.test b/test/legacy-names.test
index e20dde76..9c0c5697 100755
--- a/test/legacy-names.test
+++ b/test/legacy-names.test
@@ -69,6 +69,7 @@ ordinary_testprogs="\
   pgmslice \
   pngtopnm \
   pnmarith \
+  pnmcat \
   pnmcomp \
   pnmcut \
   pnmdepth \
diff --git a/test/lookup-roundtrip.test b/test/lookup-roundtrip.test
index 63ec0777..19ebd40a 100755
--- a/test/lookup-roundtrip.test
+++ b/test/lookup-roundtrip.test
@@ -1,4 +1,4 @@
-#! /bin/bash
+#! /bin/sh
 # This script tests: pamlookup pamunlookup
 # Also requires: ppmhist
 
@@ -10,3 +10,5 @@ ppmhist testimg.ppm -map > ${mapfile}
 # Test.  Should produce 1926073387 101484
 pamunlookup -lookupfile=${mapfile} testimg.ppm |\
   pamlookup -lookupfile=${mapfile} | cksum
+
+rm ${mapfile}
\ No newline at end of file
diff --git a/test/lps-roundtrip.ok b/test/lps-roundtrip.ok
index 02b1d1a9..c2c8ab3b 100644
--- a/test/lps-roundtrip.ok
+++ b/test/lps-roundtrip.ok
@@ -1 +1,4 @@
+Test 1.  Should print match
 match
+Test 2.  Should print 0
+0
diff --git a/test/lps-roundtrip.test b/test/lps-roundtrip.test
index f30062a8..24076ef1 100755
--- a/test/lps-roundtrip.test
+++ b/test/lps-roundtrip.test
@@ -1,22 +1,33 @@
-#! /bin/bash
+#! /bin/sh
 # This script tests: pbmtolps pstopnm
-# Also requires: gs pamdepth pamscale pnmcrop pnmpsnr
+# Also requires: gs pamdepth pamscale pnmcrop pnmpsnr pamfile
 
 # The ordinary round-trip does not work because of the way ghostscript
 # renders: a line is considered wider than a single pixel and all pixels
 # it touches are set to black if the output is PBM.  To work around this,
 # we tell pstopnm to output PGM at a high resolution (=large dpi value).
 
+tmpdir=${tmpdir:-/tmp}
+test_pgm=${tmpdir}/test.pgm
+test_ps=${tmpdir}/test.ps
 
-test_pgm=${tmpdir}/testgrid.pgm
+echo "Test 1.  Should print match"
 
+xysize=$(pamfile -size testgrid.pbm | awk '{print "-xsize="$1,"-ysize="$2}')
 pamdepth 255 testgrid.pbm > ${test_pgm}
-
-pbmtolps -dpi 72 testgrid.pbm | \
+  
+pbmtolps -dpi 72 testgrid.pbm | tee ${test_ps} | \
     pstopnm -dpi $((72*12)) -stdout -pgm | \
-    pnmcrop -white | pamscale -xsize=14 -ysize=16 | \
+    pnmcrop -white | pamscale ${xysize}  | \
     pnmpsnr -target=30 - ${test_pgm}
 
-# ghostscript version 8.71: pnmpsnr lumina 33.14dB
+    # ghostscript version 8.71: pnmpsnr lumina 33.14dB
+
+
+echo "Test 2.  Should print 0"
 
-rm ${test_pgm}
+pbmtolps -dpi 72 < testgrid.pbm | sed 's/noname/testgrid.pbm/' | \
+    cmp -s ${test_ps} -
+    echo $?
+  
+rm ${test_pgm} ${test_ps}
diff --git a/test/macp-roundtrip.ok b/test/macp-roundtrip.ok
index 9ff9d249..28c16ee0 100644
--- a/test/macp-roundtrip.ok
+++ b/test/macp-roundtrip.ok
@@ -1,5 +1,14 @@
-2425386270 41
-2425386270 41
+Test 1. Should produce 281226646 481 twice
+281226646 481
+281226646 481
+Test 2. Should produce 2329957971 51851
 2329957971 51851
+Test 3. Should produce 2907103393 5086 three times
 2907103393 5086
 2907103393 5086
+2907103393 5086
+Test 4. Should produce 3432623660 51851 four times
+3432623660 51851
+3432623660 51851
+3432623660 51851
+3432623660 51851
diff --git a/test/macp-roundtrip.test b/test/macp-roundtrip.test
index 4774a2c2..9def7c4c 100755
--- a/test/macp-roundtrip.test
+++ b/test/macp-roundtrip.test
@@ -1,31 +1,51 @@
-#! /bin/bash
+#! /bin/sh
 # This script tests: pbmtomacp macptopbm
-# Also requires: pnmcrop pbmpage pbmupc pnmpad
+# Also requires: pnmcrop pbmpage pbmupc pnmpad pbmmake
 
 tmpdir=${tmpdir:-/tmp}
-temp1_pbm=${tmpdir}/temp1.ppm
-temp2_pbm=${tmpdir}/temp2.ppm
+temp1_pbm=${tmpdir}/temp1.pbm
+temp2_pbm=${tmpdir}/temp2.pbm
+tempupc_pbm=${tmpdir}/tempupc.pbm
+temp3_pbm=${tmpdir}/temp3.pbm
+temp3_macp=${tmpdir}/temp3.macp
 
-
-# Test 1. Should produce 2425386270 41 twice
-# Because Macpaint files are fixed size (576 x 720 pixels)
+# Macpaint files are fixed size (576 x 720 pixels)
 # pbmtomacp automatically adds padding when input is smaller.
 
-pbmtomacp testgrid.pbm | macptopbm | tee ${temp1_pbm} | \
+echo "Test 1. Should produce 281226646 481 twice"
+pbmtomacp maze.pbm | macptopbm | tee ${temp1_pbm} | \
     pnmcrop | cksum
 
 pbmtomacp ${temp1_pbm} | macptopbm | pnmcrop | cksum
 
+rm ${temp1_pbm}
 
-#Test 2. Should produce 2329957971 51851
+echo "Test 2. Should produce 2329957971 51851"
 pbmpage 1 | pbmtomacp | macptopbm | cksum
 
-
-#Test 3. Should produce 2907103393 5086 twice
-pbmupc 0 12345 67890 | pnmpad -black -t 44 -b 20 -l 100 -r 251 | pbmtomacp | macptopbm | \
+echo "Test 3. Should produce 2907103393 5086 three times"
+pbmupc 0 12345 67890 | tee ${tempupc_pbm} | \
+    pnmpad -black -t 44 -b 20 -l 100 -r 251 | \
+    pbmtomacp | macptopbm | \
     tee ${temp2_pbm} | \
     pnmcrop | pnmcrop | cksum
 
+pnmpad -black -t 44 -l 100 ${tempupc_pbm} | \
+    pbmtomacp|  macptopbm | pnmcrop -white | pnmcrop | cksum
+
 pbmtomacp ${temp2_pbm} | macptopbm | pnmcrop | pnmcrop | cksum
 
-rm ${temp1_pbm} ${temp2_pbm}
+rm ${temp2_pbm} ${tempupc_pbm}
+
+
+echo "Test 4. Should produce 3432623660 51851 four times"
+pbmmake -b 576 720 | tee ${temp3_pbm} | cksum
+
+pbmtomacp ${temp3_pbm} | tee ${temp3_macp} | macptopbm | cksum
+
+pbmtomacp -norle ${temp3_pbm} | macptopbm | cksum
+
+( head -c 128 /dev/zero ; cat ${temp3_macp} ) | \
+    macptopbm -extraskip 128 | cksum
+
+rm ${temp3_pbm} ${temp3_macp}
diff --git a/test/maze.pbm b/test/maze.pbm
new file mode 100644
index 00000000..9bdd80e1
--- /dev/null
+++ b/test/maze.pbm
Binary files differdiff --git a/test/mda-roundtrip.ok b/test/mda-roundtrip.ok
index ef27ffd0..ab449885 100644
--- a/test/mda-roundtrip.ok
+++ b/test/mda-roundtrip.ok
@@ -1,2 +1,5 @@
+Test 1.  Should print 1757803444 169 twice
 1757803444 169
-2425386270 41
+1757803444 169
+Test 2.  Should print 281226646 481
+281226646 481
diff --git a/test/mda-roundtrip.test b/test/mda-roundtrip.test
index 58376f3f..c47d433e 100755
--- a/test/mda-roundtrip.test
+++ b/test/mda-roundtrip.test
@@ -1,13 +1,15 @@
-#! /bin/bash
+#! /bin/sh
 # This script tests: pbmtomda mdatopbm
-# Also requires: pbmmake pnmpad pamcut
+# Also requires: pbmmake pnmpad pamcut pamfile
 
 
 # Pbmtomda requires input width and height to be multiples of 8.
 
-# Test 1.  Should print 1757803444 169
+echo "Test 1.  Should print 1757803444 169 twice"
+pbmmake -g 32 40 | cksum
 pbmmake -g 32 40 | pbmtomda | mdatopbm | cksum
 
-# Test 2.  Should print 2425386270 41
-pnmpad -right 2 testgrid.pbm | \
-  pbmtomda | mdatopbm | pamcut 0 0 14 16 | cksum
+echo "Test 2.  Should print 281226646 481"
+size=$(pamfile -size maze.pbm | awk '{print "-width="$1,"-height="$2}')
+pnmpad -mwidth=8 -halign=0 -mheight=8 -valign=0 ${size} maze.pbm | \
+    pbmtomda | mdatopbm | pamcut -left=0 -top=0 ${size} | cksum
diff --git a/test/mgr-roundtrip.ok b/test/mgr-roundtrip.ok
index 845be5fb..0e845958 100644
--- a/test/mgr-roundtrip.ok
+++ b/test/mgr-roundtrip.ok
@@ -1 +1,7 @@
-2425386270 41
+Test 1.  Should print 281226646 481
+281226646 481
+Test 2.  Should print 429369764 1034, 448060073 4105 twice each
+429369764 1034
+429369764 1034
+448060073 4105
+448060073 4105
diff --git a/test/mgr-roundtrip.test b/test/mgr-roundtrip.test
index 252ae996..9fb6211c 100755
--- a/test/mgr-roundtrip.test
+++ b/test/mgr-roundtrip.test
@@ -1,7 +1,15 @@
-#! /bin/bash
+#! /bin/sh
 # This script tests: pbmtomgr mgrtopbm
-# Also requires:
+# Also requires: pbmmake
 
+echo "Test 1.  Should print 281226646 481"
+pbmtomgr maze.pbm | mgrtopbm | cksum
+
+echo "Test 2.  Should print 429369764 1034, 448060073 4105 twice each"
+# Maximum width and height allowed
+
+pbmmake -g 4095 2 | cksum
+pbmmake -g 4095 2 | pbmtomgr | mgrtopbm | cksum
+pbmmake -g 1 4095 | cksum
+pbmmake -g 1 4095 | pbmtomgr | mgrtopbm | cksum
 
-# Should print 2425386270 41, cksum of testgrid.pbm
-pbmtomgr testgrid.pbm | mgrtopbm | cksum
diff --git a/test/mrf-roundtrip.ok b/test/mrf-roundtrip.ok
index 845be5fb..5168378d 100644
--- a/test/mrf-roundtrip.ok
+++ b/test/mrf-roundtrip.ok
@@ -1 +1 @@
-2425386270 41
+281226646 481
diff --git a/test/mrf-roundtrip.test b/test/mrf-roundtrip.test
index c9d8ce3a..5ce604e6 100755
--- a/test/mrf-roundtrip.test
+++ b/test/mrf-roundtrip.test
@@ -1,7 +1,7 @@
-#! /bin/bash
+#! /bin/sh
 # This script tests: pbmtomrf mrftopbm
 # Also requires:
 
 
-# Should print 2425386270 41, cksum of testgrid.pbm
-pbmtomrf testgrid.pbm | mrftopbm | cksum
+# Should print 281226646 481, cksum of maze.pbm
+pbmtomrf maze.pbm | mrftopbm | cksum
diff --git a/test/pad-crop-roundtrip.ok b/test/pad-crop-roundtrip.ok
index 0e712ce7..764cadfa 100644
--- a/test/pad-crop-roundtrip.ok
+++ b/test/pad-crop-roundtrip.ok
@@ -1,4 +1,4 @@
 1926073387 101484
 1926073387 101484
-2425386270 41
-2425386270 41
+281226646 481
+281226646 481
diff --git a/test/pad-crop-roundtrip.test b/test/pad-crop-roundtrip.test
index 75979901..31e02c99 100755
--- a/test/pad-crop-roundtrip.test
+++ b/test/pad-crop-roundtrip.test
@@ -1,18 +1,26 @@
-#! /bin/bash
+#! /bin/sh
 # This script tests: pnmcrop pnmmargin pnmpad
 # Also requires:
 
+# Test 1. Should produce 1926073387 101484, cksum of testimg.ppm
+
 pnmmargin -white 10 testimg.ppm | \
   pnmcrop | cksum
 
+# Test 2. Should produce 1926073387 101484
+
 pnmpad -white -left 10 -top 10 testimg.ppm | \
   pnmpad -white -right 10 -bottom 10 | \
   pnmcrop -right -bottom | pnmcrop -left -top | cksum
 
-pnmmargin -white 10 testgrid.pbm | \
+# Test 3. Should produce 281226646 481, cksum of maze.pbm
+
+pnmmargin -white 10 maze.pbm | \
   pnmcrop | cksum
 
-pnmpad -white -left 10 -top 10 testgrid.pbm | \
+# Test 4. Should produce 281226646 481
+
+pnmpad -white -left 10 -top 10 maze.pbm | \
   pnmpad -white -right 10 -bottom 10 | \
   pnmcrop -left -right | pnmcrop -top -bottom | cksum
 
diff --git a/test/palm-roundtrip.ok b/test/palm-roundtrip.ok
index b9ea3056..d69c3a96 100644
--- a/test/palm-roundtrip.ok
+++ b/test/palm-roundtrip.ok
@@ -1,10 +1,10 @@
-Test 1
-584219238 236
-584219238 236
-584219238 236
-584219238 236
-584219238 236
-Test 2
+Test 1. Should print 2067616594 3375 five times
+2067616594 3375
+2067616594 3375
+2067616594 3375
+2067616594 3375
+2067616594 3375
+Test 2. Should print 0 0 0  : 0 four times
 0 0 0 : 0
 0 0 0 : 0
 0 0 0 : 0
diff --git a/test/palm-roundtrip.test b/test/palm-roundtrip.test
index b00454ca..20fcefa9 100755
--- a/test/palm-roundtrip.test
+++ b/test/palm-roundtrip.test
@@ -6,11 +6,9 @@ tmpdir=${tmpdir:-/tmp}
 test4bit_pgm=${tmpdir}/test4bit.pgm
 test256color_ppm=${tmpdir}/test256color.ppm
 
-# Test 1. Should print 584219238 236  5 times
+echo "Test 1. Should print 2067616594 3375 five times"
 
-echo "Test 1"
-
-pamdepth 15 testgrid.pbm | tee ${test4bit_pgm} | cksum
+pamdepth 15 maze.pbm | tee ${test4bit_pgm} | cksum
 
 for flags in "" \
              "-scanline_compression" \
@@ -21,9 +19,7 @@ for flags in "" \
 rm ${test4bit_pgm}
 
 
-# Test 2. Should print 0 4 times
-
-echo "Test 2"
+echo "Test 2. Should print 0 0 0  : 0 four times"
 
 pnmquant 256 testimg.ppm > ${test256color_ppm} || echo "pnmquant failed"
 
diff --git a/test/palm-roundtrip2.test b/test/palm-roundtrip2.test
index 4c94df8c..f0c9b7c8 100755
--- a/test/palm-roundtrip2.test
+++ b/test/palm-roundtrip2.test
@@ -1,4 +1,4 @@
-#! /bin/bash
+#! /bin/sh
 # This script tests: pnmtopalm palmtopnm
 # Also requires: pnmremap
 
diff --git a/test/pamaddnoise-parameters.ok b/test/pamaddnoise-parameters.ok
new file mode 100644
index 00000000..e86632cf
--- /dev/null
+++ b/test/pamaddnoise-parameters.ok
@@ -0,0 +1,62 @@
+Test Invalid
+Expected failure 1 (no output)
+Expected failure 2 (no output)
+Expected failure 3 (no output)
+Expected failure 4 (no output)
+Expected failure 5 (no output)
+Expected failure 6 (no output)
+Expected failure 7 (no output)
+Expected failure 8 (no output)
+Expected failure 9 (no output)
+Expected failure 10 (no output)
+Expected failure 11 (no output)
+Expected failure 12 (no output)
+Expected failure 13 (no output)
+Expected failure 14 (no output)
+Expected failure 15 (no output)
+Expected failure 16 (no output)
+Expected failure 17 (no output)
+Expected failure 18 (no output)
+Expected failure 19 (no output)
+Expected failure 20 (no output)
+Expected failure 21 (no output)
+Expected failure 22 (no output)
+Expected failure 23 (no output)
+Expected failure 24 (no output)
+Expected failure 25 (no output)
+Expected failure 26 (no output)
+Expected failure 27 (no output)
+Expected failure 28 (no output)
+Expected failure 29 (no output)
+Expected failure 30 (no output)
+Expected failure 31 (no output)
+Expected failure 32 (no output)
+Expected failure 33 (no output)
+Expected failure 34 (no output)
+Expected failure 35 (no output)
+Expected failure 36 (no output)
+Expected failure 37 (no output)
+Expected failure 38 (no output)
+Expected failure 39 (no output)
+Expected failure 40 (no output)
+Expected failure 41 (no output)
+Expected failure 42 (no output)
+Expected failure 43 (no output)
+Expected failure 44 (no output)
+Expected failure 45 (no output)
+Expected failure 46 (no output)
+Expected failure 47 (no output)
+Expected failure 48 (no output)
+Expected failure 49 (no output)
+Expected failure 50 (no output)
+Expected failure 51 (no output)
+Expected failure 52 (no output)
+Expected failure 53 (no output)
+Expected failure 54 (no output)
+Expected failure 55 (no output)
+Expected failure 56 (no output)
+Expected failure 57 (no output)
+Expected failure 58 (no output)
+Expected failure 59 (no output)
+Expected failure 60 (no output)
+Expected failure 61 (no output)
diff --git a/test/pamaddnoise-parameters.test b/test/pamaddnoise-parameters.test
new file mode 100755
index 00000000..098d4946
--- /dev/null
+++ b/test/pamaddnoise-parameters.test
@@ -0,0 +1,337 @@
+#! /bin/sh
+# This script tests: pamaddnoise
+# Also requires:
+
+tmpdir=${tmpdir:-/tmp}
+test_out=/${tmpdir}/test.out
+
+# Test Invalid
+echo "Test Invalid"
+
+echo 1>&2
+echo "Invalid command-line argument combinations." 1>&2
+echo "Error messages should appear below the line." 1>&2
+echo "-----------------------------------------------------------" 1>&2
+
+# type gaussian implied
+
+pamaddnoise -sigma1=-4.0 testgrid.pbm > ${test_out} || \
+  printf "Expected failure 1 "
+  test -s ${test_out} && echo "unexpected output" || echo "(no output)"
+  rm -f ${test_out}
+
+pamaddnoise -sigma2=-20.0 testgrid.pbm > ${test_out} || \
+  printf "Expected failure 2 "
+  test -s ${test_out} && echo "unexpected output" || echo "(no output)"
+  rm -f ${test_out}
+
+pamaddnoise -mgsigma=0.5 testgrid.pbm > ${test_out} || \
+  printf "Expected failure 3 "
+  test -s ${test_out} && echo "unexpected output" || echo "(no output)"
+  rm -f ${test_out}
+
+pamaddnoise -lsigma=10.0 testgrid.pbm > ${test_out} || \
+  printf "Expected failure 4 "
+  test -s ${test_out} && echo "unexpected output" || echo "(no output)"
+  rm -f ${test_out}
+
+pamaddnoise -tolerance=0.10 testgrid.pbm > ${test_out} || \
+  printf "Expected failure 5 "
+  test -s ${test_out} && echo "unexpected output" || echo "(no output)"
+  rm -f ${test_out}
+
+pamaddnoise -salt=0.50 testgrid.pbm > ${test_out} || \
+  printf "Expected failure 6 "
+  test -s ${test_out} && echo "unexpected output" || echo "(no output)"
+  rm -f ${test_out}
+
+pamaddnoise -lambda=12.0 testgrid.pbm > ${test_out} || \
+  printf "Expected failure 7 "
+  test -s ${test_out} && echo "unexpected output" || echo "(no output)"
+  rm -f ${test_out}
+
+# type gaussian explicitly stated
+
+pamaddnoise -type gaussian -sigma1=-0.01 testgrid.pbm > ${test_out} || \
+  printf "Expected failure 8 "
+  test -s ${test_out} && echo "unexpected output" || echo "(no output)"
+  rm -f ${test_out}
+
+pamaddnoise -type gaussian -sigma2=-0.01 testgrid.pbm > ${test_out} || \
+  printf "Expected failure 9 "
+  test -s ${test_out} && echo "unexpected output" || echo "(no output)"
+  rm -f ${test_out}
+
+pamaddnoise -type gaussian -mgsigma=0.5 testgrid.pbm > ${test_out} || \
+  printf "Expected failure 10 "
+  test -s ${test_out} && echo "unexpected output" || echo "(no output)"
+  rm -f ${test_out}
+
+pamaddnoise -type gaussian -lsigma=10.0 testgrid.pbm > ${test_out} || \
+  printf "Expected failure 11 "
+  test -s ${test_out} && echo "unexpected output" || echo "(no output)"
+  rm -f ${test_out}
+
+pamaddnoise -type gaussian -tolerance=0.10 testgrid.pbm > ${test_out} || \
+  printf "Expected failure 12 "
+  test -s ${test_out} && echo "unexpected output" || echo "(no output)"
+  rm -f ${test_out}
+
+pamaddnoise -type gaussian -salt=0.50 testgrid.pbm > ${test_out} || \
+  printf "Expected failure 13 "
+  test -s ${test_out} && echo "unexpected output" || echo "(no output)"
+  rm -f ${test_out}
+
+pamaddnoise -type gaussian -lambda=12.0 testgrid.pbm > ${test_out} || \
+  printf "Expected failure 14 "
+  test -s ${test_out} && echo "unexpected output" || echo "(no output)"
+  rm -f ${test_out}
+
+# type multiplicative gaussian
+
+pamaddnoise -type multiplicative_gaussian -sigma1=4.0 testgrid.pbm > ${test_out} || \
+  printf "Expected failure 15 "
+  test -s ${test_out} && echo "unexpected output" || echo "(no output)"
+  rm -f ${test_out}
+  
+pamaddnoise -type multiplicative_gaussian -sigma2=20.0 testgrid.pbm > ${test_out} || \
+  printf "Expected failure 16 "
+  test -s ${test_out} && echo "unexpected output" || echo "(no output)"
+  rm -f ${test_out}
+
+pamaddnoise -type multiplicative_gaussian -mgsigma=-0.5 testgrid.pbm > ${test_out} || \
+  printf "Expected failure 17 "
+  test -s ${test_out} && echo "unexpected output" || echo "(no output)"
+  rm -f ${test_out}
+
+pamaddnoise -type multiplicative_gaussian -lsigma=10.0 testgrid.pbm > ${test_out} || \
+  printf "Expected failure 18 "
+  test -s ${test_out} && echo "unexpected output" || echo "(no output)"
+  rm -f ${test_out}
+
+pamaddnoise -type multiplicative_gaussian -tolerance=0.10 testgrid.pbm > ${test_out} || \
+  printf "Expected failure 19 "
+  test -s ${test_out} && echo "unexpected output" || echo "(no output)"
+  rm -f ${test_out}
+
+pamaddnoise -type multiplicative_gaussian -salt=0.50 testgrid.pbm > ${test_out} || \
+  printf "Expected failure 20 "
+  test -s ${test_out} && echo "unexpected output" || echo "(no output)"
+  rm -f ${test_out}
+
+pamaddnoise -type multiplicative_gaussian -lambda=12.0 testgrid.pbm > ${test_out} || \
+  printf "Expected failure 21 "
+  test -s ${test_out} && echo "unexpected output" || echo "(no output)"
+  rm -f ${test_out}
+
+# type laplacian
+
+pamaddnoise -type laplacian -sigma1=4.0 testgrid.pbm > ${test_out} || \
+  printf "Expected failure 22 "
+  test -s ${test_out} && echo "unexpected output" || echo "(no output)"
+  rm -f ${test_out}
+
+pamaddnoise -type laplacian -sigma2=20.0 testgrid.pbm > ${test_out} || \
+  printf "Expected failure 23 "
+  test -s ${test_out} && echo "unexpected output" || echo "(no output)"
+  rm -f ${test_out}
+
+pamaddnoise -type laplacian -mgsigma=0.5 testgrid.pbm > ${test_out} || \
+  printf "Expected failure 24 "
+  test -s ${test_out} && echo "unexpected output" || echo "(no output)"
+  rm -f ${test_out}
+
+pamaddnoise -type laplacian -lsigma=-10.0 testgrid.pbm > ${test_out} || \
+  printf "Expected failure 25 "
+  test -s ${test_out} && echo "unexpected output" || echo "(no output)"
+  rm -f ${test_out}
+
+pamaddnoise -type laplacian -tolerance=0.10 testgrid.pbm > ${test_out} || \
+  printf "Expected failure 26 "
+  test -s ${test_out} && echo "unexpected output" || echo "(no output)"
+  rm -f ${test_out}
+
+pamaddnoise -type laplacian -salt=0.50 testgrid.pbm > ${test_out} || \
+  printf "Expected failure 27 "
+  test -s ${test_out} && echo "unexpected output" || echo "(no output)"
+  rm -f ${test_out}
+
+pamaddnoise -type laplacian -lambda=12.0 testgrid.pbm > ${test_out} || \
+  printf "Expected failure 28 "
+  test -s ${test_out} && echo "unexpected output" || echo "(no output)"
+  rm -f ${test_out}
+ 
+
+# type impulse
+
+pamaddnoise -type impulse -sigma1=4.0 testgrid.pbm > ${test_out} || \
+  printf "Expected failure 29 "
+  test -s ${test_out} && echo "unexpected output" || echo "(no output)"
+  rm -f ${test_out}
+
+pamaddnoise -type impulse -sigma2=20.0 testgrid.pbm > ${test_out} || \
+  printf "Expected failure 30 "
+  test -s ${test_out} && echo "unexpected output" || echo "(no output)"
+  rm -f ${test_out}
+
+pamaddnoise -type impulse -mgsigma=0.5 testgrid.pbm > ${test_out} || \
+  printf "Expected failure 31 "
+  test -s ${test_out} && echo "unexpected output" || echo "(no output)"
+  rm -f ${test_out}
+
+pamaddnoise -type impulse -lsigma=10.0 testgrid.pbm > ${test_out} || \
+  printf "Expected failure 32 "
+  test -s ${test_out} && echo "unexpected output" || echo "(no output)"
+  rm -f ${test_out}
+
+pamaddnoise -type impulse -tolerance=-0.10 testgrid.pbm > ${test_out} || \
+  printf "Expected failure 33 "
+  test -s ${test_out} && echo "unexpected output" || echo "(no output)"
+  rm -f ${test_out}
+
+pamaddnoise -type impulse -tolerance=1.10 testgrid.pbm > ${test_out} || \
+  printf "Expected failure 34 "
+  test -s ${test_out} && echo "unexpected output" || echo "(no output)"
+  rm -f ${test_out}
+
+pamaddnoise -type impulse -salt=-0.10 testgrid.pbm > ${test_out} || \
+  printf "Expected failure 35 "
+  test -s ${test_out} && echo "unexpected output" || echo "(no output)"
+  rm -f ${test_out}
+
+pamaddnoise -type impulse -salt=+1.10 testgrid.pbm > ${test_out} || \
+  printf "Expected failure 36 "
+  test -s ${test_out} && echo "unexpected output" || echo "(no output)"
+  rm -f ${test_out}
+
+pamaddnoise -type impulse -lambda=12.0 testgrid.pbm > ${test_out} || \
+  printf "Expected failure 37 "
+  test -s ${test_out} && echo "unexpected output" || echo "(no output)"
+  rm -f ${test_out}
+
+# type poisson
+
+pamaddnoise -type poisson -sigma1=4.0 testgrid.pbm > ${test_out} || \
+  printf "Expected failure 38 "
+  test -s ${test_out} && echo "unexpected output" || echo "(no output)"
+  rm -f ${test_out}
+
+pamaddnoise -type poisson -sigma2=20.0 testgrid.pbm > ${test_out} || \
+  printf "Expected failure 39 "
+  test -s ${test_out} && echo "unexpected output" || echo "(no output)"
+  rm -f ${test_out}
+
+pamaddnoise -type poisson -mgsigma=0.5 testgrid.pbm > ${test_out} || \
+  printf "Expected failure 40 "
+  test -s ${test_out} && echo "unexpected output" || echo "(no output)"
+  rm -f ${test_out}
+
+pamaddnoise -type poisson -lsigma=10.0 testgrid.pbm > ${test_out} || \
+  printf "Expected failure 41 "
+  test -s ${test_out} && echo "unexpected output" || echo "(no output)"
+  rm -f ${test_out}
+
+pamaddnoise -type poisson -tolerance=0.10 testgrid.pbm > ${test_out} || \
+  printf "Expected failure 42 "
+  test -s ${test_out} && echo "unexpected output" || echo "(no output)"
+  rm -f ${test_out}
+
+pamaddnoise -type poisson -salt=0.50 testgrid.pbm > ${test_out} || \
+  printf "Expected failure 43 "
+  test -s ${test_out} && echo "unexpected output" || echo "(no output)"
+  rm -f ${test_out}
+
+pamaddnoise -type poisson -lambda=0 testgrid.pbm > ${test_out} || \
+  printf "Expected failure 44 "
+  test -s ${test_out} && echo "unexpected output" || echo "(no output)"
+  rm -f ${test_out}
+
+# Missing or invalid numerical parameters
+
+pamaddnoise -sigma1 testgrid.pbm > ${test_out} || \
+  printf "Expected failure 45 "
+  test -s ${test_out} && echo "unexpected output" || echo "(no output)"
+  rm -f ${test_out}
+
+pamaddnoise -sigma1 Z testgrid.pbm > ${test_out} || \
+  printf "Expected failure 46 "
+  test -s ${test_out} && echo "unexpected output" || echo "(no output)"
+  rm -f ${test_out}
+
+pamaddnoise -type gaussian -sigma2 testgrid.pbm > ${test_out} || \
+  printf "Expected failure 47 "
+  test -s ${test_out} && echo "unexpected output" || echo "(no output)"
+  rm -f ${test_out}
+
+pamaddnoise -type gaussian -sigma2 sigma testgrid.pbm > ${test_out} || \
+  printf "Expected failure 48 "
+  test -s ${test_out} && echo "unexpected output" || echo "(no output)"
+  rm -f ${test_out}
+
+pamaddnoise -type mult -mgsigma testgrid.pbm > ${test_out} || \
+  printf "Expected failure 49 "
+  test -s ${test_out} && echo "unexpected output" || echo "(no output)"
+  rm -f ${test_out}
+
+pamaddnoise -type mult -mgsigma 10,0 testgrid.pbm > ${test_out} || \
+  printf "Expected failure 50 "
+  test -s ${test_out} && echo "unexpected output" || echo "(no output)"
+  rm -f ${test_out}
+
+pamaddnoise -type lapl -lsigma 1..0 testgrid.pbm > ${test_out} || \
+  printf "Expected failure 51 "
+  test -s ${test_out} && echo "unexpected output" || echo "(no output)"
+  rm -f ${test_out}
+
+pamaddnoise -type lapl -lsigma lsigma testgrid.pbm > ${test_out} || \
+  printf "Expected failure 52 "
+  test -s ${test_out} && echo "unexpected output" || echo "(no output)"
+  rm -f ${test_out}
+
+pamaddnoise -type impul -tolerance testgrid.pbm > ${test_out} || \
+  printf "Expected failure 53 "
+  test -s ${test_out} && echo "unexpected output" || echo "(no output)"
+  rm -f ${test_out}
+
+pamaddnoise -type impul -tolerance t testgrid.pbm > ${test_out} || \
+  printf "Expected failure 54 "
+  test -s ${test_out} && echo "unexpected output" || echo "(no output)"
+  rm -f ${test_out}
+
+pamaddnoise -type impul -salt testgrid.pbm > ${test_out} || \
+  printf "Expected failure 55 "
+  test -s ${test_out} && echo "unexpected output" || echo "(no output)"
+  rm -f ${test_out}
+
+pamaddnoise -type impul -salt pepper testgrid.pbm > ${test_out} || \
+  printf "Expected failure 56 "
+  test -s ${test_out} && echo "unexpected output" || echo "(no output)"
+  rm -f ${test_out}
+
+pamaddnoise -type pois -lambda testgrid.pbm > ${test_out} || \
+  printf "Expected failure 57 "
+  test -s ${test_out} && echo "unexpected output" || echo "(no output)"
+  rm -f ${test_out}
+
+pamaddnoise -type pois -lambda L testgrid.pbm > ${test_out} || \
+  printf "Expected failure 58 "
+  test -s ${test_out} && echo "unexpected output" || echo "(no output)"
+  rm -f ${test_out}
+
+pamaddnoise -seed -1 testgrid.pbm > ${test_out} || \
+  printf "Expected failure 59 "
+  test -s ${test_out} && echo "unexpected output" || echo "(no output)"
+  rm -f ${test_out}
+
+pamaddnoise -seed random testgrid.pbm > ${test_out} || \
+  printf "Expected failure 60 "
+  test -s ${test_out} && echo "unexpected output" || echo "(no output)"
+  rm -f ${test_out}
+
+  
+# no type specified
+
+pamaddnoise -type testgrid.pbm > ${test_out} || \
+  printf "Expected failure 61 "
+  test -s ${test_out} && echo "unexpected output" || echo "(no output)"
+  rm -f ${test_out}
diff --git a/test/pamarith-compare-equal.ok b/test/pamarith-compare-equal.ok
index ef1c2981..d6b1f624 100644
--- a/test/pamarith-compare-equal.ok
+++ b/test/pamarith-compare-equal.ok
@@ -6,6 +6,17 @@ Test 1
 1:P3
 1:8 8
 1:2
+1:1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 2 0 0 0 2 2 2 0 0 
+1:1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 2 2 2 0 0 0 2 2 
+1:1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 2 0 0 0 2 2 2 0 0 
+1:1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 2 2 2 0 0 0 2 2 
+1:1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 2 0 0 0 2 2 2 0 0 
+1:0 2 2 2 0 0 0 2 2 2 0 0 0 2 2 1 1 1 1 1 1 1 1 1 
+1:2 0 0 0 2 2 2 0 0 0 2 2 2 0 0 1 1 1 1 1 1 1 1 1 
+1:0 2 2 2 0 0 0 2 2 2 0 0 0 2 2 1 1 1 1 1 1 1 1 1 
+1:P3
+1:8 8
+1:2
 5:0 0 2 0 0 2 0 0 2 0 0 2 0 0 2 2 0 2 2 0 2 2 0 2 
 3:2 0 2 2 0 2 2 0 2 2 0 2 2 0 2 2 0 0 2 0 0 2 0 0 
 Test 2
@@ -16,14 +27,19 @@ Test 2
 1:P3
 1:8 8
 1:1
+5:1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 0 0 0 0 0 0 0 0 
+3:0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 
+1:P3
+1:8 8
+1:1
 8:0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 
 Test 3
 1:P1
-1:14 16
-16:00000000000000
+1:35 33
+33:00000000000000000000000000000000000
 1:P1
-1:14 16
-16:11111111111111
+1:35 33
+33:11111111111111111111111111111111111
 1:P1
 1:14 16
 8:10101010101010 11111111111111
@@ -32,9 +48,9 @@ Test 3
 8:01010101010101 00000000000000
 Test 4
 1:P2
-1:14 16
+1:35 33
 1:2
-16:1 1 1 1 1 1 1 1 1 1 1 1 1 1 
+33:1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 
 1:P2
 1:14 16
 1:2
@@ -48,11 +64,11 @@ Test 4
 1:2
 8:1 2 1 2 1 2 1 2 1 2 1 2 1 2  1 1 1 1 1 1 1 1 1 1 1 1 1 1 
 Test 5
-Should produce 1285449498 54
+Should produce 1285449498 54 four times
 1285449498 54
 1285449498 54
 1285449498 54
 1285449498 54
-Should produce 244506188 54
+Should produce 244506188 54 twice
 244506188 54
 244506188 54
diff --git a/test/pamarith-compare-equal.test b/test/pamarith-compare-equal.test
index 903ad538..7d1062b7 100755
--- a/test/pamarith-compare-equal.test
+++ b/test/pamarith-compare-equal.test
@@ -1,20 +1,25 @@
-#! /bin/bash
+#! /bin/sh
 # This script tests: pamarith
-# Also requires: ppmpat pnminvert pbmmake pgmmake
+# Also requires: ppmpat pnminvert pamfile pbmmake pgmmake pamcut
 
 tmpdir=${tmpdir:-/tmp}
 input1_ppm=${tmpdir}/input1.ppm
+inputm_ppm=${tmpdir}/inputm.ppm
 input2_ppm=${tmpdir}/input2.ppm
 
 echo "Test 1"
 
 ppmpat -tartan -color=rgb:00/80/ff,rgb:80/ff/00,rgb:ff/00/80 \
    8 8  > ${input1_ppm}
+ppmpat -tartan -color=rgb:00/80/ff,rgb:80/ff/00,rgb:ff/00/80 \
+   -mesh 8 8  > ${inputm_ppm}
 ppmpat -tartan -color=rgb:80/ff/00,rgb:ff/00/80,rgb:00/80/ff \
    8 8  > ${input2_ppm}
 
 pamarith -compare -plain ${input1_ppm} ${input1_ppm} | \
   uniq -c | sed -e 's/^ *//' -e 's/ /:/'
+pamarith -compare -plain ${input1_ppm} ${inputm_ppm} | \
+  uniq -c | sed -e 's/^ *//' -e 's/ /:/'
 pamarith -compare -plain ${input1_ppm} ${input2_ppm} | \
   uniq -c | sed -e 's/^ *//' -e 's/ /:/'
 
@@ -22,54 +27,66 @@ echo "Test 2"
 
 pamarith -equal -plain ${input1_ppm} ${input1_ppm} | \
   uniq -c | sed -e 's/^ *//' -e 's/ /:/'
+pamarith -equal -plain ${input1_ppm} ${inputm_ppm} | \
+  uniq -c | sed -e 's/^ *//' -e 's/ /:/'
 pamarith -equal -plain ${input1_ppm} ${input2_ppm} | \
   uniq -c | sed -e 's/^ *//' -e 's/ /:/'
 
-rm ${input1_ppm} ${input2_ppm}
+rm ${input1_ppm} ${inputm_ppm} ${input2_ppm}
 
 echo "Test 3"
 
-pamarith -equal -plain testgrid.pbm testgrid.pbm  | \
+input3_pbm=${tmpdir}/input3.pbm
+pamcut maze.pbm -left=0 -top=0 -width=35 -height=33 > ${input3_pbm} 
+
+pamarith -equal -plain ${input3_pbm} ${input3_pbm}  | \
   uniq -c | sed -e 's/^ *//' -e 's/ /:/'
-pnminvert testgrid.pbm | pamarith -equal -plain testgrid.pbm - | \
+pnminvert ${input3_pbm} | pamarith -equal -plain ${input3_pbm} - | \
   uniq -c | sed -e 's/^ *//' -e 's/ /:/'
-pbmmake -w 14 16 | pamarith -equal -plain testgrid.pbm - | \
+
+xysize=$(pamfile -size testgrid.pbm)
+
+pbmmake -w ${xysize} | pamarith -equal -plain testgrid.pbm - | \
   awk '{printf("%s%c",$0, NR<3 || NR%2==0 ? "\n" : " ")}' | 
   uniq -c | sed -e 's/^ *//' -e 's/ /:/'
-pbmmake -b 14 16 | pamarith -equal -plain testgrid.pbm - | \
+pbmmake -b ${xysize} | pamarith -equal -plain testgrid.pbm - | \
   awk '{printf("%s%c",$0, NR<3 || NR%2==0 ? "\n" : " ")}' | 
   uniq -c | sed -e 's/^ *//' -e 's/ /:/'
 
 echo "Test 4"
-  
-pamarith -compare -plain testgrid.pbm testgrid.pbm  | \
+
+
+pamarith -compare -plain ${input3_pbm} ${input3_pbm}  | \
   uniq -c | sed -e 's/^ *//' -e 's/ /:/'
+
 pnminvert testgrid.pbm | pamarith -compare -plain testgrid.pbm - | \
   awk '{printf("%s%c",$0, NR<4 || NR%2==1 ? "\n" : " ")}' | 
   uniq -c | sed -e 's/^ *//' -e 's/ /:/'
-pbmmake -w 14 16 | pamarith -compare -plain testgrid.pbm - | \
+pbmmake -w ${xysize} | pamarith -compare -plain testgrid.pbm - | \
   awk '{printf("%s%c",$0, NR<4 || NR%2==1 ? "\n" : " ")}' | 
   uniq -c | sed -e 's/^ *//' -e 's/ /:/'
-pbmmake -b 14 16 | pamarith -compare -plain testgrid.pbm - | \
+pbmmake -b ${xysize} | pamarith -compare -plain testgrid.pbm - | \
   awk '{printf("%s%c",$0, NR<4 || NR%2==1 ? "\n" : " ")}' | 
   uniq -c | sed -e 's/^ *//' -e 's/ /:/'
 
+rm ${input3_pbm}
 
 echo "Test 5"
 # -closeness
 
 input40_pgm=${tmpdir}/input40.pgm
 input50_pgm=${tmpdir}/input50.pgm
-equal_pgm=${tmpdir}/equal.pgm
 
 pgmmake -maxval=99 0.40 7 3 > ${input40_pgm}
 pgmmake -maxval=99 0.50 7 3 > ${input50_pgm}
 
-echo "Should produce 1285449498 54"
+echo "Should produce 1285449498 54 four times"
 pamarith -equal -plain ${input40_pgm} ${input40_pgm} | cksum
 pamarith -equal -plain -closeness=10.2 ${input40_pgm} ${input50_pgm} | cksum
 pamarith -equal -plain -closeness=11 ${input40_pgm} ${input50_pgm} | cksum
 pamarith -equal -plain -closeness=90 ${input40_pgm} ${input50_pgm} | cksum
-echo "Should produce 244506188 54"
+echo "Should produce 244506188 54 twice"
 pamarith -equal -plain ${input40_pgm} ${input50_pgm} | cksum
-pamarith -equal -plain -closeness=09   ${input40_pgm} ${input50_pgm} | cksum
+pamarith -equal -plain -closeness=09  ${input40_pgm} ${input50_pgm} | cksum
+
+rm ${input40_pgm} ${input50_pgm}
\ No newline at end of file
diff --git a/test/pamarith-multiple-input.test b/test/pamarith-multiple-input.test
index 7df08817..b9c09662 100755
--- a/test/pamarith-multiple-input.test
+++ b/test/pamarith-multiple-input.test
@@ -1,4 +1,4 @@
-#! /bin/bash
+#! /bin/sh
 # This script tests: pamarith
 # Also requires: pgmmake ppmpat pamfunc
 
@@ -14,7 +14,7 @@ pgmmake -maxval=99 0.01 16 11 > ${input1_pgm}
 
 add_command="pamarith -add "${input1_pgm}
 
-for ((i=1 ; i<10 ; i++ ))
+for i in 1 2 3 4 5 6 7 8 9 # for i in `seq 9`
   do
   echo ${i}":"
   add_command=${add_command}" "${input1_pgm}
@@ -58,4 +58,4 @@ for function in "-add" "-and" "-or" "-xor" "-nand" "-nor"
   pamarith ${function} ${g2_ppm} ${g3_ppm} ${g2_ppm} | cksum
   done
 
-rm ${g2_ppm} ${g3_ppm}
\ No newline at end of file
+rm ${g2_ppm} ${g3_ppm}
diff --git a/test/pamarith.ok b/test/pamarith.ok
index 0862df8e..a0942fb8 100644
--- a/test/pamarith.ok
+++ b/test/pamarith.ok
@@ -2,8 +2,8 @@ Test 1
 P2
 16 2
 15
-0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
-2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2
+0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 
+2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 
 -add
 P2 16 1 15 2 3 4 5 6 7 8 9 10 11 12 13 14 15 15 15  
 1927712885 59
@@ -193,19 +193,19 @@ Test 3
 3072492814 913
 3072492814 913
 Test 4 (input = output)
-cksum is 2425386270 41 or 2921940274 59
+Prints 281226646 481 six times, then 2921940274 59 six times
 input image
-2425386270 41
+281226646 481
 -minimum
-2425386270 41
+281226646 481
 -maximum
-2425386270 41
+281226646 481
 -mean
-2425386270 41
+281226646 481
 -and
-2425386270 41
+281226646 481
 -or
-2425386270 41
+281226646 481
 input image
 2921940274 59
 -minimum
@@ -219,13 +219,13 @@ input image
 -or
 2921940274 59
 Test 5 (blank output)
-cksum is 2817549367 41 or 320101399 59
+Prints 2247801875 481 three times, then 320101399 59 three times
 -subtract
-2817549367 41
+2247801875 481
 -difference
-2817549367 41
+2247801875 481
 -xor
-2817549367 41
+2247801875 481
 -subtract
 320101399 59
 -difference
@@ -233,45 +233,45 @@ cksum is 2817549367 41 or 320101399 59
 -xor
 320101399 59
 Test Invalid
-Expected failure 1 1
-Expected failure 2 1
-Expected failure 3 1
-Expected failure 4 1
-Expected failure 5 1
-Expected failure 6 1
-Expected failure 7 1
-Expected failure 8 1
-Expected failure 9 1
-Expected failure 10 1
-Expected failure 11 1
-Expected failure 12 1
-Expected failure 13 1
-Expected failure 14 1
-Expected failure 15 1
-Expected failure 16 1
-Expected failure 17 1
-Expected failure 18 1
-Expected failure 19 1
-Expected failure 20 1
-Expected failure 21 1
-Expected failure 22 1
-Expected failure 23 1
-Expected failure 24 1
-Expected failure 25 1
-Expected failure 26 1
-Expected failure 27 1
-Expected failure 28 1
-Expected failure 29 1
-Expected failure 30 1
-Expected failure 31 1
-Expected failure 32 1
-Expected failure 33 1
-Expected failure 34 1
-Expected failure 35 1
-Expected failure 36 1
-Expected failure 37 1
-Expected failure 38 1
-Expected failure 39 1
-Expected failure 40 1
-Expected failure 41 1
-Expected failure 42 1
+Expected failure 1 (no output)
+Expected failure 2 (no output)
+Expected failure 3 (no output)
+Expected failure 4 (no output)
+Expected failure 5 (no output)
+Expected failure 6 (no output)
+Expected failure 7 (no output)
+Expected failure 8 (no output)
+Expected failure 9 (no output)
+Expected failure 10 (no output)
+Expected failure 11 (no output)
+Expected failure 12 (no output)
+Expected failure 13 (no output)
+Expected failure 14 (no output)
+Expected failure 15 (no output)
+Expected failure 16 (no output)
+Expected failure 17 (no output)
+Expected failure 18 (no output)
+Expected failure 19 (no output)
+Expected failure 20 (no output)
+Expected failure 21 (no output)
+Expected failure 22 (no output)
+Expected failure 23 (no output)
+Expected failure 24 (no output)
+Expected failure 25 (no output)
+Expected failure 26 (no output)
+Expected failure 27 (no output)
+Expected failure 28 (no output)
+Expected failure 29 (no output)
+Expected failure 30 (no output)
+Expected failure 31 (no output)
+Expected failure 32 (no output)
+Expected failure 33 (no output)
+Expected failure 34 (no output)
+Expected failure 35 (no output)
+Expected failure 36 (no output)
+Expected failure 37 (no output)
+Expected failure 38 (no output)
+Expected failure 39 (no output)
+Expected failure 40 (no output)
+Expected failure 41 (no output)
+Expected failure 42 (no output)
diff --git a/test/pamarith.test b/test/pamarith.test
index a4c98859..20c4039d 100755
--- a/test/pamarith.test
+++ b/test/pamarith.test
@@ -1,7 +1,7 @@
-#! /bin/bash
+#! /bin/sh
 # This script tests: pamarith
-# Also requires: pamtopnm rgb3toppm pamenlarge pnmcat pamseq pbmmake pgmmake 
-# Also requires: ppmpat pamchannel 
+# Also requires: pamtopnm rgb3toppm pamenlarge pamcat pamseq pbmmake pgmmake
+# Also requires: ppmpat pamchannel
 
 tmpdir=${tmpdir:-/tmp}
 input1_pgm=${tmpdir}/input1.pgm
@@ -15,10 +15,10 @@ echo "Test 1"
 pamseq 1 15 | pamtopnm -assume > ${input1_pgm}
 pgmmake -maxval 15 0.15 16 1 > ${input2_pgm}
 
-rgb3toppm ${input1_pgm} ${input1_pgm} ${input1_pgm} > ${input1_ppm} 
-rgb3toppm ${input2_pgm} ${input2_pgm} ${input2_pgm} > ${input2_ppm} 
+rgb3toppm ${input1_pgm} ${input1_pgm} ${input1_pgm} > ${input1_ppm}
+rgb3toppm ${input2_pgm} ${input2_pgm} ${input2_pgm} > ${input2_ppm}
 
-pnmcat -tb -plain ${input1_pgm} ${input2_pgm}
+pamcat -tb ${input1_pgm} ${input2_pgm} -plain
 
 for fn in "-add" "-subtract" "-multiply" "-divide" "-difference" \
     "-minimum" "-maximum" "-mean" "-compare" "-equal" \
@@ -43,7 +43,7 @@ echo "Test 2 PBM"
 pbmmake -g 8 1 > ${input1_pbm}
 pbmmake -g 2 1 | pamenlarge -xscale=4 > ${input2_pbm}
 
-pnmcat -tb -plain ${input1_pbm} ${input2_pbm}
+pamcat -tb -plain ${input1_pbm} ${input2_pbm}
 
 for fn in "-add" "-subtract" "-multiply" "-divide" "-difference" \
     "-minimum" "-maximum" "-mean" "-compare" "-equal" \
@@ -88,12 +88,12 @@ for fn in "-subtract" "-divide" "-compare" "-shiftleft" "-shiftright"
 rm ${input3_ppm} ${input4_ppm} ${input4_pgm}
 
 echo "Test 4 (input = output)"
-echo "cksum is 2425386270 41 or 2921940274 59"
+echo "Prints 281226646 481 six times, then 2921940274 59 six times"
 
-for image in testgrid.pbm ${input1_ppm}
+for image in maze.pbm ${input1_ppm}
   do
   echo "input image"
-  cat ${image} | cksum 
+  cat ${image} | cksum
   for fn in "-minimum" "-maximum" "-mean" "-and" "-or"
     do
     echo ${fn}
@@ -103,9 +103,9 @@ for image in testgrid.pbm ${input1_ppm}
 
 
 echo "Test 5 (blank output)"
-echo "cksum is 2817549367 41 or 320101399 59"
+echo "Prints 2247801875 481 three times, then 320101399 59 three times"
 
-for image in testgrid.pbm ${input1_ppm}
+for image in maze.pbm ${input1_ppm}
   do
   for fn in "-subtract" "-difference" "-xor"
     do
@@ -116,112 +116,68 @@ for image in testgrid.pbm ${input1_ppm}
 
 rm ${input1_ppm}
 
-
-echo "Invalid command-line argument combinations." 1>&2
-echo "Error messages should appear below the line." 1>&2
-echo "-----------------------------------------------------------" 1>&2
-
 echo "Test Invalid"
 
-output_ppm=${tmpdir}/output.ppm
+. ${srcdir}/test-invalid.inc
 
 # multiple functions
 
-pamarith -add -subtract testimg.ppm testimg.ppm > ${output_ppm} || \
-  echo -n "Expected failure 1"
-  test -s ${output_ppm}; echo " "$?
-pamarith -multiply -divide testimg.ppm testimg.ppm > ${output_ppm} || \
-  echo -n "Expected failure 2"
-  test -s ${output_ppm}; echo " "$?
-pamarith -difference -minimum testimg.ppm testimg.ppm > ${output_ppm} || \
-  echo -n "Expected failure 3"
-  test -s ${output_ppm}; echo " "$?
-pamarith -maximum -mean testimg.ppm testimg.ppm > ${output_ppm} || \
-  echo -n "Expected failure 4"
-  test -s ${output_ppm}; echo " "$?
-pamarith -compare -and testimg.ppm testimg.ppm > ${output_ppm} || \
-  echo -n "Expected failure 5"
-  test -s ${output_ppm}; echo " "$?
-pamarith -compare -equal testimg.ppm testimg.ppm > ${output_ppm} || \
-  echo -n "Expected failure 6"
-  test -s ${output_ppm}; echo " "$?
-pamarith -or -nand testimg.ppm testimg.ppm > ${output_ppm} || \
-  echo -n "Expected failure 7"
-  test -s ${output_ppm}; echo " "$?
-pamarith -nor -xor testimg.ppm testimg.ppm > ${output_ppm} || \
-  echo -n "Expected failure 8"
-  test -s ${output_ppm}; echo " "$?
-pamarith -shiftleft -shiftright testimg.ppm testimg.ppm > ${output_ppm} || \
-  echo -n "Expected failure 9"
-  test -s ${output_ppm}; echo " "$?
+invCmd "pamarith -add -subtract testimg.ppm testimg.ppm"
+invCmd "pamarith -multiply -divide testimg.ppm testimg.ppm"
+invCmd "pamarith -difference -minimum testimg.ppm testimg.ppm"
+invCmd "pamarith -maximum -mean testimg.ppm testimg.ppm"
+invCmd "pamarith -compare -and testimg.ppm testimg.ppm"
+invCmd "pamarith -compare -equal testimg.ppm testimg.ppm"
+invCmd "pamarith -or -nand testimg.ppm testimg.ppm"
+invCmd "pamarith -nor -xor testimg.ppm testimg.ppm"
+invCmd "pamarith -shiftleft -shiftright testimg.ppm testimg.ppm"
 
 # -add does not take a value
 
-pamarith -add=1 testimg.ppm testimg.ppm > ${output_ppm} || \
-  echo -n "Expected failure 10"
- test -s ${output_ppm}; echo " "$?
+invCmd "pamarith -add=1 testimg.ppm testimg.ppm"
 
 # No function
 
-pamarith -plain testimg.ppm testimg.ppm > ${output_ppm} || \
-  echo -n "Expected failure 11"
-  test -s ${output_ppm}; echo " "$?
-
-pamarith testimg.ppm testimg.ppm > ${output_ppm} || \
-  echo -n "Expected failure 12"
-  test -s ${output_ppm}; echo " "$?
+invCmd "pamarith -plain testimg.ppm testimg.ppm"
+invCmd "pamarith testimg.ppm testimg.ppm"
 
 # Just one input image file
 
-pamarith -add testimg.ppm > ${output_ppm} || \
-  echo -n "Expected failure 13"
-  test -s ${output_ppm}; echo " "$?
+invCmd "pamarith -add testimg.ppm"
 
 # No input image file
 
-pamarith -add > ${output_ppm} || \
-  echo -n "Expected failure 14"
-  test -s ${output_ppm}; echo " "$?
+invCmd "pamarith -add"
 
 # Input images with different depth (number of planes)
 
-pamchannel -infile testimg.ppm 0 1 | \
-  pamarith -add testimg.ppm - > ${output_ppm} || \
-  echo -n "Expected failure 15"
-  test -s ${output_ppm}; echo " "$?
+input1_pam=${tmpdir}/input1.pam
 
+pamchannel -infile testimg.ppm 0 1 > ${input1_pam}
+invCmd "pamarith -add testimg.ppm ${input1_pam}"
+rm ${input1_pam}
 
 # Input images with different x/y dimensions
 
-pamarith -add testimg.ppm testgrid.pbm > ${output_ppm} || \
-  echo -n "Expected failure 16"
-  test -s ${output_ppm}; echo " "$?
+invCmd "pamarith -add testimg.ppm testgrid.pbm"
 
-pamenlarge -xscale=2 testgrid.pbm | \
-  pamarith -add testgrid.pbm - > ${output_ppm} || \
-  echo -n "Expected failure 17"
-  test -s ${output_ppm}; echo " "$?
+input1_pbm=${tmpdir}/input1.pbm
+input2_pbm=${tmpdir}/input2.pbm
 
-pamenlarge -yscale=3 testgrid.pbm | \
-  pamarith -add testgrid.pbm - > ${output_ppm} || \
-  echo -n "Expected failure 18"
-  test -s ${output_ppm}; echo " "$?
+pamenlarge -xscale=2 testgrid.pbm > ${input1_pbm}
+invCmd "pamarith -add testgrid.pbm ${input1_pbm}"
+rm ${input1_pbm}
 
+pamenlarge -yscale=3 testgrid.pbm > ${input2_pbm}
+invCmd "pamarith -add testgrid.pbm ${input2_pbm}"
+rm ${input2_pbm}
 
 # Invalid usage of -closeness
 
-pamarith -equal -closeness=100.1 testgrid.pbm > ${output_ppm} || \
-  echo -n "Expected failure 19"
-  test -s ${output_ppm}; echo " "$?
-pamarith -equal -closeness=-10 testgrid.pbm > ${output_ppm} || \
-  echo -n "Expected failure 20"
-  test -s ${output_ppm}; echo " "$?
-pamarith -closeness -equal testgrid.pbm > ${output_ppm} || \
-  echo -n "Expected failure 21"
-  test -s ${output_ppm}; echo " "$?
-pamarith -compare -closeness=10 testgrid.pbm > ${output_ppm} || \
-  echo -n "Expected failure 22"
-  test -s ${output_ppm}; echo " "$?
+invCmd "pamarith -equal -closeness=100.1 testgrid.pbm"
+invCmd "pamarith -equal -closeness=-10 testgrid.pbm"
+invCmd "pamarith -closeness -equal testgrid.pbm"
+invCmd "pamarith -compare -closeness=10 testgrid.pbm"
 
 # Bit string functions
 # Create PGM test input
@@ -230,52 +186,27 @@ input3_pgm=${tmpdir}/input3.pgm
 input4_pgm=${tmpdir}/input4.pgm
 input5_pgm=${tmpdir}/input5.pgm
 
-pgmmake -maxval=4095 1.0 3 1 > ${input3_pgm} 
+pgmmake -maxval=4095 1.0 3 1 > ${input3_pgm}
 pgmmake -maxval=4096 1.0 3 1 > ${input4_pgm}
 pgmmake -maxval=8191 1.0 3 1 > ${input5_pgm}
 
 # Bit string functions - Maxval must match
 
-pamarith -and ${input3_pgm} ${input5_pgm} > ${output_ppm} || \
-  echo -n "Expected failure 23"
-  test -s ${output_ppm}; echo " "$?
-pamarith -or ${input3_pgm} ${input5_pgm} > ${output_ppm} || \
-  echo -n "Expected failure 24"
-  test -s ${output_ppm}; echo " "$?
-pamarith -nand ${input3_pgm} ${input5_pgm} > ${output_ppm} || \
-  echo -n "Expected failure 25"
-  test -s ${output_ppm}; echo " "$?
-pamarith -nor ${input3_pgm} ${input5_pgm} > ${output_ppm} || \
-  echo -n "Expected failure 26"
-  test -s ${output_ppm}; echo " "$?
-pamarith -xor ${input3_pgm} ${input5_pgm} > ${output_ppm} || \
-  echo -n "Expected failure 27"
-  test -s ${output_ppm}; echo " "$?
+invCmd "pamarith -and ${input3_pgm} ${input5_pgm}"
+invCmd "pamarith -or ${input3_pgm} ${input5_pgm}"
+invCmd "pamarith -nand ${input3_pgm} ${input5_pgm}"
+invCmd "pamarith -nor ${input3_pgm} ${input5_pgm}"
+invCmd "pamarith -xor ${input3_pgm} ${input5_pgm}"
 
 # Bit string functions - Maxval must be 2^n -1
 
-pamarith -and ${input4_pgm} ${input4_pgm} > ${output_ppm} || \
-  echo -n "Expected failure 28"
-  test -s ${output_ppm}; echo " "$?
-pamarith -or ${input4_pgm} ${input4_pgm} > ${output_ppm} || \
-  echo -n "Expected failure 29"
-  test -s ${output_ppm}; echo " "$?
-pamarith -nand ${input4_pgm} ${input4_pgm} > ${output_ppm} || \
-  echo -n "Expected failure 30"
-  test -s ${output_ppm}; echo " "$?
-pamarith -nor ${input4_pgm} ${input4_pgm} > ${output_ppm} || \
-  echo -n "Expected failure 31"
-  test -s ${output_ppm}; echo " "$?
-pamarith -xor ${input4_pgm} ${input4_pgm} > ${output_ppm} || \
-  echo -n "Expected failure 32"
-  test -s ${output_ppm}; echo " "$?
-
-pamarith -shiftleft ${input4_pgm} ${input4_pgm} > ${output_ppm} || \
-  echo -n "Expected failure 33"
-  test -s ${output_ppm}; echo " "$?
-pamarith -shiftright ${input4_pgm} ${input4_pgm} > ${output_ppm} || \
-  echo -n "Expected failure 34"
-  test -s ${output_ppm}; echo " "$?
+invCmd "pamarith -and ${input4_pgm} ${input4_pgm}"
+invCmd "pamarith -or ${input4_pgm} ${input4_pgm}"
+invCmd "pamarith -nand ${input4_pgm} ${input4_pgm}"
+invCmd "pamarith -nor ${input4_pgm} ${input4_pgm}"
+invCmd "pamarith -xor ${input4_pgm} ${input4_pgm}"
+invCmd "pamarith -shiftleft ${input4_pgm} ${input4_pgm}"
+invCmd "pamarith -shiftright ${input4_pgm} ${input4_pgm}"
 
 rm ${input3_pgm} ${input4_pgm} ${input5_pgm}
 
@@ -283,33 +214,15 @@ rm ${input3_pgm} ${input4_pgm} ${input5_pgm}
 # Only the functions that are commutative and associative allow
 # three or more inputs.
 
-pamarith -subtract testimg.ppm testimg.ppm testimg.ppm > ${output_ppm} || \
-  echo -n "Expected failure 35"
-  test -s ${output_ppm}; echo " "$?
-pamarith -divide testimg.ppm testimg.ppm testimg.ppm > ${output_ppm} || \
-  echo -n "Expected failure 36"
-  test -s ${output_ppm}; echo " "$?
-pamarith -compare testimg.ppm testimg.ppm testimg.ppm > ${output_ppm} || \
-  echo -n "Expected failure 37"
-  test -s ${output_ppm}; echo " "$?
-pamarith -difference testimg.ppm testimg.ppm testimg.ppm > ${output_ppm} || \
-  echo -n "Expected failure 38"
-  test -s ${output_ppm}; echo " "$?
-pamarith -shiftleft testimg.ppm testimg.ppm testimg.ppm > ${output_ppm} || \
-  echo -n "Expected failure 39"
-  test -s ${output_ppm}; echo " "$?
-pamarith -shiftright testimg.ppm testimg.ppm testimg.ppm > ${output_ppm} || \
-  echo -n "Expected failure 40"
-  test -s ${output_ppm}; echo " "$?
+invCmd "pamarith -subtract testimg.ppm testimg.ppm testimg.ppm"
+invCmd "pamarith -divide testimg.ppm testimg.ppm testimg.ppm"
+invCmd "pamarith -compare testimg.ppm testimg.ppm testimg.ppm"
+invCmd "pamarith -difference testimg.ppm testimg.ppm testimg.ppm"
+invCmd "pamarith -shiftleft testimg.ppm testimg.ppm testimg.ppm"
+invCmd "pamarith -shiftright testimg.ppm testimg.ppm testimg.ppm"
 
 # Currently -equal and -mean do not allow more than two input images.
 # These two cases should be removed once improvements are made.
 
-pamarith -equal testgrid.pbm testgrid.pbm testgrid.pbm > ${output_ppm} || \
-  echo -n "Expected failure 41"
-  test -s ${output_ppm}; echo " "$?
-pamarith -mean testgrid.pbm  testgrid.pbm testgrid.pbm > ${output_ppm} || \
-  echo -n "Expected failure 42"
-  test -s ${output_ppm}; echo " "$?
-
-rm ${output_ppm}
+invCmd "pamarith -equal testgrid.pbm testgrid.pbm testgrid.pbm"
+invCmd "pamarith -mean testgrid.pbm  testgrid.pbm testgrid.pbm"
diff --git a/test/pambackground.test b/test/pambackground.test
index 522f4823..eca9cc93 100755
--- a/test/pambackground.test
+++ b/test/pambackground.test
@@ -1,4 +1,4 @@
-#! /bin/bash
+#! /bin/sh
 # This script tests: pambackground
 # Also requires: pamgradient pamseq pbmmake pnmmargin pnmremap pnmtile pnmpad
 
diff --git a/test/pambrighten.ok b/test/pambrighten.ok
index 6c58b4c9..8dc9e71e 100644
--- a/test/pambrighten.ok
+++ b/test/pambrighten.ok
@@ -78,19 +78,11 @@ Test 4: Should print 3990234518 268 six times
 3990234518 268
 3990234518 268
 3990234518 268
-Test Error: Should print 1 six times
-1
-1
-1
-1
-1
-1
-Test Error: Should print 99 followed by 1, four times
-99
-1
-99
-1
-99
-1
-99
-1
+Test Invalid
+Expected failure 1 (no output)
+Expected failure 2 (no output)
+Expected failure 3 (no output)
+Expected failure 4 (no output)
+Expected failure 5 (no output)
+Expected failure 6 (no output)
+Expected failure 7 (no output)
diff --git a/test/pambrighten.test b/test/pambrighten.test
index 3e1a3eb1..d79ad583 100755
--- a/test/pambrighten.test
+++ b/test/pambrighten.test
@@ -1,4 +1,4 @@
-#! /bin/bash
+#! /bin/sh
 # This script tests: pambrighten
 # Also requires: pgmramp
 
@@ -10,7 +10,7 @@ cat > ${input_ppm} << EOF
 P3
 8 1
 255
-0 0 0 0 0 100 0 100 0 0 100 100 100 0 0 100 0 100 100 100 0 100 100 100 
+0 0 0 0 0 100 0 100 0 0 100 100 100 0 0 100 0 100 100 100 0 100 100 100
 EOF
 
 # Test 1
@@ -50,50 +50,14 @@ pambrighten -s +200 ${input_pgm} | cksum
 
 rm ${input_pgm}
 
+echo "Test Invalid"
 
-# Test 2
-# These should all fail.
+. ${srcdir}/test-invalid.inc
 
-echo "Invalid command-line argument combinations." 1>&2
-echo "Error messages should appear below the line." 1>&2
-echo "-----------------------------------------------------------" 1>&2
-
-echo "Test Error: Should print 1 six times"
-
-output_ppm=${tmpdir}/output.ppm
-
-pambrighten -v -120 testimg.ppm > ${output_ppm}
-echo $?
-test -s ${output_ppm}
-echo $?
-pambrighten -s -120 testimg.ppm > ${output_ppm}
-echo $?
-test -s ${output_ppm}
-echo $?
-pambrighten 10 testimg.ppm > ${output_ppm}
-echo $?
-test -s ${output_ppm}
-echo $?
-
-
-echo "Test Error: Should print 99 followed by 1, four times"
-
-pambrighten -s 1.20 testimg.ppm > ${output_ppm}
-echo $?
-test -s ${output_ppm}
-echo $?
-pambrighten -v 10.5 testimg.ppm > ${output_ppm}
-echo $?
-test -s ${output_ppm}
-echo $?
-pambrighten -v testimg.ppm > ${output_ppm}
-echo $?
-test -s ${output_ppm}
-echo $?
-pambrighten -s testimg.ppm > ${output_ppm}
-echo $?
-test -s ${output_ppm}
-echo $?
-
-
-rm -f ${output_ppm}
+invCmd "pambrighten -v -120 testimg.ppm"
+invCmd "pambrighten -s -120 testimg.ppm"
+invCmd "pambrighten 10 testimg.ppm"
+invCmd "pambrighten -s 1.20 testimg.ppm"
+invCmd "pambrighten -v 10.5 testimg.ppm"
+invCmd "pambrighten -v testimg.ppm"
+invCmd "pambrighten -s testimg.ppm"
diff --git a/test/pamcat1.ok b/test/pamcat1.ok
new file mode 100644
index 00000000..630b635f
--- /dev/null
+++ b/test/pamcat1.ok
@@ -0,0 +1,150 @@
+Test 1.  Should print 15135078 29, then 0 fourteen times
+15135078 29
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+Test 2.  Should print 1957849403 59, 0 six times, 1 once
+1957849403 59
+0
+0
+0
+0
+0
+0
+1
+Test 3.  Should print 2673197404 69, 0 six times, 1 once
+2673197404 69
+0
+0
+0
+0
+0
+0
+1
+Test 4.  Should print 2285402562 36, then 0 twelve times
+2285402562 36
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+Test 5.  Should print 1836757613 62, 0 six times, 1 once
+1836757613 62
+0
+0
+0
+0
+0
+0
+1
+Test 6.  Should print 3601245348 137, 0 six times, 1 once
+3601245348 137
+0
+0
+0
+0
+0
+0
+1
+Test 7.  Should print 1572996771 71, then 0 twelve times
+1572996771 71
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+Test 8.  Should print 270413826 252, 0 six times, 1 once
+270413826 252
+0
+0
+0
+0
+0
+0
+1
+Test 9.  Should print 2942772630 192, 0 six times, 1 once
+2942772630 192
+0
+0
+0
+0
+0
+0
+1
+Test 10.  Should print 2700536985 95, then 0 twelve times
+2700536985 95
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+Test 11.  Should print 2193235886 195, 0 eight times, 1 once
+2193235886 195
+0
+0
+0
+0
+0
+0
+0
+0
+1
+Test 12.  Should print 2773166369 245, 0 nine times, 1 once
+2773166369 245
+0
+0
+0
+0
+0
+0
+0
+0
+0
+1
+Test Invalid
+Expected failure 1 (no output)
+Expected failure 2 (no output)
+Expected failure 3 (no output)
+Expected failure 4 (no output)
+Expected failure 5 (no output)
+Expected failure 6 (no output)
+Expected failure 7 (no output)
+Expected failure 8 (no output)
+Expected failure 9 (no output)
+Expected failure 10 (no output)
+Expected failure 11 (no output)
+Expected failure 12 (no output)
+Expected failure 13 (no output)
+Expected failure 14 (no output)
diff --git a/test/pamcat1.test b/test/pamcat1.test
new file mode 100755
index 00000000..9480228c
--- /dev/null
+++ b/test/pamcat1.test
@@ -0,0 +1,215 @@
+#! /bin/sh
+# This script tests: pamcat
+# Also requires: pbmmake pgmmake ppmmake pamseq pamrestack
+
+tmpdir=${tmpdir:-/tmp}
+check10x10_pbm=${tmpdir}/check10x10.pbm
+check40x10_pbm=${tmpdir}/check40x10.pbm
+check10x30_pbm=${tmpdir}/check10x30.pbm
+
+gray5x5_pgm=${tmpdir}/gray5x5.pgm
+gray10x5_pgm=${tmpdir}/gray10x5.pgm
+gray5x25_pgm=${tmpdir}/gray5x25.pgm
+
+yellow4x5_ppm=${tmpdir}/yellow4x5.ppm
+yellow16x5_ppm=${tmpdir}/yellow16x5.ppm
+yellow4x15_ppm=${tmpdir}/yellow4x15.ppm
+
+seq2_4h_pam=${tmpdir}/seq2_4h.pam
+seq2_4h4_pam=${tmpdir}/seq2_4h4.pam
+seq2_4v_pam=${tmpdir}/seq2_4v.pam
+seq2_4v3_pam=${tmpdir}/seq2_4v3.pam
+
+
+echo "Test 1.  Should print 15135078 29, then 0 fourteen times"
+
+pbmmake -g 10 10 | tee ${check10x10_pbm} | cksum
+for opt in "-leftright" "-lr" "-lr -jtop" "-lr -jcenter" "-lr -jbottom" \
+    "-lr -white" "-lr -black" \
+    "-topbottom" "-tb" "-tb -jleft"  "-tb -jcenter" "-tb --jright" \
+    "-tb -white" "-tb -black"
+  do
+  pamcat ${opt} ${check10x10_pbm} | cmp -s ${check10x10_pbm} - ; echo $?
+  done
+
+
+echo "Test 2.  Should print 1957849403 59, 0 six times, 1 once"
+pbmmake -g 40 10 | tee ${check40x10_pbm} | cksum
+for opt in "-leftright" "-lr -jtop" "-lr -jcenter" "-lr -jbottom" \
+    "-lr -white" "-lr -black" \
+    "-tb"
+  do
+  pamcat ${opt} ${check10x10_pbm} ${check10x10_pbm} \
+         ${check10x10_pbm} ${check10x10_pbm} | \
+  cmp -s ${check40x10_pbm} - ; echo $?
+  done
+
+
+echo "Test 3.  Should print 2673197404 69, 0 six times, 1 once"
+pbmmake -g 10 30 | tee ${check10x30_pbm} | cksum
+for opt in "-topbottom" "-tb -jleft"  "-tb -jcenter" "-tb --jright" \
+    "-tb -white" "-tb -black" \
+    "-lr"
+  do
+  pamcat ${opt} ${check10x10_pbm} ${check10x10_pbm} ${check10x10_pbm} |\
+  cmp -s ${check10x30_pbm} - ; echo $? 	
+  done
+
+rm ${check10x10_pbm} ${check40x10_pbm} ${check10x30_pbm}
+
+
+echo "Test 4.  Should print 2285402562 36, then 0 twelve times"
+
+pgmmake 0.125 5 5 | tee ${gray5x5_pgm} | cksum
+for opt in "-leftright" "-lr -jtop" "-lr -jcenter" "-lr -jbottom" \
+    "-lr -white" "-lr -black" \
+    "-topbottom" "-tb -jleft"  "-tb -jcenter" "-tb --jright" \
+    "-tb -white" "-tb -black"
+  do
+  pamcat ${opt} ${gray5x5_pgm} | cmp -s ${gray5x5_pgm} - ; echo $?
+  done
+
+
+echo "Test 5.  Should print 1836757613 62, 0 six times, 1 once"
+pgmmake 0.125 10 5 | tee ${gray10x5_pgm} | cksum
+for opt in "-leftright" "-lr -jtop" "-lr -jcenter" "-lr -jbottom" \
+    "-lr -white" "-lr -black" \
+    "-tb"
+  do
+  pamcat ${opt} ${gray5x5_pgm} ${gray5x5_pgm} |\
+  cmp -s ${gray10x5_pgm} - ; echo $?
+  done
+
+
+echo "Test 6.  Should print 3601245348 137, 0 six times, 1 once"
+pgmmake 0.125 5 25 | tee ${gray5x25_pgm} | cksum
+for opt in "-topbottom" "-tb -jleft"  "-tb -jcenter" "-tb --jright" \
+    "-tb -white" "-tb -black" \
+    "-lr"
+  do
+  pamcat ${opt} ${gray5x5_pgm} ${gray5x5_pgm} ${gray5x5_pgm} \
+	 ${gray5x5_pgm} ${gray5x5_pgm} |\
+  cmp -s ${gray5x25_pgm} - ; echo $?
+  done
+
+
+rm ${gray5x5_pgm} ${gray10x5_pgm} ${gray5x25_pgm}
+
+
+echo "Test 7.  Should print 1572996771 71, then 0 twelve times"
+ppmmake rgb:255/255/1 4 5 | tee ${yellow4x5_ppm} | cksum
+for opt in "-leftright" "-lr -jtop" "-lr -jcenter" "-lr -jbottom" \
+    "-lr -white" "-lr -black" \
+    "-topbottom" "-tb -jleft"  "-tb -jcenter" "-tb --jright" \
+    "-tb -white" "-tb -black"
+  do
+  pamcat ${opt} ${yellow4x5_ppm} |\
+  cmp -s ${yellow4x5_ppm} - ; echo $?
+  done
+
+
+echo "Test 8.  Should print 270413826 252, 0 six times, 1 once"
+ppmmake rgb:255/255/1 16 5 | tee ${yellow16x5_ppm} | cksum
+for opt in "-leftright" "-lr -jtop" "-lr -jcenter" "-lr -jbottom" \
+    "-lr -white" "-lr -black" \
+    "-tb"
+  do
+  pamcat ${opt} ${yellow4x5_ppm} ${yellow4x5_ppm} \
+         ${yellow4x5_ppm} ${yellow4x5_ppm} |\
+  cmp -s ${yellow16x5_ppm} - ; echo $?
+  done
+
+
+echo "Test 9.  Should print 2942772630 192, 0 six times, 1 once"
+ppmmake rgb:255/255/1 4 15 | tee ${yellow4x15_ppm} | cksum
+for opt in "-topbottom" "-tb -jleft"  "-tb -jcenter" "-tb --jright" \
+    "-tb -white" "-tb -black" \
+    "-lr"
+  do
+  pamcat ${opt} ${yellow4x5_ppm} ${yellow4x5_ppm} ${yellow4x5_ppm} |\
+  cmp -s ${yellow4x15_ppm} - ; echo $?
+  done
+
+rm ${yellow4x5_ppm} ${yellow16x5_ppm} ${yellow4x15_ppm}
+
+
+echo "Test 10.  Should print 2700536985 95, then 0 twelve times"
+pamseq 2 4 | tee ${seq2_4h_pam} | cksum
+for opt in "-leftright" "-lr -jtop" "-lr -jcenter" "-lr -jbottom" \
+    "-lr -white" "-lr -black" \
+    "-topbottom" "-tb -jleft"  "-tb -jcenter" "-tb --jright" \
+    "-tb -white" "-tb -black"
+  do
+  pamcat ${opt} ${seq2_4h_pam}  |\
+  cmp -s ${seq2_4h_pam} - ; echo $?
+  done
+
+
+echo "Test 11.  Should print 2193235886 195, 0 eight times, 1 once"
+pamrestack -width=1 ${seq2_4h_pam} | tee ${seq2_4v_pam} |\
+  pamenlarge -xscale=3 |\
+  tee ${seq2_4v3_pam} | cksum
+pamcat -lr ${seq2_4v_pam} ${seq2_4v_pam} | pamcat -lr - ${seq2_4v_pam} |\
+  cmp -s ${seq2_4v3_pam} - ; echo $?
+pamcat -lr ${seq2_4v_pam} | pamcat -lr - ${seq2_4v_pam}  ${seq2_4v_pam} |\
+  cmp -s ${seq2_4v3_pam} - ; echo $?
+for opt in "-leftright" "-lr -jtop" "-lr -jcenter" "-lr -jbottom" \
+    "-lr -white" "-lr -black" \
+    "-topbottom"
+  do
+  pamcat ${opt} ${seq2_4v_pam} ${seq2_4v_pam} ${seq2_4v_pam} |\
+  cmp -s ${seq2_4v3_pam} - ; echo $?
+  done
+
+
+echo "Test 12.  Should print 2773166369 245, 0 nine times, 1 once"
+pamenlarge -yscale 4 ${seq2_4h_pam} | tee ${seq2_4h4_pam} | cksum
+pamcat -tb ${seq2_4h_pam} |\
+    pamcat -tb - ${seq2_4h_pam} ${seq2_4h_pam} ${seq2_4h_pam} |\
+    cmp -s ${seq2_4h4_pam} - ; echo $?
+pamcat -tb ${seq2_4h_pam} ${seq2_4h_pam} |\
+    pamcat -tb - ${seq2_4h_pam} ${seq2_4h_pam} |\
+    cmp -s ${seq2_4h4_pam} - ; echo $?
+pamcat -tb ${seq2_4h_pam} ${seq2_4h_pam} ${seq2_4h_pam}|\
+    pamcat -tb - ${seq2_4h_pam} |\
+    cmp -s ${seq2_4h4_pam} - ; echo $?
+for opt in "-topbottom" "-tb -jleft"  "-tb -jcenter" "-tb --jright" \
+    "-tb -white" "-tb -black" \
+    "-leftright"
+  do
+  pamcat ${opt} ${seq2_4h_pam} ${seq2_4h_pam} ${seq2_4h_pam} ${seq2_4h_pam} |\
+  cmp -s ${seq2_4h4_pam} - ; echo $?
+  done
+
+rm ${seq2_4h_pam} ${seq2_4v_pam} ${seq2_4v3_pam} ${seq2_4h4_pam}
+
+
+
+echo "Test Invalid"
+
+. ${srcdir}/test-invalid.inc
+
+# direction not specified
+invCmd "pamcat testgrid.pbm testimg.ppm"
+
+# both directions specified
+invCmd "pamcat -topbottom -leftright testgrid.pbm testimg.ppm"
+
+# both pad colors specified
+invCmd "pamcat -topbottom -white -black testgrid.pbm testimg.ppm"
+invCmd "pamcat -lr -jtop -jbottom testgrid.pbm testimg.ppm"
+invCmd "pamcat -lr -jtop -jcenter testgrid.pbm testimg.ppm"
+invCmd "pamcat -lr -jcenter -jbottom testgrid.pbm testimg.ppm"
+invCmd "pamcat -tb -jleft -jright testgrid.pbm testimg.ppm"
+invCmd "pamcat -tb -jleft -jcenter testgrid.pbm testimg.ppm"
+invCmd "pamcat -tb -jcenter -jright testgrid.pbm testimg.ppm"
+invCmd "pamcat -lr -jleft    testgrid.pbm testimg.ppm"
+invCmd "pamcat -lr -jright   testgrid.pbm testimg.ppm"
+invCmd "pamcat -tb -jtop     testgrid.pbm testimg.ppm"
+invCmd "pamcat -tb -jbottom  testgrid.pbm testimg.ppm"
+
+# more than one input image from standard input
+cat testgrid.pbm | pamcat -lr - - testimg.ppm > ${test_out} || \
+  printf "Expected failure 14 "
+  test -s ${test_out} && echo "unexpected output" || echo "(no output)"
+  rm -f ${test_out}
diff --git a/test/pamcat2.ok b/test/pamcat2.ok
new file mode 100644
index 00000000..549fe97a
--- /dev/null
+++ b/test/pamcat2.ok
@@ -0,0 +1,93 @@
+Test 1.
+P1
+1 1
+0
+P1
+1 1
+0
+P1
+1 1
+1
+P1
+1 1
+0
+Test 2.
+P1
+7 5
+0000000
+1000001
+1000001
+1000001
+1000001
+P1
+7 5
+1000001
+1000001
+0000000
+1000001
+1000001
+P1
+7 5
+1000001
+1000001
+1000001
+1000001
+0000000
+P1
+7 5
+1000001
+1000001
+0000000
+1000001
+1000001
+P1
+5 7
+01111
+00000
+00000
+00000
+00000
+00000
+01111
+P1
+5 7
+11011
+00000
+00000
+00000
+00000
+00000
+11011
+P1
+5 7
+11110
+00000
+00000
+00000
+00000
+00000
+11110
+P1
+5 7
+11011
+00000
+00000
+00000
+00000
+00000
+11011
+Test 3.
+1715060535 12
+1715060535 12
+3621575043 12
+3621575043 12
+Test 4.
+1972597727 14
+1972597727 14
+Test 5.
+2175144709 10456
+2175144709 10456
+2175144709 10456
+609107534 10444
+609107534 10444
+609107534 10444
diff --git a/test/pamcat2.test b/test/pamcat2.test
new file mode 100755
index 00000000..ecc7ee5e
--- /dev/null
+++ b/test/pamcat2.test
@@ -0,0 +1,64 @@
+#! /bin/sh
+# This script tests: pamcat
+# Also requires: pbmmake pamflip
+
+tmpdir=${tmpdir:-/tmp}
+dotw_pbm=${tmpdir}/dotw.pbm
+dotb_pbm=${tmpdir}/dotb.pbm
+check5x5_pbm=${tmpdir}/check5x5.pbm
+dot_ppm=${tmpdir}/dot.ppm
+
+echo "Test 1."
+pbmmake -w 1 1 | tee ${dotw_pbm} | pamcat -tb -plain
+pamcat -lr -plain ${dotw_pbm}
+pbmmake -b 1 1 | tee ${dotb_pbm} | pamcat -tb -plain
+pamcat -tb -plain ${dotw_pbm}
+
+echo "Test 2."
+
+pbmmake -w 5 5 > ${check5x5_pbm}
+
+pamcat -lr -jt -black ${dotw_pbm} ${check5x5_pbm} ${dotw_pbm} -plain
+pamcat -lr -jc -black ${dotw_pbm} ${check5x5_pbm} ${dotw_pbm} -plain
+pamcat -lr -jb -black ${dotw_pbm} ${check5x5_pbm} ${dotw_pbm} -plain
+pamcat -lr     -black ${dotw_pbm} ${check5x5_pbm} ${dotw_pbm} -plain
+
+pamcat -tb -jl -black ${dotw_pbm} ${check5x5_pbm} ${dotw_pbm} -plain
+pamcat -tb -jc -black ${dotw_pbm} ${check5x5_pbm} ${dotw_pbm} -plain
+pamcat -tb -jr -black ${dotw_pbm} ${check5x5_pbm} ${dotw_pbm} -plain
+pamcat -tb     -black ${dotw_pbm} ${check5x5_pbm} ${dotw_pbm} -plain
+
+rm ${dotw_pbm}
+
+echo "Test 3."
+pbmmake -b 1 1 > ${dotb_pbm}
+
+pamcat -lr -jt -white ${dotb_pbm} ${check5x5_pbm} ${dotb_pbm} | cksum
+pamcat -lr -jb -white ${dotb_pbm} ${check5x5_pbm} ${dotb_pbm} |\
+  pamflip -tb | cksum
+pamcat -tb -jl -white ${dotb_pbm} ${check5x5_pbm} ${dotb_pbm} |\
+  pamflip -ccw | cksum
+pamcat -tb -jr -white ${dotb_pbm} ${check5x5_pbm} ${dotb_pbm} |\
+  pamflip -cw | cksum
+
+rm ${dotb_pbm}
+rm ${check5x5_pbm}
+
+
+echo "Test 4."
+ppmmake rgb:20/40/d0 1 1 | tee ${dot_ppm} | pamcat -lr | cksum
+pamcat -tb  ${dot_ppm} | cksum
+
+echo "Test 5."
+for just in -jtop -jcenter -jbottom
+do
+pamcat -lr ${just} ${dot_ppm} maze.pbm ${dot_ppm} | cksum
+done
+
+for just in -jleft -jcenter -jright
+do
+pamcat -tb ${just} ${dot_ppm} maze.pbm ${dot_ppm} | cksum
+done
+
+rm ${dot_ppm}
+
diff --git a/test/pamcat3.ok b/test/pamcat3.ok
new file mode 100644
index 00000000..768f6f1e
--- /dev/null
+++ b/test/pamcat3.ok
@@ -0,0 +1,19 @@
+Test 1.   Should print 585134073 133221 four times
+585134073 133221
+585134073 133221
+585134073 133221
+585134073 133221
+Test 2.   Should print 1331083756 152559 three times
+1331083756 152559
+1331083756 152559
+1331083756 152559
+Test Invalid
+Expected failure 1 (no output)
+Expected failure 2 (no output)
+Expected failure 3 (no output)
+Expected failure 4 (no output)
+Expected failure 5 (no output)
+Expected failure 6 (no output)
+Expected failure 7 (no output)
+Expected failure 8 (no output)
+Expected failure 9 (no output)
diff --git a/test/pamcat3.test b/test/pamcat3.test
new file mode 100755
index 00000000..fb89c3f6
--- /dev/null
+++ b/test/pamcat3.test
@@ -0,0 +1,97 @@
+#! /bin/sh
+# This script tests: pamcat
+# Also requires:
+
+tmpdir=${tmpdir:-/tmp}
+list=${tmpdir}/list
+list2=${tmpdir}/list2
+list3=${tmpdir}/list3
+liste1=${tmpdir}/liste1
+liste2=${tmpdir}/liste2
+liste3=${tmpdir}/liste3
+files="maze.pbm testgrid.pbm testimg.ppm"
+
+ls ${files} | tee ${list} | awk '{print ""; print $0; print ""}' > ${list3}
+sed 's/maze.pbm/-/' ${list} > ${list2}
+
+echo "Test 1.   Should print 585134073 133221 four times"
+pamcat -lr -jt ${files} | cksum
+pamcat -lr -jt -listfile=${list} | cksum
+cat maze.pbm | pamcat -lr -jt -listfile=${list2} | cksum
+pamcat -lr -jt -listfile=${list3} | cksum
+
+echo "Test 2.   Should print 1331083756 152559 three times"
+pamcat -tb -jl ${files} | cksum
+pamcat -tb -jl -listfile=${list} | cksum
+cat ${list} | pamcat -tb -jl -listfile=- | cksum
+
+echo "Test Invalid"
+
+test_out=${tmpdir}/test_out
+
+echo 1>&2
+echo "Invalid command-line argument combinations & listfile content." 1>&2
+echo "Error messages should appear below the line." 1>&2
+echo "-----------------------------------------------------------" 1>&2
+
+# listfile not specified
+pamcat -lr -listfile > ${test_out} || \
+  printf "Expected failure 1 "
+  test -s ${test_out} && echo "unexpected output" || echo "(no output)"
+  rm -f ${test_out}
+
+# listfile does not exist
+pamcat -lr -listfile=`mktemp -u` > ${test_out} || \
+  printf "Expected failure 2 "
+  test -s ${test_out} && echo "unexpected output" || echo "(no output)"
+  rm -f ${test_out}
+
+# listfile empty
+pamcat -lr -listfile=/dev/null > ${test_out} || \
+  printf "Expected failure 3 "
+  test -s ${test_out} && echo "unexpected output" || echo "(no output)"
+  rm -f ${test_out}
+
+# listfile from stdin, empty
+cat /dev/null | pamcat -lr -listfile=- > ${test_out} || \
+  printf "Expected failure 4 "
+  test -s ${test_out} && echo "unexpected output" || echo "(no output)"
+  rm -f ${test_out}
+
+# Files provided from command line in addition to listfile
+pamcat -lr -listfile=${list} testgrid.pbm testgrid.pbm > ${test_out} || \
+  printf "Expected failure 5 "
+  test -s ${test_out} && echo "unexpected output" || echo "(no output)"
+  rm -f ${test_out}
+
+# "-" (stdin) provided from command line in addition to listfile
+pamcat -lr -listfile=${list} - > ${test_out} || \
+  printf "Expected failure 6 "
+  test -s ${test_out} && echo "unexpected output" || echo "(no output)"
+  rm -f ${test_out}
+
+# listfile has nothing but blank lines
+sed 's/^.*$//' ${list3} > ${liste1}  
+pamcat -lr -listfile=${liste1} > ${test_out} || \
+  printf "Expected failure 7 "
+  test -s ${test_out} && echo "unexpected output" || echo "(no output)"
+  rm -f ${test_out} ${liste1}
+
+# Non-existing file in listfile
+( cat ${list} ; mktemp -u ) > ${liste2}
+pamcat -lr -listfile=${liste2} > ${test_out} || \
+  printf "Expected failure 8 "
+  test -s ${test_out} && echo "unexpected output" || echo "(no output)"
+  rm -f ${test_out} ${liste2}
+
+# Multiple instances of "-" in listfile
+( echo "-"; cat ${list}; echo "-"; echo "-" ) > ${liste3}
+pamcat -lr -listfile=${liste3} > ${test_out} || \
+  printf "Expected failure 9 "
+  test -s ${test_out} && echo "unexpected output" || echo "(no output)"
+  rm -f ${test_out} ${liste3}
+
+
+rm ${list} ${list2} ${list3}
+
+
diff --git a/test/pamchannel.ok b/test/pamchannel.ok
index 41d3f890..72b84354 100644
--- a/test/pamchannel.ok
+++ b/test/pamchannel.ok
@@ -1,10 +1,12 @@
-Test 1
+Test 1:red-channel  Should produce 1571496937 33838
 1571496937 33838
-Test 2
+Test 2:green-channel  Should produce 394856971 33838
 394856971 33838
-Test 3
+Test 3:blue-channel  Should produce 3164158573 33838
 3164158573 33838
+Test 4:single-channel  Should produce 281226646 481
+281226646 481
 Test Invalid
-Expected failure 1 1
-Expected failure 2 1
-Expected failure 3 1
+Expected failure 1 (no output)
+Expected failure 2 (no output)
+Expected failure 3 (no output)
diff --git a/test/pamchannel.test b/test/pamchannel.test
index 2e017ef2..f3399343 100755
--- a/test/pamchannel.test
+++ b/test/pamchannel.test
@@ -1,4 +1,4 @@
-#! /bin/bash
+#! /bin/sh
 # This script tests: pamchannel
 # Also requires: pamtopam pamtopnm
 
@@ -12,27 +12,23 @@
 # 3164158573 33838 testimg.blu
 
 
-# Test 1. red channel
-# Should produce 1571496937 33838
-echo "Test 1"
-
+echo "Test 1:red-channel  Should produce 1571496937 33838"
 pamchannel -infile testimg.ppm 0 | \
   pamtopnm --assume | cksum
 
-# Test 2. green channel
-# Should produce  394856971 33838
-echo "Test 2"
-
+echo "Test 2:green-channel  Should produce 394856971 33838"
 pamchannel -infile testimg.ppm -tupletype="GRAYSCALE" 1 | \
   pamtopnm | cksum
 
-# Test 3. blue channel
-# Should produce 3164158573 33838
-echo "Test 3"
+echo "Test 3:blue-channel  Should produce 3164158573 33838"
 
 pamchannel -infile testimg.ppm 2 | \
   pamtopnm --assume | cksum
 
+echo "Test 4:single-channel  Should produce 281226646 481"
+pamchannel -infile maze.pbm 0 | \
+  pamtopnm --assume | cksum
+
 # Test invalid: specified channel does not exist
 
 echo 1>&2
@@ -45,13 +41,8 @@ test_out=${tmpdir}/test_out
 
 echo "Test Invalid"
 
-pamchannel  -infile testgrid.pbm 1 > ${test_out} || \
-   echo -n "Expected failure 1"; test -s ${test_out}; echo " "$?
-
-pamchannel  -infile testimg.ppm 3 > ${test_out} || \
-   echo -n "Expected failure 2"; test -s ${test_out}; echo " "$?
-
-pamtopam testimg.ppm | pamchannel -infile=- 4 > ${test_out} || \
-   echo -n "Expected failure 3"; test -s ${test_out}; echo " "$?
+. ${srcdir}/test-invalid.inc
 
-rm ${test_out}
\ No newline at end of file
+invCmd "pamchannel  -infile testgrid.pbm 1"
+invCmd "pamchannel  -infile testimg.ppm 3"
+invCmd "pamtopam testimg.ppm | pamchannel -infile=- 4"
diff --git a/test/pamcrater.ok b/test/pamcrater.ok
index a5571f35..53faebf2 100644
--- a/test/pamcrater.ok
+++ b/test/pamcrater.ok
@@ -7,7 +7,7 @@ Test 2.
 2
 2
 Test Invalid.
-Expected failure 1 1
-Expected failure 2 1
-Expected failure 3 1
-Expected failure 4 1
+Expected failure 1 (no output)
+Expected failure 2 (no output)
+Expected failure 3 (no output)
+Expected failure 4 (no output)
diff --git a/test/pamcrater.test b/test/pamcrater.test
index ba10ca24..5362bde3 100755
--- a/test/pamcrater.test
+++ b/test/pamcrater.test
@@ -1,4 +1,4 @@
-#! /bin/bash
+#! /bin/sh
 # This script tests: pamcrater pamshadedrelief
 # Also requires: pamstack pamvalidate pamcut pamflip
 
@@ -52,27 +52,17 @@ pamshadedrelief ${test100_pam} > ${testshaded_pam}
   pamcut -top=$((128 - 99)) -height=1  ${testshaded_pam} | cksum
 ) | uniq -c | awk '{print $1}'
 
-rm ${testshaded_pam} ${test100_pam}
+rm ${testshaded_pam} ${test150_pam}
 
 echo "Test Invalid."
 
 test_out=${tmpdir}/test_out
 
-echo 1>&2
-echo "Invalid command-line argument combinations." 1>&2
-echo "Error messages should appear below the line." 1>&2
-echo "------------------------------" 1>&2
+. ${srcdir}/test-invalid.inc
 
-pamcrater -width 0 > ${test_out} || \
-   echo -n "Expected failure 1"; test -s ${test_out}; echo " "$?
+invCmd "pamcrater -width 0"
+invCmd "pamcrater -height 0"
+invCmd "pamcrater -number 0"
+invCmd "pamshadedrelief -gamma 0 ${test100_pam}"
 
-pamcrater -height 0 > ${test_out} || \
-   echo -n "Expected failure 2"; test -s ${test_out}; echo " "$?
-
-pamcrater -number 0 > ${test_out} || \
-   echo -n "Expected failure 3"; test -s ${test_out}; echo " "$?
-
-pamcrater -test -radius=10 | pamshadedrelief -gamma 0 > ${test_out} || \
-   echo -n "Expected failure 4"; test -s ${test_out}; echo " "$?
-
-rm -f ${test_out}
\ No newline at end of file
+rm ${test100_pam}
diff --git a/test/pamcut.ok b/test/pamcut.ok
index 3d5c5a7f..18ed88e8 100644
--- a/test/pamcut.ok
+++ b/test/pamcut.ok
@@ -1,36 +1,106 @@
-Test 1.
+Test 1a.  Should print 0 259 0 159 227 149 260 160 twice
+0 259 0 159 227 149 260 160
+0 259 0 159 227 149 260 160
+Test 1b.  Should print 2958909756 124815
 2958909756 124815
-Test 2.
-1550940962 10933
-Test 3.
+Test 2a.  Should print 120 159 120 159 227 149 40 40 three times
+120 159 120 159 227 149 40 40
+120 159 120 159 227 149 40 40
+120 159 120 159 227 149 40 40
+Test 2b.  Should print 3876978825 4813 twice
+3876978825 4813
+3876978825 4813
+Test 3a.  Should print 5 5 5 5 227 149 1 1 three times
+5 5 5 5 227 149 1 1
+5 5 5 5 227 149 1 1
+5 5 5 5 227 149 1 1
+Test 3b.  Should print 708474423 14
 708474423 14
-708474423 14
-Test 4.
-659346598 80124
-659346598 80124
-659346598 80124
+Test 4a.  Should print 10 216 10 138 227 149 207 129 five times
+10 216 10 138 227 149 207 129
+10 216 10 138 227 149 207 129
+10 216 10 138 227 149 207 129
+10 216 10 138 227 149 207 129
+10 216 10 138 227 149 207 129
+Test 4b.  Should print 659346598 80124
 659346598 80124
-Test 5.
-2425386270 41
-2425386270 41
-2425386270 41
-2425386270 41
-2425386270 41
-Test 6.
+Test 5a. Should print 0 56 0 58 57 59 57 59 five times
+0 56 0 58 57 59 57 59
+0 56 0 58 57 59 57 59
+0 56 0 58 57 59 57 59
+0 56 0 58 57 59 57 59
+0 56 0 58 57 59 57 59
+Test 5b. Should print 281226646 481 twice
+281226646 481
+281226646 481
+Test 6a.  Should print 5 34 5 34 50 50 30 30
+5 34 5 34 50 50 30 30
+Test 6b.  Should print 3412257956 129
 3412257956 129
+Test 7.  Should print 284857390 12 sixteen times
+284857390 12
+284857390 12
+284857390 12
+284857390 12
+284857390 12
+284857390 12
+284857390 12
+284857390 12
+284857390 12
+284857390 12
+284857390 12
+284857390 12
+284857390 12
+284857390 12
+284857390 12
+284857390 12
+Test 8.  Should print 3125257619 29 four times
+3125257619 29
+3125257619 29
+3125257619 29
+3125257619 29
+Test 9.  Should print 3338453023 36 sixteen times
+3338453023 36
+3338453023 36
+3338453023 36
+3338453023 36
+3338453023 36
+3338453023 36
+3338453023 36
+3338453023 36
+3338453023 36
+3338453023 36
+3338453023 36
+3338453023 36
+3338453023 36
+3338453023 36
+3338453023 36
+3338453023 36
+Test 10.  Should print 3957742883 302 four times
+3957742883 302
+3957742883 302
+3957742883 302
+3957742883 302
+Test 11.  Should print 1576602925 8 four times
+1576602925 8
+1576602925 8
+1576602925 8
+1576602925 8
 Test Invalid
-Expected failure 1 1
-Expected failure 2 1
-Expected failure 3 1
-Expected failure 4 1
-Expected failure 5 1
-Expected failure 6 1
-Expected failure 7 1
-Expected failure 8 1
-Expected failure 9 1
-Expected failure 6 1
-Expected failure 10 1
-Expected failure 11 1
-Expected failure 12 1
-Expected failure 13 1
-Expected failure 14 1
+Expected failure 1 (no output)
+Expected failure 2 (no output)
+Expected failure 3 (no output)
+Expected failure 4 (no output)
+Expected failure 5 (no output)
+Expected failure 6 (no output)
+Expected failure 7 (no output)
+Expected failure 8 (no output)
+Expected failure 9 (no output)
+Expected failure 10 (no output)
+Expected failure 11 (no output)
+Expected failure 12 (no output)
+Expected failure 13 (no output)
+Expected failure 14 (no output)
+Expected failure 15 (no output)
+Expected failure 16 (no output)
+Expected failure 17 (no output)
diff --git a/test/pamcut.test b/test/pamcut.test
index e4d8c62f..7d60e1cd 100755
--- a/test/pamcut.test
+++ b/test/pamcut.test
@@ -1,109 +1,226 @@
-#! /bin/bash
-# This script tests: pamcut pbmmake
-# Also requires:
+#! /bin/sh
+# This script tests: pamcut
+# Also requires:  pbmmake pgmmake pamfile pnmpad pamflip
 
-# Test 1.  Should print 2958909756 124815
-echo Test 1.
+tmpdir=${tmpdir:-/tmp}
+
+echo "Test 1a.  Should print 0 259 0 159 227 149 260 160 twice"
+
+pamcut -left 0 -right 259 -top 0 -bottom 159 \
+      -pad -reportonly testimg.ppm
+pamcut  -left 0 -top 0 -width 260 -height 160 \
+      -pad -reportonly testimg.ppm
+
+echo "Test 1b.  Should print 2958909756 124815"
+
+pamcut -left 0 -top 0 -width 260 -height 160 \
+ -pad testimg.ppm | cksum
+
+echo "Test 2a.  Should print 120 159 120 159 227 149 40 40 three times"
 
-pamcut -top 0 -left 0 -width 260 -height 160 \
-  -pad testimg.ppm | cksum
+pamcut -left 120 -right 159 -top 120 -bottom 159 \
+ -pad -reportonly testimg.ppm
+pamcut -right 159 -bottom 159 -width 40 -height 40 \
+ -pad -reportonly testimg.ppm
+pamcut -left 120 -top 120 -width 40 -height 40 \
+ -pad -reportonly testimg.ppm
 
-# Test 2.  Should print 1550940962 10933
-echo Test 2.
+echo "Test 2b.  Should print 3876978825 4813 twice"
 
-pamcut -top 200 -left 120 -width 40 -height 40 \
-  -pad testimg.ppm | cksum
+pamcut -left 120 -right 159 -top 120 -bottom 159 \
+ -pad testimg.ppm | cksum
+pamcut -left 120 -top 120 -width 40  \
+ -pad testimg.ppm | pnmpad -black -bottom 11 | cksum
 
-# Test 3.  Should print 708474423 14 twice
-echo Test 3.
+echo "Test 3a.  Should print 5 5 5 5 227 149 1 1 three times"
+
+pamcut -top 5 -left 5 -bottom 5 -right 5 -reportonly testimg.ppm
+pamcut -width 1 -height 1 -bottom 5 -right 5 -reportonly testimg.ppm
+pamcut -cropleft 5 -croptop 5 -width 1 -height 1 -reportonly testimg.ppm
+
+echo "Test 3b.  Should print 708474423 14"
 
 pamcut -top 5 -left 5 -bottom 5 -right 5 testimg.ppm | cksum
-pamcut -width 1 -height 1 -bottom 5 -right 5 testimg.ppm | cksum
 
+echo "Test 4a.  Should print 10 216 10 138 227 149 207 129 five times"
+
+pamcut -croptop 10 -cropleft 10 -cropbottom 10 -cropright 10 \
+      -reportonly testimg.ppm 
+pamcut -cropbottom 10 -cropright 10 -width 207 -height 129  \
+      -reportonly testimg.ppm 
+pamcut -top 10 -left 10 -bottom 138 -right 216 -reportonly testimg.ppm
+pamcut -top 10 -left 10 -bottom -11 -right -11 -reportonly testimg.ppm 
+pamcut -top 10 -left 10 -width 207 -height 129 -reportonly testimg.ppm 
 
-# Test 4.  Should print 659346598 80124 four times
-echo Test 4.
+echo "Test 4b.  Should print 659346598 80124"
 
-pamcut -croptop 10 -cropleft 10 -cropbottom 10 -cropright 10 testimg.ppm | \
-  cksum
-pamcut -top 10 -left 10 -bottom 138 -right 216 testimg.ppm | cksum
-pamcut -top 10 -left 10 -bottom -11 -right -11 testimg.ppm | cksum
 pamcut -top 10 -left 10 -width 207 -height 129 testimg.ppm | cksum
 
+echo "Test 5a. Should print 0 56 0 58 57 59 57 59 five times"
 
-# Test 5. Should print 2425386270 41 five times
-echo Test 5.
+mazesize=$(pamfile -size maze.pbm)
+width=$(echo ${mazesize} | cut -d " " -f 1)
+height=$(echo ${mazesize} | cut -d " " -f 2)
 
-pamcut -croptop 0 -cropleft 0 -cropbottom 0 -cropright 0 testgrid.pbm | \
-  cksum
-pamcut -top 0 -left 0 -bottom 15 -right 13 testgrid.pbm | cksum
-pamcut -top 0 -left 0 -bottom -1 -right -1 testgrid.pbm | cksum
-pamcut -top 0 -left 0 -width 14 -height 16 testgrid.pbm | cksum
-pamcut testgrid.pbm | cksum
+pamcut -croptop 0 -cropleft 0 -cropbottom 0 -cropright 0 \
+      -reportonly maze.pbm
+pamcut -top 0 -left 0 \
+      -bottom $((${height} -1)) -right $((${width} -1)) \
+       -reportonly maze.pbm
+pamcut -top 0 -left 0 -bottom -1 -right -1 -reportonly maze.pbm 
+pamcut -top 0 -left 0 -width ${width} -height ${height} \
+      -reportonly maze.pbm
+pamcut -reportonly maze.pbm 
 
-# Test 6.  Should print 3412257956 129
-echo Test 6.
+echo "Test 5b. Should print 281226646 481 twice"
 
-pbmmake -g 50 50 | pamcut 5 5 30 30 | cksum
+pamcut -croptop 0 -cropleft 0 -cropbottom 0 -cropright 0 maze.pbm | \
+ cksum
+pamcut maze.pbm | cksum
 
+test50_pbm=${tmpdir}/test50.pbm
 
-echo "Test Invalid"
+echo "Test 6a.  Should print 5 34 5 34 50 50 30 30"
 
-tmpdir=${tmpdir:-/tmp}
-test_out=${tmpdir}/test_out
+pbmmake -g 50 50 | tee ${test50_pbm} | pamcut -reportonly 5 5 30 30
 
-echo 1>&2
-echo "Invalid command-line argument combinations." 1>&2
-echo "Error messages should appear below the line." 1>&2
-echo "-----------------------------------------------------------" 1>&2
+echo "Test 6b.  Should print 3412257956 129"
 
-# overspecification
-pamcut -left=1 -right=1 -width=14 testgrid.pbm > ${test_out} || \
-   echo -n "Expected failure 1"; test -s ${test_out}; echo " "$?
+pamcut 5 5 30 30 ${test50_pbm} | cksum
 
-pamcut -top=1 -bottom=1 -height=16 testgrid.pbm > ${test_out} || \
-   echo -n "Expected failure 2"; test -s ${test_out}; echo " "$?
+rm  ${test50_pbm}
 
-pamcut -right=1 -cropright=1 testgrid.pbm > ${test_out} || \
-   echo -n "Expected failure 3"; test -s ${test_out}; echo " "$?
+echo "Test 7.  Should print 284857390 12 sixteen times"
 
-pamcut -top=1 -croptop=1 testgrid.pbm > ${test_out} || \
-   echo -n "Expected failure 4"; test -s ${test_out}; echo " "$?
+test1_pbm=${tmpdir}/test1.pbm
 
-pamcut -bottom=1 -cropbottom=1 testgrid.pbm > ${test_out} || \
-   echo -n "Expected failure 5"; test -s ${test_out}; echo " "$?
+pbmmake -b 1 1 > ${test1_pbm}
 
-pamcut -left=1 -cropleft=1 testgrid.pbm > ${test_out} || \
-   echo -n "Expected failure 6"; test -s ${test_out}; echo " "$?
+# pbmmake -b 5 5 | cksum
 
-# excessive cropping
-pamcut -cropleft=7 -cropright=8 testgrid.pbm > ${test_out} || \
-   echo -n "Expected failure 7"; test -s ${test_out}; echo " "$?
+pamcut  -pad -cropleft=6 -croptop=6 -width=5 -height=5 ${test1_pbm} | cksum
+pamcut  -pad -cropright=6 -croptop=6 -width=5 -height=5 ${test1_pbm} | cksum
+pamcut  -pad -cropleft=6 -cropbottom=6 -width=5 -height=5 ${test1_pbm} | cksum
+pamcut  -pad -cropright=6 -cropbottom=6 -width=5 -height=5 ${test1_pbm} | cksum
 
-pamcut -left=7 -right=6 testgrid.pbm > ${test_out} || \
-   echo -n "Expected failure 8"; test -s ${test_out}; echo " "$?
+pamcut  -pad -cropleft=6 -width=5 -height=5 ${test1_pbm} | cksum
+pamcut  -pad -croptop=6 -width=5 -height=5 ${test1_pbm} | cksum
+pamcut  -pad -cropbottom=6 -width=5 -height=5 ${test1_pbm} | cksum
+pamcut  -pad -cropright=6 -width=5 -height=5 ${test1_pbm} | cksum
 
-pamcut -croptop=8 -cropbottom=8 testgrid.pbm > ${test_out} || \
-   echo -n "Expected failure 9"; test -s ${test_out}; echo " "$?
+pamcut  -pad -cropleft=7 -croptop=7 -width=5 -height=5 ${test1_pbm} | cksum
+pamcut  -pad -cropright=7 -croptop=7 -width=5 -height=5 ${test1_pbm} | cksum
+pamcut  -pad -cropleft=7 -cropbottom=7 -width=5 -height=5 ${test1_pbm} | cksum
+pamcut  -pad -cropright=7 -cropbottom=7 -width=5 -height=5 ${test1_pbm} | cksum
 
-pamcut -top=10 -bottom=9 testgrid.pbm > ${test_out} || \
-   echo -n "Expected failure 6"; test -s ${test_out}; echo " "$?
+pamcut  -pad -cropleft=17 -width=5 -height=5 ${test1_pbm} | cksum
+pamcut  -pad -croptop=17 -width=5 -height=5 ${test1_pbm} | cksum
+pamcut  -pad -cropbottom=17 -width=5 -height=5 ${test1_pbm} | cksum
+pamcut  -pad -cropright=17 -width=5 -height=5 ${test1_pbm} | cksum
 
-# pad absent
-pamcut -cropleft=1 -width=14 testgrid.pbm > ${test_out} || \
-   echo -n "Expected failure 10"; test -s ${test_out}; echo " "$?
 
-pamcut -croptop=1  -height=16 testgrid.pbm > ${test_out} || \
-   echo -n "Expected failure 11"; test -s ${test_out}; echo " "$?
+echo "Test 8.  Should print 3125257619 29 four times"
 
-# legacy style: insufficient number of positional parameters
-pamcut 5 testimg.ppm > ${test_out} || \
-   echo -n "Expected failure 12"; test -s ${test_out}; echo " "$?
+test3_pbm=${tmpdir}/test3.pbm
+
+pbmmake -g 3 3 > ${test3_pbm}
+
+pamcut -pad -cropleft=10  -croptop=10    -width=10 -height=10 ${test3_pbm} | cksum
+pamcut  -pad -cropright=10 -croptop=10 -width=10 -height=10    ${test3_pbm} |\
+   pamflip -lr | cksum
+pamcut  -pad -cropleft=10  -cropbottom=10 -width=10 -height=10 ${test3_pbm} |\
+   pamflip -tb | cksum
+pamcut  -pad -cropright=10 -cropbottom=10 -width=10 -height=10 ${test3_pbm} |\
+   pamflip -r180 | cksum
+
+rm ${test3_pbm}
+
+echo "Test 9.  Should print 3338453023 36 sixteen times"
+
+testb_pgm=${tmpdir}/testb.pgm
+
+pgmmake 0.0 1 1 > ${testb_pgm}
+
+# pgmmake 0.0 5 5 | cksum
+
+pamcut  -pad -cropleft=6 -croptop=6 -width=5 -height=5 ${testb_pgm} | cksum
+pamcut  -pad -cropright=6 -croptop=6 -width=5 -height=5 ${testb_pgm} | cksum
+pamcut  -pad -cropleft=6 -cropbottom=6 -width=5 -height=5 ${testb_pgm} | cksum
+pamcut  -pad -cropright=6 -cropbottom=6 -width=5 -height=5 ${testb_pgm} | cksum
 
-pamcut 5 4 testimg.ppm > ${test_out} || \
-   echo -n "Expected failure 13"; test -s ${test_out}; echo " "$?
+pamcut  -pad -cropleft=6 -width=5 -height=5 ${testb_pgm} | cksum
+pamcut  -pad -croptop=6 -width=5 -height=5 ${testb_pgm} | cksum
+pamcut  -pad -cropbottom=6 -width=5 -height=5 ${testb_pgm} | cksum
+pamcut  -pad -cropright=6 -width=5 -height=5 ${testb_pgm} | cksum
 
-pamcut 5 5 30 testimg.ppm > ${test_out} || \
-   echo -n "Expected failure 14"; test -s ${test_out}; echo " "$?
+pamcut  -pad -cropleft=7 -croptop=7 -width=5 -height=5 ${testb_pgm} | cksum
+pamcut  -pad -cropright=7 -croptop=7 -width=5 -height=5 ${testb_pgm} | cksum
+pamcut  -pad -cropleft=7 -cropbottom=7 -width=5 -height=5 ${testb_pgm} | cksum
+pamcut  -pad -cropright=7 -cropbottom=7 -width=5 -height=5 ${testb_pgm} | cksum
 
-rm -f ${test_out}
\ No newline at end of file
+pamcut  -pad -cropleft=17 -width=5 -height=5 ${testb_pgm} | cksum
+pamcut  -pad -croptop=17 -width=5 -height=5 ${testb_pgm} | cksum
+pamcut  -pad -cropbottom=17 -width=5 -height=5 ${testb_pgm} | cksum
+pamcut  -pad -cropright=17 -width=5 -height=5 ${testb_pgm} | cksum
+
+rm  ${testb_pgm}
+
+echo "Test 10.  Should print 3957742883 302 four times"
+
+testg_pgm=${tmpdir}/testg.pgm
+
+pgmmake 0.5 2 2 > ${testg_pgm}
+
+# pgmmake 0.0 17 17 | cksum
+
+pamcut -pad -cropleft=17  -croptop=17    -width=17 -height=17 ${testg_pgm} |  cksum
+pamcut -pad -cropright=17 -croptop=17    -width=17 -height=17 ${testg_pgm} | \
+    pamflip -lr | cksum
+pamcut -pad -cropleft=17  -cropbottom=17 -width=17 -height=17 ${testg_pgm} | \
+    pamflip -tb | cksum
+pamcut -pad -cropright=17 -cropbottom=17 -width=17 -height=17 ${testg_pgm} |\
+    pamflip -r180 | cksum
+
+rm  ${testg_pgm}
+
+echo "Test 11.  Should print 1576602925 8 four times"
+
+test5_pbm=${tmpdir}/test5.pbm
+
+pbmmake -g 5 5 > ${test5_pbm}
+
+cat ${test1_pbm} | cksum
+pamcut -pad -left=6 -right=6 -top=6 -bottom 6 ${test5_pbm} | cksum
+pamcut -pad -left=-6 -right=-6 -top=-6 -bottom -6 ${test5_pbm} | cksum
+pamcut -pad -left=101 -right=101 -top=1001 -bottom 1001 ${test5_pbm} | cksum
+
+rm ${test1_pbm} ${test5_pbm}
+
+echo "Test Invalid"
+
+. ${srcdir}/test-invalid.inc
+
+# overspecification
+invCmd "pamcut -left=1 -right=1 -width=14 testgrid.pbm"
+invCmd "pamcut -top=1 -bottom=1 -height=16 testgrid.pbm"
+invCmd "pamcut -right=1 -cropright=1 testgrid.pbm"
+invCmd "pamcut -top=1 -croptop=1 testgrid.pbm"
+invCmd "pamcut -bottom=1 -cropbottom=1 testgrid.pbm"
+invCmd "pamcut -left=1 -cropleft=1 testgrid.pbm"
+
+# excessive amounts
+invCmd "pamcut -cropleft=14 testgrid.pbm"
+invCmd "pamcut -cropleft=7 -cropright=8 testgrid.pbm"
+invCmd "pamcut -left=7 -right=6 testgrid.pbm"
+invCmd "pamcut -croptop=16 testgrid.pbm"
+invCmd "pamcut -croptop=8 -cropbottom=8 testgrid.pbm"
+invCmd "pamcut -top=10 -bottom=9 testgrid.pbm"
+
+# pad absent
+invCmd "pamcut -cropleft=1 -width=14 testgrid.pbm"
+invCmd "pamcut -croptop=1  -height=16 testgrid.pbm"
+
+# legacy style: insufficient number of positional parameters
+invCmd "pamcut 5 testimg.ppm"
+invCmd "pamcut 5 4 testimg.ppm"
+invCmd "pamcut 5 5 30 testimg.ppm"
diff --git a/test/pamdepth-roundtrip.ok b/test/pamdepth-roundtrip.ok
index 89db1a57..28db2ee1 100644
--- a/test/pamdepth-roundtrip.ok
+++ b/test/pamdepth-roundtrip.ok
@@ -5,4 +5,4 @@
 1926073387 101484
 1926073387 101484
 1926073387 101484
-2425386270 41
+281226646 481
diff --git a/test/pamdepth-roundtrip.test b/test/pamdepth-roundtrip.test
index 0c7cb8b0..6da9a612 100755
--- a/test/pamdepth-roundtrip.test
+++ b/test/pamdepth-roundtrip.test
@@ -1,4 +1,4 @@
-#! /bin/bash
+#! /bin/sh
 # This script tests: pamdepth pgmtopbm
 # Also requires:
 
@@ -9,5 +9,5 @@ pamdepth $i testimg.ppm | \
   pamdepth 255 | cksum
 done
 
-pamdepth 255 testgrid.pbm | pamdepth 1 | \
+pamdepth 255 maze.pbm | pamdepth 1 | \
   pgmtopbm -th -val=0.5 | cksum
diff --git a/test/pamdepth.ok b/test/pamdepth.ok
index 1bd897ac..fefcc14f 100644
--- a/test/pamdepth.ok
+++ b/test/pamdepth.ok
@@ -10,5 +10,5 @@ stdin: PAM RAW 14 16 1 1 GRAYSCALE
 Test 2
 0 0 : 0
 Test Invalid
-Expected failure 1 1
-Expected failure 2 1
+Expected failure 1 (no output)
+Expected failure 2 (no output)
diff --git a/test/pamdepth.test b/test/pamdepth.test
index da198973..e938a630 100755
--- a/test/pamdepth.test
+++ b/test/pamdepth.test
@@ -24,15 +24,7 @@ pamdepth 255 testimg.ppm | cmp -s - testimg.ppm
 # Test Invalid
 echo "Test Invalid"
 
-echo 1>&2
-echo "Invalid command-line argument combinations." 1>&2
-echo "Error messages should appear below the line." 1>&2
-echo "-----------------------------------------------------------" 1>&2
+. ${srcdir}/test-invalid.inc
 
-pamdepth 0 testgrid.pbm > ${test_out} || \
-   echo -n "Expected failure 1"; test -s ${test_out}; echo " "$?
-
-pamdepth 65536 testimg.ppm > ${test_out} || \
-   echo -n "Expected failure 2"; test -s ${test_out}; echo " "$?
-
-rm ${test_out}
\ No newline at end of file
+invCmd "pamdepth 0 testgrid.pbm"
+invCmd "pamdepth 65536 testimg.ppm"
diff --git a/test/pamdice-roundtrip.ok b/test/pamdice-roundtrip.ok
index 4a850615..9f648fd0 100644
--- a/test/pamdice-roundtrip.ok
+++ b/test/pamdice-roundtrip.ok
@@ -1,18 +1,16 @@
-test 1
-2425386270 41
-test 2
-2425386270 41
-test 3
-2425386270 41
-test 4.
+Test 1.  Should print 281226646 481
+281226646 481
+Test 2.  Should print 281226646 481
+281226646 481
+Test 3.  Should print 281226646 481
+281226646 481
+Test 4.  Should print 281226646 481
+281226646 481
+Test 5.  Should print 1926073387 101484 five times
 1926073387 101484
-test 4.-hoverlap=0
 1926073387 101484
-test 4.-hoverlap=2
 1926073387 101484
-test 4.-voverlap=0
 1926073387 101484
-test 4.-voverlap=2
 1926073387 101484
-test 5
+Test 6.  Should print 1926073387 101484
 1926073387 101484
diff --git a/test/pamdice-roundtrip.test b/test/pamdice-roundtrip.test
index c5ccde66..4d3fba19 100755
--- a/test/pamdice-roundtrip.test
+++ b/test/pamdice-roundtrip.test
@@ -1,38 +1,60 @@
-#! /bin/bash
+#! /bin/sh
 # This script tests: pamdice pamundice
-# Also requires:
-
+# Also requires: pamfile
 
 tmpdir=${tmpdir:-/tmp}
 fname_stem=${tmpdir}/pamdice_part
 
-echo test 1
+mazesize=$(pamfile -size maze.pbm)
+mw=$(echo ${mazesize} | cut -d " " -f 1)
+mh=$(echo ${mazesize} | cut -d " " -f 2)
+
+echo "Test 1.  Should print 281226646 481"
 
-pamdice testgrid.pbm -outstem=${fname_stem}
+pamdice maze.pbm -outstem=${fname_stem}
 pamundice ${fname_stem}_%1d_%1a.pbm -down=1 -across=1 | cksum
 rm ${fname_stem}_0_0.pbm
 
-echo test 2
+echo "Test 2.  Should print 281226646 481"
+
+width=10
+tiles=$(( (${mw}+${width}-1) / ${width} ))
+
+
+pamdice maze.pbm -outstem=${fname_stem} -width=${width}
+pamundice ${fname_stem}_%1d_%1a.pbm -across=${tiles} | cksum
+rm ${fname_stem}_*_*.pbm
+
+echo "Test 3.  Should print 281226646 481"
 
-pamdice testgrid.pbm -outstem=${fname_stem} -width=3
-pamundice ${fname_stem}_%1d_%1a.pbm -across=5 | cksum
-rm ${fname_stem}_0_?.pbm
+width=5
+tiles=$(( (${mw}+${width}-1) / ${width} ))
 
-echo test 3
+pamdice maze.pbm -outstem=${fname_stem} -width=${width}
+pamundice ${fname_stem}_%1d_%2a.pbm -across=${tiles} | cksum
+rm ${fname_stem}_*_*.pbm
 
-pamdice testgrid.pbm -outstem=${fname_stem} -height=4
-pamundice ${fname_stem}_%1d_%1a.pbm -down=4 | cksum
-rm ${fname_stem}_?_0.pbm
 
-for flags in "" "-hoverlap=0" "-hoverlap=2" "-voverlap=0" "-voverlap=2"
+echo "Test 4.  Should print 281226646 481"
+
+height=10
+tiles=$(( (${mh}+${height}-1) / ${height} ))
+
+pamdice maze.pbm -outstem=${fname_stem} -height=${height}
+pamundice ${fname_stem}_%1d_%1a.pbm -down=${tiles} | cksum
+rm ${fname_stem}_*_*.pbm
+
+echo "Test 5.  Should print 1926073387 101484 five times"
+
+for option in "" "-hoverlap=0" "-hoverlap=2" "-voverlap=0" "-voverlap=2"
   do
-  echo test 4.${flags}
   pamdice testimg.ppm -outstem=${fname_stem} -width=50 -height=40
   pamundice ${fname_stem}_%1d_%1a.ppm -down=4 -across=5 | cksum
   rm ${fname_stem}_?_?.ppm
   done
 
-echo test 5
+echo "Test 6.  Should print 1926073387 101484"
+
 pamdice testimg.ppm -outstem=${fname_stem} -width=20 -height=10
 ls ${fname_stem}*.ppm | pamundice -listfile=- -across=12 -down=15 | cksum
 rm ${fname_stem}_??_??.ppm
\ No newline at end of file
diff --git a/test/pamdice.ok b/test/pamdice.ok
index 99504ec0..9e978168 100644
--- a/test/pamdice.ok
+++ b/test/pamdice.ok
@@ -13,9 +13,14 @@ P1@1 1@0@
 P1@1 1@1@
 Test Invalid
 Expected failure 1
+Expected failure 1.rm
 Expected failure 2
+Expected failure 2.rm
 Expected failure 3
+Expected failure 3.rm
 Expected failure 4
+Expected failure 4.rm
 Expected failure 5
+Expected failure 5.rm
 Expected failure 6
-Expected failure (output files)
+Expected failure 6.rm
diff --git a/test/pamdice.test b/test/pamdice.test
index 3199fd4a..04dd4d78 100755
--- a/test/pamdice.test
+++ b/test/pamdice.test
@@ -1,4 +1,4 @@
-#! /bin/bash
+#! /bin/sh
 # This script tests: pamdice
 # Also requires: pbmmake
 
@@ -11,7 +11,7 @@ echo "Test 1."
 pbmmake -w 2 5 | pamdice -height=1 -width=1 -outstem=${fname_stem} -plain
 ls ${fname_stem}*.pbm | while read file
   do
-  cat ${file} | tr '\n'  '@' ; echo 
+  cat ${file} | tr '\n'  '@' ; echo
   done | sort | uniq -c | sed 's/^ *//'
 
 rm ${fname_stem}*.pbm
@@ -22,7 +22,7 @@ echo "Test 2."
 pbmmake -g 2 5 | pamdice -height=1 -width=1 -outstem=${fname_stem} -plain
 ls ${fname_stem}*.pbm | while read file
   do
-  cat ${file} | tr '\n'  '@' ; echo 
+  cat ${file} | tr '\n'  '@' ; echo
   done
 
 rm ${fname_stem}*.pbm
@@ -36,33 +36,44 @@ echo "Invalid command-line argument combinations." 1>&2
 echo "Error messages should appear below the line." 1>&2
 echo "-----------------------------------------------------------" 1>&2
 
+# No output files should be producd.  With nothing to remove,
+# the rm commands should always fail.
+
 # No input file
 pamdice -width=10 -height=10  -outstem=${fname_stem} /dev/null || \
 echo "Expected failure 1"
+rm ${fname_stem}* ||
+echo "Expected failure 1.rm"
 
 # No -outstem
 pamdice -width=10 -height=10 testgrid.pbm || \
 echo "Expected failure 2"
+rm ${fname_stem}* ||
+echo "Expected failure 2.rm"
 
 # -width=0
 pamdice -width=0 -height=10 -outstem=${fname_stem} testgrid.pbm || \
 echo "Expected failure 3"
+rm ${fname_stem}* ||
+echo "Expected failure 3.rm"
 
 # -height=0
 pamdice -width=10 -height=0 -outstem=${fname_stem} testgrid.pbm || \
 echo "Expected failure 4"
+rm ${fname_stem}* ||
+echo "Expected failure 4.rm"
 
 # -hoverlap larger than width
 pamdice -width=10 -height=10 -hoverlap=11 \
   -outstem=${fname_stem} testgrid.pbm || \
 echo "Expected failure 5"
+rm ${fname_stem}* ||
+echo "Expected failure 5.rm"
+
 
 # -voverlap larger than height
 pamdice -width=10 -height=10 -voverlap=11 \
   -outstem=${fname_stem} testgrid.pbm || \
 echo "Expected failure 6"
-
-
-# Ensure that no output files are produced by the above
-ls ${fname_stem}* || \
-echo "Expected failure (output files)"
\ No newline at end of file
+rm ${fname_stem}* ||
+echo "Expected failure 6.rm"
diff --git a/test/pamditherbw-random.ok b/test/pamditherbw-random.ok
new file mode 100644
index 00000000..d21e3613
--- /dev/null
+++ b/test/pamditherbw-random.ok
@@ -0,0 +1,6 @@
+Test: Floyd-Steinberg
+Should print 3849876047 33894
+3849876047 33894
+Test: Atkinson
+Should print 2887295695 33894
+2887295695 33894
diff --git a/test/pamditherbw-random.test b/test/pamditherbw-random.test
new file mode 100755
index 00000000..7a5de7bd
--- /dev/null
+++ b/test/pamditherbw-random.test
@@ -0,0 +1,23 @@
+#! /bin/sh
+# This script tests: pamditherbw
+# Also requires: pamchannel pamtopnm
+
+tmpdir=${tmpdir:-/tmp}
+test_red=${tmpdir}/testimg.red
+
+# Test 1.  Floyd-Steinberg
+echo "Test: Floyd-Steinberg"
+echo "Should print 3849876047 33894"
+
+pamchannel -infile=testimg.ppm -tupletype="GRAYSCALE" 0 | pamtopnm | \
+  tee ${test_red} | \
+  pamditherbw -fs -randomseed=1 | cksum
+
+
+# Test 2. Atkinson
+echo "Test: Atkinson"
+echo "Should print 2887295695 33894"
+
+pamditherbw -atkinson -randomseed=1 ${test_red} | cksum
+
+rm ${test_red}
\ No newline at end of file
diff --git a/test/pamditherbw.ok b/test/pamditherbw.ok
index 02200d0f..da3f6e8b 100644
--- a/test/pamditherbw.ok
+++ b/test/pamditherbw.ok
@@ -14,15 +14,15 @@ Test: Cluster-4
 Test: Cluster-8
 3493215477 33894
 Test: Invalid
-Expected failure 1 1
-Expected failure 2 1
-Expected failure 3 1
-Expected failure 4 1
-Expected failure 5 1
-Expected failure 6 1
-Expected failure 7 1
-Expected failure 8 1
-Expected failure 9 1
-Expected failure 10 1
-Expected failure 11 1
-Expected failure 12 1
+Expected failure 1 (no output)
+Expected failure 2 (no output)
+Expected failure 3 (no output)
+Expected failure 4 (no output)
+Expected failure 5 (no output)
+Expected failure 6 (no output)
+Expected failure 7 (no output)
+Expected failure 8 (no output)
+Expected failure 9 (no output)
+Expected failure 10 (no output)
+Expected failure 11 (no output)
+Expected failure 12 (no output)
diff --git a/test/pamditherbw.test b/test/pamditherbw.test
index 40eb0a4d..76bcdbd7 100755
--- a/test/pamditherbw.test
+++ b/test/pamditherbw.test
@@ -1,4 +1,4 @@
-#! /bin/bash
+#! /bin/sh
 # This script tests: pamditherbw
 # Also requires: pamchannel pamtopnm
 
@@ -39,36 +39,19 @@ pamditherbw -cluster8 ${test_red} | cksum
 
 echo "Test: Invalid"
 
-test_out=${tmpdir}/test_out
-
-echo 1>&2
-echo "Invalid command-line argument combinations." 1>&2
-echo "Error messages should appear below the line." 1>&2
-echo "-----------------------------------------------------------" 1>&2
-
-pamditherbw -fs -atkinson       ${test_red} > ${test_out} || \
- echo -n "Expected failure 1"; test -s ${test_out}; echo " "$?
-pamditherbw -floyd -atkinson    ${test_red} > ${test_out} || \
- echo -n "Expected failure 2"; test -s ${test_out}; echo " "$?
-pamditherbw -dither8  -cluster3 ${test_red} > ${test_out} || \
- echo -n "Expected failure 3"; test -s ${test_out}; echo " "$?
-pamditherbw -cluster3 -cluster4 ${test_red} > ${test_out} || \
- echo -n "Expected failure 4"; test -s ${test_out}; echo " "$?
-pamditherbw -cluster3 -cluster8 ${test_red} > ${test_out} || \
- echo -n "Expected failure 5"; test -s ${test_out}; echo " "$?
-pamditherbw -cluster4 -cluster8 ${test_red} > ${test_out} || \
- echo -n "Expected failure 6"; test -s ${test_out}; echo " "$?
-pamditherbw -hilbert -threshold ${test_red} > ${test_out} || \
- echo -n "Expected failure 7"; test -s ${test_out}; echo " "$?
-pamditherbw -clump=8            ${test_red} > ${test_out} || \
- echo -n "Expected failure 8"; test -s ${test_out}; echo " "$?
-pamditherbw -fs -clump=8        ${test_red} > ${test_out} || \
- echo -n "Expected failure 9"; test -s ${test_out}; echo " "$?
-pamditherbw -hilbert -clump=1   ${test_red} > ${test_out} || \
- echo -n "Expected failure 10"; test -s ${test_out}; echo " "$?
-pamditherbw -th -value=-1       ${test_red} > ${test_out} || \
- echo -n "Expected failure 11"; test -s ${test_out}; echo " "$?
-pamditherbw -th -value=1.1      ${test_red} > ${test_out} || \
- echo -n "Expected failure 12"; test -s ${test_out}; echo " "$?
-
-rm ${test_red} ${test_out}
+. ${srcdir}/test-invalid.inc
+
+invCmd "pamditherbw -fs -atkinson       ${test_red}"
+invCmd "pamditherbw -floyd -atkinson    ${test_red}"
+invCmd "pamditherbw -dither8  -cluster3 ${test_red}"
+invCmd "pamditherbw -cluster3 -cluster4 ${test_red}"
+invCmd "pamditherbw -cluster3 -cluster8 ${test_red}"
+invCmd "pamditherbw -cluster4 -cluster8 ${test_red}"
+invCmd "pamditherbw -hilbert -threshold ${test_red}"
+invCmd "pamditherbw -clump=8            ${test_red}"
+invCmd "pamditherbw -fs -clump=8        ${test_red}"
+invCmd "pamditherbw -hilbert -clump=1   ${test_red}"
+invCmd "pamditherbw -th -value=-1       ${test_red}"
+invCmd "pamditherbw -th -value=1.1      ${test_red}"
+
+rm ${test_red}
diff --git a/test/pamedge.test b/test/pamedge.test
index c63b30cc..8121f858 100755
--- a/test/pamedge.test
+++ b/test/pamedge.test
@@ -1,4 +1,4 @@
-#! /bin/bash
+#! /bin/sh
 # This script tests: pamedge
 # Also requires: pbmpscale pbmtext pgmtopbm pgmtopgm ppmtopgm
 
diff --git a/test/pamendian-roundtrip.ok b/test/pamendian-roundtrip.ok
index 50450617..6245abb9 100644
--- a/test/pamendian-roundtrip.ok
+++ b/test/pamendian-roundtrip.ok
@@ -1,4 +1,5 @@
-Test 1: Should print '0 0 0 : 0'
+Test 1.  Should print '0 0 0 : 0'
 0 0 0 : 0
-Test 2 should print echo '0 0 0 0 0 : 0'
+Test 2.  Should print '0 0 0 0 0 : 0' twice
+0 0 0 0 0 : 0
 0 0 0 0 0 : 0
diff --git a/test/pamendian-roundtrip.test b/test/pamendian-roundtrip.test
index aed03c76..b060b704 100755
--- a/test/pamendian-roundtrip.test
+++ b/test/pamendian-roundtrip.test
@@ -2,7 +2,7 @@
 # This script tests: pamendian
 # Also requires: pamdepth pgmtopbm pamseq
 
-echo "Test 1: Should print '0 0 0 : 0'" 
+echo "Test 1.  Should print '0 0 0 : 0'" 
 
 tmpdir=${tmpdir:-/tmp}
 test0_pam=${tmpdir}/test0.pam
@@ -15,8 +15,12 @@ pamendian < ${test0_pam} | pamendian |\
 rm ${test0_pam}
 
 
-echo "Test 2 should print echo '0 0 0 0 0 : 0'" 
+echo "Test 2.  Should print '0 0 0 0 0 : 0' twice" 
 
 pamdepth 65535 testgrid.pbm | pamendian | pamendian | \
   pgmtopbm -th -val=0.5 | cmp -s - testgrid.pbm
+  echo ${PIPESTATUS[@]} ":" $?
+
+pamdepth 4095 maze.pbm | pamendian | pamendian | \
+  pgmtopbm -th -val=0.5 | cmp -s - maze.pbm
   echo ${PIPESTATUS[@]} ":" $?
\ No newline at end of file
diff --git a/test/pamenlarge-pamscale-point.test b/test/pamenlarge-pamscale-point.test
index 08b34bb7..f0f0948b 100755
--- a/test/pamenlarge-pamscale-point.test
+++ b/test/pamenlarge-pamscale-point.test
@@ -29,8 +29,8 @@ enlarge_pbm=${tmpdir}/enlarge.pbm
 for option in "6 -nomix" "15 -nomix -linear" "24 -nomix"
   do
   scale=${option%% *}
-  pamenlarge $scale testgrid.pbm > ${enlarge_pbm}
-  pamscale   $option testgrid.pbm | cmp -s - ${enlarge_pbm}  
+  pamenlarge $scale maze.pbm > ${enlarge_pbm}
+  pamscale   $option maze.pbm | cmp -s - ${enlarge_pbm}  
   echo $option ${PIPESTATUS[@]} ":" $?
   rm  ${enlarge_pbm}
   done
diff --git a/test/pamenlarge-pbm.test b/test/pamenlarge-pbm.test
index 10c00ba0..bea740c6 100755
--- a/test/pamenlarge-pbm.test
+++ b/test/pamenlarge-pbm.test
@@ -1,4 +1,4 @@
-#! /bin/bash
+#! /bin/sh
 # This script tests: pamenlarge
 # Also requires: pbmmake pnmpad
 
@@ -18,22 +18,26 @@ LC_ALL=C awk 'BEGIN { print "P4";         # header
 # Test 1.
 echo "test 1"
  
-for xs in `seq 23`
+for xs in 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
+  # for xs in `seq 23`
   do
-  pamenlarge -xscale=$xs ${complete256_pbm} | cksum
+  pamenlarge -xscale=${xs} ${complete256_pbm} | cksum
   done
 
 # Test 2.
 echo "test 2"
 
-for xs1 in `seq 15`
+for xs1 in 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
+  # for xs1 in `seq 15`
   do
-  xs2=$((30-$xs1))
-  pamenlarge -xscale=$xs1 ${complete256_pbm} | pamenlarge -xscale=$xs2 | cksum
-  if [ $xs1 != $xs2 ]; then
-  pamenlarge -xscale=$xs2 ${complete256_pbm} | pamenlarge -xscale=$xs1 | cksum
+  xs2=$((30-${xs1}))
+  pamenlarge -xscale=${xs1} ${complete256_pbm} | \
+    pamenlarge -xscale=${xs2} | cksum
+  if [ ${xs1} != ${xs2} ]; then
+  pamenlarge -xscale=${xs2} ${complete256_pbm} | \
+    pamenlarge -xscale=${xs1} | cksum
   fi
-  pamenlarge -xscale=$(($xs1 * $xs2)) ${complete256_pbm} | cksum
+  pamenlarge -xscale=$((${xs1} * ${xs2})) ${complete256_pbm} | cksum
   done
 
 rm ${complete256_pbm}
@@ -43,19 +47,19 @@ echo "test 3"
 
 test3_pbm=${tmpdir}/test3.pbm
 
-for width in `seq 16`
+for width in 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16  # for width in `seq 16`
   do
   pbmmake -g ${width} 1 | pnmpad -top=1 -white | \
       pnmpad -bottom=1 -black > ${test3_pbm}.${width}
   done
  
-  for xscale in `seq 16`
-    do echo -n ${xscale} " "
-    for width in `seq 16`
+  for xscale in 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16  # for xscale in `seq 16`
+    do printf "%d  " ${xscale}
+    for width in 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16  # for width in `seq 16` 
       do pamenlarge -xscale=${xscale} ${test3_pbm}.${width} ; done | cksum
       #
       # unlike most other tests we take the cksum of a composite PBM file
       #
     done
 
-rm ${test3_pbm}.[1-9]  ${test3_pbm}.1[1-6]
\ No newline at end of file
+rm ${test3_pbm}.[1-9]  ${test3_pbm}.1[0-6]
diff --git a/test/pamenlarge.ok b/test/pamenlarge.ok
index a2408871..9107e870 100644
--- a/test/pamenlarge.ok
+++ b/test/pamenlarge.ok
@@ -1,4 +1,10 @@
+Test 1.  Should print 3424505894 913236
 3424505894 913236
+Test 2.  Should print 3763267672 304422
 3763267672 304422
-3342398172 297
+Test 3.  Should print 3748791794 3905
+3748791794 3905
+Test 4.  Should print 1618994486 1194
+1618994486 1194
+Test 5.  Should print 398497872 6806
 398497872 6806
diff --git a/test/pamenlarge.test b/test/pamenlarge.test
index 3820f47e..7c46881d 100755
--- a/test/pamenlarge.test
+++ b/test/pamenlarge.test
@@ -1,14 +1,15 @@
-#! /bin/bash
+#! /bin/sh
 # This script tests: pamenlarge
 # Also requires: pamchannel pamseq pamtopnm
 
-
-# Test 1.  Should print 3424505894 913236
+echo "Test 1.  Should print 3424505894 913236"
 pamenlarge 3 testimg.ppm | cksum
-# Test 2.  Should print 3763267672 304422
+echo "Test 2.  Should print 3763267672 304422"
 pamchannel -infile=testimg.ppm -tupletype="GRAYSCALE" 0 | pamtopnm | \
   pamenlarge 3 | cksum
-# Test 3.  Should print 3342398172 297
-pamenlarge 3 testgrid.pbm | cksum
-# Test 4.  Should print 398497872 6806
+echo "Test 3.  Should print 3748791794 3905"
+pamenlarge 3 maze.pbm | cksum
+echo "Test 4.  Should print 1618994486 1194"
+pamenlarge -xscale=21 -yscale=2 testgrid.pbm | cksum
+echo "Test 5.  Should print 398497872 6806"
 pamseq 3 4 | pamtopnm -assume | pamenlarge 3 -plain | cksum
diff --git a/test/pamexec.test b/test/pamexec.test
index 44c11339..7c2bf054 100755
--- a/test/pamexec.test
+++ b/test/pamexec.test
@@ -1,4 +1,4 @@
-#! /bin/bash
+#! /bin/sh
 # This script tests: pamexec
 # Also requires: pbmtext pamfile pbmminkowski pbmtog3 g3topbm
 
@@ -6,7 +6,9 @@ tmpdir=${tmpdir:-/tmp}
 test_pbm=${tmpdir}/test.pbm
 combined_pbm=${tmpdir}/combined.pbm
 
-for i in `seq 0 9`; do echo $i | pbmtext -builtin=fixed > ${test_pbm}$i; done
+for i in 0 1 2 3 4 5 6 7 8 9  # for i in `seq 0 9`
+  do echo ${i} | pbmtext -builtin=fixed > ${test_pbm}${i}
+  done
 cat ${test_pbm}[0123456789] > ${combined_pbm}
 
 echo "Test 1 : Should print 10 stdin: PBM RAW 21 24 1 1 BLACKANDWHITE twice"
@@ -16,7 +18,8 @@ pamexec "pamfile -mach" ${combined_pbm}  | uniq -c | sed 's/^ *//'
 
 echo "Test 2: Should print 1791121103 989 twice"
 
-for i in `seq 0 9`; do pbmminkowski ${test_pbm}$i   ; done | cksum
+for i in 0 1 2 3 4 5 6 7 8 9  # for i in `seq 0 9`
+  do pbmminkowski ${test_pbm}${i}; done | cksum
 pamexec "pbmminkowski" ${combined_pbm} | cksum
 
 rm ${test_pbm}[0123456789]
@@ -27,7 +30,8 @@ pamexec "pbmtog3 -no | g3topbm" ${combined_pbm}  | cksum
 cat ${combined_pbm}  | cksum
 
 echo "Invalid command" 1>&2
-echo "Errors message should appear below the line." 1>&2
+echo "Executes quietly." 1>&2
+echo "Errors message should not appear below the line." 1>&2
 echo "-----------------------------------------------------------" 1>&2
 
 echo "Test Invalid: Should not print anything"
@@ -35,4 +39,4 @@ echo "Test Invalid: Should not print anything"
 pamexec "false" ${combined_pbm}
 pamexec "pamfile | false" ${combined_pbm}
 
-rm ${combined_pbm}
\ No newline at end of file
+rm ${combined_pbm}
diff --git a/test/pamfile.ok b/test/pamfile.ok
index e222592c..91beec60 100644
--- a/test/pamfile.ok
+++ b/test/pamfile.ok
@@ -14,6 +14,6 @@ Test 3
 testimg.ppm: PPM RAW 227 149 3 255 RGB
 stdin: PBM RAW 14 16 1 1 BLACKANDWHITE
 Test Invalid
-Expected failure 1 1
-Expected failure 2 1
-Expected failure 3 1
+Expected failure 1 (no output)
+Expected failure 2 (no output)
+Expected failure 3 (no output)
diff --git a/test/pamfile.test b/test/pamfile.test
index aa3e2895..d605326d 100755
--- a/test/pamfile.test
+++ b/test/pamfile.test
@@ -1,4 +1,4 @@
-#! /bin/bash
+#! /bin/sh
 # This script tests: pamfile
 # Also requires: pamchannel pamtopnm
 
@@ -22,19 +22,13 @@ cat testgrid.pbm testimg.ppm testgrid.pbm | pamfile -machine
 
 echo "Test Invalid"
 
-tmpdir=${tmpdir:-/tmp}
-test_out=${tmpdir}/test_out
+. ${srcdir}/test-invalid.inc
 
-echo 1>&2
-echo "Invalid command-line argument combinations." 1>&2
-echo "Error messages should appear below the line." 1>&2
-echo "-----------------------------------------------------------" 1>&2
+invCmd "pamfile -size -machine  testimg.ppm"
+invCmd "pamfile -count -machine testimg.ppm"
 
-pamfile -size -machine  testimg.ppm > ${test_out} || \
-  echo -n "Expected failure 1"; test -s ${test_out}; echo " "$?
-pamfile -count -machine testimg.ppm > ${test_out} || \
-  echo -n "Expected failure 2"; test -s ${test_out}; echo " "$?
-head -n1 testimg.ppm | pamfile > ${test_out} || \
-  echo -n "Expected failure 3"; test -s ${test_out}; echo " "$?
+head1_ppm=${tmpdir}/head1.ppm
 
-rm ${test_out}
+head -n1 testimg.ppm > ${head1_ppm}
+invCmd "pamfile  ${head1_ppm}"
+rm ${head1_ppm}
diff --git a/test/pamfind.ok b/test/pamfind.ok
index de53166e..7776ba37 100644
--- a/test/pamfind.ok
+++ b/test/pamfind.ok
@@ -258,7 +258,7 @@ Test 3
 okay
 okay
 Test Invalid
-Expected failure 1 1
-Expected failure 2 1
-Expected failure 3 1
-Expected failure 4 1
+Expected failure 1 (no output)
+Expected failure 2 (no output)
+Expected failure 3 (no output)
+Expected failure 4 (no output)
diff --git a/test/pamfind.test b/test/pamfind.test
index 074dde5c..079e35f4 100755
--- a/test/pamfind.test
+++ b/test/pamfind.test
@@ -1,4 +1,4 @@
-#! /bin/bash
+#! /bin/sh
 # This script tests: pamfind
 # Also requires:
 
@@ -8,7 +8,7 @@ sorted1_res=${tmpdir}/pamfind_sorted1.res
 
 # Test 1
 echo "Test 1"
-pamfind -color=grey17     testimg.ppm 
+pamfind -color=grey17     testimg.ppm
 pamfind -target=210,57,41 testimg.ppm
 pamfind -target=50,55,49 -machine testimg.ppm
 
@@ -25,31 +25,17 @@ pamfind -target=1 testgrid.pbm | sort > ${sorted1_res}
 comm -3 ${sorted0_res}  ${sorted1_res}  |
   awk 'END {if (NR==226) print  "okay";
             else printf("failure (line count=%d)\n", NR)}'
-comm -12 ${sorted0_res}  ${sorted1_res} | 
+comm -12 ${sorted0_res}  ${sorted1_res} |
   awk '{print}; END { if(NR == 0) print  "okay";
             else printf("failure (line count=%d)\n", NR)}'
 
 rm ${sorted0_res} ${sorted1_res}
 
-# Test 4
-
-tmpdir=${tmpdir:-/tmp}
-test_out=${tmpdir}/test_out
-
-echo 1>&2
-echo "Invalid command-line argument combinations." 1>&2
-echo "Error messages should appear below the line." 1>&2
-echo "-----------------------------------------------------------" 1>&2
-
 echo "Test Invalid"
 
-pamfind -color=black -target=1,1,1 testimg.ppm > ${test_out} || \
-  echo -n "Expected failure 1"; test -s ${test_out}; echo " "$?
-pamfind -target=0,0 testimg.ppm > ${test_out} || \
-  echo -n "Expected failure 2"; test -s ${test_out}; echo " "$?
-pamfind -target=0,0,0,0 testimg.ppm > ${test_out} || \
-  echo -n "Expected failure 3"; test -s ${test_out}; echo " "$?
-pamfind testimg.ppm > ${test_out} || \
-  echo -n "Expected failure 4"; test -s ${test_out}; echo " "$?
+. ${srcdir}/test-invalid.inc
 
-rm ${test_out}
+invCmd "pamfind -color=black -target=1,1,1 testimg.ppm"
+invCmd "pamfind -target=0,0 testimg.ppm"
+invCmd "pamfind -target=0,0,0,0 testimg.ppm"
+invCmd "pamfind testimg.ppm"
diff --git a/test/pamfix.ok b/test/pamfix.ok
index 7302f91e..ba1c678a 100644
--- a/test/pamfix.ok
+++ b/test/pamfix.ok
@@ -62,7 +62,7 @@ P2
 0 1 2 
 3 4 7 
 0 0 0 
-Test invalid
-Expected failure 1 1
-Expected failure 2 1
-Expected failure 3 1
+Test Invalid
+Expected failure 1 (no output)
+Expected failure 2 (no output)
+Expected failure 3 (no output)
diff --git a/test/pamfix.test b/test/pamfix.test
index e6021b56..c274de86 100755
--- a/test/pamfix.test
+++ b/test/pamfix.test
@@ -1,48 +1,50 @@
-#! /bin/bash
+#! /bin/sh
 # This script tests: pamfix
-# Also requires:
+# Also requires: pbmmake
+
+tmpdir=${tmpdir:-/tmp}
 
 # Test 1.
 echo "Test 1"
 
 pbmmake -g 5 5 | pamfix -truncate -plain
 
-echo -e "P1\n5 5\n01010\n10101\n01010\n00001\n1" |\
+printf "P1\n5 5\n01010\n10101\n01010\n00001\n1\n" |\
   pamfix -truncate -plain
 
-echo -e "P1\n5 5\n01010\n10101\n01010\n0000\n1" |\
+printf "P1\n5 5\n01010\n10101\n01010\n0000\n1\n" |\
   pamfix -truncate -plain
 
-echo -e "P1\n5 5\n01010\n10102\n01010\n00001\n1" |\
+printf "P1\n5 5\n01010\n10102\n01010\n00001\n1\n" |\
   pamfix -truncate -plain
 
 # Test 2
 
 echo "Test 2"
 
-echo -e "P2\n3 3\n7\n0 1 2\n3 4 5\n6 7 0" |\
+printf "P2\n3 3\n7\n0 1 2\n3 4 5\n6 7 0\n" |\
   pamfix -truncate -plain
 
-echo -e "P2\n3 3\n7\n0 1 2\n3 4 5\n6 7" |\
+printf "P2\n3 3\n7\n0 1 2\n3 4 5\n6 7\n" |\
   pamfix -truncate -plain
-echo -e "P2\n3 3\n7\n0 1 2\n3 4 5\n6 7 8" |\
+printf "P2\n3 3\n7\n0 1 2\n3 4 5\n6 7 8\n" |\
   pamfix -truncate -plain
 
-echo -e "P2\n3 3\n7\n0 1 2\n3 4 5\n6 7 8" |\
+printf "P2\n3 3\n7\n0 1 2\n3 4 5\n6 7 8\n" |\
   pamfix -change -plain
 
-echo -e "P2\n3 3\n7\n0 1 2\n3 4 5\n6 7 8" |\
+printf "P2\n3 3\n7\n0 1 2\n3 4 5\n6 7 8\n" |\
  pamfix -clip -plain
 
-echo -e "P2\n3 3\n7\n0 1 2\n3 4 8\n0 0 0" |\
+printf "P2\n3 3\n7\n0 1 2\n3 4 8\n0 0 0\n" |\
   pamfix -change -truncate -plain
 
-echo -e "P2\n3 3\n7\n0 1 2\n3 4 8\n0 0 0" |\
+printf "P2\n3 3\n7\n0 1 2\n3 4 8\n0 0 0\n" |\
   pamfix -clip -truncate -plain
 
 # Test Invalid
 
-echo "Test invalid"
+echo "Test Invalid"
 
 test_out=${tmpdir}/test_out
 
@@ -51,16 +53,17 @@ echo "Invalid command-line combination, invalid input" 1>&2
 echo "Error messages should appear below the line." 1>&2
 echo "-----------------------------------------------------------" 1>&2
 
-echo -e "P2\n3 2\n7\n0 1 2\n6 7 8" | pamfix -change -clip > ${test_out} || \
-  echo -n "Expected failure 1";
-  test -s ${test_out}; echo " "$?
-
-echo -e "P1\n5 5" | pamfix -truncate -plain > ${test_out} || \
-  echo -n "Expected failure 2";
-  test -s ${test_out}; echo " "$?
+printf "P2\n3 2\n7\n0 1 2\n6 7 8\n" | pamfix -change -clip > ${test_out} || \
+  printf "Expected failure 1 "
+  test -s ${test_out} && echo "unexpected output" || echo "(no output)"
+  rm -f ${test_out}
 
-echo -e "P2\n3 3\255" | pamfix -truncate -plain > ${test_out} || \
-  echo -n "Expected failure 3";
-  test -s ${test_out}; echo " "$?
+printf "P1\n5 5\n" | pamfix -truncate -plain > ${test_out} || \
+  printf "Expected failure 2 "
+  test -s ${test_out} && echo "unexpected output" || echo "(no output)"
+  rm -f ${test_out}
 
-rm ${test_out}
+printf "P2\n3 3\255\n" | pamfix -truncate -plain > ${test_out} || \
+  printf "Expected failure 3 "
+  test -s ${test_out} && echo "unexpected output" || echo "(no output)"
+  rm -f ${test_out}
diff --git a/test/pamflip-pbm-roundtrip.ok b/test/pamflip-pbm-roundtrip.ok
new file mode 100644
index 00000000..c72e40d6
--- /dev/null
+++ b/test/pamflip-pbm-roundtrip.ok
@@ -0,0 +1,122 @@
+Test 1.  Should print 281226646 481 seven times
+281226646 481
+281226646 481
+281226646 481
+281226646 481
+281226646 481
+281226646 481
+281226646 481
+Test 2.  Should print 1576602925 8 fourteen times
+1576602925 8
+1576602925 8
+1576602925 8
+1576602925 8
+1576602925 8
+1576602925 8
+1576602925 8
+1576602925 8
+1576602925 8
+1576602925 8
+1576602925 8
+1576602925 8
+1576602925 8
+1576602925 8
+Test 3.  Should print N : 0 thirty-two times
+1 : 0
+2 : 0
+3 : 0
+4 : 0
+5 : 0
+6 : 0
+7 : 0
+8 : 0
+9 : 0
+10 : 0
+11 : 0
+12 : 0
+13 : 0
+14 : 0
+15 : 0
+16 : 0
+17 : 0
+18 : 0
+19 : 0
+20 : 0
+21 : 0
+22 : 0
+23 : 0
+24 : 0
+25 : 0
+26 : 0
+27 : 0
+28 : 0
+29 : 0
+30 : 0
+31 : 0
+32 : 0
+Test 4.  Should print N : 0 thirty-two times
+1 : 0
+2 : 0
+3 : 0
+4 : 0
+5 : 0
+6 : 0
+7 : 0
+8 : 0
+9 : 0
+10 : 0
+11 : 0
+12 : 0
+13 : 0
+14 : 0
+15 : 0
+16 : 0
+17 : 0
+18 : 0
+19 : 0
+20 : 0
+21 : 0
+22 : 0
+23 : 0
+24 : 0
+25 : 0
+26 : 0
+27 : 0
+28 : 0
+29 : 0
+30 : 0
+31 : 0
+32 : 0
+Test 5.  Should print N : 0 thirty-two times
+1 : 0
+2 : 0
+3 : 0
+4 : 0
+5 : 0
+6 : 0
+7 : 0
+8 : 0
+9 : 0
+10 : 0
+11 : 0
+12 : 0
+13 : 0
+14 : 0
+15 : 0
+16 : 0
+17 : 0
+18 : 0
+19 : 0
+20 : 0
+21 : 0
+22 : 0
+23 : 0
+24 : 0
+25 : 0
+26 : 0
+27 : 0
+28 : 0
+29 : 0
+30 : 0
+31 : 0
+32 : 0
diff --git a/test/pamflip-pbm-roundtrip.test b/test/pamflip-pbm-roundtrip.test
new file mode 100755
index 00000000..02a342cb
--- /dev/null
+++ b/test/pamflip-pbm-roundtrip.test
@@ -0,0 +1,74 @@
+#! /bin/sh
+# This script tests: pamflip
+# Also requires: pbmmake pbmnoise
+
+tmpdir=${tmpdir:-/tmp}
+dot_pbm=${tmpdir}/dot.pbm
+noise_pbm=${tmpdir}/noise.pbm
+
+echo "Test 1.  Should print 281226646 481 seven times"
+
+pamflip -null maze.pbm | cksum
+pamflip -lr maze.pbm | pamflip -lr | cksum
+pamflip -tb maze.pbm | pamflip -tb | cksum
+pamflip -r180 maze.pbm | pamflip -r180 | cksum
+pamflip -xy maze.pbm | pamflip -xy | cksum
+pamflip -r90 maze.pbm | pamflip -r90 | pamflip -r90 | pamflip -r90 | cksum
+pamflip -r270 maze.pbm | pamflip -r270 | pamflip -r270 | pamflip -r270 | cksum
+
+echo "Test 2.  Should print 1576602925 8 fourteen times"
+
+pbmmake -b 1 1 | tee ${dot_pbm} | cksum
+pamflip -null ${dot_pbm} | cksum
+
+# the next six aren't round-trip
+pamflip -lr ${dot_pbm} | cksum
+pamflip -tb ${dot_pbm} | cksum
+pamflip -r180 ${dot_pbm} | cksum
+pamflip -xy ${dot_pbm} | cksum
+pamflip -r90 ${dot_pbm} | cksum
+pamflip -r270 ${dot_pbm} | cksum
+
+pamflip -lr ${dot_pbm} | pamflip -lr | cksum
+pamflip -tb ${dot_pbm} | pamflip -tb | cksum
+pamflip -r180 ${dot_pbm} | pamflip -r180 | cksum
+pamflip -xy ${dot_pbm} | pamflip -xy | cksum
+pamflip -r90 ${dot_pbm} | pamflip -r90 | pamflip -r90 | pamflip -r90 | cksum
+pamflip -r270 ${dot_pbm} | pamflip -r270 | \
+    pamflip -r270 | pamflip -r270 | cksum
+
+rm ${dot_pbm}
+
+echo "Test 3.  Should print N : 0 thirty-two times"
+
+for i in 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 \
+         20 21 22 23 24 25 26 27 28 29 30 31 32 
+  do
+  pbmnoise -randomseed=${i} -pack ${i} 3 > ${noise_pbm} && \
+    pamflip -lr ${noise_pbm} | pamflip -lr | cmp -s - ${noise_pbm}
+  echo $i : $?
+  rm ${noise_pbm}
+  done
+
+echo "Test 4.  Should print N : 0 thirty-two times"
+
+for i in 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 \
+         20 21 22 23 24 25 26 27 28 29 30 31 32 
+  do
+  pbmnoise -randomseed=${i} -pack 7 ${i} > ${noise_pbm} && \
+    pamflip -tb ${noise_pbm} | pamflip -tb | cmp -s - ${noise_pbm}
+  echo $i : $?
+  rm ${noise_pbm}
+  done
+
+
+echo "Test 5.  Should print N : 0 thirty-two times"
+
+for i in 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 \
+         20 21 22 23 24 25 26 27 28 29 30 31 32 
+  do
+  pbmnoise -randomseed=${i} -pack ${i} ${i} > ${noise_pbm} && \
+    pamflip -xy ${noise_pbm} | pamflip -xy | cmp -s - ${noise_pbm}
+  echo $i : $?
+  rm ${noise_pbm}
+  done
diff --git a/test/pamflip-roundtrip.ok b/test/pamflip-roundtrip.ok
index 653ab007..70ed6424 100644
--- a/test/pamflip-roundtrip.ok
+++ b/test/pamflip-roundtrip.ok
@@ -1,12 +1,65 @@
-1926073387 101484
-1926073387 101484
-1926073387 101484
-1926073387 101484
-1926073387 101484
-1926073387 101484
-2425386270 41
-2425386270 41
-2425386270 41
-2425386270 41
-2425386270 41
-2425386270 41
+Test 1.  Should print 1988581932 2989 fifteen times
+1988581932 2989
+1988581932 2989
+1988581932 2989
+1988581932 2989
+1988581932 2989
+1988581932 2989
+1988581932 2989
+1988581932 2989
+1988581932 2989
+1988581932 2989
+1988581932 2989
+1988581932 2989
+1988581932 2989
+1988581932 2989
+1988581932 2989
+Test 2.  Should print 2729474106 27 nine times
+2729474106 27
+2729474106 27
+2729474106 27
+2729474106 27
+2729474106 27
+2729474106 27
+2729474106 27
+2729474106 27
+2729474106 27
+Test 3.  Should print 1849343241 27 nine times
+1849343241 27
+1849343241 27
+1849343241 27
+1849343241 27
+1849343241 27
+1849343241 27
+1849343241 27
+1849343241 27
+1849343241 27
+Test 4.  Should print a single pixel PPM image maxval 65535 in 
+plain (ascii) format; then print 2434897823 19 fifteen times
+P3
+1 1
+65535
+1 10000 65535 
+2434897823 19
+2434897823 19
+2434897823 19
+2434897823 19
+2434897823 19
+2434897823 19
+2434897823 19
+2434897823 19
+2434897823 19
+2434897823 19
+2434897823 19
+2434897823 19
+2434897823 19
+2434897823 19
+2434897823 19
+Test 5.  Should print 281226646 481 seven times
+281226646 481
+281226646 481
+281226646 481
+281226646 481
+281226646 481
+281226646 481
+281226646 481
diff --git a/test/pamflip-roundtrip.test b/test/pamflip-roundtrip.test
index c5a34ad9..6103f6fb 100755
--- a/test/pamflip-roundtrip.test
+++ b/test/pamflip-roundtrip.test
@@ -1,35 +1,115 @@
-#! /bin/bash
+#! /bin/sh
 # This script tests: pamflip
-# Also requires:
+# Also requires: ppmpat pamseq pamtopnm
 
+tmpdir=${tmpdir:-/tmp}
+tartan_ppm=${tmpdir}/test.ppm
+test1_pgm=${tmpdir}/test1.pgm
+test2_pgm=${tmpdir}/test2.pgm
+dot_ppm=${tmpdir}/dot.ppm
 
-pamflip -lr testimg.ppm | pamflip -lr | cksum
-pamflip -tb testimg.ppm | pamflip -tb | cksum
-pamflip -r180 testimg.ppm | \
-  pamflip -r180 | cksum
-pamflip -xy testimg.ppm | pamflip -xy | cksum
-pamflip -r90 testimg.ppm | \
-  pamflip -r90 | \
-  pamflip -r90 | \
-  pamflip -r90 | cksum
-pamflip -r270 testimg.ppm | \
-  pamflip -r270 | \
-  pamflip -r270 | \
-  pamflip -r270 | cksum
-
-pamflip -lr testgrid.pbm | \
-  pamflip -lr | cksum
-pamflip -tb testgrid.pbm | \
-  pamflip -tb | cksum
-pamflip -r180 testgrid.pbm | \
+echo "Test 1.  Should print 1988581932 2989 fifteen times"
+
+ppmpat -tartan -mesh \
+       -color=rgb:0/0/0,rgb:ff/00/ff,rgb:80/90/20 31 32 > ${tartan_ppm}
+
+pamflip -null ${tartan_ppm} | cksum
+pamflip -lr ${tartan_ppm} | pamflip -lr | cksum
+pamflip -tb ${tartan_ppm} | pamflip -tb | cksum
+pamflip -r180 ${tartan_ppm} | \
   pamflip -r180 | cksum
-pamflip -xy testgrid.pbm | \
-  pamflip -xy | cksum
-pamflip -r90 testgrid.pbm | \
-  pamflip -r90 | \
-  pamflip -r90 | \
-  pamflip -r90 | cksum
-pamflip -r270 testgrid.pbm | \
-  pamflip -r270 | \
-  pamflip -r270 | \
-  pamflip -r270 | cksum
+pamflip -xy ${tartan_ppm} | pamflip -xy | cksum
+pamflip -r90 ${tartan_ppm} | pamflip -r90 | \
+  pamflip -r90 | pamflip -r90 | cksum
+pamflip -r270 ${tartan_ppm} | pamflip -r270 | \
+  pamflip -r270 | pamflip -r270 | cksum
+pamflip -xform=leftright ${tartan_ppm} | pamflip -leftright | cksum
+pamflip -xform=topbottom ${tartan_ppm} | pamflip -topbottom | cksum
+pamflip -xform=transpose ${tartan_ppm} | pamflip -transpose | cksum
+pamflip -xform=leftright,leftright ${tartan_ppm} | cksum
+pamflip -xform=topbottom,topbottom ${tartan_ppm} | cksum
+pamflip -xform=transpose,transpose ${tartan_ppm} | cksum
+pamflip -tb ${tartan_ppm} | pamflip -lr | \
+  pamflip -xform=leftright,topbottom | cksum
+pamflip -tb ${tartan_ppm} | pamflip -lr | pamflip -xy | \
+  pamflip -xform=leftright,topbottom,transpose | cksum
+
+rm ${tartan_ppm}
+
+pamseq 1 15 | pamtopnm -assume > ${test1_pgm}
+
+echo "Test 2.  Should print 2729474106 27 nine times"
+
+pamflip -null ${test1_pgm} | cksum
+pamflip -lr ${test1_pgm} | pamflip -lr | cksum
+pamflip -tb ${test1_pgm} | pamflip -tb | cksum
+pamflip -r180 ${test1_pgm} | pamflip -r180 | cksum
+pamflip -xy ${test1_pgm} | pamflip -xy | cksum
+pamflip -r90 ${test1_pgm} | pamflip -r270 | cksum
+pamflip -r270 ${test1_pgm} | pamflip -r90 | cksum
+pamflip -r90 ${test1_pgm} | pamflip -r90 | \
+  pamflip -r90 | pamflip -r90 | cksum
+pamflip -r270 ${test1_pgm} | pamflip -r270 | \
+  pamflip -r270 | pamflip -r270 | cksum
+
+pamflip -r180 ${test1_pgm} > ${test2_pgm}
+rm ${test1_pgm}
+
+echo "Test 3.  Should print 1849343241 27 nine times"
+
+pamflip -null ${test2_pgm} | cksum
+pamflip -lr ${test2_pgm} | pamflip -lr | cksum
+pamflip -tb ${test2_pgm} | pamflip -tb | cksum
+pamflip -r180 ${test2_pgm} | pamflip -r180 | cksum
+pamflip -xy ${test2_pgm} | pamflip -xy | cksum
+pamflip -r90 ${test2_pgm} | pamflip -r270 | cksum
+pamflip -r270 ${test2_pgm} | pamflip -r90 | cksum
+pamflip -r90 ${test2_pgm} | pamflip -r90 | \
+    pamflip -r90 | pamflip -r90 | cksum
+pamflip -r270 ${test2_pgm} | pamflip -r270 | \
+    pamflip -r270 | pamflip -r270 | cksum
+
+rm ${test2_pgm}
+
+cat > ${dot_ppm} <<EOF
+P3
+1 1
+65535
+1 10000 65535
+EOF
+
+echo "Test 4.  Should print a single pixel PPM image maxval 65535 in "
+echo "plain (ascii) format; then print 2434897823 19 fifteen times"
+
+pamflip -null -plain ${dot_ppm}
+
+# These are not round-trip
+pamflip -null ${dot_ppm} | cksum
+pamflip -lr ${dot_ppm} | cksum
+pamflip -tb ${dot_ppm} | cksum
+pamflip -xy ${dot_ppm} | cksum
+pamflip -r90 ${dot_ppm} | cksum
+pamflip -r180 ${dot_ppm} | cksum
+pamflip -r270 ${dot_ppm} | cksum
+
+pamflip -lr ${dot_ppm} | pamflip -lr | cksum
+pamflip -tb ${dot_ppm} | pamflip -tb | cksum
+pamflip -r180 ${dot_ppm} | pamflip -r180 | cksum
+pamflip -xy ${dot_ppm} | pamflip -xy | cksum
+pamflip -r90 ${dot_ppm} | pamflip -r270 | cksum
+pamflip -r270 ${dot_ppm} | pamflip -r90 | cksum
+pamflip -r90 ${dot_ppm} | pamflip -r90 | pamflip -r90 | pamflip -r90 | cksum
+pamflip -r270 ${dot_ppm} | pamflip -r270 | \
+    pamflip -r270 | pamflip -r270 | cksum
+
+rm ${dot_ppm}
+
+echo "Test 5.  Should print 281226646 481 seven times"
+
+pamflip -null maze.pbm | cksum
+pamflip -lr maze.pbm | pamflip -lr | cksum
+pamflip -tb maze.pbm | pamflip -tb | cksum
+pamflip -r180 maze.pbm | pamflip -r180 | cksum
+pamflip -xy maze.pbm | pamflip -xy | cksum
+pamflip -r90 maze.pbm | pamflip -r90 | pamflip -r90 | pamflip -r90 | cksum
+pamflip -r270 maze.pbm | pamflip -r270 | pamflip -r270 | pamflip -r270 | cksum
diff --git a/test/pamflip1.ok b/test/pamflip1.ok
index 64e0407e..1169d773 100644
--- a/test/pamflip1.ok
+++ b/test/pamflip1.ok
@@ -1,5 +1,10 @@
-2116496681 101484
+Test 1.  Should print 1350702313 12336
+1350702313 12336
+Test 2.  Should print 1035759697 40048
+1035759697 40048
+Test 3.  Should print 217037000 101484
 217037000 101484
-2052917888 101484
-3375384165 41
-604323149 41
+Test 4.  Should print 1178735266 481
+1178735266 481
+Test 5.  Should print 2339906255 481
+2339906255 481
diff --git a/test/pamflip1.test b/test/pamflip1.test
index 840cac73..f8da3a74 100755
--- a/test/pamflip1.test
+++ b/test/pamflip1.test
@@ -1,15 +1,19 @@
-#! /bin/bash
+#! /bin/sh
 # This script tests: pamflip
-# Also requires:
+# Also requires: pamseq
 
+echo "Test 1.  Should print 1350702313 12336"
+pamseq 3 15 | pamflip -lr | cksum
 
-# Test 1.  Should print 2116496681 101484
-pamflip -lr testimg.ppm | cksum
-# Test 2.  Should print 217037000 101484
+echo "Test 2.  Should print 1035759697 40048"
+pamseq 4 9 | pamflip -tb | cksum
+
+echo "Test 3.  Should print 217037000 101484"
 pamflip -cw testimg.ppm | cksum
-# Test 3.  Should print 2052917888 101484
-pamflip -tb testimg.ppm | cksum
-# Test 4.  Should print 3375384165 41
-pamflip -lr testgrid.pbm | cksum
-# Test 5.  Should print 604323149 41
-pamflip -tb testgrid.pbm | cksum
+
+echo "Test 4.  Should print 1178735266 481"
+pamflip -lr maze.pbm | cksum
+
+echo "Test 5.  Should print 2339906255 481"
+pamflip -tb maze.pbm | cksum
+
diff --git a/test/pamflip2.ok b/test/pamflip2.ok
index d2ea501e..e3b4185c 100644
--- a/test/pamflip2.ok
+++ b/test/pamflip2.ok
@@ -1,3 +1,6 @@
-490797850 37
-3727293411 37
-3511745816 37
+Test 1.  Should print 748061765 465
+748061765 465
+Test 2.  Should print 3217647947 465
+3217647947 465
+Test 2.  Should print 1086015439 465
+1086015439 465
diff --git a/test/pamflip2.test b/test/pamflip2.test
index 4dddb770..0393d73e 100755
--- a/test/pamflip2.test
+++ b/test/pamflip2.test
@@ -1,4 +1,4 @@
-#! /bin/bash
+#! /bin/sh
 # This script tests: pamflip
 # Also requires:
 
@@ -9,9 +9,11 @@
 ## optional SSE routine.  If you make a wrong choice during configure,
 ## this test will fail.
 
-# Test 1.  Should print 490797850 37
-pamflip -cw testgrid.pbm | cksum
-# Test 1.  Should print 3727293411 37
-pamflip -ccw testgrid.pbm | cksum
-# Test 2.  Should print 3511745816 37
-pamflip -xy testgrid.pbm | cksum
+echo "Test 1.  Should print 748061765 465"
+pamflip -cw maze.pbm | cksum
+
+echo "Test 2.  Should print 3217647947 465"
+pamflip -ccw maze.pbm | cksum
+
+echo "Test 2.  Should print 1086015439 465"
+pamflip -xy maze.pbm | cksum
diff --git a/test/pamfunc.ok b/test/pamfunc.ok
index 4a531577..0010476e 100644
--- a/test/pamfunc.ok
+++ b/test/pamfunc.ok
@@ -36,35 +36,35 @@ Test 4: Should print 1926073387 101484 eight times
 1926073387 101484
 1926073387 101484
 1926073387 101484
-Test 5: Should print 2425386270 41 six times
-2425386270 41
-2425386270 41
-2425386270 41
-2425386270 41
-2425386270 41
-2425386270 41
+Test 5: Should print 281226646 481 six times
+281226646 481
+281226646 481
+281226646 481
+281226646 481
+281226646 481
+281226646 481
 Test Invalid
-Expected failure 1 1
-Expected failure 2 1
-Expected failure 3 1
-Expected failure 4 1
-Expected failure 5 1
-Expected failure 6 1
-Expected failure 7 1
-Expected failure 8 1
-Expected failure 9 1
-Expected failure 10 1
-Expected failure 11 1
-Expected failure 12 1
-Expected failure 13 1
-Expected failure 14 1
-Expected failure 15 1
-Expected failure 16 1
-Expected failure 17 1
-Expected failure 18 1
-Expected failure 19 1
-Expected failure 20 1
-Expected failure 21 1
-Expected failure 22 1
-Expected failure 23 1
-Expected failure 24 1
+Expected failure 1 (no output)
+Expected failure 2 (no output)
+Expected failure 3 (no output)
+Expected failure 4 (no output)
+Expected failure 5 (no output)
+Expected failure 6 (no output)
+Expected failure 7 (no output)
+Expected failure 8 (no output)
+Expected failure 9 (no output)
+Expected failure 10 (no output)
+Expected failure 11 (no output)
+Expected failure 12 (no output)
+Expected failure 13 (no output)
+Expected failure 14 (no output)
+Expected failure 15 (no output)
+Expected failure 16 (no output)
+Expected failure 17 (no output)
+Expected failure 18 (no output)
+Expected failure 19 (no output)
+Expected failure 20 (no output)
+Expected failure 21 (no output)
+Expected failure 22 (no output)
+Expected failure 23 (no output)
+Expected failure 24 (no output)
diff --git a/test/pamfunc.test b/test/pamfunc.test
index f9a8a33e..b1b9edfc 100755
--- a/test/pamfunc.test
+++ b/test/pamfunc.test
@@ -1,11 +1,11 @@
-#! /bin/bash
+#! /bin/sh
 # This script tests: pamfunc
 # Also requires: pamseq pamtopnm pbmmake
 
 tmpdir=${tmpdir:-/tmp}
 input_pgm=${tmpdir}/input.pgm
 
-echo "Test 1"  
+echo "Test 1"
 
 pamseq 1 15 | pamtopnm -assume > ${input_pgm}
 pamtopnm -plain ${input_pgm} | tr '\n' ' '; echo
@@ -73,94 +73,43 @@ pamfunc -shiftleft  0 testimg.ppm | cksum
 pamfunc -shiftright 0 testimg.ppm | cksum
 
 
-echo "Test 5: Should print 2425386270 41 six times"
+echo "Test 5: Should print 281226646 481 six times"
 
-cat testgrid.pbm | cksum
+cat maze.pbm | cksum
 
-pamfunc -andmask  0x1 testgrid.pbm | cksum
-pamfunc -ormask   0x0 testgrid.pbm | cksum
-pamfunc -xormask  0x1 testgrid.pbm | pamfunc -xormask 0x1 | cksum
+pamfunc -andmask  0x1 maze.pbm | cksum
+pamfunc -ormask   0x0 maze.pbm | cksum
+pamfunc -xormask  0x1 maze.pbm | pamfunc -xormask 0x1 | cksum
 
-pamfunc -shiftleft  0 testgrid.pbm | cksum
-pamfunc -shiftright 0 testgrid.pbm | cksum
+pamfunc -shiftleft  0 maze.pbm | cksum
+pamfunc -shiftright 0 maze.pbm | cksum
 
-echo "Invalid command-line argument combinations." 1>&2
-echo "Error messages should appear below the line." 1>&2
-echo "-----------------------------------------------------------" 1>&2
 
 echo "Test Invalid"
 
-output_ppm=${tmpdir}/output.ppm
-
-pamfunc -multiplier testimg.ppm > ${output_ppm} || \
-  echo -n "Expected failure 1"
-  test -s ${output_ppm}; echo " "$?
-pamfunc -multiplier=-1 testimg.ppm > ${output_ppm} || \
-  echo -n "Expected failure 2"
-  test -s ${output_ppm}; echo " "$?
-pamfunc -divisor testimg.ppm > ${output_ppm} || \
-  echo -n "Expected failure 3"
-  test -s ${output_ppm}; echo " "$?
-pamfunc -divisor=-20 testimg.ppm > ${output_ppm} || \
-  echo -n "Expected failure 4"
-  test -s ${output_ppm}; echo " "$?
-pamfunc -adder testimg.ppm > ${output_ppm} || \
-  echo -n "Expected failure 5"
-  test -s ${output_ppm}; echo " "$?
-pamfunc -adder 0.5 testimg.ppm > ${output_ppm} || \
-  echo -n "Expected failure 6"
-  test -s ${output_ppm}; echo " "$?
-pamfunc -subtractor testimg.ppm > ${output_ppm} || \
-  echo -n "Expected failure 7"
-  test -s ${output_ppm}; echo " "$?
-pamfunc -subtractor 0.1 testimg.ppm > ${output_ppm} || \
-  echo -n "Expected failure 8"
-  test -s ${output_ppm}; echo " "$?
-pamfunc -multiplier=1 -divisor=2 testimg.ppm > ${output_ppm} || \
-  echo -n "Expected failure 9"
-  test -s ${output_ppm}; echo " "$?
-pamfunc -adder=2 -subtractor=3 testimg.ppm > ${output_ppm} || \
-  echo -n "Expected failure 10"
-  test -s ${output_ppm}; echo " "$?
-pamfunc -min testimg.ppm > ${output_ppm} || \
-  echo -n "Expected failure 11"
-  test -s ${output_ppm}; echo " "$?
-pamfunc -max testimg.ppm > ${output_ppm} || \
-  echo -n "Expected failure 12"
-  test -s ${output_ppm}; echo " "$?
-pamfunc -andmask testimg.ppm > ${output_ppm} || \
-  echo -n "Expected failure 13"
-  test -s ${output_ppm}; echo " "$?
-pamfunc -ormask testimg.ppm > ${output_ppm} || \
-  echo -n "Expected failure 14"
-  test -s ${output_ppm}; echo " "$?
-pamfunc -xormask testimg.ppm > ${output_ppm} || \
-  echo -n "Expected failure 15"
-  test -s ${output_ppm}; echo " "$?
-pamfunc -not 1 testimg.ppm > ${output_ppm} || \
-  echo -n "Expected failure 16"
-  test -s ${output_ppm}; echo " "$?
-pamfunc -min=1 -max=2 testimg.ppm > ${output_ppm} || \
-  echo -n "Expected failure 17"
-  test -s ${output_ppm}; echo " "$?
-pamfunc -andmask=1 -ormask=0 testimg.ppm > ${output_ppm} || \
-  echo -n "Expected failure 18"
-  test -s ${output_ppm}; echo " "$?
-pamfunc -andmask=0xffff testimg.ppm > ${output_ppm} || \
-  echo -n "Expected failure 19"
-  test -s ${output_ppm}; echo " "$?
-pamfunc -shiftleft testimg.ppm > ${output_ppm} || \
-  echo -n "Expected failure 20"
-  test -s ${output_ppm}; echo " "$?
-pamfunc -shiftright testimg.ppm > ${output_ppm} || \
-  echo -n "Expected failure 21"
-  test -s ${output_ppm}; echo " "$?
-pamfunc -changemaxval testimg.ppm > ${output_ppm} || \
-  echo -n "Expected failure 22"
-  test -s ${output_ppm}; echo " "$?
-pamfunc -shiftleft=1 -shiftright=1 testimg.ppm > ${output_ppm} || \
-  echo -n "Expected failure 23"
-  test -s ${output_ppm}; echo " "$?
-pamfunc -multiplier=0.5 -changemaxval=65535 testimg.ppm > ${output_ppm} || \
-  echo -n "Expected failure 24"
-  test -s ${output_ppm}; echo " "$?
+. ${srcdir}/test-invalid.inc
+
+invCmd "pamfunc -multiplier testimg.ppm"
+invCmd "pamfunc -multiplier=-1 testimg.ppm"
+invCmd "pamfunc -divisor testimg.ppm"
+invCmd "pamfunc -divisor=-20 testimg.ppm"
+invCmd "pamfunc -adder testimg.ppm"
+invCmd "pamfunc -adder 0.5 testimg.ppm"
+invCmd "pamfunc -subtractor testimg.ppm"
+invCmd "pamfunc -subtractor 0.1 testimg.ppm"
+invCmd "pamfunc -multiplier=1 -divisor=2 testimg.ppm"
+invCmd "pamfunc -adder=2 -subtractor=3 testimg.ppm"
+invCmd "pamfunc -min testimg.ppm"
+invCmd "pamfunc -max testimg.ppm"
+invCmd "pamfunc -andmask testimg.ppm"
+invCmd "pamfunc -ormask testimg.ppm"
+invCmd "pamfunc -xormask testimg.ppm"
+invCmd "pamfunc -not 1 testimg.ppm"
+invCmd "pamfunc -min=1 -max=2 testimg.ppm"
+invCmd "pamfunc -andmask=1 -ormask=0 testimg.ppm"
+invCmd "pamfunc -andmask=0xffff testimg.ppm"
+invCmd "pamfunc -shiftleft testimg.ppm"
+invCmd "pamfunc -shiftright testimg.ppm"
+invCmd "pamfunc -changemaxval testimg.ppm"
+invCmd "pamfunc -shiftleft=1 -shiftright=1 testimg.ppm"
+invCmd "pamfunc -multiplier=0.5 -changemaxval=65535 testimg.ppm"
diff --git a/test/pamgauss.ok b/test/pamgauss.ok
index e31a2ee8..98d97312 100644
--- a/test/pamgauss.ok
+++ b/test/pamgauss.ok
@@ -84,8 +84,11 @@ Test 2
 stdin:	PAM, 3 by 3 by 1 maxval 255
     Tuple type: GRAYSCALE
 Test Invalid
-Expected failure 1 1
-Expected failure 2 1
-Expected failure 3 1
-Expected failure 4 1
-Expected failure 5 1
+Expected failure 1 (no output)
+Expected failure 2 (no output)
+Expected failure 3 (no output)
+Expected failure 4 (no output)
+Expected failure 5 (no output)
+Expected failure 6 (no output)
+Expected failure 7 (no output)
+Expected failure 8 (no output)
diff --git a/test/pamgauss.test b/test/pamgauss.test
index bb006ce9..34b6630a 100755
--- a/test/pamgauss.test
+++ b/test/pamgauss.test
@@ -1,16 +1,16 @@
-#! /bin/bash
+#! /bin/sh
 # This script tests: pamgauss
 # Also requires: pamfile
 
 echo "Test 1"
 
-for i in `seq 3 11`
-do
-for s in `seq 1 9`
-do
-pamgauss $i $i -oversample=1 -sigma=.$s | cksum
-done
-done
+for i in 3 4 5 6 7 8 9 10 11    # for i in `seq 3 11`
+  do
+  for s in 1 2 3 4 5 6 7 8 9    # for s in `seq 9`
+    do
+    pamgauss ${i} ${i} -oversample=1 -sigma=.${s} | cksum
+    done
+  done
 
 echo "Test 2"
 
@@ -19,23 +19,13 @@ pamgauss 3 3 -sigma=0.5 -tupletype="GRAYSCALE" | pamfile
 
 echo "Test Invalid"
 
-echo 1>&2
-echo "Invalid command-line argument combinations." 1>&2
-echo "Error messages should appear below the line." 1>&2
-echo "-----------------------------------------------------------" 1>&2
-
-tmpdir=${tmpdir:-/tmp}
-test_out=${tmpdir}/test_out
-
-pamgauss 3 3               > ${test_out} || \
-   echo -n "Expected failure 1"; test -s ${test_out}; echo " "$?
-pamgauss 3 3   -sigma=0    > ${test_out} || \
-   echo -n "Expected failure 2"; test -s ${test_out}; echo " "$?
-pamgauss 3 3   -sigma=-1.5 > ${test_out} || \
-   echo -n "Expected failure 3"; test -s ${test_out}; echo " "$?
-pamgauss 3     -sigma=0.5  > ${test_out} || \
-   echo -n "Expected failure 4"; test -s ${test_out}; echo " "$?
-pamgauss 3 3 3 -sigma=0.5  > ${test_out} || \
-   echo -n "Expected failure 5"; test -s ${test_out}; echo " "$?
-
-rm ${test_out}
+. ${srcdir}/test-invalid.inc
+
+invCmd "pamgauss       -sigma=0.5 "
+invCmd "pamgauss 0 5   -sigma=0.5 "
+invCmd "pamgauss 5 0   -sigma=0.5"
+invCmd "pamgauss 3 3              "
+invCmd "pamgauss 3 3   -sigma=0   "
+invCmd "pamgauss 3 3   -sigma=-1.5"
+invCmd "pamgauss 3     -sigma=0.5 "
+invCmd "pamgauss 3 3 3 -sigma=0.5 "
diff --git a/test/pamhue-roundtrip.test b/test/pamhue-roundtrip.test
index 643ac99a..d68ee344 100755
--- a/test/pamhue-roundtrip.test
+++ b/test/pamhue-roundtrip.test
@@ -1,4 +1,4 @@
-#! /bin/bash
+#! /bin/sh
 # This script tests: pamhue
 # Also requires:
 
diff --git a/test/pamhue.ok b/test/pamhue.ok
index 5935cc5e..4bc4c385 100644
--- a/test/pamhue.ok
+++ b/test/pamhue.ok
@@ -33,4 +33,4 @@ Test 4
 0 0 : 0
 0 0 : 0
 Test Invalid
-Expected failure 1 1
+Expected failure 1 (no output)
diff --git a/test/pamhue.test b/test/pamhue.test
index d81a0acb..ce148a45 100755
--- a/test/pamhue.test
+++ b/test/pamhue.test
@@ -16,11 +16,11 @@ pamseq -tupletype=RGB 3 1 | pamdepth 255 | pamhue -huechange=60 | \
 
 echo "Test 3"
 # pamhue has no effect on monotone images
-# Should print 2425386270 41 twice
+# Should print 281226646 481 twice
 
-pamhue -huechange=45  testgrid.pbm | cmp -s - testgrid.pbm
+pamhue -huechange=45  maze.pbm | cmp -s - maze.pbm
   echo ${PIPESTATUS[@]} ":" $?
-pamhue -huechange=180 testgrid.pbm | cmp -s - testgrid.pbm
+pamhue -huechange=180 maze.pbm | cmp -s - maze.pbm
   echo ${PIPESTATUS[@]} ":" $?
 
 echo "Test 4"
@@ -34,15 +34,6 @@ pamhue -huechange=360 testimg.ppm | cmp -s - testimg.ppm
 
 echo "Test Invalid"
 
-tmpdir=${tmpdir:-/tmp}
-test_out=${tmpdir}/test_out
+. ${srcdir}/test-invalid.inc
 
-echo 1>&2
-echo "Omission of mandatory argument." 1>&2
-echo "An error message should appear below the line." 1>&2
-echo "-----------------------------------------------------------" 1>&2
-
-pamhue testimg.ppm  > ${test_out} || \
-   echo -n "Expected failure 1"; test -s ${test_out}; echo " "$?
-
-rm -f ${test_out}
+invCmd "pamhue testimg.ppm "
diff --git a/test/pammixmulti-identity.test b/test/pammixmulti-identity.test
index d205c359..21136fbe 100755
--- a/test/pammixmulti-identity.test
+++ b/test/pammixmulti-identity.test
@@ -1,4 +1,4 @@
-#! /bin/bash
+#! /bin/sh
 # This script tests: pammixmulti
 # Also requires: pgmnoise pnminvert pamsumm
 
diff --git a/test/pamrecolor.ok b/test/pamrecolor.ok
new file mode 100644
index 00000000..f1bd74fb
--- /dev/null
+++ b/test/pamrecolor.ok
@@ -0,0 +1,11 @@
+Test 1. Should produce 3500040755 101532
+3500040755 101532
+Test 2. Should produce 3500040755 101532 twice
+3500040755 101532
+3500040755 101532
+Expected failure 1 (no output)
+Expected failure 2 (no output)
+Expected failure 3 (no output)
+Expected failure 4 (no output)
+Expected failure 5 (no output)
+Expected failure 6 (no output)
diff --git a/test/pamrecolor.test b/test/pamrecolor.test
new file mode 100755
index 00000000..b5674776
--- /dev/null
+++ b/test/pamrecolor.test
@@ -0,0 +1,31 @@
+#! /bin/sh
+# This script tests: pamrecolor
+# Also requires: ppmtopgm pgmmake
+
+tmpdir=${tmpdir:-/tmp}
+base_pgm=${tmpdir}/base.pgm
+
+pgmmake 0.5 230 150 > ${base_pgm}
+
+echo "Test 1. Should produce 3500040755 101532"
+
+pamrecolor --colorfile=${base_pgm} testimg.ppm | cksum
+
+echo "Test 2. Should produce 3500040755 101532 twice"
+
+pamrecolor --targetcolor=rgb:80/80/80 testimg.ppm | cksum
+pamrecolor --colorspace=ntsc --targetcolor=rgb:80/80/80 testimg.ppm | cksum
+
+. ${srcdir}/test-invalid.inc
+
+truncated_file=${tmpdir}/truncated.txt
+echo P6 > ${truncated_file}
+
+invCmd "pamrecolor --targetcolor=rgb:00/11/22 --colorfile=${base_pgm} testimg.ppm"
+invCmd "pamrecolor --rmult=0.3  --gmult=0.3  --bmult=0.3 --colorfile=${base_pgm} testimg.ppm"
+invCmd "pamrecolor --colorspace=void --targetcolor=rgb:80/80/80 testimg.ppm"
+invCmd "pamrecolor --targetcolor=vague testimg.ppm"
+invCmd "pamrecolor --colorfile=${truncated_file} testimg.ppm"
+invCmd "pamrecolor --rmult=0.2989 --gmult=0.5866 testimg.ppm"
+
+rm ${base_pgm} ${truncated_file}
diff --git a/test/pamrestack.ok b/test/pamrestack.ok
new file mode 100644
index 00000000..63f809e8
--- /dev/null
+++ b/test/pamrestack.ok
@@ -0,0 +1,68 @@
+Test 1.
+P2
+24 1
+7
+0 1 2 3 4 5 6 7 0 1 2 3 4 5 6 7 0 1 2 3 4 5 6 7 
+P2
+10 3
+7
+0 1 2 3 4 5 6 7 0 1 
+2 3 4 5 6 7 0 1 2 3 
+4 5 6 7 0 0 0 0 0 0 
+P2
+10 2
+7
+0 1 2 3 4 5 6 7 0 1 
+2 3 4 5 6 7 0 1 2 3 
+P2
+4 6
+7
+0 1 2 3 
+4 5 6 7 
+0 1 2 3 
+4 5 6 7 
+0 1 2 3 
+4 5 6 7 
+P2
+12 2
+7
+0 1 2 3 4 5 6 7 0 1 2 3 
+4 5 6 7 0 1 2 3 4 5 6 7 
+Test 2.  Should print 0 twelve times
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+0
+Test 3.  Should produce 3141273448 431 fifteen times
+3141273448 431
+3141273448 431
+3141273448 431
+3141273448 431
+3141273448 431
+3141273448 431
+3141273448 431
+3141273448 431
+3141273448 431
+3141273448 431
+3141273448 431
+3141273448 431
+3141273448 431
+3141273448 431
+3141273448 431
+Test 4. Should produce 1768948962 101484 twice
+1768948962 101484
+1768948962 101484
+Test Invalid.
+Expected failure 1 (no output)
+Expected failure 2 (no output)
+Expected failure 3 (no output)
+Expected failure 4 (no output)
+Expected failure 5 (no output)
diff --git a/test/pamrestack.test b/test/pamrestack.test
new file mode 100755
index 00000000..c91830e4
--- /dev/null
+++ b/test/pamrestack.test
@@ -0,0 +1,67 @@
+#! /bin/sh
+# This script tests: pamrestack
+# Also requires: pamfile pamflip pgmramp pnmcrop pnminvert
+
+tmpdir=${tmpdir:-/tmp}
+ramp_pgm=${tmpdir}/ramp.pgm
+ramp2_pgm=${tmpdir}/ramp2.pgm
+maze_singlerow_pbm=${tmpdir}/maze_singlerow.pbm
+maze_inverted_pbm=${tmpdir}/maze_inverted.pbm
+
+echo "Test 1."
+
+pgmramp -lr -maxval=7 8 3 | tee ${ramp_pgm} | pamrestack -plain
+pamrestack -width=10 -trim=fill -plain ${ramp_pgm}
+pamrestack -width=10 -trim=crop -plain ${ramp_pgm}
+pamrestack -width=4 -trim=fill -plain ${ramp_pgm}
+pamrestack -width=12 -trim=fill -plain ${ramp_pgm}
+
+echo "Test 2.  Should print 0 twelve times"
+
+for width in 2 4 5 8 12 24
+do
+    pamrestack -width=${width} -trim=crop ${ramp_pgm} > ${ramp2_pgm}
+    for flag in "-trim=crop"  "-trim=fill"
+    do
+    pamrestack -width=${width} ${flag} ${ramp2_pgm} | cmp -s - ${ramp2_pgm}
+    echo $?
+    done
+done
+
+rm ${ramp_pgm} ${ramp2_pgm}
+
+echo "Test 3.  Should produce 3141273448 431 fifteen times"
+
+# Invert maze.pbm because the lower right corner is black
+
+pixels=`pamfile -size maze.pbm | awk '{print $1 * $2}'`
+
+pnminvert maze.pbm | tee ${maze_inverted_pbm} | \
+  pamrestack | tee ${maze_singlerow_pbm} | pnmcrop -right -black | cksum
+for width in 1 2 3 100 1000 ${pixels} $((pixels -1))
+do
+pamrestack -width=${width} ${maze_inverted_pbm} | pamrestack | \
+  pnmcrop -right -black | cksum
+pamrestack -width=${width} ${maze_singlerow_pbm} | \
+  pamrestack | pnmcrop -right -black | cksum
+done
+
+rm ${maze_inverted_pbm} ${maze_singlerow_pbm}
+
+echo "Test 4. Should produce 1768948962 101484 twice"
+
+pamrestack -width=1 testimg.ppm | pamflip -ccw | cksum
+pamrestack \
+  -width=`pamfile -size testimg.ppm | cut -d " " -f2` testimg.ppm | \
+  pamrestack | cksum
+
+test_out=${tmpdir}/test_out
+echo "Test Invalid."
+
+. ${srcdir}/test-invalid.inc
+
+invCmd "pamrestack testgrid.pbm maze.pbm"
+invCmd "pamrestack -abort -width=$((pixels * 2 + 1 )) maze.pbm"
+invCmd "pamrestack -crop -width=$((pixels * 2 + 1)) maze.pbm"
+invCmd "pamrestack -width=0 maze.pbm"
+invCmd "pamrestack -width maze.pbm"
diff --git a/test/pamscale-filters1.test b/test/pamscale-filters1.test
index 63e0d012..c81dcf9a 100755
--- a/test/pamscale-filters1.test
+++ b/test/pamscale-filters1.test
@@ -1,12 +1,12 @@
 #! /bin/bash
 # This script tests: pamscale pamenlarge
-# Also requires: pamvalidate pnmpsnr
+# Also requires: pamfile pamvalidate pnmpsnr
 
 tmpdir=${tmpdir:-/tmp}
 enlarge_ppm=${tmpdir}/enlarge.ppm
 
-width_height=`pamfile -size testimg.ppm | \
-                awk '{print "-width="$1, "-height="$2}'`
+width_height=$(pamfile -size testimg.ppm | \
+                awk '{print "-width="$1, "-height="$2}')
 
 # The target values here were determined by running the test on a
 # 32-bit GNU/Linux system and subtracting 2.5 (dB) from observed
diff --git a/test/pamscale-filters2.test b/test/pamscale-filters2.test
index f7370020..d3cb8d6c 100755
--- a/test/pamscale-filters2.test
+++ b/test/pamscale-filters2.test
@@ -1,12 +1,12 @@
 #! /bin/bash
 # This script tests: pamscale pamstretch pamstretch-gen
-# Also requires: pamvalidate pnmpsnr
+# Also requires: pamfile pamvalidate pnmpsnr
 
 tmpdir=${tmpdir:-/tmp}
 stretch_ppm=${tmpdir}/stretch.ppm
 
-width_height=`pamfile -size testimg.ppm | \
-                awk '{print "-width="$1, "-height="$2}'`
+width_height=$(pamfile -size testimg.ppm | \
+               awk '{print "-width="$1, "-height="$2}')
 
 pamstretch -xscale=4 -yscale=3 testimg.ppm | pamvalidate > ${stretch_ppm}
 echo -xscale=4 -yscale=3 mitchell:  
diff --git a/test/pamscale-filters3.test b/test/pamscale-filters3.test
index 5a865508..8d20e690 100755
--- a/test/pamscale-filters3.test
+++ b/test/pamscale-filters3.test
@@ -1,12 +1,12 @@
 #! /bin/bash
 # This script tests: pamscale pamstretch pamstretch-gen 
-# Also requires: pamvalidate pnmpsnr
+# Also requires: pamfile pamvalidate pnmpsnr
 
 tmpdir=${tmpdir:-/tmp}
 stretch_ppm=${tmpdir}/stretch.ppm
 
-width_height=`pamfile -size testimg.ppm | \
-                awk '{print "-width="$1, "-height="$2}'`
+width_height=$(pamfile -size testimg.ppm | \
+               awk '{print "-width="$1, "-height="$2}')
 
 pamstretch-gen 3.96 testimg.ppm | pamvalidate > ${stretch_ppm}
 echo 3.96 hermite:  
diff --git a/test/pamscale-reportonly.ok b/test/pamscale-reportonly.ok
index bf5cde99..a3ece300 100644
--- a/test/pamscale-reportonly.ok
+++ b/test/pamscale-reportonly.ok
@@ -12,9 +12,9 @@ Test 1
 227 149 1.400881 2.684564 318 400
 227 149 1.000000 1.000000 227 149
 Test Invalid
-Expected failure 1 1
-Expected failure 2 1
-Expected failure 3 1
-Expected failure 4 1
-Expected failure 5 1
-Expected failure 6 1
+Expected failure 1 (no output)
+Expected failure 2 (no output)
+Expected failure 3 (no output)
+Expected failure 4 (no output)
+Expected failure 5 (no output)
+Expected failure 6 (no output)
diff --git a/test/pamscale-reportonly.test b/test/pamscale-reportonly.test
index 45a38687..39745809 100755
--- a/test/pamscale-reportonly.test
+++ b/test/pamscale-reportonly.test
@@ -1,4 +1,4 @@
-#! /bin/bash
+#! /bin/sh
 # This script tests: pamscale
 # Also requires:
 
@@ -19,33 +19,13 @@ pamscale -reportonly -pixels=45000 testimg.ppm
 
 echo "Test Invalid"
 
-tmpdir=${tmpdir:-/tmp}
-test_out=${tmpdir}/test_out
+. ${srcdir}/test-invalid.inc
 
 # Expected failure cases
 
-echo 1>&2
-echo "Invalid command-line argument combinations." 1>&2
-echo "Error messages should appear below the line." 1>&2
-echo "-----------------------------------------------------------" 1>&2
-
-pamscale -reportonly -xsize=640 -ysize=400 -xscale=2 testimg.ppm > \
-  ${test_out} \
-  || echo -n "Expected failure 1"; test -s ${test_out}; echo " "$?
-pamscale -reportonly -xsize=640 -xscale=2 -yscale=3 testimg.ppm > \
-  ${test_out} \
-  || echo -n "Expected failure 2"; test -s ${test_out}; echo " "$?
-pamscale -reportonly -xsize=640 -ysize=400 -pixels=200000 testimg.ppm \
-  > ${test_out} || \
-  echo -n "Expected failure 3"; test -s ${test_out}; echo " "$?
-pamscale -reportonly -xsize=640 -ysize=400 -xysize 640 400 testimg.ppm \
-  > ${test_out} || \
-  echo -n "Expected failure 4"; test -s ${test_out}; echo " "$?
-pamscale -reportonly -xsize=640 -ysize=400 -xyfit  640 400 testimg.ppm \
-  > ${test_out} || \
-  echo -n "Expected failure 5"; test -s ${test_out}; echo " "$?
-pamscale -reportonly -xsize=640 -ysize=400 -xyfill 640 400 testimg.ppm \
-  > ${test_out} || \
-  echo -n "Expected failure 6"; test -s ${test_out}; echo " "$?
-
-rm ${test_out}
+invCmd "pamscale -reportonly -xsize=640 -ysize=400 -xscale=2 testimg.ppm"
+invCmd "pamscale -reportonly -xsize=640 -xscale=2 -yscale=3 testimg.ppm"
+invCmd "pamscale -reportonly -xsize=640 -ysize=400 -pixels=200000 testimg.ppm"
+invCmd "pamscale -reportonly -xsize=640 -ysize=400 -xysize 640 400 testimg.ppm"
+invCmd "pamscale -reportonly -xsize=640 -ysize=400 -xyfit  640 400 testimg.ppm"
+invCmd "pamscale -reportonly -xsize=640 -ysize=400 -xyfill 640 400 testimg.ppm"
diff --git a/test/pamseq.ok b/test/pamseq.ok
index 654596fb..a632de66 100644
--- a/test/pamseq.ok
+++ b/test/pamseq.ok
@@ -1,7 +1,7 @@
 Test 1
 3929266994 304
 Test Invalid
-Expected failure 1 1
-Expected failure 2 1
-Expected failure 3 1
-Expected failure 4 1
+Expected failure 1 (no output)
+Expected failure 2 (no output)
+Expected failure 3 (no output)
+Expected failure 4 (no output)
diff --git a/test/pamseq.test b/test/pamseq.test
index 0681d396..894e8d6d 100755
--- a/test/pamseq.test
+++ b/test/pamseq.test
@@ -1,4 +1,4 @@
-#! /bin/bash
+#! /bin/sh
 # This script tests: pamseq
 # Also requires:
 
@@ -8,27 +8,14 @@ pamseq 1 255 | cksum
 
 echo "Test Invalid"
 
-echo 1>&2
-echo "Invalid command-line argument combinations." 1>&2
-echo "Error messages should appear below the line." 1>&2
-echo "-----------------------------------------------------------" 1>&2
+. ${srcdir}/test-invalid.inc
 
-tmpdir=${tmpdir:-/tmp}
-test_out=${tmpdir}/test_out
-
-pamseq 1 > ${test_out} || \
-   echo -n "Expected failure 1"; test -s ${test_out}; echo " "$?
-pamseq 0 255 > ${test_out} || \
-   echo -n "Expected failure 2"; test -s ${test_out}; echo " "$?
-pamseq 3 0   > ${test_out} || \
-   echo -n "Expected failure 3"; test -s ${test_out}; echo " "$?
+invCmd "pamseq 1"
+invCmd "pamseq 0 255"
+invCmd "pamseq 3 0"
 
+# Tupletype string length=256
 c64="0123456789012345678901234567890123456789012345678901234567890123"
 c256=${c64}${c64}${c64}${c64}
 
-# Tupletype string length=256
-
-pamseq -tupletype="${c256}" 3 15 > ${test_out} || \
-   echo -n "Expected failure 4"; test -s ${test_out}; echo " "$?
-
-rm ${test_out}
+invCmd "pamseq -tupletype=${c256} 3 15"
diff --git a/test/pamshuffle.ok b/test/pamshuffle.ok
new file mode 100644
index 00000000..ec8c1a9c
--- /dev/null
+++ b/test/pamshuffle.ok
@@ -0,0 +1,19 @@
+Test 1.  Should print 1081361896 1432 five times
+1081361896 1432
+1081361896 1432
+1081361896 1432
+1081361896 1432
+1081361896 1432
+Test 2.  Should print 1936883899 143517 four times
+1936883899 143517
+1936883899 143517
+1936883899 143517
+1936883899 143517
+Test 3.  Should print nomatch three times
+nomatch
+nomatch
+nomatch
+Test Invalid.
+Expected failure 1 (no output)
+Expected failure 2 (no output)
+Expected failure 3 (no output)
diff --git a/test/pamshuffle.test b/test/pamshuffle.test
new file mode 100755
index 00000000..371b65a5
--- /dev/null
+++ b/test/pamshuffle.test
@@ -0,0 +1,53 @@
+#! /bin/sh
+# This script tests: pamshuffle
+# Also requires: pamseq pamrestack pgmhist ppmhist pnmpsnr
+
+tmpdir=${tmpdir:-/tmp}
+seq_pam=${tmpdir}/seq.pam
+seq16_pam=${tmpdir}/seq16.pam
+
+out1_pam=${tmpdir}/out1.pam
+
+echo "Test 1.  Should print 1081361896 1432 five times"
+
+pgmhist -machine maze.pbm | cksum
+pamshuffle -randomseed=1 maze.pbm | pgmhist -machine | cksum
+pamshuffle -randomseed=2 maze.pbm | pgmhist -machine | cksum
+pamshuffle -column -randomseed=3 maze.pbm | pgmhist -machine | cksum
+pamrestack maze.pbm | pamshuffle -randomseed=3 | pgmhist -machine | cksum
+
+echo "Test 2.  Should print 1936883899 143517 four times"
+
+pamseq -tupletype="RGB" 3 15 > ${seq_pam}
+
+ppmhist -map ${seq_pam} | cksum
+pamshuffle -randomseed=2 ${seq_pam} | ppmhist -map | cksum
+pamrestack -width=16 -trim=abort ${seq_pam} | tee ${seq16_pam} | \
+  ppmhist -map | cksum
+pamshuffle -column -randomseed=3 ${seq16_pam} | ppmhist -map | cksum
+
+echo "Test 3.  Should print nomatch three times"
+
+pamshuffle -randomseed=$((100 +i)) ${seq16_pam} > ${out1_pam}
+pamshuffle -randomseed=${i} ${seq16_pam} | \
+pnmpsnr -target=14.0 ${out1_pam} -
+rm ${seq_pam} ${seq16_pam} ${out1_pam}
+
+pamshuffle -randomseed=$((100 +i)) testimg.ppm > ${out1_pam}
+pamshuffle -randomseed=${i} testimg.ppm | \
+  pnmpsnr -target=14.0 ${out1_pam} -
+rm ${out1_pam}
+
+pamshuffle -randomseed=$((100 +i)) -column testimg.ppm > ${out1_pam}
+pamshuffle -randomseed=${i} -column testimg.ppm | \
+  pnmpsnr -target=14.0 ${out1_pam} -
+rm ${out1_pam}
+
+test_out=${tmpdir}/test_out
+echo "Test Invalid."
+
+. ${srcdir}/test-invalid.inc
+
+invCmd "pamshuffle testimg.ppm testgrid.pbm"
+invCmd "pamshuffle -randomseed -column testgrid.pbm"
+invCmd "pamshuffle -randomseed=null testgrid.pbm"
diff --git a/test/pamslice-roundtrip.ok b/test/pamslice-roundtrip.ok
index eae64745..50e83b2a 100644
--- a/test/pamslice-roundtrip.ok
+++ b/test/pamslice-roundtrip.ok
@@ -1,4 +1,9 @@
-2425386270 41
-914327477 4864
-914327477 4864
-914327477 4864
+Test 1.  Should print 139976034 137 twice
+139976034 137
+139976034 137
+Test 2.  Should print 1624460505 574 three times
+1624460505 574
+1624460505 574
+1624460505 574
+Test 3.  Should print 1624460505 574
+1624460505 574
diff --git a/test/pamslice-roundtrip.test b/test/pamslice-roundtrip.test
index 6cb5533f..2b7929cf 100755
--- a/test/pamslice-roundtrip.test
+++ b/test/pamslice-roundtrip.test
@@ -1,75 +1,75 @@
-#! /bin/bash
+#! /bin/sh
 # This script tests: pamslice pamdeinterlace
-# Also requires: pamcut pamtopnm pamflip
+# Also requires: pamfile pamcut pamtopnm pamflip
 
-
-# Test 1.
-# Slice rows, one by one, out of testgrid.pbm.
+echo "Test 1.  Should print 139976034 137 twice"
+# Slice rows, one by one, out of maze.pbm.
 # Add header and reconstruct pbm image.
 # Note that in pamslice output 0 is white and 1 is black: opposite of PBM
-# Should print 2425386270 41
+
+mwidth=$(pamfile -size maze.pbm | cut -d " " -f 1)
+height=16
+
+pamcut -top=0 -left=0 -height=${height} maze.pbm | cksum
 
 (echo "P1"
- echo "14 16"
- seq 0 15 | while read i;
+ echo "${mwidth} ${height}"
+ for i in `seq 0 $((${height}-1))` 
      do
-     pamslice -row=$i testgrid.pbm
-     done | awk '{print $2}' | sed 'y/01/10/' ) \
+     pamslice -row=$i maze.pbm
+     done | cut -d" " -f2- | sed 'y/01/10/' ) \
  | pamtopnm | cksum
 
-# Test 2.
+
+echo "Test 2.  Should print 1624460505 574 three times"
 # Slice rows, one by one, out of ppm test image
 # We take a part out of testimg.ppm with pamcut for processing the
 # whole image takes much time.
 # Add header and reconstruct ppm image.
-# Should print 914327477 4864
 
 tmpdir=${tmpdir:-/tmp}
+test1711_ppm=${tmpdir}/test1711.ppm
 
-test4933_ppm=${tmpdir}/test4933.ppm
-
-pamcut 50 50 49 33 testimg.ppm > ${test4933_ppm}
+pamcut -left=50 -top=50 -width=17 -height=11 testimg.ppm | \
+  tee ${test1711_ppm} | cksum
 
 (echo "P3"
- echo "49 33"
+ echo "17 11"
  echo "255"
- seq 0 32 | while read i;
+ for i in 0 1 2 3 4 5 6 7 8 9 10   # for i in `seq 0 10`
      do
-     pamslice -row=$i ${test4933_ppm}
-     done | awk '{print $2, $3, $4}' ) \
+     pamslice -row=${i} ${test1711_ppm}
+     done | cut -d" " -f2- ) \
  | pamtopnm | cksum
 
 # Same as above test 2, but take cols instead of rows.
-# Should print 914327477 4864
 
 (echo "P3"
- echo "33 49"
+ echo "11 17"
  echo "255"
- seq 0 48 | while read i;
+ for i in 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16    # for i in `seq 0 16`
      do
-     pamslice -col=$i ${test4933_ppm}
-     done | awk '{print $2, $3, $4}' ) \
- | pamflip -xy | cksum
+     pamslice -col=${i} ${test1711_ppm}
+     done | cut -d " " -f2- ) | pamflip -xy | cksum
 
-# Test 4.
+echo "Test 3.  Should print 1624460505 574"
 # Divide input image into two with pamdeinterlace and recombine.
 
 testeven_ppm=${tmpdir}/testeven.ppm
 testodd_ppm=${tmpdir}/testodd.ppm
 
-pamdeinterlace -takeodd ${test4933_ppm} > ${testodd_ppm}
-pamdeinterlace -takeeven ${test4933_ppm} > ${testeven_ppm}
+pamdeinterlace -takeodd ${test1711_ppm} > ${testodd_ppm}
+pamdeinterlace -takeeven ${test1711_ppm} > ${testeven_ppm}
 
-(echo "P3"
- echo "49 33"
- echo "255"
- ( seq 0 15 | while read i;
-     do
-     pamslice -row=$i ${testeven_ppm}
-     pamslice -row=$i ${testodd_ppm}
-     done
-     pamslice -row=16 ${testeven_ppm};
- )  | awk '{print $2, $3, $4}' ) \
- | pamtopnm | cksum
+( echo "P3"
+  echo "17 11"
+  echo "255"
+  ( for i in  0 1 2 3 4 
+        do
+        pamslice -row=${i} ${testeven_ppm}
+        pamslice -row=${i} ${testodd_ppm}
+        done
+        pamslice -row=5 ${testeven_ppm};
+  ) | cut -d" " -f2- ) | pamtopnm | cksum
 
-rm ${test4933_ppm} ${testodd_ppm} ${testeven_ppm}
+rm ${test1711_ppm} ${testodd_ppm} ${testeven_ppm}
diff --git a/test/pamstack.ok b/test/pamstack.ok
new file mode 100644
index 00000000..881cb6c5
--- /dev/null
+++ b/test/pamstack.ok
@@ -0,0 +1,38 @@
+test 0: Should print 1652911383 4046
+1652911383 4046
+test 1: Should print 1398841785 13544 three times
+1398841785 13544
+1398841785 13544
+1398841785 13544
+test 2: Should print 210239904 3186 five times
+210239904 3186
+210239904 3186
+210239904 3186
+210239904 3186
+210239904 3186
+test 3: maxval should be 65535
+stdin:	PAM, 14 by 16 by 6 maxval 65535
+    Tuple type: 
+stdin:	PAM, 14 by 16 by 6 maxval 65535
+    Tuple type: 
+stdin:	PAM, 14 by 16 by 5 maxval 65535
+    Tuple type: 
+stdin:	PAM, 14 by 16 by 2 maxval 65535
+    Tuple type: 
+test 4: maxval should be 255 then 767
+stdin:	PAM, 14 by 16 by 2 maxval 255
+    Tuple type: 
+stdin:	PAM, 14 by 16 by 2 maxval 767
+    Tuple type: 
+test 5: Should print 2741208386 719 twice
+2741208386 719
+2741208386 719
+test 6: Should print true four times
+true
+true
+true
+true
+Test Invalid
+Expected failure 1 (no output)
+Expected failure 2 (no output)
+Expected failure 3 (no output)
diff --git a/test/pamstack.test b/test/pamstack.test
new file mode 100755
index 00000000..6374c4bd
--- /dev/null
+++ b/test/pamstack.test
@@ -0,0 +1,108 @@
+#! /bin/sh
+# This script tests: pamstack
+# Also requires: pamdepth pgmmake pamfile
+
+tmpdir=${tmpdir:-/tmp}
+i1_pgm=${tmpdir}/testimg_1.pnm
+i2_pgm=${tmpdir}/testimg_2.pgm
+i7_pgm=${tmpdir}/testimg_7.pgm
+i31_pgm=${tmpdir}/testimg_31.pgm
+std_pgm=${tmpdir}/testimg_255.pgm
+max_pgm=${tmpdir}/testimg_max.pgm
+
+maze2_pbm=${tmpdir}/testimg_maze2.pgm
+maze3_pbm=${tmpdir}/testimg_maze3.pgm
+
+pamdepth 1 testgrid.pbm > ${i1_pgm}
+pgmmake -maxval=2 0 14 16 > ${i2_pgm}
+pgmmake -maxval=7 0.5 14 16 > ${i7_pgm}
+pgmmake -maxval=31 0.5 14 16 > ${i31_pgm}
+pgmmake -maxval=255 0.5 14 16 > ${std_pgm}
+pgmmake -maxval=65535 0.5 14 16 > ${max_pgm}
+cat maze.pbm maze.pbm > ${maze2_pbm}
+cat maze.pbm maze.pbm maze.pbm > ${maze3_pbm}
+
+# test 0
+echo test 0: Should print 1652911383 4046
+
+# Test the integrity of the input files
+cat ${i1_pgm} ${i2_pgm} ${i7_pgm} ${i31_pgm} ${std_pgm} ${max_pgm} \
+    ${maze2_pbm} ${maze3_pbm}| cksum
+
+# test 1
+echo test 1: Should print 1398841785 13544 three times
+pamstack ${maze2_pbm} ${maze2_pbm} | cksum
+pamstack ${maze3_pbm} ${maze2_pbm} | cksum
+pamstack ${maze2_pbm} ${maze3_pbm} | cksum
+
+rm ${maze2_pbm} ${maze3_pbm}
+
+# test 2
+echo test 2: Should print 210239904 3186 five times
+pamstack -firstmaxval ${max_pgm} ${std_pgm} ${i31_pgm} \
+                      ${i7_pgm} ${i2_pgm} ${i1_pgm} ${i1_pgm} | cksum
+pamstack -firstmaxval ${max_pgm} ${std_pgm} ${i31_pgm} \
+	              ${i7_pgm} ${i2_pgm} ${i1_pgm} testgrid.pbm | cksum
+
+pamstack -lcmmaxval   ${max_pgm} ${std_pgm} ${i31_pgm} \
+	              ${i7_pgm} ${i2_pgm} ${i1_pgm} ${i1_pgm} | cksum
+pamstack ${i1_pgm} ${i1_pgm} |\
+  pamstack -firstmaxval ${max_pgm} ${std_pgm} ${i31_pgm} ${i7_pgm} ${i2_pgm} - | cksum
+pamstack -firstmaxval ${i2_pgm} testgrid.pbm ${i1_pgm} |\
+  pamstack -firstmaxval ${max_pgm} ${std_pgm} ${i31_pgm} ${i7_pgm} - | cksum
+
+
+# test 3
+echo test 3: maxval should be 65535
+pamstack -firstmaxval ${max_pgm} ${std_pgm} ${i31_pgm} \
+	              ${i7_pgm} ${i2_pgm} ${i1_pgm} | pamfile
+
+pamstack -lcmmaxval ${max_pgm} ${std_pgm} ${i31_pgm} \
+	            ${i7_pgm} ${i2_pgm} ${i1_pgm} | pamfile
+
+pamstack -lcmmaxval ${max_pgm} ${std_pgm} ${i31_pgm} ${i7_pgm} ${i1_pgm} | pamfile
+
+pamstack -firstmaxval ${max_pgm} ${i2_pgm} | pamfile
+
+
+# test 4
+echo test 4: maxval should be 255 then 767
+pamstack -firstmaxval ${std_pgm} ${i2_pgm} | pamfile
+pamstack -lcmmaxval ${std_pgm} ${i2_pgm} | pamfile
+
+# test 5
+echo test 5: Should print 2741208386 719 twice
+
+pamstack -lcmmaxval   ${i31_pgm} ${i1_pgm} ${i7_pgm} | cksum
+pamstack -firstmaxval ${i31_pgm} ${i1_pgm} ${i7_pgm}  | cksum
+
+# test 6
+echo test 6: Should print true four times
+
+s0=$(pamstack ${i1_pgm} | pamfile)
+s1=$(pamstack -lcmmaxval ${i1_pgm} | pamfile)
+s2=$(pamstack -firstmaxval ${i1_pgm} | pamfile)
+
+test "$s0" = "$s1" && echo "true" || echo "false"
+test "$s0" = "$s2" && echo "true" || echo "false"
+
+
+s0=$(pamstack ${std_pgm} | pamfile)
+s1=$(pamstack -lcmmaxval ${std_pgm} | pamfile)
+s2=$(pamstack -firstmaxval ${std_pgm} | pamfile)
+
+test "$s0" = "$s1" && echo "true" || echo "false"
+test "$s0" = "$s2" && echo "true" || echo "false"
+
+
+# Test Invalid
+echo "Test Invalid"
+
+. ${srcdir}/test-invalid.inc
+
+invCmd "pamstack testgrid.pbm testimg.ppm"
+invCmd "pamstack ${i1_pgm} ${std_pgm}"
+invCmd "pamstack -lcmmaxval -firstmaxval testgrid.pbm testgrid.pbm"
+
+rm ${i1_pgm} ${i2_pgm} ${i7_pgm} ${i31_pgm} ${std_pgm} ${max_pgm}
+
diff --git a/test/pamstereogram.ok b/test/pamstereogram.ok
new file mode 100644
index 00000000..265a4fc5
--- /dev/null
+++ b/test/pamstereogram.ok
@@ -0,0 +1,32 @@
+Test 00. Should print 729348909 237
+729348909 237
+Test 01. Should print 3308667841 293
+3308667841 293
+Test 02. Should print 3308667841 293
+3308667841 293
+Test 03. Should print 748200469 170
+748200469 170
+Test 04. Should print 1538641408 1070
+1538641408 1070
+Test 10. Should print 1266273778 293
+1266273778 293
+Test 11. Should print 55276708 1070
+55276708 1070
+Test 20. Should print 1920539795 289
+1920539795 289
+Test 21. Should print 4069109690 4068
+4069109690 4068
+Test 22. Should print 1163376052 4068
+1163376052 4068
+Test 30. Should print 2127252909 731
+2127252909 731
+Test 31. Should print 858421050 12062
+858421050 12062
+Test 40. Should print 1236679620 660
+1236679620 660
+Test 41. Should print 1022068930 5014
+1022068930 5014
+Test 51. Should print 3784833098 11071
+3784833098 11071
+Test 52. Should print 1419662425 1441
+1419662425 1441
diff --git a/test/pamstereogram.test b/test/pamstereogram.test
new file mode 100755
index 00000000..02da9724
--- /dev/null
+++ b/test/pamstereogram.test
@@ -0,0 +1,80 @@
+#! /bin/sh
+# This script tests: pamstereogram
+# Also requires: pamdepth
+
+tmpdir=${tmpdir:-/tmp}
+testgrid_pgm=${tmpdir}/testgrid.pgm
+
+# Make input file
+
+echo "Test 00. Should print 729348909 237"
+pamdepth -quiet 255 testgrid.pbm | tee ${testgrid_pgm} | cksum
+
+
+# Random pattern
+
+echo "Test 01. Should print 3308667841 293"
+pamstereogram -randomseed=1 testgrid.pbm | cksum 
+echo "Test 02. Should print 3308667841 293"
+pamstereogram -randomseed=1 -blackandwhite testgrid.pbm | cksum 
+echo "Test 03. Should print 748200469 170"
+pamseq -tupletype=GRAYSCALE 1 100 | pamstereogram -randomseed=1 | cksum 
+echo "Test 04. Should print 1538641408 1070"
+pamgauss 100 10 -maxval=10000 -sigma 20 | pamfunc -multiplier=500 | \
+  pamstereogram -randomseed=1 -dpi=10 | cksum
+
+# Makemask
+
+echo "Test 10. Should print 1266273778 293"
+pamstereogram -randomseed=1 -makemask testgrid.pbm | cksum 
+
+echo "Test 11. Should print 55276708 1070"
+pamgauss 100 10 -maxval=10000 -sigma 20 | pamfunc -multiplier=500 | \
+  pamstereogram -randomseed=1 -dpi=10 -makemask | cksum
+
+# Grayscale
+
+echo "Test 20. Should print 1920539795 289"
+pamstereogram -randomseed=1 -grayscale testgrid.pbm | cksum 
+echo "Test 21. Should print 4069109690 4068"
+pamseq 1 100 | pnmtile 200 20 | \
+  pamstereogram -randomseed=1 -dpi=10 -grayscale | \
+  cksum
+echo "Test 22. Should print 1163376052 4068"
+pamseq 1 100 | pnmtile 200 20 | \
+  pamstereogram -randomseed=1 -dpi=10 -grayscale -maxval 255 | \
+  cksum
+
+# Color
+
+echo "Test 30. Should print 2127252909 731"
+pamstereogram -randomseed=1 -color testgrid.pbm | cksum 
+echo "Test 31. Should print 858421050 12062"
+pamseq 1 100 | pnmtile 200 20 | \
+  pamstereogram -randomseed=1 -dpi=10 -color | \
+  cksum
+
+# Pattern file
+
+echo "Test 40. Should print 1236679620 660"
+pamgradient black gray50 white gray50 100 50 | \
+  pamstereogram -patfile testgrid.pbm -eyesep=.1 -crosseyed | cksum
+
+echo "Test 41. Should print 1022068930 5014"
+pamgradient black gray50 white gray50 100 50 | \
+  pamstereogram -patfile  ${testgrid_pgm} -eyesep=.1 -crosseyed | cksum
+
+# drawguides
+
+echo "Test 51. Should print 3784833098 11071"
+pamgradient black gray50 white gray50 100 50 | \
+  pamstereogram -randomseed=1 -dpi 10 -guidesize=20 -guidetop | cksum
+
+echo "Test 52. Should print 1419662425 1441"
+pamgradient black gray50 white gray50 100 50 | \
+  pamstereogram -patfile=testgrid.pbm -dpi 10 -guidesize=20 -guidetop | cksum
+
+
+# Clean up files we created
+rm  ${testgrid_pgm}
+
diff --git a/test/pamstretch.test b/test/pamstretch.test
index 55dd4e9c..38e3a649 100755
--- a/test/pamstretch.test
+++ b/test/pamstretch.test
@@ -1,4 +1,4 @@
-#! /bin/bash
+#! /bin/sh
 # This script tests: pamstretch
 # Also requires: pamcut pamfile
 
@@ -13,6 +13,7 @@ pamstretch -xscale=2 -blackedge testimg.ppm | cksum
 
 # Test 3.  Should print 3427416462 301047
 echo test 3
+tmpdir=${tmpdir:-/tmp}
 dropedge1_ppm=${tmpdir}/drop1.ppm
 pamstretch -yscale=3 -dropedge testimg.ppm | tee ${dropedge1_ppm} | cksum
 
@@ -39,10 +40,10 @@ blackedge_ppm=${tmpdir}/black.ppm
 pamstretch 3 testimg.ppm | tee ${stretch_ppm} | cksum
 pamstretch 3 -blackedge testimg.ppm | tee ${blackedge_ppm} | cksum
 pamstretch -xscale=3 -dropedge ${dropedge1_ppm} | tee ${dropedge_ppm} | cksum
-width_height=`pamfile -size ${dropedge_ppm} | \
-              awk '{print "-width="$1, "-height="$2}'`
+width_height=$(pamfile -size ${dropedge_ppm} | \
+              awk '{print "-width="$1, "-height="$2}')
 pamcut -left=0 -top=0 ${width_height} ${stretch_ppm} | cksum
 pamcut -left=0 -top=0 ${width_height} ${blackedge_ppm} | cksum
 pamcut -left=0 -top=0 ${width_height} ${dropedge_ppm} | cksum
 
-rm ${stretch_ppm} ${dropedge_ppm} ${dropedge1_ppm} ${blackedge_ppm}
\ No newline at end of file
+rm ${stretch_ppm} ${dropedge_ppm} ${dropedge1_ppm} ${blackedge_ppm}
diff --git a/test/pamsumm.ok b/test/pamsumm.ok
index 63b5f6bd..5524e7b5 100644
--- a/test/pamsumm.ok
+++ b/test/pamsumm.ok
@@ -1,15 +1,20 @@
-Test 1
+Test 1.  Should print in order: 56, 0, 1, 0.250000
 56
 0
 1
 0.250000
-Test 2
+Test 2.  Should print in order: 1627, 0, 1, 0.483794
+1627
+0
+1
+0.483794
+Test 3.  Should print in order: 10772432, 15, 255, 106.164760
 10772432
 15
 255
 106.164760
 Test Invalid
-Expected failure 1 1
-Expected failure 2 1
-Expected failure 3 1
-Expected failure 4 1
+Expected failure 1 (no output)
+Expected failure 2 (no output)
+Expected failure 3 (no output)
+Expected failure 4 (no output)
diff --git a/test/pamsumm.test b/test/pamsumm.test
index 5b4fdb17..eb41ee36 100755
--- a/test/pamsumm.test
+++ b/test/pamsumm.test
@@ -1,39 +1,34 @@
-#! /bin/bash
+#! /bin/sh
 # This script tests: pamsumm
 # Also requires:
 
-echo "Test 1"
+echo "Test 1.  Should print in order: 56, 0, 1, 0.250000"
 
 for type in -sum -min -max -mean
   do
   pamsumm -brief $type testgrid.pbm
   done
 
-echo "Test 2"
+echo "Test 2.  Should print in order: 1627, 0, 1, 0.483794"
 
 for type in -sum -min -max -mean
   do
-  pamsumm -brief $type testimg.ppm
+  pamsumm -brief $type maze.pbm
   done
 
+echo "Test 3.  Should print in order: 10772432, 15, 255, 106.164760"
 
-echo "Test Invalid"
+for type in -sum -min -max -mean
+  do
+  pamsumm -brief $type testimg.ppm
+  done
 
-tmpdir=${tmpdir:-/tmp}
-test_out=${tmpdir}/test_out
 
-echo 1>&2
-echo "Invalid command-line argument combinations." 1>&2
-echo "Error messages should appear below the line." 1>&2
-echo "-----------------------------------------------------------" 1>&2
+echo "Test Invalid"
 
-pamsumm -sum -min  testimg.ppm > ${test_out} || \
-   echo -n "Expected failure 1"; test -s ${test_out}; echo " "$?
-pamsumm -sum -max  testimg.ppm > ${test_out} || \
-   echo -n "Expected failure 2"; test -s ${test_out}; echo " "$?
-pamsumm -mean -max testimg.ppm > ${test_out} || \
-   echo -n "Expected failure 3"; test -s ${test_out}; echo " "$?
-pamsumm            testimg.ppm > ${test_out} || \
-   echo -n "Expected failure 4"; test -s ${test_out}; echo " "$?
+. ${srcdir}/test-invalid.inc
 
-rm ${test_out}
+invCmd "pamsumm -sum -min  testimg.ppm"
+invCmd "pamsumm -sum -max  testimg.ppm"
+invCmd "pamsumm -mean -max testimg.ppm"
+invCmd "pamsumm            testimg.ppm"
diff --git a/test/pamtable.ok b/test/pamtable.ok
index c8db6002..b63a74c2 100644
--- a/test/pamtable.ok
+++ b/test/pamtable.ok
@@ -1,3 +1,4 @@
+Test 1
 0 1 0 1 0 1 0 1 0 1 0 1 0 1
 0 0 0 0 0 0 0 0 0 0 0 0 0 0
 0 1 0 1 0 1 0 1 0 1 0 1 0 1
@@ -15,10 +16,66 @@
 0 1 0 1 0 1 0 1 0 1 0 1 0 1
 0 0 0 0 0 0 0 0 0 0 0 0 0 0
 
+Test 2
 0 0 0|0 0 1|0 0 2|0 1 0|0 1 1|0 1 2|0 2 0|0 2 1|0 2 2|1 0 0|1 0 1|1 0 2|1 1 0|1 1 1|1 1 2|1 2 0|1 2 1|1 2 2|2 0 0|2 0 1|2 0 2|2 1 0|2 1 1|2 1 2|2 2 0|2 2 1|2 2 2
 
+Test 3
 0 0 0 0|0 0 0 1|0 0 1 0|0 0 1 1|0 1 0 0|0 1 0 1|0 1 1 0|0 1 1 1|1 0 0 0|1 0 0 1|1 0 1 0|1 0 1 1|1 1 0 0|1 1 0 1|1 1 1 0|1 1 1 1
 
+Test 4
+(1) (0) (1) (0) (1)
+
+Test 5
+(1)
+(0)
+(1)
+(0)
+(1)
+(0)
+(1)
+(0)
+(1)
+(0)
+
+Test 6
+(0,0,0) (0,0,1) (0,0,2)
+(0,0,3) (0,1,0) (0,1,1)
+(0,1,2) (0,1,3) (0,2,0)
+(0,2,1) (0,2,2) (0,2,3)
+(0,3,0) (0,3,1) (0,3,2)
+(0,3,3) (1,0,0) (1,0,1)
+(1,0,2) (1,0,3) (1,1,0)
+(1,1,1) (1,1,2) (1,1,3)
+(1,2,0) (1,2,1) (1,2,2)
+(1,2,3) (1,3,0) (1,3,1)
+(1,3,2) (1,3,3) (2,0,0)
+(2,0,1) (2,0,2) (2,0,3)
+(2,1,0) (2,1,1) (2,1,2)
+(2,1,3) (2,2,0) (2,2,1)
+(2,2,2) (2,2,3) (2,3,0)
+(2,3,1) (2,3,2) (2,3,3)
+(3,0,0) (3,0,1) (3,0,2)
+(3,0,3) (3,1,0) (3,1,1)
+(3,1,2) (3,1,3) (3,2,0)
+(3,2,1) (3,2,2) (3,2,3)
+(3,3,0) (3,3,1) (3,3,2)
+(3,3,3) (0,0,0) (0,0,0)
+
+Test 7
+00 00|00 11|00 22|00 33|00 44|00 55|00 66|00 77
+00 88|00 99|00 aa|00 bb|00 cc|00 dd|00 ee|00 ff
+0a 00|0a 11|0a 22|0a 33|0a 44|0a 55|0a 66|0a 77
+0a 88|0a 99|0a aa|0a bb|0a cc|0a dd|0a ee|0a ff
+14 00|14 11|14 22|14 33|14 44|14 55|14 66|14 77
+14 88|14 99|14 aa|14 bb|14 cc|14 dd|14 ee|14 ff
+1e 00|1e 11|1e 22|1e 33|1e 44|1e 55|1e 66|1e 77
+1e 88|1e 99|1e aa|1e bb|1e cc|1e dd|1e ee|1e ff
+28 00|28 11|28 22|28 33|28 44|28 55|28 66|28 77
+28 88|28 99|28 aa|28 bb|28 cc|28 dd|28 ee|28 ff
+32 00|32 11|32 22|32 33|32 44|32 55|32 66|32 77
+32 88|32 99|32 aa|32 bb|32 cc|32 dd|32 ee|32 ff
+
+Test 8
 9 0
 0 9
 
@@ -64,3 +121,5 @@
 65535     0     0|    0     0 65535|    0     0 65535|    0 65535     0
 65535     0     0|    0     0 65535|    0     0 65535|    0 65535     0
 
+Test Invalid
+Expected failure 1 (no output)
diff --git a/test/pamtable.test b/test/pamtable.test
index 335d45c4..d42187f9 100755
--- a/test/pamtable.test
+++ b/test/pamtable.test
@@ -1,20 +1,55 @@
-#! /bin/bash
+#! /bin/sh
 # This script tests: pamtable
-# Also requires: pamseq pamdepth pbmmake ppmrainbow
+# Also requires: pamseq pamrestack pamdepth pbmmake ppmrainbow
 
+echo "Test 1"
 pamtable testgrid.pbm
+
 echo
+echo "Test 2"
 pamseq 3 2 -tupletype=RGB | pamtable
+
 echo
+echo "Test 3"
 pamseq 4 1 -tupletype=RGBA | pamtable
+
+echo
+echo "Test 4"
+pbmmake -gray 5 1 | pamtable -tuple
+
+echo
+echo "Test 5"
+pbmmake -gray 1 10 | pamtable -tuple
+
 echo
+echo "Test 6"
+pamseq 3 3 -tupletype=RGB | pamrestack -width=3 | pamtable -tuple
+
+echo
+echo "Test 7"
+pamseq 2 255 -max=50,255 -step=10,17 | pamrestack -width=8 | \
+  pamtable -hex
+
+echo
+echo "Test 8"
 for maxval in 9 10 9999 10000 65535
-  do pbmmake -g 2 2 | pamdepth $maxval | pamtable
-     echo
-     ppmrainbow -width=3 -height=2 -norepeat black white | \
-     pamdepth $maxval | pamtable
-     echo
-     ppmrainbow -width=4 -height=2 -norepeat red blue green | \
-     pamdepth $maxval | pamtable
-     echo
+  do
+  pbmmake -g 2 2 | pamdepth ${maxval} | pamtable
+  echo
+  ppmrainbow -width=3 -height=2 -norepeat black white | \
+    pamdepth ${maxval} | pamtable
+  echo
+  ppmrainbow -width=4 -height=2 -norepeat red blue green | \
+    pamdepth ${maxval} | pamtable
+  echo
   done
+
+echo "Test Invalid"
+
+. ${srcdir}/test-invalid.inc
+
+input1_pam=${tmpdir}/input1.pam
+
+pamseq -tupletype="void" 1 1 > ${input1_pam}
+invCmd "pamtable -tuple -hex ${input1_pam}"
+rm ${input1_pam}
diff --git a/test/pamtopam.ok b/test/pamtopam.ok
index dcb597d3..d84b2b6c 100644
--- a/test/pamtopam.ok
+++ b/test/pamtopam.ok
@@ -1,3 +1,18 @@
+Test 1. Should print five PAM headers
+P7
+WIDTH 14
+HEIGHT 16
+DEPTH 1
+MAXVAL 1
+TUPLTYPE BLACKANDWHITE
+ENDHDR
+P7
+WIDTH 1
+HEIGHT 1
+DEPTH 1
+MAXVAL 255
+TUPLTYPE GRAYSCALE
+ENDHDR
 P7
 WIDTH 227
 HEIGHT 149
@@ -6,11 +21,26 @@ MAXVAL 255
 TUPLTYPE RGB
 ENDHDR
 P7
-WIDTH 14
-HEIGHT 16
-DEPTH 1
+WIDTH 64
+HEIGHT 1
+DEPTH 2
+MAXVAL 7
+TUPLTYPE GRAYSCALE_ALPHA
+ENDHDR
+P7
+WIDTH 16
+HEIGHT 1
+DEPTH 4
 MAXVAL 1
-TUPLTYPE BLACKANDWHITE
+TUPLTYPE RGB_ALPHA
 ENDHDR
-1873848880 101532
+Test 2. Should print 2260748250 293
 2260748250 293
+Test 3. Should print 1873848880 101532
+1873848880 101532
+Test 4. Should print 1475247910 3432 twice
+1475247910 3432
+1475247910 3432
+Test 5. Should print 2347274358 101825 twice
+2347274358 101825
+2347274358 101825
diff --git a/test/pamtopam.test b/test/pamtopam.test
index 394d9904..c12470ec 100755
--- a/test/pamtopam.test
+++ b/test/pamtopam.test
@@ -1,10 +1,25 @@
-#! /bin/bash
+#! /bin/sh
 # This script tests: pamtopam
-# Also requires:
+# Also requires: pgmmake pamseq
 
+echo "Test 1. Should print five PAM headers"
 
-pamtopam < testimg.ppm  | sed '/ENDHDR/q'
 pamtopam < testgrid.pbm | sed '/ENDHDR/q'
+pgmmake 0.5 1 1 | pamtopam | sed '/ENDHDR/q'
+pamtopam < testimg.ppm  | sed '/ENDHDR/q'
+pamseq -tupletype="GRAYSCALE_ALPHA" 2 7 | pamtopam | sed '/ENDHDR/q'
+pamseq -tupletype="RGB_ALPHA" 4 1 | pamtopam | sed '/ENDHDR/q'
 
-pamtopam < testimg.ppm   | cksum
+echo "Test 2. Should print 2260748250 293"
 pamtopam < testgrid.pbm  | cksum
+
+echo "Test 3. Should print 1873848880 101532"
+pamtopam < testimg.ppm   | cksum
+
+echo "Test 4. Should print 1475247910 3432 twice"
+pamtopam < maze.pbm  | cksum
+pamtopam < maze.pbm  | pamtopam | cksum
+
+echo "Test 5. Should print 2347274358 101825 twice"
+cat testgrid.pbm testimg.ppm | pamtopam | cksum
+( pamtopam  < testgrid.pbm; pamtopam < testimg.ppm ) | cksum
diff --git a/test/pamtopdbimg.test b/test/pamtopdbimg.test
index 9afee8f1..d6c105bf 100755
--- a/test/pamtopdbimg.test
+++ b/test/pamtopdbimg.test
@@ -82,13 +82,13 @@ awk 'BEGIN { ABC="ABCDEFGHIJKLMNOPQRSTUVWXYZ";
 
 head -c 65533 ${text65597} > ${text65533}
 head -c 65534 ${text65597} > ${text65534}
-pamtopdbimg -uncompressed testgrid.pbm | \
+pamtopdbimg -uncompressed maze.pbm | \
   wc -c | tr -d ' '
   echo ${PIPESTATUS[0]}
-pamtopdbimg -uncompressed -notefile=${text65533} testgrid.pbm | \
+pamtopdbimg -uncompressed -notefile=${text65533} maze.pbm | \
   wc -c | tr -d ' '
   echo ${PIPESTATUS[0]}
-pamtopdbimg -uncompressed -notefile=${text65534} testgrid.pbm | \
+pamtopdbimg -uncompressed -notefile=${text65534} maze.pbm | \
   wc -c | tr -d ' '
   echo ${PIPESTATUS[0]}
 
diff --git a/test/pamtosvg.ok b/test/pamtosvg.ok
new file mode 100644
index 00000000..918555e0
--- /dev/null
+++ b/test/pamtosvg.ok
@@ -0,0 +1,4 @@
+Test 1.  Should print match
+match
+Test 2.  Should print match
+match
diff --git a/test/pamtosvg.test b/test/pamtosvg.test
new file mode 100755
index 00000000..4acf1fd9
--- /dev/null
+++ b/test/pamtosvg.test
@@ -0,0 +1,45 @@
+#! /bin/sh
+# This script tests: pamtosvg
+# Also requires: ppmmake ppmdraw
+
+tmpdir=${tmpdir:-/tmp}
+testline_svg=${tmpdir}/testline.svg
+testgrid_svg=${tmpdir}/testgrid.svg
+
+cat > ${testline_svg} << EOF
+<?xml version="1.0" standalone="yes"?>
+<svg width="20" height="20">
+<path style="fill:#000000; stroke:none;" d="M0 0L0 20L20 20L20 0L0 0z"/>
+<path style="fill:#ffffff; stroke:none;" d="M5 2L15 18L16 18L5 2z"/>
+</svg>
+EOF
+
+echo "Test 1.  Should print match"
+
+ppmmake black 20 20 | ppmdraw -script="line 5 2 15 17" | pamtosvg |\
+    cmp -s ${testline_svg} - && echo "match" || echo "no match"
+rm ${testline_svg}
+
+cat > ${testgrid_svg} << EOF
+<?xml version="1.0" standalone="yes"?>
+<svg width="14" height="16">
+<path style="fill:#000000; stroke:none;" d="M0 0L0 16L14 16L14 1L13 0L0 0z"/>
+<path style="fill:#ffffff; stroke:none;" d="M1 0L2 1L1 0M3 0L4 1L3 0M5 0L6 \
+1L5 0M7 0L8 1L7 0M9 0L10 1L9 0M11 0L12 1L11 0M13 0L14 1L13 0M1 2L2 3L1 2M3 \
+2L4 3L3 2M5 2L6 3L5 2M7 2L8 3L7 2M9 2L10 3L9 2M11 2L12 3L11 2M13 2L14 3L13 \
+2M1 4L2 5L1 4M3 4L4 5L3 4M5 4L6 5L5 4M7 4L8 5L7 4M9 4L10 5L9 4M11 4L12 5L11 \
+4M13 4L14 5L13 4M1 6L2 7L1 6M3 6L4 7L3 6M5 6L6 7L5 6M7 6L8 7L7 6M9 6L10 7L9 \
+6M11 6L12 7L11 6M13 6L14 7L13 6M1 8L2 9L1 8M3 8L4 9L3 8M5 8L6 9L5 8M7 8L8 9L7 \
+8M9 8L10 9L9 8M11 8L12 9L11 8M13 8L14 9L13 8M1 10L2 11L1 10M3 10L4 11L3 10M5 \
+10L6 11L5 10M7 10L8 11L7 10M9 10L10 11L9 10M11 10L12 11L11 10M13 10L14 11L13 \
+10M1 12L2 13L1 12M3 12L4 13L3 12M5 12L6 13L5 12M7 12L8 13L7 12M9 12L10 13L9 \
+12M11 12L12 13L11 12M13 12L14 13L13 12M1 14L2 15L1 14M3 14L4 15L3 14M5 14L6 \
+15L5 14M7 14L8 15L7 14M9 14L10 15L9 14M11 14L12 15L11 14M13 14L14 15L13 14z"/>
+</svg>
+EOF
+
+echo "Test 2.  Should print match"
+
+pamtosvg testgrid.pbm |\
+    cmp -s ${testgrid_svg} - && echo "match" || echo "no match"
+rm ${testgrid_svg}
diff --git a/test/pamundice.ok b/test/pamundice.ok
index ef0f6e13..9c869609 100644
--- a/test/pamundice.ok
+++ b/test/pamundice.ok
@@ -1,27 +1,27 @@
-Test 1.
+Test 1.  Should print 2096818803 2818 twice
 2096818803 2818
 2096818803 2818
-Test 2.
+Test 2.  Should print 2096818803 2818 twice
 2096818803 2818
 2096818803 2818
-Test 3.
+Test 3.  Should print 2096818803 2818 twice
 2096818803 2818
 2096818803 2818
-Test 4.
-557392151 459
-557392151 459
-557392151 459
-557392151 459
+Test 4.  Should print 2434390296 4436 four times
+2434390296 4436
+2434390296 4436
+2434390296 4436
+2434390296 4436
 Test Invalid
-Expected failure 1 1
-Expected failure 2 1
-Expected failure 3 1
-Expected failure 4 1
-Expected failure 5 1
-Expected failure 6 1
-Expected failure 7 1
-Expected failure 8 1
-Expected failure 9 1
-Expected failure 10 1
-Expected failure 11 1
-Expected failure 12 1
+Expected failure 1 (no output)
+Expected failure 2 (no output)
+Expected failure 3 (no output)
+Expected failure 4 (no output)
+Expected failure 5 (no output)
+Expected failure 6 (no output)
+Expected failure 7 (no output)
+Expected failure 8 (no output)
+Expected failure 9 (no output)
+Expected failure 10 (no output)
+Expected failure 11 (no output)
+Expected failure 12 (no output)
diff --git a/test/pamundice.test b/test/pamundice.test
index e8add587..1190fbdc 100755
--- a/test/pamundice.test
+++ b/test/pamundice.test
@@ -1,15 +1,14 @@
-#! /bin/bash
+#! /bin/sh
 # This script tests: pamundice
-# Also requires: pgmmake pnmtile pnmcat pnmpad
+# Also requires: pamfile pgmmake pnmtile pamcat
 
 tmpdir=${tmpdir:-/tmp}
 fname_stem=${tmpdir}/part
 
-# Test 1.
-echo "Test 1."
+echo "Test 1.  Should print 2096818803 2818 twice"
 
-for ((x=0; x<3; ++x))
-  do for ((y=0; y<5; ++y))
+for x in 0 1 2
+  do for y in 0 1 2 3 4
     do
     pgmmake "."$(( x* 25 + y )) 11 17 > ${fname_stem}_${y}_${x}.pgm
     done
@@ -18,46 +17,43 @@ for ((x=0; x<3; ++x))
 pamundice -across=3 -down=5 ${fname_stem}"_%1d_%1a".pgm | cksum
 
 ls ${fname_stem}_?_?.pgm | \
-    pamundice -across=3 -down=5 -listfile=- | cksum 
+    pamundice -across=3 -down=5 -listfile=- | cksum
 
-
-# Test 2.
-echo "Test 2."
+echo "Test 2.  Should print 2096818803 2818 twice"
 
 tempfile=${tmpdir}/temp
 
-for ((y=0; y<5; ++y))
+for y in 0 1 2 3 4
   do
   pamundice -across=3 ${fname_stem}"_"$y"_%1a".pgm > ${tempfile}_"$y"
   done
- 
-pnmcat -tb ${tempfile}_[01234] | cksum
+
+pamcat -tb ${tempfile}_[01234] | cksum
 rm ${tempfile}_[01234]
 
 # Note: the following 2 are valid.  There should not be warning messages.
 
-for ((x=0; x<3; ++x))
+for x in 0 1 2
   do
   pamundice -down=5 ${fname_stem}"_%1d_"$x.pgm > ${tempfile}"_"$x
   done
 
-pnmcat -lr ${tempfile}_[012] | cksum
+pamcat -lr ${tempfile}_[012] | cksum
 rm ${tempfile}_[012]
 
 rm ${fname_stem}_?_?.pgm
 
-# Test 3.
-echo "Test 3."
+echo "Test 3.  Should print 2096818803 2818 twice"
 
-for ((x=0; x<2; ++x))
-  do for ((y=0; y<5; ++y))
+for x in 0 1
+  do for y in 0 1 2 3 4
     do
     pgmmake "."$(( x* 25 + y )) 12 17 > ${fname_stem}_${y}_${x}.pgm
     done
   done
 
-for ((x=2; x<3; ++x))
-  do for ((y=0; y<5; ++y))
+for x in 2
+  do for y in 0 1 2 3 4
     do
     pgmmake "."$(( x* 25 + y )) 11 17 > ${fname_stem}_${y}_${x}.pgm
     done
@@ -68,15 +64,15 @@ pamundice -across=3 -down=5 \
 
 rm ${fname_stem}_?_?.pgm
 
-for ((x=0; x<3; ++x))
-  do for ((y=0; y<4; ++y))
+for x in 0 1 2
+  do for y in 0 1 2 3
     do
     pgmmake "."$(( x* 25 + y )) 11 18 > ${fname_stem}_${y}_${x}.pgm
     done
   done
 
-for ((x=0; x<3; ++x))
-  do for ((y=4; y<5; ++y))
+for x in 0 1 2
+  do for y in 4
     do
     pgmmake "."$(( x* 25 + y )) 11 17 > ${fname_stem}_${y}_${x}.pgm
     done
@@ -89,21 +85,22 @@ rm ${fname_stem}_?_?.pgm
 
 
 # Test 4.
-echo "Test 4."
+echo "Test 4.  Should print 2434390296 4436 four times"
 
-# Add margins to testgrid.pbm
+msize=$(pamfile -size maze.pbm)
+mw=$(echo ${msize} | cut -d " " -f 1)
+mh=$(echo ${msize} | cut -d " " -f 2)
 
-testimg_pbm=${tmpdir}/testimg.pbm
-pnmpad -top=2 -left=3 -black testgrid.pbm > ${testimg_pbm}
+pnmtile $((${mw} * 2)) $((${mh} * 5)) maze.pbm | cksum
 
-for x in `seq 0 1`
-  do for y in `seq 0 4`
-    do cp ${testimg_pbm} ${fname_stem}_${y}_${x}.pbm; done
+for x in 0 1
+  do for y in 0 1 2 3 4
+    do cp maze.pbm ${fname_stem}_${y}_${x}.pbm; done
   done
 
-for (( i=0 ; i<=9; ++i))
+for i in 0 1 2 3 4 5 6 7 8 9
   do
-  echo ${testimg_pbm}
+  echo maze.pbm
   done | pamundice -down=5 -across=2 -listfile=- | cksum
 
 pamundice -down=5 -across=2 ${fname_stem}_"%1d"_"%1a".pbm | cksum
@@ -111,11 +108,8 @@ pamundice -down=5 -across=2 ${fname_stem}_"%1d"_"%1a".pbm | cksum
 echo "A warning message should appear below the line." 1>&2
 echo "-----------------------------------------------------------" 1>&2
 
-pamundice -down=5 -across=2 ${testimg_pbm} | cksum
-
-pnmtile 34 90 ${testimg_pbm} | cksum
+pamundice -down=5 -across=2 maze.pbm | cksum
 
-rm ${testimg_pbm}
 
 # Test Invalid.
 echo "Test Invalid"
@@ -129,55 +123,80 @@ echo "-----------------------------------------------------------" 1>&2
 
 # No input file pattern specified
 pamundice -down=5 -across=2 > ${test_out} || \
-echo -n "Expected failure 1"; test -s ${test_out}; echo " "$?
+  printf "Expected failure 1 "
+  test -s ${test_out} && echo "unexpected output" || echo "(no output)"
+  rm -f ${test_out}
 
 # -down=0
 pamundice -down=0 -across=2 ${fname_stem}_"%1d"_"%1a".pbm > ${test_out} || \
-echo -n "Expected failure 2"; test -s ${test_out}; echo " "$?
+  printf "Expected failure 2 "
+  test -s ${test_out} && echo "unexpected output" || echo "(no output)"
+  rm -f ${test_out}
 
 # -across=0
 pamundice -down=5 -across=0 ${fname_stem}_"%1d"_"%1a".pbm > ${test_out} || \
-echo -n "Expected failure 3"; test -s ${test_out}; echo " "$?
+  printf "Expected failure 3 "
+  test -s ${test_out} && echo "unexpected output" || echo "(no output)"
+  rm -f ${test_out}
 
 # -down too large
 pamundice -down=6 -across=2 ${fname_stem}_"%1d"_"%1a".pbm > ${test_out} || \
-echo -n "Expected failure 4"; test -s ${test_out}; echo " "$?
+  printf "Expected failure 4 "
+  test -s ${test_out} && echo "unexpected output" || echo "(no output)"
+  rm -f ${test_out}
 
 # -across too large
 pamundice -down=5 -across=3 ${fname_stem}_"%1d"_"%1a".pbm > ${test_out} || \
-echo -n "Expected failure 5"; test -s ${test_out}; echo " "$?
+  printf "Expected failure 5 "
+  test -s ${test_out} && echo "unexpected output" || echo "(no output)"
+  rm -f ${test_out}
 
 # precision does not match
 pamundice -down=5 -across=2 ${fname_stem}_"%2d"_"%2a".pbm > ${test_out} || \
-echo -n "Expected failure 6"; test -s ${test_out}; echo " "$?
+  printf "Expected failure 6 "
+  test -s ${test_out} && echo "unexpected output" || echo "(no output)"
+  rm -f ${test_out}
 
 # precision set to zero
 pamundice -down=5 -across=2 ${fname_stem}_"%0d"_"%0a".pbm > ${test_out} || \
-echo -n "Expected failure 7"; test -s ${test_out}; echo " "$?
+  printf "Expected failure 7 "
+  test -s ${test_out} && echo "unexpected output" || echo "(no output)"
+  rm -f ${test_out}
 
 # no precision
 pamundice -down=5 -across=2 ${fname_stem}_"%d"_"%a".pbm > ${test_out} || \
-echo -n "Expected failure 8"; test -s ${test_out}; echo " "$?
+  printf "Expected failure 8 "
+  test -s ${test_out} && echo "unexpected output" || echo "(no output)"
+  rm -f ${test_out}
 
 # -hoverlap too large
-pamundice -down=5 -across=2 -hoverlap=18 \
+pamundice -down=5 -across=2 -hoverlap=$((${mw}+1)) \
   ${fname_stem}_"%1d"_"%1a".pbm > ${test_out} || \
-echo -n "Expected failure 9"; test -s ${test_out}; echo " "$?
+  printf "Expected failure 9 "
+  test -s ${test_out} && echo "unexpected output" || echo "(no output)"
+  rm -f ${test_out}
 
 # -voverlap too large
-pamundice -down=5 -across=2 -voverlap=19 \
+pamundice -down=5 -across=2 -voverlap=$((${mh}+1)) \
   ${fname_stem}_"%1d"_"%1a".pbm > ${test_out} || \
-echo -n "Expected failure 10"; test -s ${test_out}; echo " "$?
+  printf "Expected failure 10 "
+  test -s ${test_out} && echo "unexpected output" || echo "(no output)"
+  rm -f ${test_out}
 
 # corrupt listfile : file names do not exist
-seq 10 | sed -e 's/^/::::::/' -e 's/$/::::::/' | \
-  pamundice -down=5 -across=2 -listfile=- > ${test_out} || \
-echo -n "Expected failure 11"; test -s ${test_out}; echo " "$?
+for i in 0 1 2 3 4 5 6 7 8 9
+  do
+  mktemp -u XXXXXXXXXX.${i} || echo ":::::::::::"${i}":::::::::::"
+  done | pamundice -down=5 -across=2 -listfile=- > ${test_out} || \
+  printf "Expected failure 11 "
+  test -s ${test_out} && echo "unexpected output" || echo "(no output)"
+  rm -f ${test_out}
 
 # listfile with insufficient lines (insufficient file entries)
 ls ${fname_stem}_*_*.pbm | head -n 9 | \
   pamundice -down=5 -across=2 -listfile=- > ${test_out} || \
-echo -n "Expected failure 12"; test -s ${test_out}; echo " "$?
+  printf "Expected failure 12 "
+  test -s ${test_out} && echo "unexpected output" || echo "(no output)"
+  rm -f ${test_out}
 
 rm ${fname_stem}*.pbm
-
diff --git a/test/pamvalidate.test b/test/pamvalidate.test
index 4cabc7df..708197da 100755
--- a/test/pamvalidate.test
+++ b/test/pamvalidate.test
@@ -1,20 +1,20 @@
-#! /bin/bash
+#! /bin/sh
 # This script tests: pamvalidate
 # Also requires:
 
 echo "valid"
-echo -e "P1\n5 5\n01010\n10101\n01010\n00000\n11111\n" | pamvalidate -plain
+printf "P1\n5 5\n01010\n10101\n01010\n00000\n11111\n" | pamvalidate -plain
 
 echo "not valid: Should print 0 four times"
-echo -e "P1\n5 5\n01010\n10101\n01010\n00000\n1111\n"  | pamvalidate | \
+printf "P1\n5 5\n01010\n10101\n01010\n00000\n1111\n"  | pamvalidate | \
   wc -c | tr -d ' '
 
-echo -e "P1\n5 5\n01010\n10102\n01010\n00001\n11111\n" | pamvalidate | \
+printf "P1\n5 5\n01010\n10102\n01010\n00001\n11111\n" | pamvalidate | \
   wc -c | tr -d ' '
 
-echo -e "P1\n5\n01010\n10101\n01010\n00000\n11111\n" | pamvalidate | \
+printf "P1\n5\n01010\n10101\n01010\n00000\n11111\n" | pamvalidate | \
   wc -c | tr -d ' '
 
-echo -e "P1\n5 5" | pamvalidate | wc -c | tr -d ' '
+printf "P1\n5 5" | pamvalidate | wc -c | tr -d ' '
 
 
diff --git a/test/pbm-misc-converters.ok b/test/pbm-misc-converters.ok
index a137102f..1ae5d817 100644
--- a/test/pbm-misc-converters.ok
+++ b/test/pbm-misc-converters.ok
@@ -1,27 +1,58 @@
-1638343024 43
-2141128209 77
-2542756600 120
-3102495729 32
-2414506375 47
-3241517214 145
-1454090165 46
-1436169407 46
-1454090165 46
-2912484298 46
-3576177652 52
-1478164284 52
-3213223606 141
-3213223606 141
-3213223606 141
-1463148415 108
-203901789 30
-3732005859 92
-2459345477 86
-424535246 92
-609530223 252
-4195053594 248
-2602382240 43
-129620534 361
-2256096096 80
-1349121911 149
+pbmto10x
+3017587389 501
+3017587389 501
+pbmto4425
+2529120683 622
+2529120683 622
+pbmtoascii
+2361485126 1740
+2361485126 1740
+4017331268 450
+pbmtodjvurle
+2707446245 1744
+2707446245 1744
+pbmtoepson
+2100180787 510
+2100180787 510
+2963515498 510
+2100180787 510
+1513122412 510
+pbmtogo
+34750317 804
+34750317 804
+pbmtoibm23xx
+1731023722 546
+1731023722 546
+pbmtolj
+1540204160 762
+1540204160 762
+908699854 763
+908699854 763
+pbmtoln03
+1554612498 636
+1554612498 636
+pbmtomatrixorbital
+1574732995 458
+1574732995 458
+pbmtonokia
+3813814418 972
+3813814418 972
+1385394245 966
+3924854157 972
+3970098281 3388
+167529797 3384
+2260274013 483
+pbmtoplot
+2120102625 5318
+2120102625 5318
+pbmtoptx
+541430122 708
+541430122 708
+pbmtozinc
+2297581967 1725
+2297581967 1725
+pbmtobbnbg
+3481527833 672
+pbmtoppa
+3955750161 284701
 3955750161 284701
diff --git a/test/pbm-misc-converters.test b/test/pbm-misc-converters.test
index ad96f13c..ba350bc7 100755
--- a/test/pbm-misc-converters.test
+++ b/test/pbm-misc-converters.test
@@ -1,40 +1,98 @@
-#! /bin/bash
+#! /bin/sh
 # This script tests: pbmto10x pbmto4425 pbmtoascii pbmtobbnbg
 # This script tests: pbmtodjvurle pbmtoepson pbmtogo pbmtoibm23xx
 # This script tests: pbmtolj pbmtoln03 pbmtomatrixorbital pbmtonokia
-# This script tests: pbmtoplot pbmtoptx pbmtozinc
-# Also requires: pbmpage pbmtoppa
+# This script tests: pbmtoplot pbmtoppa pbmtoptx pbmtozinc
+# Also requires: pbmpage
 
 # Note: one-way test.
 # These converters do not have counterparts that work in the opposite
 # direction.  We check whether the output is unchanged from older
 # versions.
 
-pbmto10x             testgrid.pbm | cksum
-pbmto4425            testgrid.pbm | cksum
-pbmtoascii           testgrid.pbm | cksum
-pbmtoascii -2x4      testgrid.pbm | cksum
-pbmtobbnbg         < testgrid.pbm | cksum
-pbmtodjvurle         testgrid.pbm | cksum
-pbmtoepson           testgrid.pbm | cksum
-pbmtoepson -protocol=escp   testgrid.pbm | cksum
-pbmtoepson -protocol=escp9  testgrid.pbm | cksum
-pbmtoepson -nonadjacent     testgrid.pbm | cksum
-pbmtogo              testgrid.pbm | cksum
-pbmtoibm23xx -xres=60 -yres=60 testgrid.pbm | cksum
-pbmtolj              testgrid.pbm | cksum
-pbmtolj  -packbits   testgrid.pbm | cksum
-pbmtolj  -compress   testgrid.pbm | cksum
-pbmtoln03            testgrid.pbm | cksum
-pbmtomatrixorbital < testgrid.pbm | cksum
-pbmtonokia -fmt HEX_NOL testgrid.pbm | cksum
-pbmtonokia -fmt HEX_NGG testgrid.pbm | cksum
-pbmtonokia -fmt HEX_NPM testgrid.pbm | cksum
-pbmtonokia -fmt NOL  testgrid.pbm | cksum
-pbmtonokia -fmt NGG  testgrid.pbm | cksum
-pbmtonokia -fmt NPM  testgrid.pbm | cksum
-pbmtoplot            testgrid.pbm | cksum
-pbmtoptx             testgrid.pbm | cksum
-pbmtozinc            testgrid.pbm | cksum
-
-(pbmpage 1; pbmpage 2; pbmpage 3) | pbmtoppa | cksum
+echo "pbmto10x"
+pbmto10x               maze.pbm | cksum
+pbmto10x             < maze.pbm | cksum
+
+echo "pbmto4425"
+pbmto4425              maze.pbm | cksum
+pbmto4425            < maze.pbm | cksum
+
+# Asciitopgm works in the opposite direction, but the round-trip is not accurate
+
+echo "pbmtoascii"
+pbmtoascii             maze.pbm | cksum
+pbmtoascii           < maze.pbm | cksum
+pbmtoascii -2x4        maze.pbm | cksum
+
+echo "pbmtodjvurle"
+pbmtodjvurle           maze.pbm | cksum
+pbmtodjvurle         < maze.pbm | cksum
+
+echo "pbmtoepson"
+pbmtoepson             maze.pbm | cksum
+pbmtoepson           < maze.pbm | cksum
+pbmtoepson -protocol=escp   maze.pbm | cksum
+pbmtoepson -protocol=escp9  maze.pbm | cksum
+pbmtoepson -nonadjacent     maze.pbm | cksum
+
+echo "pbmtogo"
+pbmtogo                maze.pbm | cksum
+pbmtogo              < maze.pbm | cksum
+
+echo "pbmtoibm23xx"
+pbmtoibm23xx -xres=60 -yres=60    maze.pbm | cksum
+pbmtoibm23xx -xres=60 -yres=60  < maze.pbm | cksum
+
+echo "pbmtolj"
+pbmtolj                maze.pbm | cksum
+pbmtolj              < maze.pbm | cksum
+pbmtolj  -packbits     maze.pbm | cksum
+pbmtolj  -compress     maze.pbm | cksum
+
+echo "pbmtoln03"
+pbmtoln03              maze.pbm | cksum
+pbmtoln03            < maze.pbm | cksum
+
+echo "pbmtomatrixorbital"
+pbmtomatrixorbital     maze.pbm | cksum
+pbmtomatrixorbital   < maze.pbm | cksum
+
+echo "pbmtonokia"
+pbmtonokia -fmt HEX_NOL   maze.pbm | cksum
+pbmtonokia -fmt HEX_NOL < maze.pbm | cksum
+pbmtonokia -fmt HEX_NGG   maze.pbm | cksum
+pbmtonokia -fmt HEX_NPM   maze.pbm | cksum
+pbmtonokia -fmt NOL       maze.pbm | cksum
+pbmtonokia -fmt NGG       maze.pbm | cksum
+pbmtonokia -fmt NPM       maze.pbm | cksum
+
+echo "pbmtoplot"
+pbmtoplot              maze.pbm | cksum
+pbmtoplot            < maze.pbm | cksum
+
+echo "pbmtoptx"
+pbmtoptx               maze.pbm | cksum
+pbmtoptx             < maze.pbm | cksum
+
+# pbmtozinc embeds input filename in the output
+
+echo "pbmtozinc"
+pbmtozinc   maze.pbm | cksum
+pbmtozinc < maze.pbm | sed 's/noname/maze/' | cksum
+
+# pbmtobbnbg input must be from stdin
+
+echo "pbmtobbnbg"
+pbmtobbnbg < maze.pbm | cksum
+
+# pbmtoppa has constraints on what can be accepted as input; maze.pbm is not accepted
+# pbmpage produces suitable input
+
+tmpdir=${tmpdir:-/tmp}
+testpage_pbm=${tmpdir}/testpage.pbm
+
+echo "pbmtoppa"
+(pbmpage 1; pbmpage 2; pbmpage 3) | tee ${testpage_pbm} | pbmtoppa | cksum
+pbmtoppa ${testpage_pbm} | cksum
+rm ${testpage_pbm}
diff --git a/test/pbm-ppm-roundtrip.ok b/test/pbm-ppm-roundtrip.ok
new file mode 100644
index 00000000..91c502b5
--- /dev/null
+++ b/test/pbm-ppm-roundtrip.ok
@@ -0,0 +1,39 @@
+Test 1.  Should print 281226646 481 five times.
+281226646 481
+281226646 481
+281226646 481
+281226646 481
+281226646 481
+Test 2.  Should print three all-white, then three all-black PBM images
+P1
+7 3
+0000000
+0000000
+0000000
+
+P1
+7 3
+0000000
+0000000
+0000000
+
+P1
+7 3
+0000000
+0000000
+0000000
+
+P1
+17 2
+11111111111111111
+11111111111111111
+
+P1
+17 2
+11111111111111111
+11111111111111111
+
+P1
+17 2
+11111111111111111
+11111111111111111
diff --git a/test/pbm-ppm-roundtrip.test b/test/pbm-ppm-roundtrip.test
new file mode 100755
index 00000000..9a3ff79f
--- /dev/null
+++ b/test/pbm-ppm-roundtrip.test
@@ -0,0 +1,34 @@
+#! /bin/sh
+# This script tests: pgmtoppm ppmtopgm ppmtoppm pgmtopbm
+# Also requires: pbmmake ppmcolormask pnminvert
+
+echo "Test 1.  Should print 281226646 481 five times."
+
+cat maze.pbm | cksum
+pgmtoppm black-white maze.pbm | ppmtopgm | \
+  pgmtopbm -th -val=0.5 | cksum
+pgmtoppm white-black maze.pbm | ppmtopgm | \
+  pgmtopbm -th -val=0.5 | pnminvert | cksum
+pgmtoppm white-black maze.pbm | ppmcolormask white | cksum
+ppmtoppm < maze.pbm | ppmtopgm | pgmtopbm -th -val=0.5 | cksum
+
+echo "Test 2.  Should print three all-white, then three all-black PBM images"
+
+pbmmake -w 7 3  -plain
+echo
+
+pbmmake -w 7 3 | pgmtoppm black-white | ppmtopgm | \
+  pgmtopbm -th -val=0.5 -plain
+echo
+pbmmake -w 7 3 | ppmtoppm | ppmtopgm | \
+  pgmtopbm -th -val=0.5 -plain
+echo
+
+pbmmake -b 17 2 -plain
+echo
+
+pbmmake -b 17 2 | pgmtoppm black-white | ppmtopgm | \
+  pgmtopbm -th -val=0.5 -plain
+echo
+pbmmake -b 17 2 | ppmtoppm | ppmtopgm | \
+  pgmtopbm -th -val=0.5 -plain
diff --git a/test/pbmclean.ok b/test/pbmclean.ok
index 17ee0338..5fc9a2d5 100644
--- a/test/pbmclean.ok
+++ b/test/pbmclean.ok
@@ -85,4 +85,4 @@ Test 3
 436062787 5051
 4188415575 5051
 Test Invalid
-Expected failure 1 1
+Expected failure 1 (no output)
diff --git a/test/pbmclean.test b/test/pbmclean.test
index c0c3a759..64ed6df0 100755
--- a/test/pbmclean.test
+++ b/test/pbmclean.test
@@ -1,4 +1,4 @@
-#! /bin/bash
+#! /bin/sh
 # This script tests: pbmclean
 # Also requires: pbmmake pbmpage pbmtext pnmmargin pnmpad
 
@@ -37,17 +37,8 @@ rm ${sheet_pbm}
 
 echo "Test Invalid"
 
-test_out=${tmpdir}/test_out
-
-echo 1>&2
-echo "Invalid command-line argument combination." 1>&2
-echo "An error message should appear below the line." 1>&2
-echo "-----------------------------------------------------------" 1>&2
+. ${srcdir}/test-invalid.inc
 
 # overspecification
-pbmclean -black -white -min=1 -extended testgrid.pbm > ${test_out} || \
-   echo -n "Expected failure 1"; test -s ${test_out}; echo " "$?
-
+invCmd "pbmclean -black -white -min=1 -extended testgrid.pbm"
 # note that without -extended the above is valid.
-
-rm -f ${test_out}
\ No newline at end of file
diff --git a/test/pbmlife.ok b/test/pbmlife.ok
new file mode 100644
index 00000000..bd214dfb
--- /dev/null
+++ b/test/pbmlife.ok
@@ -0,0 +1,63 @@
+P1
+63 29
+000000000000000000000000000000000000000000000000000000000000000
+000000000000000000000000000000000000000000000000000000000000000
+000000000000000000000000000000000000000000000000000000000000000
+000000000000000000000000000000000000000000000000000000000000000
+000000000000000000000000000000000000000000000000000000000000000
+000000000000000000000000000000000000000000000000000000000000000
+000000000000000000000000000000000000000000000000000000000000000
+000000000000000000000000000000000000000000000000000000000000000
+000000000000000000000000000000000000000000000000000000000000000
+000000000000000000000000000000000000000000000000000000000000000
+000000000000001111111000111100000000000111000111000000000000000
+000000000000000100001001100110000000001000101001100000000000000
+000000000000000100000001000010000000001000101000100000000000000
+000000000000000100010010000001000010001100101000100000000000000
+000000000000000111110010000001000010000111001100100000000000000
+000000000000000100010010000001001111101001100111100000000000000
+000000000000000100000001000010000010001000100001000000000000000
+000000000000000100000001100110000010001000100011000000000000000
+000000000000001111000000111100000000000111001100000000000000000
+000000000000000000000000000000000000000000000000000000000000000
+000000000000000000000000000000000000000000000000000000000000000
+000000000000000000000000000000000000000000000000000000000000000
+000000000000000000000000000000000000000000000000000000000000000
+000000000000000000000000000000000000000000000000000000000000000
+000000000000000000000000000000000000000000000000000000000000000
+000000000000000000000000000000000000000000000000000000000000000
+000000000000000000000000000000000000000000000000000000000000000
+000000000000000000000000000000000000000000000000000000000000000
+000000000000000000000000000000000000000000000000000000000000000
+
+   tiles:	1722
+ x-edges:	1812
+ y-edges:	1842
+vertices:	1920
+    area:	1722
+perimeter:	420
+ eulerchi:	-12
+
+   tiles:	17
+ x-edges:	33
+ y-edges:	33
+vertices:	64
+    area:	17
+perimeter:	64
+ eulerchi:	15
+
+   tiles:	2
+ x-edges:	3
+ y-edges:	4
+vertices:	6
+    area:	2
+perimeter:	6
+ eulerchi:	1
+
+   tiles:	0
+ x-edges:	0
+ y-edges:	0
+vertices:	0
+    area:	0
+perimeter:	0
+ eulerchi:	0
diff --git a/test/pbmlife.test b/test/pbmlife.test
new file mode 100755
index 00000000..c292ee65
--- /dev/null
+++ b/test/pbmlife.test
@@ -0,0 +1,13 @@
+#! /bin/sh
+# This script tests: pbmlife pbmminkowski
+# Also requires: pbmtext
+
+pbmtext FO+89 -plain
+echo
+pbmtext FO+89 | pbmminkowski
+echo
+pbmtext FO+89 | pbmlife | pbmminkowski
+echo
+pbmtext FO+89 | pbmlife | pbmlife | pbmminkowski
+echo
+pbmtext FO+89 | pbmlife | pbmlife | pbmlife | pbmminkowski
diff --git a/test/pbmmake.ok b/test/pbmmake.ok
index e39f4cf8..4b13cf54 100644
--- a/test/pbmmake.ok
+++ b/test/pbmmake.ok
@@ -44,11 +44,11 @@ Test 2
 3651864954 3375
 3302595397 3849
 Test Invalid
-Expected failure 1 1
-Expected failure 2 1
-Expected failure 3 1
-Expected failure 4 1
-Expected failure 5 1
-Expected failure 6 1
-Expected failure 7 1
-Expected failure 8 1
+Expected failure 1 (no output)
+Expected failure 2 (no output)
+Expected failure 3 (no output)
+Expected failure 4 (no output)
+Expected failure 5 (no output)
+Expected failure 6 (no output)
+Expected failure 7 (no output)
+Expected failure 8 (no output)
diff --git a/test/pbmmake.test b/test/pbmmake.test
index 3f815617..32153f95 100755
--- a/test/pbmmake.test
+++ b/test/pbmmake.test
@@ -1,51 +1,36 @@
-#! /bin/bash
+#! /bin/sh
 # This script tests: pbmmake
 # Also requires:
 
 echo "Test 1"
 
-for i in `seq 1 8`
-do
-for color in -white -black -gray
-do
-pbmmake -plain $color $i $i | tr -d '\n'; echo
-done
-done
+for size in 1 2 3 4 5 6 7 8             # for size in `seq 8`
+  do
+  for color in -white -black -gray
+    do
+    pbmmake -plain ${color} ${size} ${size} | tr -d '\n'; echo
+    done
+  done
 
 echo "Test 2"
 
-for i in `seq 8 5 98`
-do
- ( pbmmake -w $i $i ;
-  pbmmake -b $i $i ;
-  pbmmake  -g $i $i ) | cksum
+for size in 8 13 18 23 28 33 38 43 48 53 58 63 68 73 78 83 88 93 98
+	    # for size in `seq 8 5 98`
+  do
+  ( pbmmake -w ${size} ${size} ;
+    pbmmake -b ${size} ${size} ;
+    pbmmake -g ${size} ${size} ) | cksum
 done
 
 echo "Test Invalid"
 
-echo 1>&2
-echo "Invalid command-line argument combinations." 1>&2
-echo "Error messages should appear below the line." 1>&2
-echo "-----------------------------------------------------------" 1>&2
-
-tmpdir=${tmpdir:-/tmp}
-test_out=${tmpdir}/test_out
-
-pbmmake -b -w -plain 1 1 > ${test_out} || \
-   echo -n "Expected failure 1"; test -s ${test_out}; echo " "$?
-pbmmake -b -g -plain 1 1 > ${test_out} || \
-   echo -n "Expected failure 2"; test -s ${test_out}; echo " "$?
-pbmmake -white -gray -plain 1 1 > ${test_out} || \
-   echo -n "Expected failure 3"; test -s ${test_out}; echo " "$?
-pbmmake -white -plain   > ${test_out} || \
-   echo -n "Expected failure 4"; test -s ${test_out}; echo " "$?
-pbmmake -white -plain 1 > ${test_out} || \
-   echo -n "Expected failure 5"; test -s ${test_out}; echo " "$?
-pbmmake -white -plain 1 0 > ${test_out} || \
-   echo -n "Expected failure 6"; test -s ${test_out}; echo " "$?
-pbmmake -white -plain 0 1 > ${test_out} || \
-   echo -n "Expected failure 7"; test -s ${test_out}; echo " "$?
-pbmmake -white -plain 1 1 1 > ${test_out} || \
-   echo -n "Expected failure 8"; test -s ${test_out}; echo " "$?
+. ${srcdir}/test-invalid.inc
 
-rm ${test_out}
+invCmd "pbmmake -b -w -plain 1 1"
+invCmd "pbmmake -b -g -plain 1 1"
+invCmd "pbmmake -white -gray -plain 1 1"
+invCmd "pbmmake -white -plain"
+invCmd "pbmmake -white -plain 1"
+invCmd "pbmmake -white -plain 1 0"
+invCmd "pbmmake -white -plain 0 1"
+invCmd 'pbmmake -white -plain 1 1 1'
diff --git a/test/pbmminkowski.ok b/test/pbmminkowski.ok
index 71a909ce..9780e3c2 100644
--- a/test/pbmminkowski.ok
+++ b/test/pbmminkowski.ok
@@ -21,3 +21,11 @@ vertices:	224
     area:	56
 perimeter:	224
  eulerchi:	56
+
+   tiles:	1627
+ x-edges:	2479
+ y-edges:	2427
+vertices:	3376
+    area:	1627
+perimeter:	3304
+ eulerchi:	97
diff --git a/test/pbmminkowski.test b/test/pbmminkowski.test
index 389ff44a..790e45bd 100755
--- a/test/pbmminkowski.test
+++ b/test/pbmminkowski.test
@@ -1,11 +1,12 @@
-#! /bin/bash
+#! /bin/sh
 # This script tests: pbmminkowski
-# Also requires: pbmmake pnmmargin pnmpad
+# Also requires: pbmmake pnmpad
 
-
-pbmmake -w 1 1 | pnmmargin -b 1 | \
+pbmmake -w 1 1 | pnmpad -black -top=1 -left=1 -bottom=1 -right=1 | \
   pbmminkowski
 echo
 pbmmake -g 3 3 | pbmminkowski
 echo
 pbmminkowski testgrid.pbm
+echo
+pbmminkowski maze.pbm
\ No newline at end of file
diff --git a/test/pbmnoise-parameters.ok b/test/pbmnoise-parameters.ok
new file mode 100644
index 00000000..640b438d
--- /dev/null
+++ b/test/pbmnoise-parameters.ok
@@ -0,0 +1,28 @@
+Test Invalid
+Expected failure 1 (no output)
+Expected failure 2 (no output)
+Expected failure 3 (no output)
+Expected failure 4 (no output)
+Expected failure 5 (no output)
+Expected failure 6 (no output)
+Expected failure 7 (no output)
+Expected failure 8 (no output)
+Expected failure 9 (no output)
+Expected failure 10 (no output)
+Expected failure 11 (no output)
+Expected failure 12 (no output)
+Expected failure 13 (no output)
+Expected failure 14 (no output)
+Expected failure 15 (no output)
+Expected failure 16 (no output)
+Expected failure 17 (no output)
+Expected failure 18 (no output)
+Expected failure 19 (no output)
+Expected failure 20 (no output)
+Expected failure 21 (no output)
+Expected failure 22 (no output)
+Expected failure 23 (no output)
+Expected failure 24 (no output)
+Expected failure 25 (no output)
+Expected failure 26 (no output)
+Expected failure 27 (no output)
diff --git a/test/pbmnoise-parameters.test b/test/pbmnoise-parameters.test
new file mode 100755
index 00000000..d0e04ebf
--- /dev/null
+++ b/test/pbmnoise-parameters.test
@@ -0,0 +1,43 @@
+#! /bin/sh
+# This script tests: pbmnoise
+# Also requires:
+
+echo "Test Invalid"
+
+. ${srcdir}/test-invalid.inc
+
+# Invalid -ratio arguments
+
+invCmd "pbmnoise -ratio       100 100"
+invCmd "pbmnoise -ratio 0     1  100"
+invCmd "pbmnoise -ratio=1.1   100 100"
+invCmd "pbmnoise -ratio=-1    100 100"
+invCmd "pbmnoise -ratio=half  100 100"
+invCmd "pbmnoise -ratio=0/1/1 100 100"
+invCmd "pbmnoise -ratio=-1/2  100 100"
+invCmd "pbmnoise -ratio=1/0   100 100"
+invCmd "pbmnoise -ratio=/2    100 100"
+invCmd "pbmnoise -ratio=4/2   100 100"
+invCmd "pbmnoise -ratio=6/    100 100"
+invCmd "pbmnoise -ratio=1.0/2.0 100 100"
+
+# denominator must be power of 2
+invCmd "pbmnoise -ratio=3/9  100 100"
+invCmd "pbmnoise -ratio=a/2  100 100"
+invCmd "pbmnoise -ratio=2/a  100 100"
+invCmd "pbmnoise -ratio=1/-2 100 100"
+
+# Denominator must be 65536 or less
+invCmd "pbmnoise -ratio=1/65537 100 100"
+invCmd "pbmnoise -ratio=1/131072 100 100"
+
+# Other
+invCmd "pbmnoise"
+invCmd "pbmnoise 100"
+invCmd "pbmnoise 100 0"
+invCmd "pbmnoise 0 100"
+invCmd "pbmnoise 100 200 300"
+invCmd "pbmnoise -endian=large 100 100"
+invCmd "pbmnoise -randomseed 100 100"
+invCmd "pbmnoise -randomseed=-1 100 100"
+invCmd "pbmnoise -randomseed=0.1 100 100"
diff --git a/test/pbmnoise1.ok b/test/pbmnoise1.ok
new file mode 100644
index 00000000..84f1f04e
--- /dev/null
+++ b/test/pbmnoise1.ok
@@ -0,0 +1,50 @@
+Test 1.  Should print 242292858 962 five times
+242292858 962
+242292858 962
+242292858 962
+242292858 962
+242292858 962
+Test 2.
+P1 32 1 00000000000000000000000000000000 
+P1 32 1 00010000000001000000000000000000 
+P1 32 1 00010000000001000010000000000000 
+P1 32 1 00010000000001000000000000000000 
+P1 32 1 00010000000001000010010000000000 
+P1 32 1 01010001000101000000000000000000 
+P1 32 1 00010000000001000010100000000000 
+P1 32 1 01010001000111000000000000100010 
+P1 32 1 10011001000001100010010000000000 
+P1 32 1 01010001000111000000010100100010 
+P1 32 1 01011001000101000010100000000000 
+P1 32 1 01010001000111000001010100100110 
+P1 32 1 00010000000001000111110000000100 
+P1 32 1 01010001010111001001010100100110 
+P1 32 1 01011011000111000010101000101010 
+P1 32 1 01010001011111011001010100110110 
+P1 32 1 10011001001001110010011000101110 
+P1 32 1 01010001011111011011010101110110 
+P1 32 1 01011011000111000010111110101010 
+P1 32 1 01010001011111011011110101110110 
+P1 32 1 11011001010101101111110000000100 
+P1 32 1 01011001011111011011110101110110 
+P1 32 1 01011011000111000111111110101110 
+P1 32 1 01011011011111011011111101111110 
+P1 32 1 10111111101011110111111000111111 
+P1 32 1 01011011011111011011111111111110 
+P1 32 1 11011011010111101111111110101110 
+P1 32 1 01011011011111011111111111111110 
+P1 32 1 11111111111111111111111000111111 
+P1 32 1 11011011011111111111111111111110 
+P1 32 1 11111111111111111111111110111111 
+P1 32 1 11111111111111111111111111111111 
+P1 32 1 11111111111111111111111111111111 
+Test 3.  Should print 126142586 1218 four times
+126142586 1218
+126142586 1218
+126142586 1218
+126142586 1218
+Test 4.
+P1 64 1 1000010001101101101000100101001110101011010010011111001011100110 
+P1 64 1 1000010001101101101000100101001110101011010010011111001011100110 
+P1 64 1 0101001110100010011011011000010011100110111100100100100110101011 
+P1 64 1 0101001110100010011011011000010011100110111100100100100110101011 
diff --git a/test/pbmnoise1.test b/test/pbmnoise1.test
new file mode 100755
index 00000000..855a5629
--- /dev/null
+++ b/test/pbmnoise1.test
@@ -0,0 +1,38 @@
+#! /bin/sh
+# This script tests: pbmnoise
+#
+
+# Assumes that the random number generator is Mersenne Twister
+
+echo "Test 1.  Should print 242292858 962 five times"
+
+for arg in "" "-ratio=1/2" "-ratio=256/512" "-ratio=32768/65536" "-pack" 
+    do
+    pbmnoise -endian=big -randomseed=1 1088 7 ${arg} | cksum
+done
+
+echo "Test 2."
+
+for i in 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 \
+	 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 
+         # for i in `seq 0 32`
+  do
+  pbmnoise -endian=little -randomseed=11 -ratio=$i/32 -plain 32 1 | \
+  tr '\n' ' ';  echo
+done
+
+echo "Test 3.  Should print 126142586 1218 four times"
+
+pbmnoise -endian=big -pack -randomseed=12 -plain 19 64 | sed 2d | tr -d '\n' | cksum
+pbmnoise -endian=big -pack -randomseed=12 -plain 152 8 | sed 2d | tr -d '\n' | cksum
+pbmnoise -endian=big -pack -randomseed=12 -plain 64 19 | sed 2d | tr -d '\n' | cksum
+pbmnoise -endian=big       -randomseed=12 -plain 64 19 | sed 2d | tr -d '\n' | cksum
+
+echo "Test 4."
+
+   pbmnoise -endian=big    -randomseed=23 64 1 -plain | tr '\n' ' '; echo
+(  pbmnoise -endian=native -randomseed=23 64 1 -plain | tr '\n' ' '; echo 
+   pbmnoise -endian=swap   -randomseed=23 64 1 -plain | tr '\n' ' '; echo
+)  | sort -nr
+   pbmnoise -endian=little -randomseed=23 64 1 -plain | tr '\n' ' '; echo
+
diff --git a/test/pbmnoise2.ok b/test/pbmnoise2.ok
new file mode 100644
index 00000000..5c3959e0
--- /dev/null
+++ b/test/pbmnoise2.ok
@@ -0,0 +1,19 @@
+Test 1.  Should print OK 1, then OK 2 three times
+OK 1
+OK 2
+OK 2
+OK 2
+Test 2.  Should print OK 1, then OK 2 three times
+OK 1
+OK 2
+OK 2
+OK 2
+Test 3-black.  Should print 255    384    100%    100% four times
+  255    384    100%    100%
+  255    384    100%    100%
+  255    384    100%    100%
+  255    384    100%    100%
+Test 3-white.  Should print 0    320    100%    100% three times
+    0    320    100%    100%
+    0    320    100%    100%
+    0    320    100%    100%
diff --git a/test/pbmnoise2.test b/test/pbmnoise2.test
new file mode 100755
index 00000000..8845e3b8
--- /dev/null
+++ b/test/pbmnoise2.test
@@ -0,0 +1,85 @@
+#! /bin/sh
+# This script tests: pbmnoise
+# Also requires: pgmhist
+
+# Expected value and variance of binominal distribution:
+# Pb: probability of getting a black pixel (=ratio)
+# Pw: probability of getting a white pixel (= 1 - Pb = 1 - ratio)
+#
+# E(width, height, Pb, Pw) = width * height * Pb
+# V(width, height, Pb, Pw) = width * height * Pb * Pw
+#
+# When width * height is large and Pb is not too near edges
+# approximate with normal distribution
+
+echo "Test 1.  Should print OK 1, then OK 2 three times"
+
+args1="-endian=big -randomseed=1"
+
+( pbmnoise            ${args1} 320 200 | pgmhist
+  pbmnoise -ratio=1/2 ${args1} 160 400 | pgmhist
+  pbmnoise -ratio=2/4 ${args1} 64000 1 | pgmhist
+  pbmnoise -pack      ${args1} 10 6400 | pgmhist ) | \
+  awk 'BEGIN { pixels=64000; Pb=Pw=0.5;
+               average=pixels*Pb;
+               sd=sqrt(pixels*Pb*Pw);  # standard deviation
+               sl=1.96                 # significance level 
+               limit1 = average - sd * sl;
+               limit2 = average + sd * sl
+               count=-1  # initial value
+              }
+       $1!=0  { next }
+              { v=1  }    # initial value
+       limit1 < $2 && $2 < limit2 { v=0 }
+       v==0   {print "OK", (count==prev)+1}
+       v==1   {print "NG" $0}
+              {prev=count}'
+
+
+
+echo "Test 2.  Should print OK 1, then OK 2 three times"
+
+args2="-endian=big -randomseed=2"
+
+( pbmnoise -ratio=11/32        ${args1} 32  119 | pgmhist
+  pbmnoise -ratio=11/32        ${args1} 224  17 | pgmhist
+  pbmnoise -ratio=22/64        ${args1} 3808  1 | pgmhist
+  pbmnoise -ratio=44/128 -pack ${args1} 1904 2 | pgmhist ) | \
+  awk 'BEGIN {pixels=32*119; Pb=11/32; Pw=1-Pb;
+               average=pixels*Pb;
+               sd=sqrt(pixels*Pb*Pw);  # standard deviation
+               sl=1.96                 # significance level 
+               limit1 = average - sd * sl;
+               limit2 = average + sd * sl
+               count=-1  # initial value
+              }
+       $1!=0  { next }
+              { v=1  }    # initial value
+       limit1 < $2 && $2 < limit2 { v=0 }
+       v==0   {print "OK", (count==prev)+1}
+       v==1   {print "NG" $0}
+              {prev=count}'
+
+
+
+
+echo "Test 3-black.  Should print 255    384    100%    100% four times"
+
+pbmnoise -ratio=0/1     -randomseed=1       128 3 | pgmhist | \
+  awk '$1==0 || $1==255'
+pbmnoise -ratio=0/1024  -randomseed=1       64  6 | pgmhist | \
+  awk '$1==0 || $1==255'
+pbmnoise -ratio=0/8192  -randomseed=1       32 12 | pgmhist | \
+  awk '$1==0 || $1==255'
+pbmnoise -ratio=0/65536 -randomseed=1 -pack 1 384 | pgmhist | \
+  awk '$1==0 || $1==255'
+
+echo "Test 3-white.  Should print 0    320    100%    100% three times"
+
+pbmnoise -ratio=1/1         -randomseed=1       64  5 | pgmhist | \
+  awk '$1==0 || $1==255'
+pbmnoise -ratio=8/8         -randomseed=1       32 10 | pgmhist | \
+  awk '$1==0 || $1==255'
+pbmnoise -ratio=65536/65536 -randomseed=1 -pack 2 160 | pgmhist | \
+  awk '$1==0 || $1==255'
+
diff --git a/test/pbmpage.ok b/test/pbmpage.ok
index 8013f2f2..21731b08 100644
--- a/test/pbmpage.ok
+++ b/test/pbmpage.ok
@@ -4,6 +4,6 @@ Test 1
 2347597649 4210813
 3453559794 4349933
 Test Invalid
-Expected failure 1 1
-Expected failure 2 1
-Expected failure 3 1
+Expected failure 1 (no output)
+Expected failure 2 (no output)
+Expected failure 3 (no output)
diff --git a/test/pbmpage.test b/test/pbmpage.test
index 50570e3e..9cb46e22 100755
--- a/test/pbmpage.test
+++ b/test/pbmpage.test
@@ -1,4 +1,4 @@
-#! /bin/bash
+#! /bin/sh
 # This script tests: pbmpage
 # Also requires:
 
@@ -11,19 +11,9 @@ pbmpage -a4 2 | cksum
 
 echo "Test Invalid"
 
-echo 1>&2
-echo "Invalid command-line argument combinations." 1>&2
-echo "Error messages should appear below the line." 1>&2
-echo "-----------------------------------------------------------" 1>&2
+. ${srcdir}/test-invalid.inc
 
-tmpdir=${tmpdir:-/tmp}
-test_out=${tmpdir}/test_out
+invCmd "pbmpage -a3 1"
+invCmd "pbmpage 0"
+invCmd "pbmpage 4"
 
-pbmpage -a3 1 > ${test_out} || \
-   echo -n "Expected failure 1"; test -s ${test_out}; echo " "$?
-pbmpage 0 > ${test_out} || \
-   echo -n "Expected failure 2"; test -s ${test_out}; echo " "$?
-pbmpage 4 > ${test_out} || \
-   echo -n "Expected failure 3"; test -s ${test_out}; echo " "$?
-
-rm ${test_out}
diff --git a/test/pbmpscale.ok b/test/pbmpscale.ok
index c26ffef3..25552343 100644
--- a/test/pbmpscale.ok
+++ b/test/pbmpscale.ok
@@ -1,53 +1,178 @@
+Test 1.  Should print "abc" rendered in PBM plain format
 P1
-21 45
-000000000000000000000
-000000000000000000000
-000000000000000000000
-000000000000000000000
-000000000000000000000
-000000000000000000000
-000000000000000000000
-000000000000000000000
-000000000000000000000
-111111111111111111110
-111111111111111111111
-111111111111111111111
-001111100000000001111
-000111000000000000111
-000111000000000000111
-000111000000000000000
-000111000000000000000
-000111000000000000000
-000111000000000111000
-000111000000000111000
-000111100000001111000
-000111111111111111000
-000111111111111111000
-000111111111111111000
-000111100000001111000
-000111000000000111000
-000111000000000111000
-000111000000000000000
-000111000000000000000
-000111000000000000000
-000111000000000000000
-000111000000000000000
-001111100000000000000
-111111111111000000000
-111111111111000000000
-111111111111000000000
-000000000000000000000
-000000000000000000000
-000000000000000000000
-000000000000000000000
-000000000000000000000
-000000000000000000000
-000000000000000000000
-000000000000000000000
-000000000000000000000
-2150868536 457
-3761734242 1065
-3462719777 1803
-Expected failure 1 1
-Expected failure 2 1
-Expected failure 3 1
+17 15
+00000000000000000
+00000000000000000
+00000000000000000
+00000011000000000
+00000001000000000
+00000001000000000
+00110001110000110
+01001001001001001
+00111001001001000
+01001001001001000
+01001001001001001
+00110101110000110
+00000000000000000
+00000000000000000
+00000000000000000
+Test 2.  "ABC" in PBM plain format
+P1
+48 30
+000000000000000000000000000000000000000000000000
+000000000000000000000000000000000000000000000000
+000000000000000000000000000000000000000000000000
+000000000000000000000000000000000000000000000000
+000000000000000000000000000000000000000000000000
+000000000000000000000000000000000000000000000000
+000000001100000000111111111110000000000111100011
+000000001100000000111111111111100000011111110011
+000000001100000000011110000111100000011110011111
+000000011110000000001100000011110000111100001111
+000000010010000000001100000000110000111000000111
+000000110011000000001100000000110001110000000011
+000000110011000000001100000011110001100000000000
+000001100001100000001110000111100011000000000000
+000001000000100000001111111111000011000000000000
+000011000000110000001111111111000011000000000000
+000011111111110000001110000001100011000000000000
+000011111111110000001100000000110001100000000000
+000011100001110000001100000000110001110000000011
+000111000000111000001100000001110000111000000111
+001100000000001100001100000011110000111100001111
+011100000000001110011110000111100000011110011110
+111111000000111111111111111111100000011111111110
+111111000000111111111111111110000000000111111000
+000000000000000000000000000000000000000000000000
+000000000000000000000000000000000000000000000000
+000000000000000000000000000000000000000000000000
+000000000000000000000000000000000000000000000000
+000000000000000000000000000000000000000000000000
+000000000000000000000000000000000000000000000000
+Test 3.  "D.!" in PBM plain format
+P1
+42 45
+000000000000000000000000000000000000000000
+000000000000000000000000000000000000000000
+000000000000000000000000000000000000000000
+000000000000000000000000000000000000000000
+000000000000000000000000000000000000000000
+000000000000000000000000000000000000000000
+000000000000000000000000000000000000000000
+000000000000000000000000000000000000000000
+000000000000000000000000000000000000000000
+111111111111111110000000000000000000000111
+111111111111111111000000000000000000000111
+111111111111111111100000000000000000000111
+001111100000001111110000000000000000000111
+000111000000000111111000000000000000000111
+000111000000000111111000000000000000000111
+000111000000000001111000000000000000000111
+000111000000000000111000000000000000000111
+000111000000000000111100000000000000000111
+000111000000000000001110000000000000000111
+000111000000000000000111000000000000000111
+000111000000000000000111000000000000000111
+000111000000000000000111000000000000000111
+000111000000000000000111000000000000000111
+000111000000000000000111000000000000000111
+000111000000000000000111000000000000000111
+000111000000000000000111000000000000000111
+000111000000000000001110000000000000000111
+000111000000000000111100000000000000000111
+000111000000000000111000000000000000000111
+000111000000000001111000000000000000000111
+000111000000000111111000000000000000000000
+000111000000000111111000000000000000000000
+001111100000001111110000000000000000000000
+111111111111111111100000000000111000000111
+111111111111111111000000000000111000000111
+111111111111111110000000000000111000000111
+000000000000000000000000000000000000000000
+000000000000000000000000000000000000000000
+000000000000000000000000000000000000000000
+000000000000000000000000000000000000000000
+000000000000000000000000000000000000000000
+000000000000000000000000000000000000000000
+000000000000000000000000000000000000000000
+000000000000000000000000000000000000000000
+000000000000000000000000000000000000000000
+Test 3.  "E,?" in PBM plain format
+P1
+60 60
+000000000000000000000000000000000000000000000000000000000000
+000000000000000000000000000000000000000000000000000000000000
+000000000000000000000000000000000000000000000000000000000000
+000000000000000000000000000000000000000000000000000000000000
+000000000000000000000000000000000000000000000000000000000000
+000000000000000000000000000000000000000000000000000000000000
+000000000000000000000000000000000000000000000000000000000000
+000000000000000000000000000000000000000000000000000000000000
+000000000000000000000000000000000000000000000000000000000000
+000000000000000000000000000000000000000000000000000000000000
+000000000000000000000000000000000000000000000000000000000000
+000000000000000000000000000000000000000000000000000000000000
+011111111111111111111111110000000000000000000000011111100000
+111111111111111111111111111000000000000000000000111111110000
+111111111111111111111111111100000000000000000001111111111000
+011111111111111111111111111100000000000000000011111111111100
+001111111100000000000011111100000000000000000111110000111110
+000111111000000000000001111100000000000000001111100000011111
+000011110000000000000000111100000000000000001111000000001111
+000011110000000000000000011000000000000000000110000000001111
+000011110000000000000000000000000000000000000000000000001111
+000011110000000000000000000000000000000000000000000000001111
+000011110000000000000000000000000000000000000000000000011111
+000011110000000000000000000000000000000000000000000000111110
+000011110000000000000110000000000000000000000000000001111100
+000011110000000000001111000000000000000000000000000011111000
+000011111000000000011111000000000000000000000000000111110000
+000011111100000000111111000000000000000000000000001111100000
+000011111111111111111111000000000000000000000000011111000000
+000011111111111111111111000000000000000000000000111110000000
+000011111111111111111111000000000000000000000000111100000000
+000011111111111111111111000000000000000000000000111100000000
+000011111100000000111111000000000000000000000000111100000000
+000011111000000000011111000000000000000000000000111100000000
+000011110000000000001111000000000000000000000000111100000000
+000011110000000000000110000000000000000000000000111100000000
+000011110000000000000000000000000000000000000000111100000000
+000011110000000000000000000000000000000000000000111100000000
+000011110000000000000000000000000000000000000000111100000000
+000011110000000000000000000000000000000000000000011000000000
+000011110000000000000000011000000000000000000000000000000000
+000011110000000000000000111100000000000000000000000000000000
+000111111000000000000001111100000000000000000000000000000000
+001111111100000000000011111100000000000000000000000000000000
+011111111111111111111111111100000000011000000000011000000000
+111111111111111111111111111100000000111100000000111100000000
+111111111111111111111111111000000000111100000000111100000000
+011111111111111111111111110000000000111100000000011000000000
+000000000000000000000000000000000000111100000000000000000000
+000000000000000000000000000000000000111100000000000000000000
+000000000000000000000000000000000001111100000000000000000000
+000000000000000000000000000000000011111000000000000000000000
+000000000000000000000000000000000111110000000000000000000000
+000000000000000000000000000000001111100000000000000000000000
+000000000000000000000000000000001111000000000000000000000000
+000000000000000000000000000000000110000000000000000000000000
+000000000000000000000000000000000000000000000000000000000000
+000000000000000000000000000000000000000000000000000000000000
+000000000000000000000000000000000000000000000000000000000000
+000000000000000000000000000000000000000000000000000000000000
+Test 5.  Should print 576003211 10631
+576003211 10631
+Test 6.  Should print 3501321825 369
+3501321825 369
+Test 7.  Should print 1588181271 535
+1588181271 535
+Test 8.  Should print 2843090781 610
+2843090781 610
+Test 9.  Should print 146160766 820
+146160766 820
+Test 10. Should print 3327221668 2111
+3327221668 2111
+Test Invalid
+Expected failure 1 (no output)
+Expected failure 2 (no output)
+Expected failure 3 (no output)
diff --git a/test/pbmpscale.test b/test/pbmpscale.test
index 9c34734a..b99561f6 100755
--- a/test/pbmpscale.test
+++ b/test/pbmpscale.test
@@ -1,30 +1,34 @@
-#! /bin/bash
+#! /bin/sh
 # This script tests: pbmpscale
-# Also requires: pamenlarge pbmtext
-
-
-pbmtext -nomargin "F" | pbmpscale 3 -plain
-
-for i in 2 3 4
-do
-pamenlarge 2 testgrid.pbm | \
-  pbmpscale $i | cksum
-done
-
-test_out=${tmpdir}/test_out
-
-echo 1>&2
-echo "Invalid command-line argument combinations." 1>&2
-echo "Error messages should appear below the line." 1>&2
-echo "-----------------------------------------------------------" 1>&2
-
-pbmpscale testgrid.pbm > ${test_out} || \
-   echo -n "Expected failure 1"; test -s ${test_out}; echo " "$?
-
-pbmpscale 0 testgrid.pbm > ${test_out} || \
-   echo -n "Expected failure 2"; test -s ${test_out}; echo " "$?
-
-pbmpscale 2 3 testgrid.pbm > ${test_out} || \
-   echo -n "Expected failure 3"; test -s ${test_out}; echo " "$?
-
-rm -f ${test_out}
\ No newline at end of file
+# Also requires: pbmtext
+
+echo "Test 1.  Should print \"abc\" rendered in PBM plain format"
+pbmtext -nomargin "abc" | pbmpscale 1 -plain
+echo "Test 2.  \"ABC\" in PBM plain format"
+pbmtext -nomargin "ABC" | pbmpscale 2 -plain
+echo "Test 3.  \"D.!\" in PBM plain format"
+pbmtext -nomargin "D.!" | pbmpscale 3 -plain
+echo "Test 3.  \"E,?\" in PBM plain format"
+pbmtext -nomargin "E,?" | pbmpscale 4 -plain
+
+echo "Test 5.  Should print 576003211 10631"
+pbmpscale 5 maze.pbm | cksum
+
+echo "Test 6.  Should print 3501321825 369"
+pbmtext -nomargin "6" | pbmpscale 6 | cksum
+echo "Test 7.  Should print 1588181271 535"
+pbmtext -nomargin "7" | pbmpscale 7 | cksum
+echo "Test 8.  Should print 2843090781 610"
+pbmtext -nomargin "8" | pbmpscale 8 | cksum
+echo "Test 9.  Should print 146160766 820"
+pbmtext -nomargin "9" | pbmpscale 9 | cksum
+echo "Test 10. Should print 3327221668 2111"
+pbmtext -nomargin "10" | pbmpscale 10 | cksum
+
+echo "Test Invalid"
+
+. ${srcdir}/test-invalid.inc
+
+invCmd "pbmpscale testgrid.pbm"
+invCmd "pbmpscale 0 testgrid.pbm"
+invCmd "pbmpscale 2 3 testgrid.pbm"
diff --git a/test/pbmtext-bdf.test b/test/pbmtext-bdf.test
index b12c10bf..f1d2019e 100755
--- a/test/pbmtext-bdf.test
+++ b/test/pbmtext-bdf.test
@@ -1,4 +1,4 @@
-#! /bin/bash
+#! /bin/sh
 # This script tests: pbmtext
 # Also requires:
 
@@ -173,3 +173,5 @@ do
   echo $?
   rm ${font_corrupt_bdf}
 done
+
+rm ${font_bdf}
\ No newline at end of file
diff --git a/test/pbmtext-iso88591.test b/test/pbmtext-iso88591.test
index 69e6ec90..1472b89e 100755
--- a/test/pbmtext-iso88591.test
+++ b/test/pbmtext-iso88591.test
@@ -1,9 +1,9 @@
-#! /bin/bash
+#! /bin/sh
 # This script tests: pbmtext
 # Also requires:
 
 # This test requires an iso-8859-1 locale
-# Skip this test if it is not available
+# Skip this test if none are available
 
 LANG=C
 LC_ALL=C
@@ -12,26 +12,30 @@ export LANG LC_ALL
 tmpdir=${tmpdir:-/tmp}
 iso88591_locale_list=${tmpdir}/iso88591_locale_list
 
+locale_to_test="en_US.iso88591"  # Initial value; this
+# does not have to be actually available.
+# Edit the above value if you have a preferred locale.
 
-locale_to_test="en_US.iso88591"  # Initial value
-# Edit the above value if necessary
-  
-# Make a list of available locales which end in "iso88591"
-locale -a | grep "\.iso88591$" > ${iso88591_locale_list}
+# Make a list of available locales which end in "iso88591" etc.
+# If none are found, abort test
 
-# Hunt for a valid iso-8859-1 locale  
+locale -a |\
+    grep -e "\.iso88591$" -e "\.iso-8859-1$" -e "\.ISO-8859-1$" \
+	 > ${iso88591_locale_list} || locale_to_test=""
+
+# Hunt for a valid iso-8859-1 locale
 # Submit each candidate to a trial pbmtext run until one that works is
 # encountered
 
-i=0
 until [ -z ${locale_to_test} ] || \
   echo "A" | LC_ALL=${locale_to_test} pbmtext -wchar > /dev/null
   do
-    let i=$(($i+1));
-    locale_to_test=`sed "$i"p -n  ${iso88591_locale_list}`;
+      # Read first line of file
+      locale_to_test=`head -n 1 ${iso88591_locale_list}`;
+      # then erase the line
+      sed -i 1d ${iso88591_locale_list};
   done;
 
-rm ${iso88591_locale_list};
 if [ -z  ${locale_to_test} ]
   then echo "No iso-8859-1 locale available." 1>&2
        echo "Skipping." 1>&2
@@ -42,7 +46,6 @@ fi;
 
 locale_for_test=${locale_to_test};
 
-
 # Two rows
 # Should print 2066913605 5110 twice
 echo "Test 1"
diff --git a/test/pbmtext-utf8.ok b/test/pbmtext-utf8.ok
index 84743a09..0d40adde 100644
--- a/test/pbmtext-utf8.ok
+++ b/test/pbmtext-utf8.ok
@@ -13,12 +13,12 @@ Test 5 Invalid
 9998
 989454365 52512
 9999
-Expected failure 1 1
-Expected failure 2 1
+Expected failure 1 (no output)
+Expected failure 2 (no output)
 Test 6 Invalid
-6-1: 0 1 : 1 1
-6-2: 0 1 : 1 1
-6-3: 0 1 : 1 1
-6-4: 0 1 : 1 1
-6-5: 0 1 : 1 1
-6-6: 0 1 : 1 1
+6-1: 0 1 : 1 (no output)
+6-2: 0 1 : 1 (no output)
+6-3: 0 1 : 1 (no output)
+6-4: 0 1 : 1 (no output)
+6-5: 0 1 : 1 (no output)
+6-6: 0 1 : 1 (no output)
diff --git a/test/pbmtext-utf8.test b/test/pbmtext-utf8.test
index 8ebb6e31..551cfe29 100755
--- a/test/pbmtext-utf8.test
+++ b/test/pbmtext-utf8.test
@@ -6,9 +6,8 @@ LANG=C
 LC_ALL=C
 export LANG LC_ALL
 
-
-# This test requires a working UTF-8 locale 
-# Skip this test if it is are not available
+# This test requires a working UTF-8 locale
+# Skip this test if none are available
 
 iconv /dev/null
 if [ $? -ne 0  ]
@@ -20,25 +19,29 @@ fi
 tmpdir=${tmpdir:-/tmp}
 utf_locale_list=${tmpdir}/utf_locale_list
 
-locale_to_test="en_US.utf8"  # Initial value
-# Edit the above value if necessary
-  
-# Make a list of available locales which end in "utf8"
-locale -a | grep "\.utf8$" > ${utf_locale_list}
+locale_to_test="en_US.utf8"  # Initial value; this
+# does not have to be actually available.
+# Edit the above value if you have a preferred locale.
+
+# Make a list of available locales which end in "utf8" etc.
+# If none are found, abort test
 
-# Hunt for a valid utf8 locale  
+locale -a | grep -e "\.utf8$" -e "\.utf-8$" -e "\.UTF-8$" \
+    > ${utf_locale_list} || locale_to_test=""
+
+# Hunt for a valid utf8 locale
 # Submit each candidate to a trial pbmtext run until one that works is
 # encountered
 
-i=0
 until [ -z ${locale_to_test} ] || \
   echo "A" | LC_ALL=${locale_to_test} pbmtext -wchar > /dev/null
     do
-      let i=$(($i+1));
-      locale_to_test=`sed "$i"p -n  ${utf_locale_list}`;
+      # Read first line of file
+      locale_to_test=`head -n 1 ${utf_locale_list}`;
+      # then erase the line
+      sed -i 1d ${utf_locale_list};
     done;
 
-rm ${utf_locale_list};
 if [ -z  ${locale_to_test} ]
   then echo "No utf-8 locale available." 1>&2
        echo "Skipping." 1>&2
@@ -115,10 +118,10 @@ awk 'BEGIN { for (i=32; i<=126;++i) printf("%c",i); print "" } '
 awk 'BEGIN { for (i=32; i<=126;++i) printf("%c",i); print ""}' | \
         LC_ALL=${locale_for_test} pbmtext -builtin bdf -wchar -text-dump
 
+
 # Test 5.
 # Long input text
 
-
 echo "Test 5 Invalid"
 
 long_txt=${tmpdir}/long.txt
@@ -135,19 +138,22 @@ echo "Test input text which exceeds length limit" 1>&2
 echo "Error messages should appear below the line." 1>&2
 echo "-----------------------------------------------------------" 1>&2
 
-echo -n "z" >> ${long_txt}
+printf "z" >> ${long_txt}
 cat ${long_txt} | wc -c | tr -d ' '
 
 cat ${long_txt} | \
   LC_ALL=${locale_for_test} \
   pbmtext -nomargins -builtin fixed -wchar > ${test_out} || \
-  echo -n "Expected failure 1";
-  test -s ${test_out}; echo " "$? 
+  printf "Expected failure 1 "
+  test -s ${test_out} && echo "unexpected output" || echo "(no output)"
+  rm -f ${test_out}
+
 cat ${long_txt} | \
   LC_ALL=${locale_for_test} \
   pbmtext -nomargins -builtin fixed -wchar > ${test_out} || \
-  echo -n "Expected failure 2";
-  test -s ${test_out}; echo " "$?  
+  printf "Expected failure 2 "
+  test -s ${test_out} && echo "unexpected output" || echo "(no output)"
+  rm -f ${test_out}
 
 rm ${long_txt}
 
@@ -165,39 +171,42 @@ echo "Test 6 Invalid"
 
 awk 'BEGIN { printf("%c%c",128,129);  print ""}' | \
         LC_ALL=${locale_for_test} \
-        pbmtext -builtin bdf -wchar -text-dump > ${test_out} 
-  echo -n "6-1:" ${PIPESTATUS[@]} ":" $?
-  test -s ${test_out}; echo " "$?  
-  
+        pbmtext -builtin bdf -wchar -text-dump > ${test_out}
+  printf "6-1: ${PIPESTATUS[*]} : $? "
+  test -s ${test_out} && echo "unexpected output" || echo "(no output)"
+  rm -f ${test_out}
+
 awk 'BEGIN { printf("ABC%c%c",192, 193);  print ""}' | \
         LC_ALL=${locale_for_test} \
-        pbmtext -builtin bdf -wchar -text-dump > ${test_out} 
-  echo -n "6-2:" ${PIPESTATUS[@]} ":" $?
-  test -s ${test_out}; echo " "$?  
+        pbmtext -builtin bdf -wchar -text-dump > ${test_out}
+  printf "6-2: ${PIPESTATUS[*]} : $? "
+  test -s ${test_out} && echo "unexpected output" || echo "(no output)"
+  rm -f ${test_out}
 
 awk 'BEGIN { printf("abcde%c%c", 254, 253);  print ""}' | \
         LC_ALL=${locale_for_test} \
-        pbmtext -builtin bdf -wchar -text-dump > ${test_out} 
-  echo -n "6-3:" ${PIPESTATUS[@]} ":" $?
-  test -s ${test_out}; echo " "$?  
-  
+        pbmtext -builtin bdf -wchar -text-dump > ${test_out}
+  printf "6-3: ${PIPESTATUS[*]} : $? "
+  test -s ${test_out} && echo "unexpected output" || echo "(no output)"
+  rm -f ${test_out}
+
 awk 'BEGIN { printf("abcdefg%c%c", 195, 15);  print ""}' | \
         LC_ALL=${locale_for_test} \
-        pbmtext -builtin bdf -wchar -text-dump > ${test_out} 
-  echo -n "6-4:" ${PIPESTATUS[@]} ":" $?
-  test -s ${test_out}; echo " "$?  
+        pbmtext -builtin bdf -wchar -text-dump > ${test_out}
+  printf "6-4: ${PIPESTATUS[*]} : $? "
+  test -s ${test_out} && echo "unexpected output" || echo "(no output)"
+  rm -f ${test_out}
 
 awk 'BEGIN { printf("123456789%c%c%c", 224, 143 ,0);  print ""}' | \
         LC_ALL=${locale_for_test} \
-        pbmtext -builtin bdf -wchar -text-dump > ${test_out} 
-  echo -n "6-5:" ${PIPESTATUS[@]} ":" $?
-  test -s ${test_out}; echo " "$?  
+        pbmtext -builtin bdf -wchar -text-dump > ${test_out}
+  printf "6-5: ${PIPESTATUS[*]} : $? "
+  test -s ${test_out} && echo "unexpected output" || echo "(no output)"
+  rm -f ${test_out}
 
 awk 'BEGIN { printf("abcdefg123ABCDEFG%c%c%c%c",247, 135, 135, 7);  print ""}' | \
         LC_ALL=${locale_for_test} \
-        pbmtext -builtin bdf -wchar -text-dump > ${test_out} 
-  echo -n "6-6:" ${PIPESTATUS[@]} ":" $?
-  test -s ${test_out}; echo " "$? 
-  
-rm ${test_out}
-  
+        pbmtext -builtin bdf -wchar -text-dump > ${test_out}
+  printf "6-6: ${PIPESTATUS[*]} : $? "
+  test -s ${test_out} && echo "unexpected output" || echo "(no output)"
+  rm -f ${test_out}
diff --git a/test/pbmtext.ok b/test/pbmtext.ok
index 68ed40d8..975911f2 100644
--- a/test/pbmtext.ok
+++ b/test/pbmtext.ok
@@ -20,20 +20,20 @@ Test 5
 2547645687 4564
 1174281741 5741
 Test 6 Invalid
-Expected failure 1 1
-Expected failure 2 1
-Expected failure 3 1
-Expected failure 4 1
-Expected failure 5 1
-Expected failure 6 1
-Expected failure 7 1
-Expected failure 8 1
+Expected failure 1 (no output)
+Expected failure 2 (no output)
+Expected failure 3 (no output)
+Expected failure 4 (no output)
+Expected failure 5 (no output)
+Expected failure 6 (no output)
+Expected failure 7 (no output)
+Expected failure 8 (no output)
 Test 7
 text length: 4999
 1854691667 52512
 1854691667 52512
 Test 8 Invalid
 text length: 5000
-Expected failure 1 1
-Expected failure 2 1
-Expected failure 3 1
+Expected failure 1 (no output)
+Expected failure 2 (no output)
+Expected failure 3 (no output)
diff --git a/test/pbmtext.test b/test/pbmtext.test
index 515711e4..d4ab027e 100755
--- a/test/pbmtext.test
+++ b/test/pbmtext.test
@@ -1,4 +1,4 @@
-#! /bin/bash
+#! /bin/sh
 # This script tests: pbmtext
 # Also requires: pamfile
 
@@ -10,13 +10,13 @@ echo "Test 1"
 # Should print 3898818212 967 twice
 
 pbmtext UNIX Philosophy: Do one thing and do it well. | cksum
-echo -n "UNIX Philosophy: Do one thing and do it well." | pbmtext | cksum
+printf "UNIX Philosophy: Do one thing and do it well." | pbmtext | cksum
 
 # Should print 2506052117 1354 twice
 
 pbmtext -builtin fixed \
     For truth is always strange. Stranger than fiction. Lord Byron | cksum
-echo -n "For truth is always strange. Stranger than fiction. Lord Byron" | \
+printf "For truth is always strange. Stranger than fiction. Lord Byron" | \
     pbmtext -builtin fixed | cksum
 
 
@@ -41,7 +41,7 @@ for flags in "" "-builtin fixed"
 do
 pbmtext ${flags} ${text} | tee ${temp_pbm} | cksum
 width1=`pamfile ${temp_pbm} | awk '$2=="PBM" && NR==1 {w=$4}; END {print w}' `
-width2=`pbmtext ${flags} ${text} --dry-run | awk '{print $1}' `
+width2=`pbmtext ${flags} ${text} --dry-run | cut -d " " -f 1`
 
 if [ ${width1} -eq ${width2} ]; then
     pbmtext ${flags} -width=${width1} ${text} | cksum
@@ -112,29 +112,44 @@ echo "Test 6 Invalid"
 test_out=${tmpdir}/test_out
 
 pbmtext -font=testgrid.pbm foo > ${test_out} || \
-  echo -n "Expected failure 1";
-  test -s ${test_out}; echo " "$?
+  printf "Expected failure 1 "
+  test -s ${test_out} && echo "unexpected output" || echo "(no output)"
+  rm -f ${test_out}
+
 pbmtext -font=testimg.ppm  foo > ${test_out} || \
-  echo -n "Expected failure 2";
-  test -s ${test_out}; echo " "$?
+  printf "Expected failure 2 "
+  test -s ${test_out} && echo "unexpected output" || echo "(no output)"
+  rm -f ${test_out}
+
 pbmtext -builtin=void      foo > ${test_out} || \
-  echo -n "Expected failure 3";  
-  test -s ${test_out}; echo " "$?
+  printf "Expected failure 3 "
+  test -s ${test_out} && echo "unexpected output" || echo "(no output)"
+  rm -f ${test_out}
+
 pbmtext -font=${font_pbm} -builtin=fixed foo > ${test_out}  || \
-  echo -n "Expected failure 4";
-  test -s ${test_out}; echo " "$?  
+  printf "Expected failure 4 "
+  test -s ${test_out} && echo "unexpected output" || echo "(no output)"
+  rm -f ${test_out}
+
 pbmtext -dry-run    -text-dump  foo > ${test_out} || \
-  echo -n "Expected failure 5";
-  test -s ${test_out}; echo " "$?
+  printf "Expected failure 5 "
+  test -s ${test_out} && echo "unexpected output" || echo "(no output)"
+  rm -f ${test_out}
+
 pbmtext -dump-sheet -text-dump  foo > ${test_out} || \
-  echo -n "Expected failure 6";
-  test -s ${test_out}; echo " "$?
+  printf "Expected failure 6 "
+  test -s ${test_out} && echo "unexpected output" || echo "(no output)"
+  rm -f ${test_out}
+
 pbmtext -dry-run    -dump-sheet foo > ${test_out} || \
-  echo -n "Expected failure 7";
-  test -s ${test_out}; echo " "$?
+  printf "Expected failure 7 "
+  test -s ${test_out} && echo "unexpected output" || echo "(no output)"
+  rm -f ${test_out}
+
 pbmtext -wchar foo > ${test_out} || \
-  echo -n "Expected failure 8";
-  test -s ${test_out}; echo " "$?
+  printf "Expected failure 8 "
+  test -s ${test_out} && echo "unexpected output" || echo "(no output)"
+  rm -f ${test_out}
 
 rm ${font_pbm}
 
@@ -153,7 +168,7 @@ cat ${long_txt} | pbmtext -nomargins -builtin fixed  | cksum
 
 echo "Test 8 Invalid"
 
-echo -n "z" >> ${long_txt}
+printf "z" >> ${long_txt}
 awk '{print "text length:", length($0)}' ${long_txt}
 
 echo 1>&2
@@ -162,14 +177,19 @@ echo "Error messages should appear below the line." 1>&2
 echo "-----------------------------------------------------------" 1>&2
 
 pbmtext -nomargins -builtin fixed `cat ${long_txt}` > ${test_out}  || \
-  echo -n "Expected failure 1";
-  test -s ${test_out}; echo " "$?
+  printf "Expected failure 1 "
+  test -s ${test_out} && echo "unexpected output" || echo "(no output)"
+  rm -f ${test_out}
+
 cat ${long_txt} | pbmtext -nomargins -builtin fixed > ${test_out}  || \
-  echo -n "Expected failure 2";
-  test -s ${test_out}; echo " "$?
+  printf "Expected failure 2 "
+  test -s ${test_out} && echo "unexpected output" || echo "(no output)"
+  rm -f ${test_out}
+
 cat ${long_txt} | \
   LC_ALL=C pbmtext -nomargins -builtin fixed -wchar > ${test_out}  || \
-  echo -n "Expected failure 3";
-  test -s ${test_out}; echo " "$?
+  printf "Expected failure 3 "
+  test -s ${test_out} && echo "unexpected output" || echo "(no output)"
+  rm -f ${test_out}
 
-rm ${long_txt} ${test_out}
+rm ${long_txt}
diff --git a/test/pbmtextps-dump.ok b/test/pbmtextps-dump.ok
new file mode 100644
index 00000000..71b2d2a2
--- /dev/null
+++ b/test/pbmtextps-dump.ok
@@ -0,0 +1,88 @@
+Test 1
+-font=ZQUEl8eS38RlsvEahHGNfnrbSswrcJKFwvlCdEttwcheuXvCN49MvWmndqj4
+< /FindFont {/Times-Roman findfont} def
+> /FindFont {/ZQUEl8eS38RlsvEahHGNfnrbSswrcJKFwvlCdEttwcheuXvCN49MvWmndqj4 findfont} def
+-fontsize 2000
+< /fontsize 24.000000 def
+> /fontsize 2000.000000 def
+< /descent 36.000000 def
+< /leftmargin 12.000000 def
+> /descent 3000.000000 def
+> /leftmargin 1000.000000 def
+-resolution 7200
+-leftmargin=15
+< /leftmargin 12.000000 def
+> /leftmargin 15.000000 def
+-rightmargin=20
+< /rightmargin 0.000000 def
+> /rightmargin 20.000000 def
+-topmargin=10
+< /topmargin 0.000000 def
+> /topmargin 10.000000 def
+-bottommargin=14
+< /descent 36.000000 def
+> /descent 0.000000 def
+< /bottommargin 0.000000 def
+> /bottommargin 14.000000 def
+-ascent=30
+< /ascent 0.000000 def
+> /ascent 30.000000 def
+-descent=20
+< /descent 36.000000 def
+> /descent 20.000000 def
+-pad
+< /descent 36.000000 def
+> /descent 0.000000 def
+< /pad false def
+> /pad true def
+-crop
+< /descent 36.000000 def
+< /leftmargin 12.000000 def
+> /descent 0.000000 def
+> /leftmargin 0.000000 def
+-stroke 1
+< /pensize -1.000000 def
+> /pensize 1.000000 def
+Test 2
+30 31 32 20 41 42 43 2d 78 79 7a 2e
+1
+303132204142432d78797a2e
+1
+<303132 20 414243 2d 78797a 2e>
+1
+Test Invalid
+Expected failure 1 (-fontsize) (no output)
+Expected failure 2 (-fontsize 0) (no output)
+Expected failure 3 (-resolution) (no output)
+Expected failure 4 (-resolution=0) (no output)
+Expected failure 5 (-leftmargin) (no output)
+Expected failure 6 (-leftmargin -1) (no output)
+Expected failure 7 (-rightmargin) (no output)
+Expected failure 8 (-rightmargin -1) (no output)
+Expected failure 9 (-topmargin) (no output)
+Expected failure 10 (-topmargin -1) (no output)
+Expected failure 11 (-bottommargin) (no output)
+Expected failure 12 (-bottommargin -1) (no output)
+Expected failure 13 (-ascent) (no output)
+Expected failure 14 (-ascent -1) (no output)
+Expected failure 15 (-descent) (no output)
+Expected failure 16 (-descent -1) (no output)
+Expected failure 17 (-stroke=A) (no output)
+Expected failure 18 (-pad -crop) (no output)
+Expected failure 19 (-asciihex <a>) (no output)
+Expected failure 20 (-asciihex ) (no output)
+Expected failure 21 (-asciihex <53756c667572) (no output)
+Expected failure 22 (-asciihex 53756c667572>) (no output)
+Expected failure 23 (-asciihex <5375<6c667572>) (no output)
+Expected failure 24 (-asciihex <53756c>667572>) (no output)
+Expected failure 25 (-ascii85 <~@<6O!FD5W(~) (no output)
+Expected failure 26 (-ascii85 ~@<6O!FD5W(~>) (no output)
+Expected failure 27 (-ascii85 <~@<6O<~!FD5W(~>) (no output)
+Expected failure 28 (-ascii85 <~@<6O~>!FD5W(~>) (no output)
+Expected failure 29 (-ascii85 <~@<6O!FD5W(~~>) (no output)
+Expected failure 30 (-ascii85 v) (no output)
+Expected failure 31 (-ascii85 y) (no output)
+Expected failure 32 (-ascii85 1z) (no output)
+Expected failure 33 (-ascii85 z1z) (no output)
+Expected failure 34 (-ascii85 <~0123z~>) (no output)
+Expected failure 35 (-font="") (no output)
diff --git a/test/pbmtextps-dump.test b/test/pbmtextps-dump.test
new file mode 100755
index 00000000..fd68667d
--- /dev/null
+++ b/test/pbmtextps-dump.test
@@ -0,0 +1,136 @@
+#! /bin/sh
+# This script tests: pbmtextps
+# Also requires:
+
+# Dump several variants of the ps file and compare against default.
+# Ghostscript is not required.
+
+tmpdir=${tmpdir:-/tmp}
+text1_ps=${tmpdir}/text1.ps
+text2_ps=${tmpdir}/text2.ps
+
+text="UNIX Philosophy: Do one thing and do it well."
+
+# Test 1:
+echo "Test 1"
+
+pbmtextps -dump-ps ${text} > ${text1_ps}
+
+# Font name is random sequence of alphanumerical characters.
+# Should not match any real name.
+
+for flag in \
+  "-font=ZQUEl8eS38RlsvEahHGNfnrbSswrcJKFwvlCdEttwcheuXvCN49MvWmndqj4" \
+  "-fontsize 2000" \
+  "-resolution 7200" \
+  "-leftmargin=15" \
+  "-rightmargin=20" \
+  "-topmargin=10" \
+  "-bottommargin=14" \
+  "-ascent=30" \
+  "-descent=20" \
+  "-pad" \
+  "-crop" \
+  "-stroke 1"
+  do
+  echo ${flag}
+  pbmtextps -dump-ps ${flag} ${text} | diff ${text1_ps} - | grep "^[<>]"
+  done
+
+rm ${text1_ps}
+
+
+# Test 2:
+echo "Test 2"
+
+pbmtextps -dump-ps "012 ABC-xyz." > ${text2_ps}
+
+for hextext in \
+  "30 31 32  20	 41 42 43  2d	78 79 7a  2e" \
+  "303132204142432d78797a2e" \
+  "<303132 20 414243 2d 78797a 2e>" 
+  do
+  echo ${hextext}
+  pbmtextps -dump-ps -asciihex ${hextext} | diff ${text2_ps} - | grep "^[<>]"
+  echo $?
+  done
+
+rm ${text2_ps}
+
+
+echo "Test Invalid"
+
+echo 1>&2
+echo "Invalid command line arguments" 1>&2
+echo "Error messages should appear below the line." 1>&2
+echo "-----------------------------------------------------------" 1>&2
+
+test_out=${tmpdir}/test.out
+
+n=1
+
+for error_flag in \
+  "-fontsize" \
+  "-fontsize 0" \
+  "-resolution" \
+  "-resolution=0" \
+  "-leftmargin" \
+  "-leftmargin -1" \
+  "-rightmargin" \
+  "-rightmargin -1" \
+  "-topmargin" \
+  "-topmargin -1" \
+  "-bottommargin" \
+  "-bottommargin -1" \
+  "-ascent" \
+  "-ascent -1" \
+  "-descent" \
+  "-descent -1" \
+  "-stroke=A" \
+  "-pad -crop"
+  do
+    pbmtextps ${error_flag} -dump-ps ${text} >${test_out} || \
+    printf "Expected failure $n (${error_flag}) "
+    test -s ${test_out} && echo "unexpected output" || echo "(no output)"
+    rm -f ${test_out}
+    n=$((n + 1))
+  done
+
+for asciihex_string in \
+  "<a>" \
+  "" \
+  "<53756c667572" \
+  "53756c667572>" \
+  "<5375<6c667572>" \
+  "<53756c>667572>"
+  do
+    pbmtextps -dump-ps -asciihex ${asciihex_string} >${test_out} || \
+    printf "Expected failure $n (-asciihex ${asciihex_string}) "
+    test -s ${test_out} && echo "unexpected output" || echo "(no output)"
+    rm -f ${test_out}
+    n=$((n + 1))
+  done
+
+for ascii85_string in \
+  '<~@<6O!FD5W(~'\
+  '~@<6O!FD5W(~>'\
+  "<~@<6O<~!FD5W(~>"\
+  "<~@<6O~>!FD5W(~>"\
+  "<~@<6O!FD5W(~~>"\
+  "v"\
+  "y"\
+  "1z"\
+  "z1z"\
+  "<~0123z~>"
+  do
+    pbmtextps -dump-ps -ascii85 ${ascii85_string} >${test_out} || \
+	printf "Expected failure $n (-ascii85 ${ascii85_string}) "
+    test -s ${test_out} && echo "unexpected output" || echo "(no output)"
+    rm -f ${test_out}
+    n=$((n + 1))
+  done
+
+  pbmtextps -font="" -dump-ps ${text} >${test_out} || \
+  printf "Expected failure $n (-font=\"\") "
+  test -s ${test_out} && echo "unexpected output" || echo "(no output)"
+  rm -f ${test_out}
diff --git a/test/pbmtextps.ok b/test/pbmtextps.ok
new file mode 100644
index 00000000..2063ac4a
--- /dev/null
+++ b/test/pbmtextps.ok
@@ -0,0 +1,18 @@
+Test 1.  Should print 0 five times.
+0
+0
+0
+0
+0
+Test 2.  Should print P1 1 1 0 five times
+P1 1 1 0 
+P1 1 1 0 
+P1 1 1 0 
+P1 1 1 0 
+P1 1 1 0 
+Test 3.  Should print eulerchi: N
+ eulerchi:	1
+ eulerchi:	2
+ eulerchi:	3
+ eulerchi:	4
+ eulerchi:	5
diff --git a/test/pbmtextps.test b/test/pbmtextps.test
new file mode 100755
index 00000000..55f3f96a
--- /dev/null
+++ b/test/pbmtextps.test
@@ -0,0 +1,55 @@
+#! /bin/sh
+# This script tests: pbmtextps pbmminkowski
+# Also requires: gs pnmcrop
+
+tmpdir=${tmpdir:-/tmp}
+text_pbm=${tmpdir}/text.pbm
+
+text="Do one thing and do it well."
+
+echo "Test 1.  Should print 0 five times."
+# -ascent -descent values too small to have effect
+
+pbmtextps -descent=1 ${text} > ${text_pbm}
+  echo $?
+  test -s ${text_pbm}
+  echo $?
+pbmtextps -ascent=10 -descent=1 ${text} | cmp -s - ${text_pbm}
+  echo $?
+pbmtextps -ascent=1 -descent=1 ${text}  | cmp -s - ${text_pbm}
+  echo $?
+pbmtextps -descent=2 ${text} | cmp -s - ${text_pbm}
+  echo $?
+
+rm ${text_pbm}
+
+
+echo "Test 2.  Should print P1 1 1 0 five times"
+# blank images
+
+pbmtextps " " | pnmcrop -plain -blank-image=minimize |\
+  tr '\n' ' ' ; echo
+pbmtextps -fontsize=12   " " | pnmcrop -plain -blank-image=minimize |\
+  tr '\n' ' ' ; echo
+pbmtextps -resolution=50 " " | pnmcrop -plain -blank-image=minimize |\
+  tr '\n' ' ' ; echo
+pbmtextps -asciihex "20" | pnmcrop -plain -blank-image=minimize |\
+  tr '\n' ' ' ; echo
+pbmtextps -ascii85  "+9" | pnmcrop -plain -blank-image=minimize |\
+  tr '\n' ' ' ; echo
+
+
+
+echo "Test 3.  Should print eulerchi: N"
+# Test with characters known to produce stable eulerchi values
+# accross various fonts
+
+pbmtextps " " | pbmminkowski | grep "eulerchi"
+
+pbmtextps "+" | pbmminkowski | grep "eulerchi"
+
+pbmtextps "+" | pnmcrop -left -right | pbmminkowski | grep "eulerchi"
+
+pbmtextps "+" | pnmcrop | pbmminkowski | grep "eulerchi"
+
+pbmtextps "o" | pnmcrop | pbmminkowski | grep "eulerchi"
diff --git a/test/pbmtog3.ok b/test/pbmtog3.ok
index cef9e3f9..6660206b 100644
--- a/test/pbmtog3.ok
+++ b/test/pbmtog3.ok
@@ -1,10 +1,20 @@
-3697098186 144
-1248301383 122
-686713716 144
-215463240 122
+Test 1.  Should print 2156383714 1106
+2156383714 1106
+Test 2.  Should print 162371073 1049
+162371073 1049
+Test 3.  Should print 750267045 1106
+750267045 1106
+Test 4.  Should print 1140269483 1049
+1140269483 1049
+Test 5.  Should print 28792587 47
 28792587 47
+Test 6.  Should print 277456854 32
 277456854 32
+Test 7.  Should print 28792587 47
 28792587 47
+Test 8.  Should print 3736247115 62
 3736247115 62
+Test 9.  Should print 2820255307 2191856
 2820255307 2191856
+Test 10.  Should print 4159089282 2226575
 4159089282 2226575
diff --git a/test/pbmtog3.test b/test/pbmtog3.test
index c5dc3357..8b9c29e1 100755
--- a/test/pbmtog3.test
+++ b/test/pbmtog3.test
@@ -1,25 +1,34 @@
-#! /bin/bash
+#! /bin/sh
 # This script tests: pbmtog3
 # Also requires: pbmmake
 
-# Test 1.  Should print 3697098186 144
-pbmtog3 testgrid.pbm | cksum
-# Test 2.  Should print 1248301383 122
-pbmtog3 -nofixedwidth testgrid.pbm | cksum
-# Test 3.  Should print 686713716 144
-pbmtog3 -reverse testgrid.pbm | cksum
-# Test 4.  Should print 215463240 122
-pbmtog3 -nofixedwidth -reverse testgrid.pbm | cksum
-# Test 5.  Should print 28792587 47
+echo "Test 1.  Should print 2156383714 1106"
+pbmtog3 maze.pbm | cksum
+
+echo "Test 2.  Should print 162371073 1049"
+pbmtog3 -nofixedwidth maze.pbm | cksum
+
+echo "Test 3.  Should print 750267045 1106"
+pbmtog3 -reverse maze.pbm | cksum
+
+echo "Test 4.  Should print 1140269483 1049"
+pbmtog3 -nofixedwidth -reverse maze.pbm | cksum
+
+echo "Test 5.  Should print 28792587 47"
 pbmmake -w 10 10 | pbmtog3 | cksum
-# Test 6.  Should print 277456854 32
+
+echo "Test 6.  Should print 277456854 32"
 pbmmake -w 10 10 | \
   pbmtog3 -nofixedwidth | cksum
-# Test 7.  Should print 28792587 47
+
+echo "Test 7.  Should print 28792587 47"
 pbmmake -w 10000 10 | pbmtog3 | cksum
-# Test 8.  Should print 3736247115 62
+
+echo "Test 8.  Should print 3736247115 62"
 pbmmake -b 10 10 | pbmtog3 | cksum
-# Test 9.  Should print 2820255307 2191856
+
+echo "Test 9.  Should print 2820255307 2191856"
 pbmmake -g 1700 2286 | pbmtog3 | cksum
-# Test 10.  Should print 4159089282 2226575
+
+echo "Test 10.  Should print 4159089282 2226575"
 pbmmake -g 1800 2286 | pbmtog3 | cksum
diff --git a/test/pbmtopgm.ok b/test/pbmtopgm.ok
index 6ccf9c64..11242259 100644
--- a/test/pbmtopgm.ok
+++ b/test/pbmtopgm.ok
@@ -19,7 +19,7 @@ P2
 0 1 0 1 0 1 0 1 0 1 0 1 0 1
 0 0 0 0 0 0 0 0 0 0 0 0 0 0
 Test Invalid
-Expected failure 1 1
-Expected failure 2 1
-Expected failure 3 1
-Expected failure 4 1
+Expected failure 1 (no output)
+Expected failure 2 (no output)
+Expected failure 3 (no output)
+Expected failure 4 (no output)
diff --git a/test/pbmtopgm.test b/test/pbmtopgm.test
index a7ba6f7c..19378bb6 100755
--- a/test/pbmtopgm.test
+++ b/test/pbmtopgm.test
@@ -1,4 +1,4 @@
-#! /bin/bash
+#! /bin/sh
 # This script tests: pbmtopgm
 # Also requires:
 
@@ -9,24 +9,9 @@ pbmtopgm -plain 1 1 testgrid.pbm
 
 echo "Test Invalid"
 
-tmpdir=${tmpdir:-/tmp}
-test_out=${tmpdir}/test_out
+. ${srcdir}/test-invalid.inc
 
-echo 1>&2
-echo "Invalid command-line argument combinations." 1>&2
-echo "Error messages should appear below the line." 1>&2
-echo "-----------------------------------------------------------" 1>&2
-
-pbmtopgm 5 0 testgrid.pbm > ${test_out} || \
-   echo -n "Expected failure 1"; test -s ${test_out}; echo " "$?
-
-pbmtopgm 0 9 testgrid.pbm > ${test_out} || \
-   echo -n "Expected failure 2"; test -s ${test_out}; echo " "$?
-
-pbmtopgm 15 5 testgrid.pbm > ${test_out} || \
-   echo -n "Expected failure 3"; test -s ${test_out}; echo " "$?
-
-pbmtopgm 5 17 testgrid.pbm > ${test_out} || \
-   echo -n "Expected failure 4"; test -s ${test_out}; echo " "$?
-
-rm -f ${test_out}
+invCmd "pbmtopgm 5 0 testgrid.pbm"
+invCmd "pbmtopgm 0 9 testgrid.pbm"
+invCmd "pbmtopgm 15 5 testgrid.pbm"
+invCmd "pbmtopgm 5 17 testgrid.pbm"
diff --git a/test/pbmupc.ok b/test/pbmupc.ok
index f1b91e99..4f2fd0ae 100644
--- a/test/pbmupc.ok
+++ b/test/pbmupc.ok
@@ -1,12 +1,12 @@
 Test 1
 2619309127 10172
 Test Invalid
-Expected failure 1 1
-Expected failure 2 1
-Expected failure 3 1
-Expected failure 4 1
-Expected failure 5 1
-Expected failure 6 1
-Expected failure 7 1
-Expected failure 8 1
-Expected failure 9 1
+Expected failure 1 (no output)
+Expected failure 2 (no output)
+Expected failure 3 (no output)
+Expected failure 4 (no output)
+Expected failure 5 (no output)
+Expected failure 6 (no output)
+Expected failure 7 (no output)
+Expected failure 8 (no output)
+Expected failure 9 (no output)
diff --git a/test/pbmupc.test b/test/pbmupc.test
index fb9ec90e..74bd54d9 100755
--- a/test/pbmupc.test
+++ b/test/pbmupc.test
@@ -1,4 +1,4 @@
-#! /bin/bash
+#! /bin/sh
 # This script tests: pbmupc
 # Also requires:
 
@@ -20,22 +20,46 @@ echo "Error messages should appear below the line." 1>&2
 echo "-----------------------------------------------------------" 1>&2
 
 pbmupc -s3 0 72890 00011     > ${test_out} || \
-   echo -n "Expected failure 1"; test -s ${test_out}; echo " "$?
+  printf "Expected failure 1 "
+  test -s ${test_out} && echo "unexpected output" || echo "(no output)"
+  rm -f ${test_out}
+
 pbmupc -s1   72890 00011     > ${test_out} || \
-   echo -n "Expected failure 2"; test -s ${test_out}; echo " "$?
+  printf "Expected failure 2 "
+  test -s ${test_out} && echo "unexpected output" || echo "(no output)"
+  rm -f ${test_out}
+
 pbmupc -s1 0 72890           > ${test_out} || \
-   echo -n "Expected failure 3"; test -s ${test_out}; echo " "$?
+  printf "Expected failure 3 "
+  test -s ${test_out} && echo "unexpected output" || echo "(no output)"
+  rm -f ${test_out}
+
 pbmupc -s1 10 72890 00011    > ${test_out} || \
-   echo -n "Expected failure 4"; test -s ${test_out}; echo " "$?
+  printf "Expected failure 4 "
+  test -s ${test_out} && echo "unexpected output" || echo "(no output)"
+  rm -f ${test_out}
+
 pbmupc -s1 0 172890 00011    > ${test_out} || \
-   echo -n "Expected failure 5"; test -s ${test_out}; echo " "$?
+  printf "Expected failure 5 "
+  test -s ${test_out} && echo "unexpected output" || echo "(no output)"
+  rm -f ${test_out}
+
 pbmupc -s1 0   2890 00011    > ${test_out} || \
-   echo -n "Expected failure 6"; test -s ${test_out}; echo " "$?
+  printf "Expected failure 6 "
+  test -s ${test_out} && echo "unexpected output" || echo "(no output)"
+  rm -f ${test_out}
+
 pbmupc -s1 0 72890 100011    > ${test_out} || \
-   echo -n "Expected failure 7"; test -s ${test_out}; echo " "$?
+  printf "Expected failure 7 "
+  test -s ${test_out} && echo "unexpected output" || echo "(no output)"
+  rm -f ${test_out}
+
 pbmupc -s1 0 72890   0011    > ${test_out} || \
-   echo -n "Expected failure 8"; test -s ${test_out}; echo " "$?
-pbmupc -s1 0 72890 100011 1  > ${test_out} || \
-   echo -n "Expected failure 9"; test -s ${test_out}; echo " "$?
+  printf "Expected failure 8 "
+  test -s ${test_out} && echo "unexpected output" || echo "(no output)"
+  rm -f ${test_out}
 
-rm ${test_out}
+pbmupc -s1 0 72890 100011 1  > ${test_out} || \
+  printf "Expected failure 9 "
+  test -s ${test_out} && echo "unexpected output" || echo "(no output)"
+  rm -f ${test_out}
diff --git a/test/pcx-roundtrip.ok b/test/pcx-roundtrip.ok
index 968f46b9..0f5ac87d 100644
--- a/test/pcx-roundtrip.ok
+++ b/test/pcx-roundtrip.ok
@@ -1,5 +1,9 @@
+Test 1.  Should print 1926073387 101484
 1926073387 101484
+Test 2.  Should print 369063776 101484 three times
 369063776 101484
 369063776 101484
 369063776 101484
-829921912 685
+Test 3.  Should print 669206373 10102 twice
+669206373 10102
+669206373 10102
diff --git a/test/pcx-roundtrip.test b/test/pcx-roundtrip.test
index 3dba42b9..194af131 100755
--- a/test/pcx-roundtrip.test
+++ b/test/pcx-roundtrip.test
@@ -1,7 +1,6 @@
-#! /bin/bash
+#! /bin/sh
 # This script tests: ppmtopcx pcxtoppm
-# Also requires: pnmremap
-
+# Also requires: pgmtoppm pnmremap
 
 tmpdir=${tmpdir:-/tmp}
 pcxstd_ppm=${tmpdir}/pcxstd_ppm
@@ -29,17 +28,16 @@ P3
 255 255 255
 EOF
 
-# Test 1. Should print 1926073387 101484
+echo "Test 1.  Should print 1926073387 101484"
 ppmtopcx testimg.ppm | pcxtoppm | cksum
 
-# Test 2.  Should print 369063776 101484 three times
+echo "Test 2.  Should print 369063776 101484 three times"
 pnmremap testimg.ppm -mapfile=${pcxstd_ppm} | tee ${testpcx_ppm} | cksum
 ppmtopcx -stdpalette -packed ${testpcx_ppm} | pcxtoppm | cksum
 ppmtopcx -stdpalette -packed -8bit ${testpcx_ppm} | pcxtoppm | cksum
 
 rm ${testpcx_ppm} ${pcxstd_ppm}
 
-# Test 3. Should print 829921912 685 which is the
-# result of:
-# pgmtoppm < testgrid.pbm | cksum
-ppmtopcx -stdpalette -packed testgrid.pbm | pcxtoppm | cksum
+echo "Test 3.  Should print 669206373 10102 twice"
+pgmtoppm < maze.pbm | cksum
+ppmtopcx -stdpalette -packed maze.pbm | pcxtoppm | cksum
diff --git a/test/pdb-roundtrip.ok b/test/pdb-roundtrip.ok
index b903da8d..fbc897fe 100644
--- a/test/pdb-roundtrip.ok
+++ b/test/pdb-roundtrip.ok
@@ -1,18 +1,18 @@
-pbm grid
+Test 1: pbm grid : Should print 2224198737 25671 three times
 2224198737 25671
 2224198737 25671
 2224198737 25671
-pbm tiled
+Test 2: pbmnoise : Should print 0 0 0 0 : 0 four times
 0 0 0 0 : 0
 0 0 0 0 : 0
 0 0 0 0 : 0
 0 0 0 0 : 0
-pgm ellipse
+Test 3: pgm ellipse : Should print 0 0 0 0 0 : 0 four times
 0 0 0 0 0 : 0
 0 0 0 0 0 : 0
 0 0 0 0 0 : 0
 0 0 0 0 0 : 0
-pgm ellipse -4depth
+Test 4: pgm ellipse -4depth : Should print 0 0 0 0 0 : 0 three times
 0 0 0 0 0 : 0
 0 0 0 0 0 : 0
 0 0 0 0 0 : 0
diff --git a/test/pdb-roundtrip.test b/test/pdb-roundtrip.test
index 32d7aa87..f56be1bf 100755
--- a/test/pdb-roundtrip.test
+++ b/test/pdb-roundtrip.test
@@ -1,37 +1,31 @@
 #! /bin/bash
 # This script tests: pamtopdbimg pdbimgtopam
-# Also requires: pnmtile pgmramp pamtopnm pamdepth
+# Also requires: pbmnoise pgmramp pamtopnm pamdepth
 
 tmpdir=${tmpdir:-/tmp}
-tiled_pbm=${tmpdir}/tiled.pbm
+noise_pbm=${tmpdir}/noise.pbm
 ellipse_pgm=${tmpdir}/ellipse.pgm
 
 
-# Test 1. Should produce 2224198737 25671
-# 3 times 
-echo pbm grid
+echo "Test 1: pbm grid : Should print 2224198737 25671 three times"
 for flag in "-compressed" "-maybecompressed" "-uncompressed"
    do
    pamtopdbimg ${flag} testgrid.pbm | pdbimgtopam | cksum
    done
 
 
-# Test 2. Should produce 0 0 0
-# 4 times 
-echo pbm tiled
-pnmtile 160 160 testgrid.pbm > ${tiled_pbm}
+echo "Test 2: pbmnoise : Should print 0 0 0 0 : 0 four times" 
+pbmnoise -randomseed=1 160 160 > ${noise_pbm}
 for flag in "" "-compressed" "-maybecompressed" "-uncompressed"
   do
-  pamtopdbimg ${flag} ${tiled_pbm} | pdbimgtopam | pamtopnm | \
-    cmp -s - ${tiled_pbm}
+  pamtopdbimg ${flag} ${noise_pbm} | pdbimgtopam | pamtopnm | \
+    cmp -s - ${noise_pbm}
   echo ${PIPESTATUS[@]} ":" $?
   done
-rm ${tiled_pbm}
+rm ${noise_pbm}
 
 
-# Test 3. Should produce 0 0 0
-# 4 times
-echo pgm ellipse
+echo "Test 3: pgm ellipse : Should print 0 0 0 0 0 : 0 four times"
 pgmramp -ellipse 160 160 -maxval=3 > ${ellipse_pgm}
 for flag in "" "-compressed" "-maybecompressed" "-uncompressed"
     do
@@ -42,9 +36,7 @@ for flag in "" "-compressed" "-maybecompressed" "-uncompressed"
 rm ${ellipse_pgm}
 
 
-# Test 3. Should produce 0 0 0
-# 3 times 
-echo pgm ellipse -4depth
+echo "Test 4: pgm ellipse -4depth : Should print 0 0 0 0 0 : 0 three times"
 pgmramp -ellipse 160 160 -maxval=15 > ${ellipse_pgm}
 for flag in "-compressed" "-maybecompressed" "-uncompressed"
     do
@@ -52,4 +44,4 @@ for flag in "-compressed" "-maybecompressed" "-uncompressed"
       pamtopnm | pamdepth 15 | cmp -s - ${ellipse_pgm}
     echo ${PIPESTATUS[@]} ":" $?
     done
-rm ${ellipse_pgm}
\ No newline at end of file
+rm ${ellipse_pgm}
diff --git a/test/pfm-roundtrip.test b/test/pfm-roundtrip.test
index f1b5d418..95bfc62f 100755
--- a/test/pfm-roundtrip.test
+++ b/test/pfm-roundtrip.test
@@ -1,4 +1,4 @@
-#! /bin/bash
+#! /bin/sh
 # This script tests: pamtopfm pfmtopam
 # Also requires: pamtopnm
 
diff --git a/test/pgmbentley.test b/test/pgmbentley.test
index 0429d54b..800aa1f7 100755
--- a/test/pgmbentley.test
+++ b/test/pgmbentley.test
@@ -1,4 +1,4 @@
-#! /bin/bash
+#! /bin/sh
 # This script tests: pgmbentley
 # Also requires: pgmramp
 
diff --git a/test/pgmhist.ok b/test/pgmhist.ok
index 3be73ff9..f9184828 100644
--- a/test/pgmhist.ok
+++ b/test/pgmhist.ok
@@ -30,7 +30,7 @@ Test 2
 230
 255
 Test Invalid
-Expected failure 1 1
-Expected failure 2 1
-Expected failure 3 1
-Expected failure 4 1
+Expected failure 1 (no output)
+Expected failure 2 (no output)
+Expected failure 3 (no output)
+Expected failure 4 (no output)
diff --git a/test/pgmhist.test b/test/pgmhist.test
index ab3763fd..5c458a57 100755
--- a/test/pgmhist.test
+++ b/test/pgmhist.test
@@ -1,4 +1,4 @@
-#! /bin/bash
+#! /bin/sh
 # This script tests: pgmhist
 # Also requires: pgmramp
 
@@ -26,21 +26,9 @@ pgmramp -lr 256 1 | pgmhist -machine -decile   | \
 
 echo "Test Invalid"
 
-tmpdir=${tmpdir:-/tmp}
-test_out=${tmpdir}/test_out
+. ${srcdir}/test-invalid.inc
 
-echo 1>&2
-echo "Invalid command-line argument combinations." 1>&2
-echo "Error messages should appear below the line." 1>&2
-echo "-----------------------------------------------------------" 1>&2
-
-pgmhist -median   -quartile testgrid.pbm > ${test_out} || \
-  echo -n "Expected failure 1"; test -s ${test_out}; echo " "$?
-pgmhist -median   -decile   testgrid.pbm > ${test_out} || \
-  echo -n "Expected failure 2"; test -s ${test_out}; echo " "$?
-pgmhist -quartile -decile   testgrid.pbm > ${test_out} || \
-  echo -n "Expected failure 3"; test -s ${test_out}; echo " "$?
-pgmhist testimg.ppm > ${test_out} || \
-  echo -n "Expected failure 4"; test -s ${test_out}; echo " "$?
-
-rm ${test_out}
+invCmd "pgmhist -median   -quartile testgrid.pbm"
+invCmd "pgmhist -median   -decile   testgrid.pbm"
+invCmd "pgmhist -quartile -decile   testgrid.pbm"
+invCmd "pgmhist testimg.ppm"
diff --git a/test/pgmmake.ok b/test/pgmmake.ok
index 8b242822..9460162d 100644
--- a/test/pgmmake.ok
+++ b/test/pgmmake.ok
@@ -1,12 +1,25 @@
 Test 1
+P2
+1 1
+255
+0
+P2
+1 1
+255
+255
+P2
+1 1
+2
+1
 3662611538 2513
 3109612402 5012
 Test Invalid
-Expected failure 1 1
-Expected failure 2 1
-Expected failure 3 1
-Expected failure 4 1
-Expected failure 5 1
-Expected failure 6 1
-Expected failure 7 1
-Expected failure 8 1
+Expected failure 1 (no output)
+Expected failure 2 (no output)
+Expected failure 3 (no output)
+Expected failure 4 (no output)
+Expected failure 5 (no output)
+Expected failure 6 (no output)
+Expected failure 7 (no output)
+Expected failure 8 (no output)
+Expected failure 9 (no output)
diff --git a/test/pgmmake.test b/test/pgmmake.test
index 2fc63e72..d8e248d4 100755
--- a/test/pgmmake.test
+++ b/test/pgmmake.test
@@ -1,38 +1,25 @@
-#! /bin/bash
+#! /bin/sh
 # This script tests: pgmmake
 # Also requires:
 
 echo "Test 1"
 
+pgmmake -plain 0 1 1
+pgmmake -plain 1 1 1
+pgmmake -plain -maxval=2 0.5 1 1
 pgmmake 1 50 50 | cksum
 pgmmake .2 50 100 -maxval=5 | cksum
 
-
 echo "Test Invalid"
 
-echo 1>&2
-echo "Invalid command-line argument combinations." 1>&2
-echo "Error messages should appear below the line." 1>&2
-echo "-----------------------------------------------------------" 1>&2
-
-tmpdir=${tmpdir:-/tmp}
-test_out=${tmpdir}/test_out
-
-pgmmake 100  5 5 > ${test_out} || \
-   echo -n "Expected failure 1"; test -s ${test_out}; echo " "$?
-pgmmake 1.01 5 5 > ${test_out} || \
-   echo -n "Expected failure 2"; test -s ${test_out}; echo " "$?
-pgmmake .5   5   > ${test_out} || \
-   echo -n "Expected failure 3"; test -s ${test_out}; echo " "$?
-pgmmake .5       > ${test_out} || \
-   echo -n "Expected failure 4"; test -s ${test_out}; echo " "$?
-pgmmake -maxval=5        5 5 > ${test_out} || \
-   echo -n "Expected failure 5"; test -s ${test_out}; echo " "$?
-pgmmake -maxval=0     .5 5 5 > ${test_out} || \
-   echo -n "Expected failure 6"; test -s ${test_out}; echo " "$?
-pgmmake -maxval=-1    .5 5 5 > ${test_out} || \
-   echo -n "Expected failure 7"; test -s ${test_out}; echo " "$?
-pgmmake -maxval=65536 .5 5 5 > ${test_out} || \
-   echo -n "Expected failure 8"; test -s ${test_out}; echo " "$?
-
-rm ${test_out}
+. ${srcdir}/test-invalid.inc
+
+invCmd "pgmmake"
+invCmd "pgmmake 100  5 5"
+invCmd "pgmmake 1.01 5 5"
+invCmd "pgmmake .5   5"
+invCmd "pgmmake .5"
+invCmd "pgmmake -maxval=5        5 5"
+invCmd "pgmmake -maxval=0     .5 5 5"
+invCmd "pgmmake -maxval=-1    .5 5 5"
+invCmd "pgmmake -maxval=65536 .5 5 5"
diff --git a/test/pgmminkowski.test b/test/pgmminkowski.test
index 52e02e19..e81de3e1 100755
--- a/test/pgmminkowski.test
+++ b/test/pgmminkowski.test
@@ -1,8 +1,8 @@
-#! /bin/bash
+#! /bin/sh
 # This script tests: pgmminkowski
-# Also requires: pbmmake pgmmake pnmmargin pnmpad
+# Also requires: pbmmake pgmmake pnmpad
 
-pgmmake .5 1 1 | pnmmargin -b 1 | \
+pgmmake .5 1 1 | pnmpad -black -top=1 -left=1 -bottom=1 -right=1 | \
   pgmminkowski
 echo
 pbmmake -g 3 3 | pgmminkowski
diff --git a/test/pgmnoise-parameters.ok b/test/pgmnoise-parameters.ok
index 1bb1cd59..1e321f00 100644
--- a/test/pgmnoise-parameters.ok
+++ b/test/pgmnoise-parameters.ok
@@ -1,5 +1,7 @@
-Expected failure 1 1
-Expected failure 2 1
-Expected failure 3 1
-Expected failure 4 1
-Expected failure 5 1
+Test Invalid
+Expected failure 1 (no output)
+Expected failure 2 (no output)
+Expected failure 3 (no output)
+Expected failure 4 (no output)
+Expected failure 5 (no output)
+Expected failure 6 (no output)
diff --git a/test/pgmnoise-parameters.test b/test/pgmnoise-parameters.test
index 1682afca..871aacf9 100755
--- a/test/pgmnoise-parameters.test
+++ b/test/pgmnoise-parameters.test
@@ -1,26 +1,14 @@
-#! /bin/bash
+#! /bin/sh
 # This script tests: pgmnoise
 # Also requires:
 
-tmpdir=${tmpdir:-/tmp}
-test_out=${tmpdir}/test_out
+echo "Test Invalid"
 
-echo 1>&2
-echo "Invalid command-line argument combinations." 1>&2
-echo "Error messages should appear below the line." 1>&2
-echo "-----------------------------------------------------------" 1>&2
+. ${srcdir}/test-invalid.inc
 
-pgmnoise -maxval=255  -randomseed=1 > ${test_out} || \
-   echo -n "Expected failure 1"; test -s ${test_out}; echo " "$?
-
-pgmnoise 100 -randomseed=1 > ${test_out} || \
-   echo -n "Expected failure 2"; test -s ${test_out}; echo " "$?
-
-pgmnoise 100 0 -randomseed=1 > ${test_out} || \
-   echo -n "Expected failure 3"; test -s ${test_out}; echo " "$?
-
-pgmnoise 0 100 -randomseed=1 > ${test_out} || \
-   echo -n "Expected failure 4"; test -s ${test_out}; echo " "$?
-
-pgmnoise 100 100 100 -randomseed=1 > ${test_out} || \
-   echo -n "Expected failure 5"; test -s ${test_out}; echo " "$?
+invCmd "pgmnoise"
+invCmd "pgmnoise -maxval=255  -randomseed=1"
+invCmd "pgmnoise 100 -randomseed=1"
+invCmd "pgmnoise 100 0 -randomseed=1"
+invCmd "pgmnoise 0 100 -randomseed=1"
+invCmd "pgmnoise 100 100 100 -randomseed=1"
diff --git a/test/pgmnoise.ok b/test/pgmnoise.ok
new file mode 100644
index 00000000..2a2db565
--- /dev/null
+++ b/test/pgmnoise.ok
@@ -0,0 +1,102 @@
+Test 1.
+Should print: 2132901423 10015
+2132901423 10015
+Test 2.
+P2
+5 20
+9999
+1612 9302 6734 4585 4204
+5391 9429 3985 2298 7403
+2835 4565 740 4426 8239
+2720 519 8804 4697 8106
+3009 4609 4243 4039 746
+2626 2536 8553 8460 1771
+7212 4909 929 1418 4126
+2695 4553 893 8587 4728
+4844 7306 495 5920 2597
+8076 445 6934 5307 8902
+9058 5693 9660 3006 2222
+2786 6116 5227 1234 7006
+4839 1161 1026 3808 5152
+3250 4612 9652 7801 1673
+4425 7642 6209 5879 1891
+1326 2609 3880 4788 4008
+2678 1923 1099 1100 9586
+2873 7582 3983 1720 6969
+2059 8444 8154 2595 3247
+6536 8742 7111 4600 9344
+Test 3.
+1
+P2 16 1 1 1 0 1 0 0 1 0 0 0 0 1 0 1 1 1 1 2
+P2 16 1 2 1 2 0 2 1 1 2 2 2 0 2 0 1 2 1 0 3
+P2 16 1 3 1 1 2 0 0 1 3 3 1 0 0 3 2 2 2 1 4
+P2 16 1 4 0 4 4 3 3 3 1 1 4 2 3 4 1 3 3 0 5
+P2 16 1 5 1 5 0 2 1 1 5 5 5 0 2 3 4 5 1 0 6
+P2 16 1 6 0 3 4 3 3 6 0 5 0 3 4 6 5 5 2 5 7
+P2 16 1 7 5 4 0 2 7 3 0 6 2 5 5 5 6 1 0 4 8
+P2 16 1 8 4 5 0 5 7 1 2 5 8 0 2 3 1 8 4 0 9
+P2 16 1 9 5 9 4 8 3 3 1 1 9 2 8 9 6 3 3 0 10
+P2 16 1 10 0 3 5 0 3 1 5 1 0 0 9 1 4 5 5 6 11
+P2 16 1 11 1 11 0 8 7 1 11 5 11 0 8 9 4 11 1 0 12
+P2 16 1 12 6 9 3 1 6 1 7 2 12 9 1 0 9 11 12 1 13
+P2 16 1 13 7 3 4 10 3 13 7 5 7 10 4 13 12 5 9 12 14
+P2 16 1 14 10 14 9 8 13 13 11 11 14 12 8 9 1 8 13 0 15
+P2 16 1 15 5 2 4 15 1 12 10 6 11 14 0 8 7 4 15 15 16
+P2 16 1 16 2 9 15 8 14 7 7 16 5 5 16 2 4 6 1 14 255
+P2 16 1 255 37 244 193 106 235 128 71 255 140 47 103 184 72 20 188 238 65535
+P2 16 1 65535 62501 27329 33003 65351 12172 47207 5192 61116 32511 7 50057 8396 43723 19813 7813 65473 
+Test 4.
+1  stdin:	PGM raw, 1 by 10  maxval 1
+2  stdin:	PGM raw, 2 by 10  maxval 2
+3  stdin:	PGM raw, 3 by 10  maxval 3
+4  stdin:	PGM raw, 4 by 10  maxval 4
+5  stdin:	PGM raw, 5 by 10  maxval 5
+6  stdin:	PGM raw, 6 by 10  maxval 6
+7  stdin:	PGM raw, 7 by 10  maxval 7
+8  stdin:	PGM raw, 8 by 10  maxval 8
+9  stdin:	PGM raw, 9 by 10  maxval 9
+10  stdin:	PGM raw, 10 by 10  maxval 10
+11  stdin:	PGM raw, 11 by 10  maxval 11
+12  stdin:	PGM raw, 12 by 10  maxval 12
+13  stdin:	PGM raw, 13 by 10  maxval 13
+14  stdin:	PGM raw, 14 by 10  maxval 14
+15  stdin:	PGM raw, 15 by 10  maxval 15
+16  stdin:	PGM raw, 16 by 10  maxval 16
+30  stdin:	PGM raw, 30 by 10  maxval 30
+31  stdin:	PGM raw, 31 by 10  maxval 31
+32  stdin:	PGM raw, 32 by 10  maxval 32
+254  stdin:	PGM raw, 254 by 10  maxval 254
+255  stdin:	PGM raw, 255 by 10  maxval 255
+256  stdin:	PGM raw, 256 by 10  maxval 256
+65534  stdin:	PGM raw, 65534 by 10  maxval 65534
+65535  stdin:	PGM raw, 65535 by 10  maxval 65535
+Test 5.
+Should print four identical lines
+969759084 1682
+969759084 1682
+969759084 1682
+969759084 1682
+Test 6.
+First column should be 2^n - 1.  Last column should be 'pool'.
+1 pgmnoise: method: pool
+3 pgmnoise: method: pool
+7 pgmnoise: method: pool
+15 pgmnoise: method: pool
+31 pgmnoise: method: pool
+63 pgmnoise: method: pool
+127 pgmnoise: method: pool
+255 pgmnoise: method: pool
+511 pgmnoise: method: pool
+1023 pgmnoise: method: pool
+65535 pgmnoise: method: pool
+Test Invalid
+Expected failure 1 (no output)
+Expected failure 2 (no output)
+Expected failure 3 (no output)
+Expected failure 4 (no output)
+Expected failure 5 (no output)
+Expected failure 6 (no output)
+Expected failure 7 (no output)
+Expected failure 8 (no output)
+Expected failure 9 (no output)
+Expected failure 10 (no output)
diff --git a/test/pgmnoise.rand-ok b/test/pgmnoise.rand-ok
deleted file mode 100644
index b69f48e5..00000000
--- a/test/pgmnoise.rand-ok
+++ /dev/null
@@ -1,3 +0,0 @@
-000|0
-081|2005134911 10015
-082|3516404574 10015
diff --git a/test/pgmnoise.test b/test/pgmnoise.test
index 03301ce6..36f16ab0 100755
--- a/test/pgmnoise.test
+++ b/test/pgmnoise.test
@@ -1,7 +1,126 @@
-#! /bin/bash
+#! /bin/sh
 # This script tests: pgmnoise
-# Also requires:
+# Also requires: pgmhist pamvalidate pamfile
 
-# Should print: 1663614689 10015 (Glibc)
-#               3516404574 10015 (MAC OS)
+echo "Test 1."
+echo "Should print: 2132901423 10015" # (Mersenne Twister)
 pgmnoise --randomseed=0 100 100 | cksum
+
+
+echo "Test 2."
+# Output is similar to that of Test 2. of random-generator.test
+# The lowest four decimal digits are printed.
+
+pgmnoise --randomseed=5489 -maxval=9999 -plain 5 20
+
+
+echo "Test 3."
+for maxval in 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 255 65535
+  do
+  echo ${maxval}
+  pgmnoise -maxval=${maxval} -randomseed=1 -plain 16 1 | tr '\n' ' '
+  done
+echo
+
+echo "Test 4."
+# Check for maxval violation
+for maxval in  1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 \
+               30 31 32 254 255 256 65534 65535
+  do
+  printf "%d  " ${maxval}
+  pgmnoise -maxval=${maxval} -randomseed=1 -plain ${maxval} 10 | \
+    pamvalidate | pamfile
+  done
+
+echo "Test 5."
+echo "Should print four identical lines"
+# width height values do not affect random number sequence
+for xysize in "1 10000" "100 100" "250 40" "1000 10"
+  do pgmnoise --randomseed=0 ${xysize} | pgmhist -mach | cksum
+  done
+
+
+tmpdir=${tmpdir:-/tmp}
+outfile=${tmpdir}/out
+
+echo "Test 6."
+echo "First column should be 2^n - 1.  Last column should be 'pool'."
+# The "pool" method of generating pixvals is used iff maxval is
+# a power of 2 minus 1: 1, 3, 7, 15, 31 ...
+
+    
+for maxval in \
+    1 2 3 4 5 6 7 8 9 \
+    10 11 12 13 14 15 16 17 18 19 \
+    20 21 22 23 24 25 26 27 28 29 \
+    30 31 32 33  60 61 62 63 64 65 \
+    127 255 511 1023  65535 \
+    129 142 186 219 677 1068 1788 1820 2067 2154 2301 2317 \
+    5180 5321 5596 6304 7565 9525 \
+    10501 14178 25797 27451 28653
+    do
+    pgmnoise -maxval=${maxval} -plain -randomseed=1 -verbose 1 1 \
+		 > /dev/null 2> ${outfile}
+    awk -v mval=${maxval} '/method/ && /pool/ { print mval, $0 }' ${outfile}
+    rm ${outfile}
+    done
+
+
+echo "Test Invalid"
+
+test_out=${tmpdir}/test_out
+
+echo 1>&2
+echo "Invalid command-line arguments." 1>&2
+echo "Error messages should appear below the line." 1>&2
+echo "-----------------------------------------------------------" 1>&2
+
+pgmnoise 0 0  > ${test_out} || \
+  printf "Expected failure 1 "
+  test -s ${test_out} && echo "unexpected output" || echo "(no output)"
+  rm -f ${test_out}
+
+pgmnoise 0 1  > ${test_out} || \
+  printf "Expected failure 2 "
+  test -s ${test_out} && echo "unexpected output" || echo "(no output)"
+  rm -f ${test_out}
+
+pgmnoise 1 0  > ${test_out} || \
+  printf "Expected failure 3 "
+  test -s ${test_out} && echo "unexpected output" || echo "(no output)"
+  rm -f ${test_out}
+
+pgmnoise      > ${test_out} || \
+  printf "Expected failure 4 "
+  test -s ${test_out} && echo "unexpected output" || echo "(no output)"
+  rm -f ${test_out}
+
+pgmnoise 1    > ${test_out} || \
+  printf "Expected failure 5 "
+  test -s ${test_out} && echo "unexpected output" || echo "(no output)"
+  rm -f ${test_out}
+
+pgmnoise 100 -1 > ${test_out} || \
+  printf "Expected failure 6 "
+  test -s ${test_out} && echo "unexpected output" || echo "(no output)"
+  rm -f ${test_out}
+
+pgmnoise -randomseed=-1 100 100  > ${test_out} || \
+  printf "Expected failure 7 "
+  test -s ${test_out} && echo "unexpected output" || echo "(no output)"
+  rm -f ${test_out}
+
+pgmnoise -maxval=-1 100 100  > ${test_out} || \
+  printf "Expected failure 8 "
+  test -s ${test_out} && echo "unexpected output" || echo "(no output)"
+  rm -f ${test_out}
+
+pgmnoise -maxval=0 100 100  > ${test_out} || \
+  printf "Expected failure 9 "
+  test -s ${test_out} && echo "unexpected output" || echo "(no output)"
+  rm -f ${test_out}
+
+pgmnoise -maxval=$((256 * 256 * 256 * 256)) 10 10 > ${test_out} || \
+  printf "Expected failure 10 "
+  test -s ${test_out} && echo "unexpected output" || echo "(no output)"
+  rm -f ${test_out}
diff --git a/test/pgmramp.ok b/test/pgmramp.ok
index de0d9206..71f92b13 100644
--- a/test/pgmramp.ok
+++ b/test/pgmramp.ok
@@ -42,8 +42,10 @@ Test 2
 Test 3
 886972785 131087
 Test Invalid
-Expected failure: -lr -tb 1
-Expected failure: -lr -rectangle 1
-Expected failure: -rectangle -ellipse 1
-Expected failure: insufficient parameters 1
-Expected failure: excessive parameters 1
+Expected failure 1 (no output)
+Expected failure 2 (no output)
+Expected failure 3 (no output)
+Expected failure 4 (no output)
+Expected failure 5 (no output)
+Expected failure 6 (no output)
+Expected failure 7 (no output)
diff --git a/test/pgmramp.test b/test/pgmramp.test
index 3ec73749..84fe02ca 100755
--- a/test/pgmramp.test
+++ b/test/pgmramp.test
@@ -1,4 +1,4 @@
-#! /bin/bash
+#! /bin/sh
 # This script tests: pgmramp
 # Also requires:
 
@@ -21,24 +21,16 @@ pgmramp -diagonal -maxval=510 256 256 | cksum
 
 echo "Test Invalid"
 
-echo 1>&2
-echo "Invalid command-line argument combinations." 1>&2
-echo "Error messages should appear below the line." 1>&2
-echo "-----------------------------------------------------------" 1>&2
+. ${srcdir}/test-invalid.inc
 
-tmpdir=${tmpdir:-/tmp}
-test_out=${tmpdir}/test_out
 
 for combination in "-lr -tb" "-lr -rectangle" "-rectangle -ellipse"
-do pgmramp $combination 10 10 > ${test_out} || \
-   echo -n "Expected failure: $combination" ; test -s ${test_out}; echo " "$?
-done
+  do
+    invCmd "pgmramp ${combination} 10 10"
+  done
 
-pgmramp -lr     1 > ${test_out} || \
-  echo -n "Expected failure: insufficient parameters"; \
-  test -s ${test_out}; echo " "$?
-pgmramp -tb 1 1 1 > ${test_out} || \
-  echo -n "Expected failure: excessive parameters"; \
-  test -s ${test_out}; echo " "$?
+invCmd "pgmramp -lr 10 0"
+invCmd "pgmramp -lr 0 10"
+invCmd "pgmramp -lr 1"
+invCmd "pgmramp -tb 1 1 1"
 
-rm ${test_out}
diff --git a/test/pgmtopgm.ok b/test/pgmtopgm.ok
index 53c25a44..38cfd268 100644
--- a/test/pgmtopgm.ok
+++ b/test/pgmtopgm.ok
@@ -1 +1,11 @@
-729348909 237
+Test 1.  Should print two identical PGM images
+P2
+10 1
+255
+0 0 0 0 0 0 0 0 0 0
+P2
+10 1
+255
+0 0 0 0 0 0 0 0 0 0
+Test 2.  Should print 2582999797 3376
+2582999797 3376
diff --git a/test/pgmtopgm.test b/test/pgmtopgm.test
index e919fdac..d81260d8 100755
--- a/test/pgmtopgm.test
+++ b/test/pgmtopgm.test
@@ -1,6 +1,12 @@
-#! /bin/bash
+#! /bin/sh
 # This script tests: pgmtopgm
-# Also requires:
+# Also requires: pgmmake
 
+echo "Test 1.  Should print two identical PGM images"
 
-pgmtopgm < testgrid.pbm | cksum
+pgmmake -plain 0 10 1
+pgmmake 0 10 1 | pgmtopgm -plain
+
+echo "Test 2.  Should print 2582999797 3376"
+
+pgmtopgm < maze.pbm | cksum
diff --git a/test/pgmtoppm.ok b/test/pgmtoppm.ok
index 55e5af95..4a2114ab 100644
--- a/test/pgmtoppm.ok
+++ b/test/pgmtoppm.ok
@@ -1,3 +1,39 @@
+Test 1.  Should print 1767073524 779 twice, then 1676700883 779
+1767073524 779
 1767073524 779
 1676700883 779
+Test 2.  Should print 718580145 779 twice
+718580145 779
+718580145 779
+Test 3.  Should print 718580145 779 twice
+718580145 779
 718580145 779
+Test 4.  Should print 829921912 685 seven times
+829921912 685
+829921912 685
+829921912 685
+829921912 685
+829921912 685
+829921912 685
+829921912 685
+Test 5.  Should print 934505096 685 four times
+934505096 685
+934505096 685
+934505096 685
+934505096 685
+Test 6. Should print 3083028153 685 three times
+3083028153 685
+3083028153 685
+3083028153 685
+Test 7 Invalid
+Expected failure 1 (no output)
+Expected failure 2 (no output)
+Expected failure 3 (no output)
+Expected failure 4 (no output)
+Expected failure 5 (no output)
+Expected failure 6 (no output)
+Expected failure 7 (no output)
+Expected failure 8 (no output)
+Expected failure 9 (no output)
+Expected failure 10 (no output)
+Expected failure 11 (no output)
diff --git a/test/pgmtoppm.test b/test/pgmtoppm.test
index 70df0d97..6054fc03 100755
--- a/test/pgmtoppm.test
+++ b/test/pgmtoppm.test
@@ -1,22 +1,139 @@
-#! /bin/bash
+#! /bin/sh
 # This script tests: pgmtoppm
-# Also requires: pamseq pamtopnm pgmramp
-
+# Also requires: pamtopnm pnminvert pamseq pgmramp
 
 tmpdir=${tmpdir:-/tmp}
 
+echo "Test 1.  Should print 1767073524 779 twice, then 1676700883 779"
+
 test_pgm=${tmpdir}/test.pgm
-palette=${tmpdir}/palette
+palette_pam=${tmpdir}/palette.pam
+palette_ppm=${tmpdir}/palette.ppm
 
-pgmramp -maxval=5 -lr 256 1 >${test_pgm}
-pamseq 3 5 -tupletype=RGB | pamtopnm \
-  >${palette}
+pgmramp -maxval=5 -lr 256 1 > ${test_pgm}
 
-# Test 1.
 pgmtoppm green ${test_pgm} | cksum
-
+pgmtoppm black-green ${test_pgm} | cksum
 pgmtoppm yellow-blue ${test_pgm} | cksum
 
-pgmtoppm -map=${palette} ${test_pgm} | cksum
 
-rm ${test_pgm} ${palette}
+echo "Test 2.  Should print 718580145 779 twice"
+pamseq 3 5 -tupletype=RGB | tee ${palette_pam} | pamtopnm > ${palette_ppm}
+pgmtoppm -map=${palette_pam} ${test_pgm} | cksum
+pgmtoppm -map=${palette_ppm} ${test_pgm} | cksum
+
+rm ${palette_pam}
+
+echo "Test 3.  Should print 718580145 779 twice"
+
+pgmtoppm white-black ${test_pgm} | pnminvert | cksum
+pnminvert ${test_pgm} | pgmtoppm white-black | cksum
+
+rm ${test_pgm}
+
+echo "Test 4.  Should print 829921912 685 seven times"
+
+pgmtoppm white testgrid.pbm | cksum
+pgmtoppm black-white testgrid.pbm | cksum
+pgmtoppm rgb:ff/ff/ff testgrid.pbm | cksum
+pgmtoppm -white=rgb-255:255/255/255 testgrid.pbm | cksum
+pgmtoppm rgb:00/00/00-rgb:ff/ff/ff testgrid.pbm | cksum
+pgmtoppm rgbi:0/0/0-rgbi:1/1/1 testgrid.pbm | cksum
+pgmtoppm -black=rgb-255:0/0/0 -white=rgb-255:255/255/255 testgrid.pbm | cksum
+
+echo "Test 5.  Should print 934505096 685 four times"
+
+pgmtoppm white-black testgrid.pbm | cksum
+pgmtoppm white testgrid.pbm | pnminvert| cksum
+pnminvert testgrid.pbm | pgmtoppm black-white | cksum
+pnminvert testgrid.pbm | pgmtoppm white | cksum
+
+echo "Test 6. Should print 3083028153 685 three times"
+
+pgmtoppm black testgrid.pbm | cksum
+pgmtoppm black-black testgrid.pbm | cksum
+pgmtoppm rgbi:0/0/0-rgbi:0/0/0 testgrid.pbm | cksum
+
+echo "Test 7 Invalid"
+
+tmpdir=${tmpdir:-/tmp}
+test_out=${tmpdir}/test_out
+
+echo 1>&2
+echo "Invalid command-line argument combinations." 1>&2
+echo "Error messages should appear below the line." 1>&2
+echo "-----------------------------------------------------------" 1>&2
+
+pgmtoppm white testimg.ppm > \
+  ${test_out} || \
+  printf "Expected failure 1 "
+  test -s ${test_out} && echo "unexpected output" || echo "(no output)"
+  rm -f ${test_out}
+
+pgmtoppm -map=/dev/null testgrid.pbm > \
+  ${test_out} || \
+  printf "Expected failure 2 "
+  test -s ${test_out} && echo "unexpected output" || echo "(no output)"
+  rm -f ${test_out}
+
+pgmtoppm black white testgrid.pbm > \
+  ${test_out} || \
+  printf "Expected failure 3 "
+  test -s ${test_out} && echo "unexpected output" || echo "(no output)"
+  rm -f ${test_out}
+
+pgmtoppm hwite testgrid.pbm > \
+  ${test_out} || \
+  printf "Expected failure 4 "
+  test -s ${test_out} && echo "unexpected output" || echo "(no output)"
+  rm -f ${test_out}
+
+pgmtoppm off-color testgrid.pbm > \
+  ${test_out} || \
+  printf "Expected failure 5 "
+  test -s ${test_out} && echo "unexpected output" || echo "(no output)"
+  rm -f ${test_out}
+
+pgmtoppm rgb-255:7/7/7 testgrid.pbm > \
+  ${test_out} || \
+  printf "Expected failure 6 "
+  test -s ${test_out} && echo "unexpected output" || echo "(no output)"
+  rm -f ${test_out}
+
+pgmtoppm -black=black -white=white white testgrid.pbm > \
+  ${test_out} || \
+  printf "Expected failure 7 "
+  test -s ${test_out} && echo "unexpected output" || echo "(no output)"
+  rm -f ${test_out}
+
+pgmtoppm -black=rgb:0/0/0 -map=${palette_ppm} testgrid.pbm > \
+  ${test_out} || \
+  printf "Expected failure 8 "
+  test -s ${test_out} && echo "unexpected output" || echo "(no output)"
+  rm -f ${test_out}
+
+pgmtoppm -white=rgb:ff/ff/ff -map=${palette_ppm} testgrid.pbm > \
+  ${test_out} || \
+  printf "Expected failure 9 "
+  test -s ${test_out} && echo "unexpected output" || echo "(no output)"
+  rm -f ${test_out}
+
+pgmtoppm rgb:ff/ff/ff -map=${palette_ppm} testgrid.pbm > \
+  ${test_out} || \
+  printf "Expected failure 10 "
+  test -s ${test_out} && echo "unexpected output" || echo "(no output)"
+  rm -f ${test_out}
+
+pgmtoppm rgb:00/00/00-rgb:ff/ff/ff -map=${palette_ppm} testgrid.pbm > \
+  ${test_out} || \
+  printf "Expected failure 11 "
+  test -s ${test_out} && echo "unexpected output" || echo "(no output)"
+  rm -f ${test_out}
+
+#pgmtoppm rgb-255:7/7/7 testgrid.pbm > \
+#  ${test_out} || \
+#  printf "Expected failure 12 "
+#  test -s ${test_out} && echo "unexpected output" || echo "(no output)"
+#  rm -f ${test_out}
+
+rm -f ${palette_ppm}
diff --git a/test/pi3-roundtrip.ok b/test/pi3-roundtrip.ok
index 3fde31b1..c4351b83 100644
--- a/test/pi3-roundtrip.ok
+++ b/test/pi3-roundtrip.ok
@@ -1,2 +1,5 @@
+Test 1. Should print: 3139449799 32011 twice
 3139449799 32011
-2425386270 41
+3139449799 32011
+Test 2. Should print: 281226646 481, cksum of maze.pbm
+281226646 481
diff --git a/test/pi3-roundtrip.test b/test/pi3-roundtrip.test
index 5700337d..d795157d 100755
--- a/test/pi3-roundtrip.test
+++ b/test/pi3-roundtrip.test
@@ -1,16 +1,15 @@
-#! /bin/bash
+#! /bin/sh
 # This script tests: pbmtopi3 pi3topbm
-# Also requires: pbmmake pamcut
-
+# Also requires: pbmmake pamcut pamfile
 
 # The pi3 image format specifies a fixed image size of 640x400.
 # Pbmtopi3 rejects images that do not conform.
 
-# Test
-# Should print: 3139449799 32011
+echo "Test 1. Should print: 3139449799 32011 twice"
+pbmmake -g 640 400 | cksum
 pbmmake -g 640 400 | pbmtopi3 | pi3topbm | cksum
 
-# Test 2.
-# Should print: 2425386270 41
-pamcut -pad 0 0 640 400 testgrid.pbm | \
-  pbmtopi3 | pi3topbm | pamcut 0 0 14 16 | cksum
+echo "Test 2. Should print: 281226646 481, cksum of maze.pbm"
+size=$(pamfile -size maze.pbm | awk '{print "-width="$1,"-height="$2}')
+pamcut -pad -left=0 -top=0 -width=640 -height=400 maze.pbm | \
+  pbmtopi3 | pi3topbm | pamcut -left=0 -top=0 ${size} | cksum
diff --git a/test/pict-roundtrip.test b/test/pict-roundtrip.test
index cd207d48..b4910064 100755
--- a/test/pict-roundtrip.test
+++ b/test/pict-roundtrip.test
@@ -1,4 +1,4 @@
-#! /bin/bash
+#! /bin/sh
 # This script tests: picttoppm ppmtopict
 # Also requires: pamseq pamdepth pamtopnm pnmremap
 
diff --git a/test/pj-roundtrip.test b/test/pj-roundtrip.test
index 2b0d61e5..3ed30927 100755
--- a/test/pj-roundtrip.test
+++ b/test/pj-roundtrip.test
@@ -19,8 +19,8 @@ echo "Test 2. Should print:  0 0 : 0"
 
 testout_ppm=${tmpdir}/testout.ppm
 
-ppmtopj testgrid.pbm | pjtoppm > ${testout_ppm}
-  ppmtoppm < testgrid.pbm | cmp -s - ${testout_ppm} > /dev/null
+ppmtopj maze.pbm | pjtoppm > ${testout_ppm}
+  ppmtoppm < maze.pbm | cmp -s - ${testout_ppm} > /dev/null
   echo ${PIPESTATUS[@]} ":" $?
 
 rm ${testout_ppm}
diff --git a/test/png-roundtrip.ok b/test/png-roundtrip.ok
index 28b8c057..ec0a1937 100644
--- a/test/png-roundtrip.ok
+++ b/test/png-roundtrip.ok
@@ -16,21 +16,21 @@
 1926073387 101484
 1926073387 101484
 1926073387 101484
-2425386270 41
-2425386270 41
-2425386270 41
-2425386270 41
-2425386270 41
-2425386270 41
-2425386270 41
-2425386270 41
-2425386270 41
-2425386270 41
-2425386270 41
-2425386270 41
-2425386270 41
-2425386270 41
-2425386270 41
-2425386270 41
-2425386270 41
-2425386270 41
+281226646 481
+281226646 481
+281226646 481
+281226646 481
+281226646 481
+281226646 481
+281226646 481
+281226646 481
+281226646 481
+281226646 481
+281226646 481
+281226646 481
+281226646 481
+281226646 481
+281226646 481
+281226646 481
+281226646 481
+281226646 481
diff --git a/test/png-roundtrip.test b/test/png-roundtrip.test
index 7e7c4a9b..97cf9b2c 100755
--- a/test/png-roundtrip.test
+++ b/test/png-roundtrip.test
@@ -1,4 +1,4 @@
-#! /bin/bash
+#! /bin/sh
 # This script tests: pngtopam pnmtopng
 # Also requires:
 
@@ -28,7 +28,7 @@ for flags in "" -interlace \
 pnmtopng testimg.ppm $flags | pngtopam | cksum
 done
 
-# Test 2.  Should print 2425386270 41 18 times
+# Test 2.  Should print 281226646 481 18 times
 for flags in "" -interlace \
   -gamma=.45 \
   -hist \
@@ -47,5 +47,5 @@ for flags in "" -interlace \
   -comp_strategy=filtered \
   -force
   do
-  pnmtopng testgrid.pbm $flags | pngtopam | cksum
+  pnmtopng maze.pbm $flags | pngtopam | cksum
   done
diff --git a/test/png-roundtrip2.ok b/test/png-roundtrip2.ok
index 0e712ce7..764cadfa 100644
--- a/test/png-roundtrip2.ok
+++ b/test/png-roundtrip2.ok
@@ -1,4 +1,4 @@
 1926073387 101484
 1926073387 101484
-2425386270 41
-2425386270 41
+281226646 481
+281226646 481
diff --git a/test/png-roundtrip2.test b/test/png-roundtrip2.test
index af2ad029..85149a91 100755
--- a/test/png-roundtrip2.test
+++ b/test/png-roundtrip2.test
@@ -1,4 +1,4 @@
-#! /bin/bash
+#! /bin/sh
 # This script tests: pngtopam pamtopng
 # Also requires:
 
@@ -15,8 +15,8 @@ for flags in "" -gamma=.45
   pamtopng testimg.ppm $flags | pngtopam | cksum
   done
 
-# Test 2.  Should print 2425386270 41 twice
+# Test 2.  Should print 281226646 481 twice
 for flags in "" -gamma=.45
   do
-  pamtopng testgrid.pbm $flags | pngtopam | cksum
+  pamtopng maze.pbm $flags | pngtopam | cksum
   done
diff --git a/test/pnm-pam-roundtrip.ok b/test/pnm-pam-roundtrip.ok
index 67f7a1fe..ace97410 100644
--- a/test/pnm-pam-roundtrip.ok
+++ b/test/pnm-pam-roundtrip.ok
@@ -1,2 +1,2 @@
 1926073387 101484
-2425386270 41
+281226646 481
diff --git a/test/pnm-pam-roundtrip.test b/test/pnm-pam-roundtrip.test
index b8e60c88..da3021f9 100755
--- a/test/pnm-pam-roundtrip.test
+++ b/test/pnm-pam-roundtrip.test
@@ -1,7 +1,7 @@
-#! /bin/bash
+#! /bin/sh
 # This script tests: pamtopam pamtopnm
 # Also requires:
 
 
 pamtopam < testimg.ppm | pamtopnm | cksum
-pamtopam < testgrid.pbm | pamtopnm | cksum
+pamtopam < maze.pbm | pamtopnm | cksum
diff --git a/test/pnm-plain-roundtrip.ok b/test/pnm-plain-roundtrip.ok
index 67f7a1fe..ace97410 100644
--- a/test/pnm-plain-roundtrip.ok
+++ b/test/pnm-plain-roundtrip.ok
@@ -1,2 +1,2 @@
 1926073387 101484
-2425386270 41
+281226646 481
diff --git a/test/pnm-plain-roundtrip.test b/test/pnm-plain-roundtrip.test
index 3779d761..14b8ca57 100755
--- a/test/pnm-plain-roundtrip.test
+++ b/test/pnm-plain-roundtrip.test
@@ -1,9 +1,9 @@
-#! /bin/bash
+#! /bin/sh
 # This script tests: pamtopnm
 #
 
 
 pamtopnm -plain testimg.ppm | \
   pamtopnm | cksum
-pamtopnm -plain testgrid.pbm | \
+pamtopnm -plain maze.pbm | \
   pamtopnm | cksum
diff --git a/test/pnmcat.ok b/test/pnmcat.ok
index b92a1420..9958ad62 100644
--- a/test/pnmcat.ok
+++ b/test/pnmcat.ok
@@ -1,20 +1,98 @@
-Test 1.
-1704087873 73
-4150323653 73
-1522490272 202953
-2862441566 202953
+Test 1.  Should print a simple PBM image five times
+P1
+2 2
+01
+10
+P1
+2 2
+01
+10
+P1
+2 2
+01
+10
+P1
+2 2
+01
+10
+P1
+2 2
+01
+10
+Test 2.  Should print 2197356643 895 twice
+2197356643 895
+2197356643 895
+Test 3.  Should print 3313353797 954
+3313353797 954
+Test 4.  Should print 1731660895 1308 three times
+1731660895 1308
+1731660895 1308
+1731660895 1308
+Test 5.  Should print 2985957591 1426 three times
+2985957591 1426
+2985957591 1426
+2985957591 1426
+Test 6.  Should print a simple PGM image three times
+P2
+4 4
+3
+0 0 1 1
+0 1 1 2
+1 1 2 2
+1 2 2 3
+P2
+4 4
+3
+0 0 1 1
+0 1 1 2
+1 1 2 2
+1 2 2 3
+P2
+4 4
+3
+0 0 1 1
+0 1 1 2
+1 1 2 2
+1 2 2 3
+Test 7.  Should print 2097565808 394 twice
+2097565808 394
+2097565808 394
+Test 8.  Should print 3086569577 394
+3086569577 394
+Test 9.  Should print 4288335051 586 three times
+4288335051 586
+4288335051 586
+4288335051 586
+Test 10.  Should print 642720605 586 three times
+642720605 586
+642720605 586
+642720605 586
+Test 11.  Should print 3622741282 1019 twice
+3622741282 1019
+3622741282 1019
+Test 12.  Should print 1401081637 1019
+1401081637 1019
+Test 13.  Should print 2756501917 1019
+2756501917 1019
+Test 14. Should print 587933655 107742 twice
+587933655 107742
+587933655 107742
+Test 15.  Should print 3948141157 107742
+3948141157 107742
+Test 16.  Should print 3910239002 107742
+3910239002 107742
 Test Invalid
-Expected failure 1 1
-Expected failure 2 1
-Expected failure 3 1
-Expected failure 4 1
-Expected failure 5 1
-Expected failure 6 1
-Expected failure 7 1
-Expected failure 8 1
-Expected failure 9 1
-Expected failure 10 1
-Expected failure 11 1
-Expected failure 12 1
-Expected failure 13 1
-Expected failure 14 1
+Expected failure 1 (no output)
+Expected failure 2 (no output)
+Expected failure 3 (no output)
+Expected failure 4 (no output)
+Expected failure 5 (no output)
+Expected failure 6 (no output)
+Expected failure 7 (no output)
+Expected failure 8 (no output)
+Expected failure 9 (no output)
+Expected failure 10 (no output)
+Expected failure 11 (no output)
+Expected failure 12 (no output)
+Expected failure 13 (no output)
+Expected failure 14 (no output)
diff --git a/test/pnmcat.test b/test/pnmcat.test
index 40c29f50..8779638b 100755
--- a/test/pnmcat.test
+++ b/test/pnmcat.test
@@ -1,71 +1,132 @@
-#! /bin/bash
+#! /bin/sh
 # This script tests: pnmcat
-# Also requires:
+# Also requires: pbmmake pgmramp ppmtoppm pamcat
 
-echo "Test 1."
+if [ ${CHECK_TYPE} = tree ]
+  then echo "Skipping." 1>&2
+       echo "Running \"make package; make check\" is recommended." 1>&2
+  exit 80;
+fi
 
-pnmcat -lr testgrid.pbm testgrid.pbm | cksum
-pnmcat -tb testgrid.pbm testgrid.pbm | cksum
-
-pnmcat -lr testimg.ppm testimg.ppm | cksum
-pnmcat -tb testimg.ppm testimg.ppm | cksum
+tmpdir=${tmpdir:-/tmp}
+check2x2_pbm=${tmpdir}/check2x2.pbm
+maze2lr_pbm=${tmpdir}/maze2lr.pbm
+maze2tb_pbm=${tmpdir}/maze2tb.pbm
+diag_pgm=${tmpdir}/diag.pgm
+diag_ppm=${tmpdir}/diag.ppm
+diag2lr_ppm=${tmpdir}/diag2lr.ppm
+diag2tb_ppm=${tmpdir}/diag2tb.ppm
+
+echo "Test 1.  Should print a simple PBM image five times"
+# Check input from stdin and from designated input file
+# Similar to tests in stdin-p?m.test
+
+pbmmake -g 2 2 | tee ${check2x2_pbm} | pnmcat -lr -plain
+pnmcat -tb -plain ${check2x2_pbm}
+pnmcat -tb -plain < ${check2x2_pbm}
+pnmcat -lr -black -plain ${check2x2_pbm}
+cat ${check2x2_pbm} | pnmcat -tb -white -plain
+
+rm ${check2x2_pbm}
+
+echo "Test 2.  Should print 2197356643 895 twice"
+pnmcat -lr -white maze.pbm maze.pbm | tee ${maze2lr_pbm} | cksum
+cat maze.pbm | pnmcat -lr -black maze.pbm - | cksum
+
+echo "Test 3.  Should print 3313353797 954"
+pnmcat -tb maze.pbm maze.pbm | tee ${maze2tb_pbm} | cksum
+
+echo "Test 4.  Should print 1731660895 1308 three times"
+pnmcat -lr maze.pbm maze.pbm maze.pbm | cksum
+pnmcat -lr ${maze2lr_pbm} maze.pbm | cksum
+cat ${maze2lr_pbm} | pnmcat -lr - maze.pbm | cksum
+
+echo "Test 5.  Should print 2985957591 1426 three times"
+pnmcat -tb maze.pbm maze.pbm maze.pbm | cksum
+pnmcat -tb maze.pbm ${maze2tb_pbm} | cksum
+cat maze.pbm | pnmcat -tb - ${maze2tb_pbm} | cksum
+
+rm ${maze2lr_pbm} ${maze2tb_pbm}
+
+echo "Test 6.  Should print a simple PGM image three times"
+# Use sed to scrape off space at line end for compatibility
+# with older versions of pnmcat
+
+pgmramp -diag 4 4 -maxval=3 | tee ${diag_pgm} | pnmcat -lr -plain |\
+  sed 's/ *$//'
+pnmcat -tb -plain ${diag_pgm} | sed 's/ *$//'
+cat ${diag_pgm} | pnmcat -tb -plain | sed 's/ *$//'
+
+rm ${diag_pgm}
+
+pgmramp -diag 8 8 -maxval 7 | ppmtoppm > ${diag_ppm}
+
+echo "Test 7.  Should print 2097565808 394 twice"
+pnmcat -lr -black ${diag_ppm} ${diag_ppm} | tee ${diag2lr_ppm} | cksum
+cat ${diag_ppm} | pnmcat -lr -white ${diag_ppm} - | cksum
+
+echo "Test 8.  Should print 3086569577 394"
+pnmcat -tb ${diag_ppm} ${diag_ppm} | tee ${diag2tb_ppm} | cksum
+
+echo "Test 9.  Should print 4288335051 586 three times"
+pnmcat -lr ${diag_ppm} ${diag_ppm} ${diag_ppm} | cksum
+pnmcat -lr ${diag_ppm}  ${diag2lr_ppm} | cksum
+cat ${diag2lr_ppm} | pnmcat -lr - ${diag_ppm} | cksum
+
+echo "Test 10.  Should print 642720605 586 three times"
+pnmcat -tb ${diag_ppm} ${diag_ppm} ${diag_ppm} | cksum
+pnmcat -tb ${diag2tb_ppm} ${diag_ppm} | cksum
+cat ${diag_ppm} | pnmcat -tb ${diag2tb_ppm} - | cksum
+
+rm ${diag2lr_ppm} ${diag2tb_ppm}
+
+echo "Test 11.  Should print 3622741282 1019 twice"
+pnmcat -tb -white testgrid.pbm ${diag_ppm} | cksum
+pnmcat -tb -jcenter -white testgrid.pbm ${diag_ppm} | cksum
+echo "Test 12.  Should print 1401081637 1019"
+pnmcat -tb -jleft -white testgrid.pbm ${diag_ppm}  | cksum
+echo "Test 13.  Should print 2756501917 1019"
+pnmcat -tb -jright -white testgrid.pbm ${diag_ppm} | cksum
+
+echo "Test 14. Should print 587933655 107742 twice"
+pnmcat -lr -black testgrid.pbm testimg.ppm | cksum
+pnmcat -lr -jcenter -black testgrid.pbm testimg.ppm | cksum
+echo "Test 15.  Should print 3948141157 107742"
+pnmcat -lr -jtop -black testgrid.pbm testimg.ppm | cksum
+echo "Test 16.  Should print 3910239002 107742"
+pnmcat -lr -jbottom -black testgrid.pbm testimg.ppm | cksum
+
+rm ${diag_ppm}
 
 echo "Test Invalid"
 
-tmpdir=${tmpdir:-/tmp}
-test_out=${tmpdir}/test_out
-
-echo 1>&2
-echo "Invalid command-line argument combinations." 1>&2
-echo "Error messages should appear below the line." 1>&2
-echo "-----------------------------------------------------------" 1>&2
+. ${srcdir}/test-invalid.inc
 
 # direction not specified
-pnmcat testgrid.pbm testimg.ppm > ${test_out} || \
-   echo -n "Expected failure 1"; test -s ${test_out}; echo " "$?
+invCmd "pnmcat testgrid.pbm testimg.ppm"
 
 # both directions specified
-pnmcat -topbottom -leftright testgrid.pbm testimg.ppm > ${test_out} || \
-   echo -n "Expected failure 2"; test -s ${test_out}; echo " "$?
+invCmd "pnmcat -topbottom -leftright testgrid.pbm testimg.ppm"
 
 # both pad colors specified
-pnmcat -topbottom -white -black testgrid.pbm testimg.ppm > ${test_out} || \
-   echo -n "Expected failure 3"; test -s ${test_out}; echo " "$?
+invCmd "pnmcat -topbottom -white -black testgrid.pbm testimg.ppm"
 
 # justification parameters overspecified
-pnmcat -lr -jtop -jbottom testgrid.pbm testimg.ppm > ${test_out} || \
-   echo -n "Expected failure 4"; test -s ${test_out}; echo " "$?
-
-pnmcat -lr -jtop -jcenter testgrid.pbm testimg.ppm > ${test_out} || \
-   echo -n "Expected failure 5"; test -s ${test_out}; echo " "$?
-
-pnmcat -lr -jcenter -jbottom testgrid.pbm testimg.ppm > ${test_out} || \
-   echo -n "Expected failure 6"; test -s ${test_out}; echo " "$?
-
-pnmcat -tb -jleft -jright testgrid.pbm testimg.ppm > ${test_out} || \
-   echo -n "Expected failure 7"; test -s ${test_out}; echo " "$?
-
-pnmcat -tb -jleft -jcenter testgrid.pbm testimg.ppm > ${test_out} || \
-   echo -n "Expected failure 8"; test -s ${test_out}; echo " "$?
-
-pnmcat -tb -jcenter -jright testgrid.pbm testimg.ppm > ${test_out} || \
-   echo -n "Expected failure 9"; test -s ${test_out}; echo " "$?
+invCmd "pnmcat -lr -jtop -jbottom testgrid.pbm testimg.ppm"
+invCmd "pnmcat -lr -jtop -jcenter testgrid.pbm testimg.ppm"
+invCmd "pnmcat -lr -jcenter -jbottom testgrid.pbm testimg.ppm"
+invCmd "pnmcat -tb -jleft -jright testgrid.pbm testimg.ppm"
+invCmd "pnmcat -tb -jleft -jcenter testgrid.pbm testimg.ppm"
+invCmd "pnmcat -tb -jcenter -jright testgrid.pbm testimg.ppm"
 
 # justification parameter in the wrong direction
-pnmcat -lr -jleft    testgrid.pbm testimg.ppm > ${test_out} || \
-   echo -n "Expected failure 10"; test -s ${test_out}; echo " "$?
-
-pnmcat -lr -jright   testgrid.pbm testimg.ppm > ${test_out} || \
-   echo -n "Expected failure 11"; test -s ${test_out}; echo " "$?
-
-pnmcat -tb -jtop     testgrid.pbm testimg.ppm > ${test_out} || \
-   echo -n "Expected failure 12"; test -s ${test_out}; echo " "$?
-
-pnmcat -tb -jbottom  testgrid.pbm testimg.ppm > ${test_out} || \
-   echo -n "Expected failure 13"; test -s ${test_out}; echo " "$?
+invCmd "pnmcat -lr -jleft    testgrid.pbm testimg.ppm"
+invCmd "pnmcat -lr -jright   testgrid.pbm testimg.ppm"
+invCmd "pnmcat -tb -jtop     testgrid.pbm testimg.ppm"
+invCmd "pnmcat -tb -jbottom  testgrid.pbm testimg.ppm"
 
 # more than one input image from standard input
 cat testgrid.pbm | pnmcat -lr - - testimg.ppm > ${test_out} || \
-   echo -n "Expected failure 14"; test -s ${test_out}; echo " "$?
-
-rm -f ${test_out}
+  printf "Expected failure 14 "
+  test -s ${test_out} && echo "unexpected output" || echo "(no output)"
+  rm -f ${test_out}
diff --git a/test/pnmcolormap.ok b/test/pnmcolormap.ok
index 126dfea4..8918cf25 100644
--- a/test/pnmcolormap.ok
+++ b/test/pnmcolormap.ok
@@ -1,16 +1,40 @@
+Test 1.
 P1
 2 1
 10
+
 P1
 2 1
 10
+
 P1
 2 1
 10
-Expected failure 1 1
-Expected failure 2 1
-Expected failure 3 1
-Expected failure 4 1
-Expected failure 5 1
-Expected failure 6 1
-Expected failure 7 1
+
+Test 2.
+P3
+3 1
+255
+0 0 255 64 0 191 128 0 128 
+
+P3
+2 2
+255
+0 0 255 64 0 191 
+128 0 128 128 0 128 
+
+Test 3.
+ok
+ok
+ok
+ok
+ok
+
+Test Invalid.
+Expected failure 1 (no output)
+Expected failure 2 (no output)
+Expected failure 3 (no output)
+Expected failure 4 (no output)
+Expected failure 5 (no output)
+Expected failure 6 (no output)
+Expected failure 7 (no output)
diff --git a/test/pnmcolormap.test b/test/pnmcolormap.test
index 13be8a44..953dece3 100755
--- a/test/pnmcolormap.test
+++ b/test/pnmcolormap.test
@@ -1,33 +1,47 @@
-#! /bin/bash
+#! /bin/sh
 # This script tests: pnmcolormap
-# Also requires:
+# Also requires: ppmpat
 
-pnmcolormap -plain -sort 2 testgrid.pbm
-pnmcolormap -plain -sort -square 2 testgrid.pbm 
-pnmcolormap -plain -sort all testgrid.pbm
-
-echo 1>&2
-echo "Invalid command-line arguments." 1>&2
-echo "Error messages should appear below the line." 1>&2
-echo "-----------------------------------------------------------" 1>&2
+echo "Test 1."
 
+pnmcolormap -plain -sort 2 maze.pbm
+echo
+pnmcolormap -plain -sort -square 2 maze.pbm
+echo
+pnmcolormap -plain -sort all maze.pbm
+echo
 tmpdir=${tmpdir:-/tmp}
-test_out=${tmpdir}/test_out
-
-pnmcolormap 0 testimg.ppm   > ${test_out} || \
-  echo -n "Expected failure 1"; test -s ${test_out}; echo " "$?
-pnmcolormap -1 testimg.ppm  > ${test_out} || \
-  echo -n "Expected failure 2"; test -s ${test_out}; echo " "$?
-pnmcolormap 0.1 testimg.ppm > ${test_out} || \
-  echo -n "Expected failure 3"; test -s ${test_out}; echo " "$?
-pnmcolormap -center -meancolor 16 testimg.ppm    > ${test_out} || \
-  echo -n "Expected failure 4"; test -s ${test_out}; echo " "$?
-pnmcolormap -center -meanpixel 16 testimg.ppm    > ${test_out} || \
-  echo -n "Expected failure 5"; test -s ${test_out}; echo " "$?
-pnmcolormap -meancolor -meanpixel 16 testimg.ppm > ${test_out} || \
-  echo -n "Expected failure 6"; test -s ${test_out}; echo " "$?
-pnmcolormap -spreadbrightness -spreadluminosity 16 \
-  testimg.ppm > ${test_out} || \
-  echo -n "Expected failure 7"; test -s ${test_out}; echo " "$?
-
-rm ${test_out}
+tartan_ppm=${tmpdir}/tartan.ppm
+
+echo "Test 2."
+
+ppmpat -tartan -color="rgb:00/00/ff,rgb:00/80/ff,rgb:80/00/80" 20 20 |\
+    tee ${tartan_ppm} | pnmcolormap -plain -sort all
+echo
+pnmcolormap -plain -sort -square all ${tartan_ppm}
+rm ${tartan_ppm}
+echo
+echo "Test 3."
+# Explicitly specify default options.  Output should not vary.
+
+map=${tmpdir}/map.ppm
+
+pnmcolormap 64 testimg.ppm > ${map} && echo ok || echo bad
+test -s ${map} && echo ok || echo bad
+pnmcolormap -center 64 testimg.ppm | cmp -s ${map} - && echo ok || echo bad
+pnmcolormap -spreadbrightness 64 testimg.ppm | cmp -s ${map} - && echo ok || echo bad
+pnmcolormap -splitpixelct 64 testimg.ppm | cmp -s ${map} - && echo ok || echo bad
+rm ${map}
+
+echo
+echo "Test Invalid."
+
+. ${srcdir}/test-invalid.inc
+
+invCmd "pnmcolormap 0 testimg.ppm  "
+invCmd "pnmcolormap -1 testimg.ppm "
+invCmd "pnmcolormap 0.1 testimg.ppm"
+invCmd "pnmcolormap -center -meancolor 16 testimg.ppm   "
+invCmd "pnmcolormap -center -meanpixel 16 testimg.ppm   "
+invCmd "pnmcolormap -meancolor -meanpixel 16 testimg.ppm"
+invCmd "pnmcolormap -spreadbrightness -spreadluminosity 16 testimg.ppm"
diff --git a/test/pnmcolormap2.ok b/test/pnmcolormap2.ok
new file mode 100644
index 00000000..aaf9fd42
--- /dev/null
+++ b/test/pnmcolormap2.ok
@@ -0,0 +1,37 @@
+Test.  Should print 'match' eighteen times.
+pnmcolormap 256
+match
+pnmcolormap 128
+match
+pnmcolormap 64
+match
+pnmcolormap -meancolor 256
+match
+pnmcolormap -meancolor 128
+match
+pnmcolormap -meancolor 64
+match
+pnmcolormap -meanpixel 256
+match
+pnmcolormap -meanpixel 128
+match
+pnmcolormap -meanpixel 64
+match
+pnmcolormap -spreadluminosity 256
+match
+pnmcolormap -spreadluminosity 128
+match
+pnmcolormap -spreadluminosity 64
+match
+pnmcolormap -splitcolorct 256
+match
+pnmcolormap -splitcolorct 128
+match
+pnmcolormap -splitcolorct 64
+match
+pnmcolormap -splitspread 256
+match
+pnmcolormap -splitspread 128
+match
+pnmcolormap -splitspread 64
+match
diff --git a/test/pnmcolormap2.test b/test/pnmcolormap2.test
new file mode 100755
index 00000000..cea521aa
--- /dev/null
+++ b/test/pnmcolormap2.test
@@ -0,0 +1,147 @@
+#! /bin/sh
+# This script tests: pnmcolormap
+# Also requires: pnmremap pnmpsnr
+
+tmpdir=${tmpdir:-/tmp}
+map=${tmpdir}/map.ppm
+
+echo "Test.  Should print 'match' eighteen times."
+
+# Threshold values (tgtN=xx.xx) were produced by calculating
+# the S/N ratio when the original image is compared against a
+# reference image with fewer colors than the target output image.
+
+# colors in following tests / colors for calculating threshold
+# 256 / 224
+# 128 /  96  -splitspread
+# 128 / 108  other
+#  64 /  44  -center (default)
+#  64 /  48  -splitspread
+#  64 /  56  other
+
+# -center
+echo pnmcolormap  256
+tgt1=37.19;  tgt2=37.86;  tgt3=37.77
+pnmcolormap 256 testimg.ppm > ${map}
+pnmremap -mapfile=${map} testimg.ppm |\
+pnmpsnr -target1=${tgt1} -target2=${tgt2} -target3=${tgt3} testimg.ppm -
+rm ${map}
+
+echo pnmcolormap  128
+tgt1=34.46;  tgt2=35.61;  tgt3=34.97
+pnmcolormap 128 testimg.ppm > ${map}
+pnmremap -mapfile=${map} testimg.ppm |\
+pnmpsnr -target1=${tgt1} -target2=${tgt2} -target3=${tgt3} testimg.ppm -
+rm ${map}
+
+echo pnmcolormap  64
+tgt1=30.30;  tgt2=33.10;  tgt3=31.74
+pnmcolormap 64 testimg.ppm > ${map}
+pnmremap -mapfile=${map} testimg.ppm |\
+pnmpsnr -target1=${tgt1} -target2=${tgt2} -target3=${tgt3} testimg.ppm -
+rm ${map}
+
+echo pnmcolormap -meancolor 256
+tgt1=38.36;  tgt2=38.63;  tgt3=38.95
+pnmcolormap -meancolor 256 testimg.ppm > ${map}
+pnmremap -mapfile=${map} testimg.ppm |\
+pnmpsnr -target1=${tgt1} -target2=${tgt2} -target3=${tgt3} testimg.ppm -
+rm ${map}
+
+echo pnmcolormap -meancolor 128
+tgt1=35.86;  tgt2=37.17;  tgt3=36.65
+pnmcolormap -meancolor 128 testimg.ppm > ${map}
+pnmremap -mapfile=${map} testimg.ppm |\
+pnmpsnr -target1=${tgt1} -target2=${tgt2} -target3=${tgt3} testimg.ppm -
+rm ${map}
+
+echo pnmcolormap -meancolor 64
+tgt1=33.64;  tgt2=34.92;  tgt3=34.44
+pnmcolormap -meancolor 64 testimg.ppm > ${map}
+pnmremap -mapfile=${map} testimg.ppm |\
+pnmpsnr -target1=${tgt1} -target2=${tgt2} -target3=${tgt3} testimg.ppm -
+rm ${map}
+
+echo pnmcolormap -meanpixel 256
+tgt1=38.40;  tgt2=38.65;  tgt3=38.90
+pnmcolormap -meanpixel 256 testimg.ppm > ${map}
+pnmremap -mapfile=${map} testimg.ppm |\
+pnmpsnr -target1=${tgt1} -target2=${tgt2} -target3=${tgt3} testimg.ppm -
+rm ${map}
+
+echo pnmcolormap -meanpixel 128
+tgt1=35.75;  tgt2=37.13;  tgt3=36.69
+pnmcolormap -meanpixel 128 testimg.ppm > ${map}
+pnmremap -mapfile=${map} testimg.ppm |\
+pnmpsnr -target1=${tgt1} -target2=${tgt2} -target3=${tgt3} testimg.ppm -
+rm ${map}
+
+echo pnmcolormap -meanpixel 64
+tgt1=33.75;  tgt2=34.79;  tgt3=34.53
+pnmcolormap -meanpixel 64 testimg.ppm > ${map}
+pnmremap -mapfile=${map} testimg.ppm |\
+pnmpsnr -target1=${tgt1} -target2=${tgt2} -target3=${tgt3} testimg.ppm -
+rm ${map}
+
+echo pnmcolormap -spreadluminosity 256
+tgt1=36.82;  tgt2=36.87;  tgt3=37.25
+pnmcolormap -spreadluminosity 256 testimg.ppm > ${map}
+pnmremap -mapfile=${map} testimg.ppm |\
+pnmpsnr -target1=${tgt1} -target2=${tgt2} -target3=${tgt3} testimg.ppm -
+rm ${map}
+
+echo pnmcolormap -spreadluminosity 128
+tgt1=34.61;  tgt2=33.40;  tgt3=34.66
+pnmcolormap -spreadluminosity 128 testimg.ppm > ${map}
+pnmremap -mapfile=${map} testimg.ppm |\
+pnmpsnr -target1=${tgt1} -target2=${tgt2} -target3=${tgt3} testimg.ppm -
+rm ${map}
+
+echo pnmcolormap -spreadluminosity 64
+tgt1=32.35;  tgt2=30.23;  tgt3=32.35
+pnmcolormap -spreadluminosity 64 testimg.ppm > ${map}
+pnmremap -mapfile=${map} testimg.ppm |\
+pnmpsnr -target1=${tgt1} -target2=${tgt2} -target3=${tgt3} testimg.ppm -
+rm ${map}
+
+echo pnmcolormap -splitcolorct 256
+tgt1=37.55;  tgt2=38.37;  tgt3=38.04
+pnmcolormap -splitcolorct 256 testimg.ppm > ${map}
+pnmremap -mapfile=${map} testimg.ppm |\
+pnmpsnr -target1=${tgt1} -target2=${tgt2} -target3=${tgt3} testimg.ppm -
+rm ${map}
+
+echo pnmcolormap -splitcolorct 128
+tgt1=34.84;  tgt2=35.72;  tgt3=34.64
+pnmcolormap -splitcolorct 128 testimg.ppm > ${map}
+pnmremap -mapfile=${map} testimg.ppm |\
+pnmpsnr -target1=${tgt1} -target2=${tgt2} -target3=${tgt3} testimg.ppm -
+rm ${map}
+
+echo pnmcolormap -splitcolorct 64
+tgt1=31.56;  tgt2=33.74;  tgt3=32.93
+pnmcolormap -splitcolorct 64 testimg.ppm > ${map}
+pnmremap -mapfile=${map} testimg.ppm |\
+pnmpsnr -target1=${tgt1} -target2=${tgt2} -target3=${tgt3} testimg.ppm -
+rm ${map}
+
+echo pnmcolormap -splitspread 256
+tgt1=35.18;  tgt2=37.26;  tgt3=36.17
+pnmcolormap -splitspread 256 testimg.ppm > ${map}
+pnmremap -mapfile=${map} testimg.ppm |\
+pnmpsnr -target1=${tgt1} -target2=${tgt2} -target3=${tgt3} testimg.ppm -
+rm ${map}
+
+echo pnmcolormap -splitspread 128
+tgt1=33.18;  tgt2=35.58;  tgt3=33.71
+pnmcolormap -splitspread 128 testimg.ppm > ${map}
+pnmremap -mapfile=${map} testimg.ppm |\
+pnmpsnr -target1=${tgt1} -target2=${tgt2} -target3=${tgt3} testimg.ppm -
+rm ${map}
+
+echo pnmcolormap -splitspread 64
+tgt1=31.27;  tgt2=33.03;  tgt3=30.97
+pnmcolormap -splitspread 64 testimg.ppm > ${map}
+pnmremap -mapfile=${map} testimg.ppm |\
+pnmpsnr -target1=${tgt1} -target2=${tgt2} -target3=${tgt3} testimg.ppm -
+rm ${map}
diff --git a/test/pnmcrop-blank.test b/test/pnmcrop-blank.test
index 087ad65e..bb26bdc0 100755
--- a/test/pnmcrop-blank.test
+++ b/test/pnmcrop-blank.test
@@ -1,4 +1,4 @@
-#! /bin/bash
+#! /bin/sh
 # This script tests: pnmcrop
 # Also requires: pbmmake ppmmake
 
diff --git a/test/pnmcrop1.ok b/test/pnmcrop1.ok
index d02d14b3..35852c8c 100644
--- a/test/pnmcrop1.ok
+++ b/test/pnmcrop1.ok
@@ -1,103 +1,82 @@
 Test 1
-test.pbm
-
-0 0 -7 0 28 25 rgb-1:1/1/1 0.000000
--white
-0 0 -7 0 28 25 rgb-1:1/1/1 0.000000
--black
-0 0 0 -2 28 30 rgb-1:0/0/0 0.000000
--sides
-0 0 -7 0 28 25 rgb-1:1/1/1 0.000000
--top
-0 0 -7 0 28 25 rgb-1:1/1/1 0.000000
--bottom
-0 0 0 0 28 32 rgb-1:1/1/1 0.000000
--left
-0 0 0 0 28 32 rgb-1:1/1/1 0.000000
--right
-0 0 0 0 28 32 rgb-1:1/1/1 0.000000
--top -bottom
-0 0 -7 0 28 25 rgb-1:1/1/1 0.000000
--bottom -bg-corner=bottomright
-0 0 0 -2 28 30 rgb-1:0/0/0 0.000000
--right -bg-corner=bottomright
-0 0 0 0 28 32 rgb-1:0/0/0 0.000000
--bg-color=white
-0 0 0 0 28 32 rgb-1:1/1/1 0.000000
--bg-color=black
-0 0 0 -2 28 30 rgb-1:0/0/0 0.000000
--bg-color=red
-0 0 0 0 28 32 rgb-1:0/0/0 0.000000
-test.ppm
-
+file: maze.pbm option: 
+0 0 -7 0 71 68 rgb-1:1/1/1 0.000000
+file: maze.pbm option: -white
+0 0 -7 0 71 68 rgb-1:1/1/1 0.000000
+file: maze.pbm option: -black
+0 0 0 -2 71 73 rgb-1:0/0/0 0.000000
+file: maze.pbm option: -sides
+0 0 -7 0 71 68 rgb-1:1/1/1 0.000000
+file: maze.pbm option: -top
+0 0 -7 0 71 68 rgb-1:1/1/1 0.000000
+file: maze.pbm option: -bottom
+0 0 0 0 71 75 rgb-1:1/1/1 0.000000
+file: maze.pbm option: -left
+0 0 0 0 71 75 rgb-1:1/1/1 0.000000
+file: maze.pbm option: -right
+0 0 0 0 71 75 rgb-1:1/1/1 0.000000
+file: maze.pbm option: -top -bottom
+0 0 -7 0 71 68 rgb-1:1/1/1 0.000000
+file: maze.pbm option: -bottom -bg-corner=bottomright
+0 0 0 -2 71 73 rgb-1:0/0/0 0.000000
+file: maze.pbm option: -right -bg-corner=bottomright
+0 0 0 0 71 75 rgb-1:0/0/0 0.000000
+file: maze.pbm option: -bg-color=white
+0 0 0 0 71 75 rgb-1:1/1/1 0.000000
+file: maze.pbm option: -bg-color=black
+0 0 0 -2 71 73 rgb-1:0/0/0 0.000000
+file: maze.pbm option: -bg-color=red
+0 0 0 0 71 75 rgb-1:0/0/0 0.000000
+file: rose.ppm option: 
 0 0 0 0 250 161 rgb-255:127/127/127 0.000000
--white
+file: rose.ppm option: -white
 -6 0 0 0 244 161 rgb-255:255/255/255 0.000000
--black
+file: rose.ppm option: -black
 0 -11 0 0 239 161 rgb-255:0/0/0 0.000000
--sides
+file: rose.ppm option: -sides
 -6 0 0 0 244 161 rgb-255:255/255/255 0.000000
--top
+file: rose.ppm option: -top
 0 0 0 0 250 161 rgb-255:127/127/127 0.000000
--bottom
+file: rose.ppm option: -bottom
 0 0 0 0 250 161 rgb-255:127/127/127 0.000000
--left
+file: rose.ppm option: -left
 0 0 0 0 250 161 rgb-255:127/127/127 0.000000
--right
+file: rose.ppm option: -right
 0 0 0 0 250 161 rgb-255:127/127/127 0.000000
--top -bottom
+file: rose.ppm option: -top -bottom
 0 0 0 0 250 161 rgb-255:127/127/127 0.000000
--bottom -bg-corner=bottomright
+file: rose.ppm option: -bottom -bg-corner=bottomright
 0 0 0 0 250 161 rgb-255:0/0/0 0.000000
--right -bg-corner=bottomright
+file: rose.ppm option: -right -bg-corner=bottomright
 0 -11 0 0 239 161 rgb-255:0/0/0 0.000000
--bg-color=white
+file: rose.ppm option: -bg-color=white
 -6 0 0 0 244 161 rgb-255:255/255/255 0.000000
--bg-color=black
+file: rose.ppm option: -bg-color=black
 0 -11 0 0 239 161 rgb-255:0/0/0 0.000000
--bg-color=red
+file: rose.ppm option: -bg-color=red
 0 0 0 0 250 161 rgb-255:255/0/0 0.000000
-Test 2
-test.pbm
-
-3130931737 109
-3130931737 109
--white
-3130931737 109
-3130931737 109
--top
-3130931737 109
-3130931737 109
-test.ppm
-
-1435955776 120765
-1435955776 120765
--white
-638507845 117867
-638507845 117867
--top
-1435955776 120765
-1435955776 120765
+Test 2.  Should print 0 six times
+file: maze.pbm option:
+0
+file: maze.pbm option: -white
+0
+file: maze.pbm option: -top
+0
+file: rose.ppm option:
+0
+file: rose.ppm option: -white
+0
+file: rose.ppm option: -top
+0
 Test Invalid
--reportfull -reportsize
-Expected failure:  -reportfull -reportsize 1
--reportfull -borderfile=testgrid.pbm
-Expected failure:  -reportfull -borderfile=testgrid.pbm 1
--reportsize -borderfile=testgrid.pbm
-Expected failure:  -reportsize -borderfile=testgrid.pbm 1
--black -white
-Expected failure:  -black -white 1
--black -sides
-Expected failure:  -black -sides 1
--white -bg-color=red
-Expected failure:  -white -bg-color=red 1
--white -bg-corner=topleft
-Expected failure:  -white -bg-corner=topleft 1
--white -bg-corner=top
-Expected failure:  -white -bg-corner=top 1
--blank-image=pasturize
-Expected failure:  -blank-image=pasturize 1
--bg-color=black -closeness=-1
-Expected failure:  -bg-color=black -closeness=-1 1
--bg-color=black -closeness=101
-Expected failure:  -bg-color=black -closeness=101 1
+Expected failure:  -reportfull -reportsize (no output)
+Expected failure:  -reportfull -borderfile=testgrid.pbm (no output)
+Expected failure:  -reportsize -borderfile=testgrid.pbm (no output)
+Expected failure:  -black -white (no output)
+Expected failure:  -black -sides (no output)
+Expected failure:  -white -bg-color=red (no output)
+Expected failure:  -white -bg-corner=topleft (no output)
+Expected failure:  -white -bg-corner=top (no output)
+Expected failure:  -blank-image=pasturize (no output)
+Expected failure:  -bg-color=black -closeness=-1 (no output)
+Expected failure:  -bg-color=black -closeness=101 (no output)
diff --git a/test/pnmcrop1.test b/test/pnmcrop1.test
index 34c7534a..811b36d8 100755
--- a/test/pnmcrop1.test
+++ b/test/pnmcrop1.test
@@ -1,13 +1,13 @@
-#! /bin/bash
+#! /bin/sh
 # This script tests: pnmcrop
 # Also requires: pnmpad pnmmargin pamcut
 
 tmpdir=${tmpdir:-/tmp}
 
-test_pbm=${tmpdir}/test.pbm
-test_ppm=${tmpdir}/test.ppm
+test_pbm=${tmpdir}/maze.pbm
+test_ppm=${tmpdir}/rose.ppm
 
-pnmmargin -white 7 testgrid.pbm | pnmpad -black -bottom=2  > ${test_pbm}
+pnmmargin -white 7 maze.pbm | pnmpad -black -bottom=2  > ${test_pbm}
 pnmmargin -white 6 testimg.ppm  | pnmpad -black -right=11  > ${test_ppm}
 
 #Test 1
@@ -15,36 +15,41 @@ echo Test 1
 
 for input_file in ${test_pbm} ${test_ppm}
   do
-  echo `basename ${input_file}`
+  bfile=`basename ${input_file}`
   for option in "" "-white" "-black" "-sides" \
               "-top" "-bottom" "-left" "-right" "-top -bottom" \
               "-bottom -bg-corner=bottomright" \
               "-right -bg-corner=bottomright" \
               "-bg-color=white" "-bg-color=black" "-bg-color=red"
     do
-    echo ${option}
+    echo "file: ${bfile} option: ${option}"
     pnmcrop -reportfull ${option} ${input_file} || echo fail
     done
   done
 
 #Test 2
-echo Test 2
+echo "Test 2.  Should print 0 six times"
+
+out_pnm=${tmpdir}/out.pnm
 
 for input_file in ${test_pbm} ${test_ppm}
   do
-  echo `basename ${input_file}`
+  bfile=`basename ${input_file}`
   for option in "" "-white" "-top"
     do
-    echo ${option}
+    echo file: ${bfile} option: ${option}
     # Normal crop operation
-    pnmcrop ${option} ${input_file} | cksum
+    pnmcrop ${option} ${input_file} > ${out_pnm}
 
     # Compute edge extents with pnmcrop; let pamcut do the actual cropping
     pamcut ${input_file} `pnmcrop -reportsize ${option} ${input_file} | \
         awk 'NF==6 && NR==1 && \
              $1<=0 && $2<=0 && $3<=0 && $4<=0 && $5>=0 && $6>=0 \
-             { printf("-cropleft=%d -cropright=%d  ", -$1, -$2);
-               printf("-croptop=%d -cropbottom=%d", -$3, -$4) }' ` | cksum
+             { printf("-cropleft=%d -cropright=%d ", -$1, -$2);
+               printf("-croptop=%d -cropbottom=%d ", -$3, -$4) }' ` | \
+        cmp -s - ${out_pnm}
+    echo $?
+    rm ${out_pnm}
     done
   done
 
@@ -72,8 +77,8 @@ for option in "-reportfull -reportsize" \
               "-bg-color=black -closeness=-1" \
               "-bg-color=black -closeness=101"
     do
-    echo ${option}
     pnmcrop -reportfull ${option} testgrid.pbm > ${test_out} || \
-        echo -n "Expected failure: " ${option}; test -s ${test_out}; echo " "$?
-        rm ${test_out} 
+        printf "Expected failure:  %s" "${option} "
+        test -s ${test_out} && echo "unexpected output" || echo "(no output)"	
+        rm ${test_out}
     done
diff --git a/test/pnmcrop2.test b/test/pnmcrop2.test
index d6c83c73..3d402a57 100755
--- a/test/pnmcrop2.test
+++ b/test/pnmcrop2.test
@@ -1,4 +1,4 @@
-#! /bin/bash
+#! /bin/sh
 # This script tests: pnmcrop
 # Also requires:
 
@@ -44,7 +44,7 @@ for corner in topleft topright bottomleft bottomright
 
 echo Test 3
 
-for closeness in `seq 0 6`
+for closeness in 0 1 2 3 4 5 6  # for closeness in `seq 0 6`
   do
   echo ${closeness}
   pnmcrop -reportfull -bg-corner=topleft -closeness=${closeness} ${test_pgm} \
diff --git a/test/pnmcrop3.ok b/test/pnmcrop3.ok
index 6824143a..4b096940 100644
--- a/test/pnmcrop3.ok
+++ b/test/pnmcrop3.ok
@@ -86,5 +86,5 @@ P1
 1111111111111
 -3 -1 -1 -1 9 13
 544280424 101484
-4294967295 0
-4294967295 0
+Expected failure 1 (no output)
+Expected failure 2 (no output)
diff --git a/test/pnmcrop3.test b/test/pnmcrop3.test
index c46fd7ea..3d32ca21 100755
--- a/test/pnmcrop3.test
+++ b/test/pnmcrop3.test
@@ -1,4 +1,4 @@
-#! /bin/bash
+#! /bin/sh
 # This script tests: pnmcrop
 # Also requires: pnmpad pamfile pgmmake
 
@@ -16,7 +16,7 @@ pnmpad -top=11 -bottom=1 -left=21 -right=9 testimg.ppm > ${test_ppm}
 pnmpad -top=4 -bottom=4 -left=8 -right=5 testgrid.pbm > ${border_pbm}
 pnmpad -top=7 -bottom=5 -left=30 -right=0 testimg.ppm > ${border_ppm}
 
-pgmmake 0.5 `pamfile -size ${test_pbm}` > ${gray_pgm}
+pgmmake 0.5 $(pamfile -size ${test_pbm}) > ${gray_pgm}
 
 # Test 1
 echo Test 1
@@ -38,7 +38,7 @@ echo Test 2
 for input_file in ${test_pbm} ${test_ppm}
   do
   echo `basename ${input_file}`
-  for margin in `seq 0 5`
+  for margin in 0 1 2 3 4 5  # for margin in `seq 0 5`
     do
     pnmcrop -reportsize -margin=${margin} ${input_file} || echo fail2
     done
@@ -59,13 +59,22 @@ pnmcrop -borderfile=${border_pbm} ${test_pbm} | pnmcrop -black -reportsize
 
 pnmcrop -borderfile=${border_ppm} ${test_ppm} | cksum 
 
-# The following two cases are expected to fai
+test_out=${tmpdir}/test_out
 
+# The following two cases are expected to fail
+
+echo "Border file size mismatch" 1>&2
 echo "Error messages should appear below the line." 1>&2
 echo "--------------------------------------------" 1>&2
 
-pnmcrop -borderfile=${border_ppm} ${test_pbm} | cksum 
-pnmcrop -borderfile=${border_pbm} ${test_ppm} | cksum 
+pnmcrop -borderfile=${border_ppm} ${test_pbm} > ${test_out} || \
+  printf "Expected failure 1 "
+  test -s ${test_out} && echo "unexpected output" || echo "(no output)"
+  rm ${test_out}
 
+pnmcrop -borderfile=${border_pbm} ${test_ppm} > ${test_out} || \
+  printf "Expected failure 2 "
+  test -s ${test_out} && echo "unexpected output" || echo "(no output)"
+  rm ${test_out}
 
-rm ${test_pbm} ${test_ppm} ${border_pbm} ${border_ppm} ${gray_pgm}
\ No newline at end of file
+rm ${test_pbm} ${test_ppm} ${border_pbm} ${border_ppm} ${gray_pgm}
diff --git a/test/pnmindex.ok b/test/pnmindex.ok
new file mode 100644
index 00000000..6155428d
--- /dev/null
+++ b/test/pnmindex.ok
@@ -0,0 +1,34 @@
+Test 1. Should print 3391481002 889
+3391481002 889
+Test 2. Should print 1998876959 5290 twice
+1998876959 5290
+1998876959 5290
+Test 3. Should print 3099638253 5290
+3099638253 5290
+Test 4. Should print 1397700642 3160
+1397700642 3160
+Test 5. Should print 243472565 28514
+243472565 28514
+Test 6. Should print 801388440 100455
+801388440 100455
+Test 7. Should print 256 twice
+256
+256
+Test 8. Should print 100 twice
+100
+100
+Test 9. Should print match
+match
+Test Invalid
+Expected failure 1 (no output)
+Expected failure 2 (no output)
+Expected failure 3 (no output)
+Expected failure 4 (no output)
+Expected failure 5 (no output)
+Expected failure 6 (no output)
+Expected failure 7 (no output)
+Expected failure 8 (no output)
+Expected failure 9 (no output)
+Expected failure 10 (no output)
+Expected failure 11 (no output)
+Expected failure 12 (no output)
diff --git a/test/pnmindex.test b/test/pnmindex.test
new file mode 100755
index 00000000..174f60bd
--- /dev/null
+++ b/test/pnmindex.test
@@ -0,0 +1,60 @@
+#! /bin/sh
+# This script tests: pnmindex
+# Also requires: pamcat pamscale pbmtext pnmcolormap pnmindex
+# Also requires: pnminvert pnmquant pnmremap
+
+tmpdir=${tmpdir:-/tmp}
+pnmindex256_ppm=${tmpdir}/pnmindex256.ppm
+
+echo "Test 1. Should print 3391481002 889"
+pnmindex maze.pbm | cksum
+
+echo "Test 2. Should print 1998876959 5290 twice"
+pnmindex maze.pbm maze.pbm maze.pbm maze.pbm maze.pbm maze.pbm | cksum
+pnmindex -noquant maze.pbm maze.pbm maze.pbm maze.pbm maze.pbm maze.pbm | cksum
+
+echo "Test 3. Should print 3099638253 5290"
+pnmindex -black maze.pbm maze.pbm maze.pbm maze.pbm maze.pbm maze.pbm | cksum
+
+echo "Test 4. Should print 1397700642 3160"
+pnmindex -size 20 -across=3 testgrid.pbm testgrid.pbm testgrid.pbm \
+         testgrid.pbm testgrid.pbm testgrid.pbm | cksum
+
+echo "Test 5. Should print 243472565 28514"
+pnmindex -noquant testimg.ppm | cksum
+
+echo "Test 6. Should print 801388440 100455"
+pnmindex -size 50 -across=2 -noquant testimg.ppm testimg.ppm testimg.ppm \
+         testimg.ppm testimg.ppm testimg.ppm | tee ${pnmindex256_ppm} | cksum
+
+echo "Test 7. Should print 256 twice"
+pnmindex testimg.ppm | ppmhist -nomap -noheader | wc -l
+pnmindex -colors 256 testimg.ppm | ppmhist -nomap -noheader | wc -l
+
+echo "Test 8. Should print 100 twice"
+pnmindex -colors 100 testimg.ppm | ppmhist -nomap -noheader | wc -l
+pnmindex -colors 100 testimg.ppm testimg.ppm | ppmhist -nomap -noheader | wc -l
+
+
+echo "Test 9. Should print match"
+pnmindex -size 50 -across=2 -quant -colors=256 testimg.ppm testimg.ppm testimg.ppm \
+         testimg.ppm testimg.ppm testimg.ppm |\
+    pnmpsnr -rgb -target1=41.31 -target2=40.76 -target3=40.71 ${pnmindex256_ppm} -
+
+
+echo "Test Invalid"
+
+. ${srcdir}/test-invalid.inc
+
+invCmd "pnmindex -size -1 testgrid.pbm"
+invCmd "pnmindex -size  0 testgrid.pbm"
+invCmd "pnmindex -size    testgrid.pbm"
+invCmd "pnmindex -across -1 testgrid.pbm"
+invCmd "pnmindex -across  0 testgrid.pbm"
+invCmd "pnmindex -across    testgrid.pbm"
+invCmd "pnmindex -colors -1 testgrid.pbm"
+invCmd "pnmindex -colors  0 testgrid.pbm"
+invCmd "pnmindex -colors    testgrid.pbm"
+invCmd "pnmindex -quant -noquant testgrid.pbm"
+invCmd "pnmindex -colors 100 -noquant testgrid.pbm"
+invCmd "pnmindex"
diff --git a/test/pnminvert-roundtrip.ok b/test/pnminvert-roundtrip.ok
index 67f7a1fe..ace97410 100644
--- a/test/pnminvert-roundtrip.ok
+++ b/test/pnminvert-roundtrip.ok
@@ -1,2 +1,2 @@
 1926073387 101484
-2425386270 41
+281226646 481
diff --git a/test/pnminvert-roundtrip.test b/test/pnminvert-roundtrip.test
index 52d15039..c0f702c2 100755
--- a/test/pnminvert-roundtrip.test
+++ b/test/pnminvert-roundtrip.test
@@ -1,7 +1,7 @@
-#! /bin/bash
+#! /bin/sh
 # This script tests: pnminvert
 # Also requires:
 
 
 pnminvert testimg.ppm | pnminvert | cksum
-pnminvert testgrid.pbm | pnminvert | cksum
+pnminvert maze.pbm | pnminvert | cksum
diff --git a/test/pnminvert.ok b/test/pnminvert.ok
index 6cf5f011..d35b30b9 100644
--- a/test/pnminvert.ok
+++ b/test/pnminvert.ok
@@ -1,7 +1,12 @@
-1240379484 41
+Test 1.  Should print 1739442872 481
+1739442872 481
+Test 2.  Should print 1416115901 101484
 1416115901 101484
+Test 3.  Should print 1174803406 33838
 1174803406 33838
+Test 4.  Should print 2595564405 14 three times
 2595564405 14
 2595564405 14
 2595564405 14
+Test 7.  Should print 2896726098 15
 2896726098 15
diff --git a/test/pnminvert.test b/test/pnminvert.test
index b80716ef..d2789bdf 100755
--- a/test/pnminvert.test
+++ b/test/pnminvert.test
@@ -1,26 +1,21 @@
-#! /bin/bash
+#! /bin/sh
 # This script tests: pnminvert
 # Also requires: pbmmake pamchannel pamtopnm
 
+echo "Test 1.  Should print 1739442872 481"
+pnminvert maze.pbm | cksum
 
-# Test 1.  Should print 1240379484 41
-pnminvert testgrid.pbm | cksum
-
-# Test 2.  Should print 1416115901 101484
+echo "Test 2.  Should print 1416115901 101484"
 pnminvert testimg.ppm | cksum
 
-# Test 3.  Should print 1174803406 33838
+echo "Test 3.  Should print 1174803406 33838"
 pamchannel -infile=testimg.ppm -tupletype="GRAYSCALE" 0 | pamtopnm | \
   pnminvert | cksum
 
-# Test 4.  Should print 2595564405 14
+echo "Test 4.  Should print 2595564405 14 three times"
 pbmmake -w 7 7 | pnminvert | cksum
-
-# Test 5.  Should print 2595564405 14
 pbmmake -b 7 7 | cksum
-
-# Test 6.  Should print 2595564405 14
 pbmmake -b 7 7 | pnminvert | pnminvert | cksum
 
-# Test 7.  Should print 2896726098 15
+echo "Test 7.  Should print 2896726098 15"
 pbmmake -g 8 8 | pnminvert | cksum
diff --git a/test/pnmpad-color.ok b/test/pnmpad-color.ok
new file mode 100644
index 00000000..91e3b264
--- /dev/null
+++ b/test/pnmpad-color.ok
@@ -0,0 +1,222 @@
+Test 1. PBM white infile
+Should print match seven times
+match
+match
+match
+match
+match
+match
+match
+Should print match seven times
+match
+match
+match
+match
+match
+match
+match
+Should print match once
+match
+Should print match once
+match
+Should print match twice
+match
+match
+Should print match twice
+match
+match
+Should print match once
+match
+Should print match twice
+match
+match
+
+Test 2. PBM black infile
+Should print match nine times
+match
+match
+match
+match
+match
+match
+match
+match
+match
+Should print match five times
+match
+match
+match
+match
+match
+
+Test 3. PGM maxval 127 infile
+Should print match five times
+match
+match
+match
+match
+match
+Should print match four times
+match
+match
+match
+match
+Should print match twice
+match
+match
+Should print match twice
+match
+match
+Should print match twice
+match
+match
+Should print match once
+match
+Should print match twice
+match
+match
+Should print match twice
+match
+match
+Should print match once
+match
+Should print match twice
+match
+match
+
+Test 4. PGM maxval 255 infile
+Should print match five times
+match
+match
+match
+match
+match
+Should print match four times
+match
+match
+match
+match
+Should print match twice
+match
+match
+Should print match twice
+match
+match
+Should print match twice
+match
+match
+Should print match once
+match
+Should print match four times
+match
+match
+match
+match
+Should print match four times
+match
+match
+match
+match
+Should print match three times
+match
+match
+match
+
+Test 5. PGM maxval 511 infile
+Should print match five times
+match
+match
+match
+match
+match
+Should print match four times
+match
+match
+match
+match
+Should print match twice
+match
+match
+Should print match twice
+match
+match
+Should print match twice
+match
+match
+Should print match once
+match
+Should print match twice
+match
+match
+Should print match twice
+match
+match
+Should print match three times
+match
+match
+match
+
+Test 6. PPM maxval 127 infile
+Should print match five times
+match
+match
+match
+match
+match
+Should print match four times
+match
+match
+match
+match
+Should print match twice
+match
+match
+Should print match twice
+match
+match
+Should print match twice
+match
+match
+Should print match once
+match
+Should print match twice
+match
+match
+Should print match twice
+match
+match
+Should print match twice
+match
+match
+
+Test 7. PPM maxval 511 infile
+Should print match five times
+match
+match
+match
+match
+match
+Should print match four times
+match
+match
+match
+match
+Should print match six times
+match
+match
+match
+match
+match
+match
+Should print match twice
+match
+match
+Should print match twice
+match
+match
+Should print match twice
+match
+match
+Should print match twice
+match
+match
diff --git a/test/pnmpad-color.test b/test/pnmpad-color.test
new file mode 100755
index 00000000..05e8acca
--- /dev/null
+++ b/test/pnmpad-color.test
@@ -0,0 +1,446 @@
+#! /bin/sh
+# This script tests: pnmpad
+# Also requires: pbmmake pgmmake ppmmake pamcut ppmtopgm
+
+tmpdir=${tmpdir:-/tmp}
+
+white_pbm=${tmpdir}/white.pbm
+black_pbm=${tmpdir}/black.pbm
+test127_pgm=${tmpdir}/testimg1.pgm
+test255_pgm=${tmpdir}/testimg2.pgm
+test511_pgm=${tmpdir}/testimg3.pgm
+test127_ppm=${tmpdir}/testimg1.ppm
+test255_ppm=${tmpdir}/testimg2.ppm
+test511_ppm=${tmpdir}/testimg3.ppm
+target_pnm=${tmpdir}/target.pnm
+
+BLACK="rgbi:0.0/0.0/0.0"
+WHITE="rgbi:1.0/1.0/1.0"
+LIGHTGRAY="rgbi:0.6/0.6/0.6"
+LIGHTGRAYv=0.6
+DARKGRAY="rgbi:0.01/0.01/0.01"
+DARKGRAYv=0.01
+PURPLE="rgb:A0/20/F0"
+YELLOW="rgb:F0/F0/00"
+
+pbmmake -w 1 1 > ${white_pbm}
+pbmmake -b 1 1 > ${black_pbm}
+pgmmake 0.25 1 1 -maxval 127 > ${test127_pgm}
+pgmmake 0.25 1 1 -maxval 255 > ${test255_pgm}
+pgmmake 0.25 1 1 -maxval 511 > ${test511_pgm}
+ppmmake ${YELLOW} 1 1 -maxval 127 > ${test127_ppm}
+ppmmake ${YELLOW} 1 1 -maxval 255 > ${test255_ppm}
+ppmmake ${YELLOW} 1 1 -maxval 511 > ${test511_ppm}
+
+ptop="-top 1"
+
+# define function
+cmptarget () { pamcut -top 0 -left 0 -height 1 -width 1 $@ |\
+                cmp -s ${target_ppm} - && echo "match" || echo "failure";  }
+
+echo "Test 1. PBM white infile"
+
+infile=${white_pbm}
+
+echo "Should print match seven times"
+
+pbmmake -w 1 1 > ${target_pnm}
+pnmpad ${ptop} -white ${infile} | cmptarget
+pnmpad ${ptop} -extend-edge ${infile} | cmptarget
+pnmpad ${ptop} -detect-background ${infile} | cmptarget
+pnmpad ${ptop} -color ${WHITE} ${infile} | cmptarget
+pnmpad ${ptop} -color ${WHITE} -promote none   ${infile} | cmptarget
+pnmpad ${ptop} -color ${WHITE} -promote format ${infile} | cmptarget
+pnmpad ${ptop} -color ${LIGHTGRAY}  -promote none   ${infile} | cmptarget
+
+echo "Should print match seven times"
+
+pbmmake -b 1 1 > ${target_pnm}
+pnmpad ${ptop} ${infile} | cmptarget
+pnmpad ${ptop} -black ${infile} | cmptarget
+pnmpad ${ptop} -color ${BLACK} ${infile} | cmptarget
+pnmpad ${ptop} -color ${BLACK} -promote none   ${infile} | cmptarget
+pnmpad ${ptop} -color ${BLACK} -promote format ${infile} | cmptarget
+pnmpad ${ptop} -color ${DARKGRAY} -promote none ${infile} | cmptarget
+pnmpad ${ptop} -color ${PURPLE}   -promote none ${infile} | cmptarget
+
+echo "Should print match once"
+
+pgmmake -maxval 1 ${LIGHTGRAYv} 1 1 > ${target_pnm}
+pnmpad ${ptop} -color ${LIGHTGRAY} -promote format ${infile} | cmptarget
+
+echo "Should print match once"
+
+pgmmake -maxval 1 ${DARKGRAYv} 1 1 > ${target_pnm}
+pnmpad ${ptop} -color ${DARKGRAY} -promote format ${infile} | cmptarget
+
+echo "Should print match twice"
+
+pgmmake -maxval 255 ${LIGHTGRAYv} 1 1 > ${target_pnm}
+pnmpad ${ptop} -color ${LIGHTGRAY} ${infile} | cmptarget
+pnmpad ${ptop} -color ${LIGHTGRAY} -promote all ${infile} | cmptarget
+
+echo "Should print match twice"
+
+pgmmake -maxval 255 ${DARKGRAYv} 1 1 > ${target_pnm}
+pnmpad ${ptop} -color ${DARKGRAY} ${infile} | cmptarget
+pnmpad ${ptop} -color ${DARKGRAY} -promote all ${infile} | cmptarget
+
+echo "Should print match once"
+
+ppmmake -maxval 1 ${PURPLE} 1 1 > ${target_pnm}
+pnmpad ${ptop} -color ${PURPLE} -promote format ${infile} | cmptarget
+
+echo "Should print match twice"
+
+ppmmake -maxval 255 ${PURPLE} 1 1 > ${target_pnm}
+pnmpad ${ptop} -color ${PURPLE} ${infile} | cmptarget
+pnmpad ${ptop} -color ${PURPLE} -promote all ${infile} | cmptarget
+
+echo
+echo "Test 2. PBM black infile"
+
+infile=${black_pbm}
+
+echo "Should print match nine times"
+
+pbmmake -b 1 1 > ${target_pnm}
+pnmpad ${ptop} ${infile} | cmptarget
+pnmpad ${ptop} -black ${infile} | cmptarget
+pnmpad ${ptop} -color ${BLACK} ${infile} | cmptarget
+pnmpad ${ptop} -color ${BLACK} -promote none   ${infile} | cmptarget
+pnmpad ${ptop} -color ${BLACK} -promote format ${infile} | cmptarget
+pnmpad ${ptop} -color ${DARKGRAY} -promote none ${infile} | cmptarget
+pnmpad ${ptop} -color ${PURPLE}   -promote none ${infile} | cmptarget
+pnmpad ${ptop} -extend-edge ${infile} | cmptarget
+pnmpad ${ptop} -detect-background ${infile} | cmptarget
+
+echo "Should print match five times"
+
+pbmmake -w 1 1 > ${target_pnm}
+pnmpad ${ptop} -white ${infile} | cmptarget
+pnmpad ${ptop} -color ${WHITE} ${infile} | cmptarget
+pnmpad ${ptop} -color ${WHITE} -promote none   ${infile} | cmptarget
+pnmpad ${ptop} -color ${WHITE} -promote format ${infile} | cmptarget
+pnmpad ${ptop} -color ${LIGHTGRAY} -promote none ${infile} | cmptarget
+
+echo
+echo "Test 3. PGM maxval 127 infile"
+
+infile=${test127_pgm}
+
+echo "Should print match five times"
+
+pgmmake -maxval 127 0.0 1 1 > ${target_pnm}
+pnmpad ${ptop} ${infile} | cmptarget
+pnmpad ${ptop} -black ${infile} | cmptarget
+pnmpad ${ptop} -color ${BLACK} ${infile} | cmptarget
+pnmpad ${ptop} -color ${BLACK} -promote none   ${infile} | cmptarget
+pnmpad ${ptop} -color ${BLACK} -promote format ${infile} | cmptarget
+
+echo "Should print match four times"
+
+pgmmake -maxval 127 1.0 1 1 > ${target_pnm}
+pnmpad ${ptop} -white ${infile} | cmptarget
+pnmpad ${ptop} -color ${WHITE} ${infile} | cmptarget
+pnmpad ${ptop} -color ${WHITE} -promote none   ${infile} | cmptarget
+pnmpad ${ptop} -color ${WHITE} -promote format ${infile} | cmptarget
+
+echo "Should print match twice"
+
+pamcut -t 0 -h 1 -w 1 ${infile} > ${target_pnm}
+pnmpad ${ptop} -extend-edge ${infile} | cmptarget
+pnmpad ${ptop} -detect-background ${infile} | cmptarget
+
+echo "Should print match twice"
+
+pgmmake -maxval 127 ${LIGHTGRAYv} 1 1 > ${target_pnm}
+pnmpad ${ptop} -color ${LIGHTGRAY} -promote none ${infile} | cmptarget
+pnmpad ${ptop} -color ${LIGHTGRAY} -promote format ${infile} | cmptarget
+
+echo "Should print match twice"
+
+pgmmake -maxval 127 ${DARKGRAYv} 1 1 > ${target_pnm}
+pnmpad ${ptop} -color ${DARKGRAY} -promote none ${infile} | cmptarget
+pnmpad ${ptop} -color ${DARKGRAY} -promote format ${infile} | cmptarget
+
+echo "Should print match once"
+
+ppmmake -maxval 127 ${PURPLE} 1 1 | ppmtopgm > ${target_pnm} 
+pnmpad ${ptop} -color ${PURPLE}   -promote none ${infile} | cmptarget
+
+echo "Should print match twice"
+
+pgmmake -maxval 255 ${LIGHTGRAYv} 1 1 > ${target_pnm}
+pnmpad ${ptop} -color ${LIGHTGRAY}              ${infile} | cmptarget
+pnmpad ${ptop} -color ${LIGHTGRAY} -promote all ${infile} | cmptarget
+
+echo "Should print match twice"
+
+pgmmake -maxval 255 ${DARKGRAYv} 1 1 > ${target_pnm}
+pnmpad ${ptop} -color ${DARKGRAY}              ${infile} | cmptarget
+pnmpad ${ptop} -color ${DARKGRAY} -promote all ${infile} | cmptarget
+
+echo "Should print match once"
+
+ppmmake -maxval 127 ${PURPLE} 1 1 > ${target_pnm}
+pnmpad ${ptop} -color ${PURPLE} -promote format ${infile} | cmptarget
+
+echo "Should print match twice"
+
+ppmmake -maxval 255 ${PURPLE} 1 1 > ${target_pnm}
+pnmpad ${ptop} -color ${PURPLE} ${infile} | cmptarget
+pnmpad ${ptop} -color ${PURPLE} -promote all    ${infile} | cmptarget
+
+
+echo
+echo "Test 4. PGM maxval 255 infile"
+
+infile=${test255_pgm}
+
+echo "Should print match five times"
+
+pgmmake -maxval 255 0.0 1 1 > ${target_pnm}
+pnmpad ${ptop} ${infile} | cmptarget
+pnmpad ${ptop} -black ${infile} | cmptarget
+pnmpad ${ptop} -color ${BLACK} ${infile} | cmptarget
+pnmpad ${ptop} -color ${BLACK} -promote none   ${infile} | cmptarget
+pnmpad ${ptop} -color ${BLACK} -promote format ${infile} | cmptarget
+
+echo "Should print match four times"
+
+pgmmake -maxval 255 1.0 1 1 > ${target_pnm}
+pnmpad ${ptop} -white ${infile} | cmptarget
+pnmpad ${ptop} -color ${WHITE} ${infile} | cmptarget
+pnmpad ${ptop} -color ${WHITE} -promote none   ${infile} | cmptarget
+pnmpad ${ptop} -color ${WHITE} -promote format ${infile} | cmptarget
+
+echo "Should print match twice"
+
+pamcut -t 0 -h 1 -w 1 ${infile} > ${target_pnm}
+pnmpad ${ptop} -extend-edge ${infile} | cmptarget
+pnmpad ${ptop} -detect-background ${infile} | cmptarget
+
+echo "Should print match twice"
+
+pgmmake -maxval 255 ${LIGHTGRAYv} 1 1 > ${target_pnm}
+pnmpad ${ptop} -color ${LIGHTGRAY} -promote none ${infile} | cmptarget
+pnmpad ${ptop} -color ${LIGHTGRAY} -promote format ${infile} | cmptarget
+
+echo "Should print match twice"
+
+pgmmake -maxval 255 ${DARKGRAYv} 1 1 > ${target_pnm}
+pnmpad ${ptop} -color ${DARKGRAY} -promote none ${infile} | cmptarget
+pnmpad ${ptop} -color ${DARKGRAY} -promote format ${infile} | cmptarget
+
+echo "Should print match once"
+
+ppmmake -maxval 255  ${PURPLE} 1 1 | ppmtopgm > ${target_pnm}
+pnmpad ${ptop} -color ${PURPLE}   -promote none ${infile} | cmptarget
+
+echo "Should print match four times"
+
+pgmmake -maxval 255 ${LIGHTGRAYv} 1 1 > ${target_pnm}
+pnmpad ${ptop} -color ${LIGHTGRAY}                 ${infile} | cmptarget
+pnmpad ${ptop} -color ${LIGHTGRAY} -promote none   ${infile} | cmptarget
+pnmpad ${ptop} -color ${LIGHTGRAY} -promote format ${infile} | cmptarget
+pnmpad ${ptop} -color ${LIGHTGRAY} -promote all    ${infile} | cmptarget
+
+echo "Should print match four times"
+
+pgmmake -maxval 255 ${DARKGRAYv} 1 1 > ${target_pnm}
+pnmpad ${ptop} -color ${DARKGRAY}                 ${infile} | cmptarget
+pnmpad ${ptop} -color ${DARKGRAY} -promote none   ${infile} | cmptarget
+pnmpad ${ptop} -color ${DARKGRAY} -promote format ${infile} | cmptarget
+pnmpad ${ptop} -color ${DARKGRAY} -promote all    ${infile} | cmptarget
+
+echo "Should print match three times"
+
+ppmmake -maxval 255 ${PURPLE} 1 1 > ${target_pnm}
+pnmpad ${ptop} -color ${PURPLE} ${infile} | cmptarget
+pnmpad ${ptop} -color ${PURPLE} -promote format ${infile} | cmptarget
+pnmpad ${ptop} -color ${PURPLE} -promote all    ${infile} | cmptarget
+
+echo
+echo "Test 5. PGM maxval 511 infile"
+
+infile=${test511_pgm}
+
+echo "Should print match five times"
+
+pgmmake -maxval 511 0.0 1 1 > ${target_pnm}
+pnmpad ${ptop} ${infile} | cmptarget
+pnmpad ${ptop} -black ${infile} | cmptarget
+pnmpad ${ptop} -color ${BLACK} ${infile} | cmptarget
+pnmpad ${ptop} -color ${BLACK} -promote none   ${infile} | cmptarget
+pnmpad ${ptop} -color ${BLACK} -promote format ${infile} | cmptarget
+
+echo "Should print match four times"
+
+pgmmake -maxval 511 1.0 1 1 > ${target_pnm}
+pnmpad ${ptop} -white ${infile} | cmptarget
+pnmpad ${ptop} -color ${WHITE} ${infile} | cmptarget
+pnmpad ${ptop} -color ${WHITE} -promote none   ${infile} | cmptarget
+pnmpad ${ptop} -color ${WHITE} -promote format ${infile} | cmptarget
+
+echo "Should print match twice"
+
+pamcut -t 0 -h 1 -w 1 ${infile} > ${target_pnm}
+pnmpad ${ptop} -extend-edge ${infile} | cmptarget
+pnmpad ${ptop} -detect-background ${infile} | cmptarget
+
+echo "Should print match twice"
+
+pgmmake -maxval 511 ${LIGHTGRAYv} 1 1 > ${target_pnm}
+pnmpad ${ptop} -color ${LIGHTGRAY} -promote none ${infile} | cmptarget
+pnmpad ${ptop} -color ${LIGHTGRAY} -promote format ${infile} | cmptarget
+
+echo "Should print match twice"
+
+pgmmake -maxval 511 ${DARKGRAYv} 1 1 > ${target_pnm}
+pnmpad ${ptop} -color ${DARKGRAY} -promote none ${infile} | cmptarget
+pnmpad ${ptop} -color ${DARKGRAY} -promote format ${infile} | cmptarget
+
+echo "Should print match once"
+
+ppmmake -maxval 511 ${PURPLE} 1 1 | ppmtopgm > ${target_pnm}
+pnmpad ${ptop} -color ${PURPLE} -promote none ${infile} | cmptarget
+
+echo "Should print match twice"
+
+pgmmake -maxval 511 ${LIGHTGRAYv} 1 1 > ${target_pnm}
+pnmpad ${ptop} -color ${LIGHTGRAY}              ${infile} | cmptarget
+pnmpad ${ptop} -color ${LIGHTGRAY} -promote all ${infile} | cmptarget
+
+echo "Should print match twice"
+
+pgmmake -maxval 511 ${DARKGRAYv} 1 1 > ${target_pnm}
+pnmpad ${ptop} -color ${DARKGRAY}              ${infile} | cmptarget
+pnmpad ${ptop} -color ${DARKGRAY} -promote all ${infile} | cmptarget
+
+echo "Should print match three times"
+
+ppmmake -maxval 511 ${PURPLE} 1 1 > ${target_pnm}
+pnmpad ${ptop} -color ${PURPLE} ${infile} | cmptarget
+pnmpad ${ptop} -color ${PURPLE} -promote format ${infile} | cmptarget
+pnmpad ${ptop} -color ${PURPLE} -promote all    ${infile} | cmptarget
+
+
+echo
+echo "Test 6. PPM maxval 127 infile"
+
+infile=${test127_ppm}
+
+echo "Should print match five times"
+
+ppmmake -maxval 127 ${BLACK} 1 1 > ${target_pnm}
+pnmpad ${ptop} ${infile} | cmptarget
+pnmpad ${ptop} -black ${infile} | cmptarget
+pnmpad ${ptop} -color ${BLACK} ${infile} | cmptarget
+pnmpad ${ptop} -color ${BLACK} -promote none   ${infile} | cmptarget
+pnmpad ${ptop} -color ${BLACK} -promote format ${infile} | cmptarget
+
+echo "Should print match four times"
+
+ppmmake -maxval 127 ${WHITE} 1 1 > ${target_pnm}
+pnmpad ${ptop} -white ${infile} | cmptarget
+pnmpad ${ptop} -color ${WHITE} ${infile} | cmptarget
+pnmpad ${ptop} -color ${WHITE} -promote none   ${infile} | cmptarget
+pnmpad ${ptop} -color ${WHITE} -promote format ${infile} | cmptarget
+
+echo "Should print match twice"
+
+ppmmake -maxval 127 ${PURPLE} 1 1 > ${target_pnm}
+ppmmake -maxval 127 ${PURPLE} 1 2 | pnmpad ${ptop} -extend-edge | cmptarget
+ppmmake -maxval 127 ${PURPLE} 1 2 | pnmpad ${ptop} -detect-background | cmptarget
+
+echo "Should print match twice"
+
+ppmmake -maxval 127 ${LIGHTGRAY} 1 1 > ${target_pnm}
+pnmpad ${ptop} -color ${LIGHTGRAY} -promote none ${infile} | cmptarget
+pnmpad ${ptop} -color ${LIGHTGRAY} -promote format ${infile} | cmptarget
+
+echo "Should print match twice"
+
+ppmmake -maxval 127 ${DARKGRAY} 1 1 > ${target_pnm}
+pnmpad ${ptop} -color ${DARKGRAY} -promote none ${infile} | cmptarget
+pnmpad ${ptop} -color ${DARKGRAY} -promote format ${infile} | cmptarget
+
+echo "Should print match once"
+
+ppmmake -maxval 127 ${PURPLE} 1 1 > ${target_pnm} 
+pnmpad ${ptop} -color ${PURPLE} -promote none ${infile} | cmptarget
+
+echo "Should print match twice"
+
+ppmmake -maxval 255 ${LIGHTGRAY} 1 1 > ${target_pnm}
+pnmpad ${ptop} -color ${LIGHTGRAY}                  ${infile} | cmptarget
+pnmpad ${ptop} -color ${LIGHTGRAY}     -promote all ${infile} | cmptarget
+
+echo "Should print match twice"
+
+ppmmake -maxval 255 ${DARKGRAY} 1 1 > ${target_pnm}
+pnmpad ${ptop} -color ${DARKGRAY}              ${infile} | cmptarget
+pnmpad ${ptop} -color ${DARKGRAY} -promote all ${infile} | cmptarget
+
+echo "Should print match twice"
+
+ppmmake -maxval 255 ${PURPLE} 1 1 > ${target_pnm}
+pnmpad ${ptop} -color ${PURPLE} ${infile} | cmptarget
+pnmpad ${ptop} -color ${PURPLE} -promote all ${infile} | cmptarget
+
+echo
+echo "Test 7. PPM maxval 511 infile"
+
+infile=${test511_ppm}
+
+echo "Should print match five times"
+
+ppmmake -maxval 511 ${BLACK} 1 1 > ${target_pnm}
+pnmpad ${ptop} ${infile} | cmptarget
+pnmpad ${ptop} -black ${infile} | cmptarget
+pnmpad ${ptop} -color ${BLACK} ${infile} | cmptarget
+pnmpad ${ptop} -color ${BLACK} -promote none   ${infile} | cmptarget
+pnmpad ${ptop} -color ${BLACK} -promote format ${infile} | cmptarget
+
+echo "Should print match four times"
+
+ppmmake -maxval 511 ${WHITE} 1 1 > ${target_pnm}
+pnmpad ${ptop} -white ${infile} | cmptarget
+pnmpad ${ptop} -color ${WHITE} ${infile} | cmptarget
+pnmpad ${ptop} -color ${WHITE} -promote none   ${infile} | cmptarget
+pnmpad ${ptop} -color ${WHITE} -promote format ${infile} | cmptarget
+
+echo "Should print match six times"
+
+ppmmake -maxval 511 ${PURPLE} 1 1 > ${target_pnm}
+ppmmake -maxval 511 ${PURPLE} 1 5 | pnmpad ${ptop} -extend-edge | cmptarget
+ppmmake -maxval 511 ${PURPLE} 1 5 | pnmpad ${ptop} -detect-background | cmptarget
+pnmpad ${ptop} -color ${PURPLE} ${infile} | cmptarget
+pnmpad ${ptop} -color ${PURPLE} -promote none ${infile} | cmptarget
+pnmpad ${ptop} -color ${PURPLE} -promote format ${infile} | cmptarget
+pnmpad ${ptop} -color ${PURPLE} -promote all    ${infile} | cmptarget
+
+echo "Should print match twice"
+
+ppmmake -maxval 511 ${LIGHTGRAY} 1 1 > ${target_pnm}
+pnmpad ${ptop} -color ${LIGHTGRAY} -promote none ${infile} | cmptarget
+pnmpad ${ptop} -color ${LIGHTGRAY} -promote format ${infile} | cmptarget
+
+echo "Should print match twice"
+
+ppmmake -maxval 511 ${DARKGRAY} 1 1 > ${target_pnm}
+pnmpad ${ptop} -color ${DARKGRAY} -promote none ${infile} | cmptarget
+pnmpad ${ptop} -color ${DARKGRAY} -promote format ${infile} | cmptarget
+
+echo "Should print match twice"
+
+ppmmake -maxval 511 ${LIGHTGRAY} 1 1 > ${target_pnm}
+pnmpad ${ptop} -color ${LIGHTGRAY}                  ${infile} | cmptarget
+pnmpad ${ptop} -color ${LIGHTGRAY}     -promote all ${infile} | cmptarget
+
+echo "Should print match twice"
+
+ppmmake -maxval 511 ${DARKGRAY} 1 1 > ${target_pnm}
+pnmpad ${ptop} -color ${DARKGRAY}              ${infile} | cmptarget
+pnmpad ${ptop} -color ${DARKGRAY} -promote all ${infile} | cmptarget
diff --git a/test/pnmpad-extend-enlarge.ok b/test/pnmpad-extend-enlarge.ok
new file mode 100644
index 00000000..d1539022
--- /dev/null
+++ b/test/pnmpad-extend-enlarge.ok
@@ -0,0 +1,163 @@
+Test 1.  Should print match forty-eight (24x2) times
+match
+match
+match
+match
+match
+match
+match
+match
+match
+match
+match
+match
+match
+match
+match
+match
+match
+match
+match
+match
+match
+match
+match
+match
+match
+match
+match
+match
+match
+match
+match
+match
+match
+match
+match
+match
+match
+match
+match
+match
+match
+match
+match
+match
+match
+match
+match
+match
+Test 2.  Should print match thirty-six (18x2) times
+match
+match
+match
+match
+match
+match
+match
+match
+match
+match
+match
+match
+match
+match
+match
+match
+match
+match
+match
+match
+match
+match
+match
+match
+match
+match
+match
+match
+match
+match
+match
+match
+match
+match
+match
+match
+Test 3.  Should print match twenty-four (4x6) times
+match
+match
+match
+match
+match
+match
+match
+match
+match
+match
+match
+match
+match
+match
+match
+match
+match
+match
+match
+match
+match
+match
+match
+match
+Test 4.  Should print match eighteen (3x6) times
+match
+match
+match
+match
+match
+match
+match
+match
+match
+match
+match
+match
+match
+match
+match
+match
+match
+match
+Test 5.  Should print match thirty-two (8x4) times
+match
+match
+match
+match
+match
+match
+match
+match
+match
+match
+match
+match
+match
+match
+match
+match
+match
+match
+match
+match
+match
+match
+match
+match
+match
+match
+match
+match
+match
+match
+match
+match
diff --git a/test/pnmpad-extend-enlarge.test b/test/pnmpad-extend-enlarge.test
new file mode 100755
index 00000000..fde609a6
--- /dev/null
+++ b/test/pnmpad-extend-enlarge.test
@@ -0,0 +1,177 @@
+#! /bin/sh
+# This script tests: pnmpad pamenlarge
+# Also requires: pamcat pamcut pamenlarge pbmmake pbmnoise pgmmake pgmnoise
+# Also requires: ppmmake ppmpat
+
+# If the padding function for -extend-edge is altered, make sure to run this
+# test in a more thorough form.  Replace "for leftpad in 0 1 7 9 16"
+# with "for leftpad in `seq 0 16`".
+
+tmpdir=${tmpdir:-/tmp}
+test_pnm=${tmpdir}/test.pnm
+
+padded_pnm=${tmpdir}/padded.pnm
+#middle_pnm=${tmpdir}/middle.pnm
+left_pnm=${tmpdir}/left.pnm
+right_pnm=${tmpdir}/right.pnm
+top_pnm=${tmpdir}/top.pnm
+bottom_pnm=${tmpdir}/bottom.pnm
+
+echo "Test 1.  Should print match forty-eight (24x2) times"
+
+for generator in "pbmnoise -randomseed=100 17 17" \
+                 "ppmpat -tartan -randomseed=100 11 11"          
+    do
+    ${generator} > ${test_pnm}
+    for leftpad in 0 1 7 9 16
+    do
+        for rightpad in  0 1 8
+        do
+            pnmpad -extend-edge -l=${leftpad} -r=${rightpad} ${test_pnm} > ${padded_pnm}
+            pamcut -left=0 -width=1 ${test_pnm} |\
+                pamenlarge -xscale=$(( ${leftpad} + 1 )) > ${left_pnm}
+            pamcut -right=-1 -width=1  ${test_pnm} |\
+                pamenlarge -xscale=$(( ${rightpad} + 1 )) > ${right_pnm}
+            pamcut -cropleft=1 -cropright=1 ${test_pnm} |\
+                pamcat -lr ${left_pnm} - ${right_pnm} |\
+                cmp -s - ${padded_pnm} && echo "match" ||\
+                    echo "no match: lr ${generator} ${leftpad} ${rightpad}";
+            rm ${left_pnm} ${right_pnm} ${padded_pnm}
+        done
+    done
+    
+    for toppad in 0 2 5
+    do
+        for bottompad in  0 1 10
+        do
+            pnmpad -extend-edge -t=${toppad} -b=${bottompad} ${test_pnm} > ${padded_pnm}
+            pamcut -top=0 -height=1 ${test_pnm} |\
+                pamenlarge -yscale=$(( ${toppad} + 1 )) > ${top_pnm}
+            pamcut -bottom=-1 -height=1  ${test_pnm} |\
+                pamenlarge -yscale=$(( ${bottompad} + 1 )) > ${bottom_pnm}
+            pamcut -croptop=1 -cropbottom=1 ${test_pnm} |\
+            pamcat -tb ${top_pnm} - ${bottom_pnm} |\
+                cmp -s - ${padded_pnm} && echo "match" ||\
+                    echo "no match: tb ${generator} ${toppad} ${bottompad}";
+            rm ${top_pnm} ${bottom_pnm} ${padded_pnm}
+        done
+    done
+    rm ${test_pnm}
+done
+
+
+echo "Test 2.  Should print match thirty-six (18x2) times"
+
+for generator in "pbmnoise -randomseed=100 17 17" \
+                 "ppmpat -tartan -randomseed=100 11 11"
+    do
+    ${generator} > ${test_pnm}
+    for leftpad in 0 1 2
+    do
+        for rightpad in  0 1 3
+        do
+            pnmpad -extend-edge -l=${leftpad} -r=${rightpad} ${test_pnm} > ${padded_pnm}
+            pamcut -left=0 -width=1 ${test_pnm} |\
+                pamenlarge -xscale=$(( ${leftpad} + 1 )) > ${left_pnm}
+            pamcut -right=-1 -width=1  ${test_pnm} |\
+                pamenlarge -xscale=$(( ${rightpad} + 1 )) > ${right_pnm}
+            pamcut -cropleft=1 -cropright=1 ${test_pnm} |\
+                pamcat -lr ${left_pnm} - ${right_pnm} |\
+                cmp -s - ${padded_pnm} && echo "match" ||\
+                    echo "no match: lr ${generator} ${leftpad} ${rightpad}";
+            rm ${left_pnm} ${right_pnm} ${padded_pnm}
+        done
+    done
+    
+    for toppad in 0 1 12
+    do
+        for bottompad in 0 1 5
+        do
+            pnmpad -extend-edge -t=${toppad} -b=${bottompad} ${test_pnm} > ${padded_pnm}
+            pamcut -top=0 -height=1 ${test_pnm} |\
+                pamenlarge -yscale=$(( ${toppad} + 1 )) > ${top_pnm}
+            pamcut -bottom=-1 -height=1  ${test_pnm} |\
+                pamenlarge -yscale=$(( ${bottompad} + 1 )) > ${bottom_pnm}
+            pamcut -croptop=1 -cropbottom=1 ${test_pnm} |\
+                pamcat -tb ${top_pnm} - ${bottom_pnm} |\
+                cmp -s - ${padded_pnm} && echo "match" ||\
+                    echo "no match: tb ${generator} ${toppad} ${bottompad}";
+            rm ${top_pnm} ${bottom_pnm} ${padded_pnm}
+        done
+    done
+    rm ${test_pnm}
+done
+
+
+echo "Test 3.  Should print match twenty-four (4x6) times"
+
+stretch_pnm=${tmpdir}/stretch.pnm
+
+for generator in "pbmmake -b 1 1" \
+                 "pbmmake -b 1 11" \
+                 "pbmmake -w 1 1" \
+                 "pbmmake -w 1 8" \
+                 "pbmnoise -randomseed=100 1 17" \
+                 "pgmnoise -randomseed=100 1 12"                 
+    do
+        ${generator} > ${test_pnm}
+     pamenlarge -xscale=17 ${test_pnm} > ${stretch_pnm} 
+        
+    for leftpad in 0 1 7 16
+    do
+        pnmpad -extend-edge -l=${leftpad} -r=$((16 - ${leftpad})) ${test_pnm} |\
+                cmp -s - ${stretch_pnm} && echo "match" ||\
+                    echo "no match: ${generator} ${leftpad}";
+    done
+    rm ${stretch_pnm} ${test_pnm}
+done
+
+
+echo "Test 4.  Should print match eighteen (3x6) times"
+
+stretch_pnm=${tmpdir}/stretch.pnm
+
+for generator in "pbmmake -b 1 1" \
+                 "pbmmake -b 8 1" \
+                 "pbmmake -w 1 1" \
+                 "pbmmake -w 3 1" \
+                 "pbmnoise -randomseed=100 17 1" \
+                 "pgmnoise -randomseed=100 8 1"          
+    do
+        ${generator} > ${test_pnm}
+     pamenlarge -yscale=15 ${test_pnm} > ${stretch_pnm} 
+        
+    for toppad in  0 1 14
+    do
+        pnmpad -extend-edge -t=${toppad} -b=$((14 - ${toppad})) ${test_pnm} |\
+                cmp -s - ${stretch_pnm} && echo "match" ||\
+                    echo "no match: ${generator} ${toppad}";
+    done
+    rm ${stretch_pnm} ${test_pnm}
+done
+
+
+echo "Test 5.  Should print match thirty-two (8x4) times"
+
+stretch_pnm=${tmpdir}/stretch.pnm
+
+for generator in "pbmmake -b 1 1" \
+                 "pbmmake -w 1 1" \
+                 "pgmmake 0.3 1 1" \
+                 "ppmmake rgbi:0.5/0.3/0.8 1 1"
+    do
+        ${generator} > ${test_pnm}
+        pamenlarge -xscale=66 -yscale=10 ${test_pnm} > ${stretch_pnm}
+        
+    for toppad in  0 8
+    do
+    for leftpad in  0 1 15 64
+    do
+        pnmpad -extend-edge -t=${toppad} -b=$((9 - ${toppad})) \
+         -l=${leftpad} -r=$((65 - ${leftpad})) ${test_pnm} |\
+                cmp -s - ${stretch_pnm} && echo "match" ||\
+                echo "no match: ${generator} ${toppad} ${leftpad}"
+    done
+    done
+    rm ${stretch_pnm} ${test_pnm}
+done
diff --git a/test/pnmpad-flip.ok b/test/pnmpad-flip.ok
new file mode 100644
index 00000000..af596ad3
--- /dev/null
+++ b/test/pnmpad-flip.ok
@@ -0,0 +1,64 @@
+Test 1.  Should print match sixteen (8x2) times
+(pbmnoise -randomseed=100 11 16)
+match
+match
+match
+match
+match
+match
+match
+match
+(pgmnoise -randomseed=100 31 41)
+match
+match
+match
+match
+match
+match
+match
+match
+Test 2.  Should print match forty (10x4) times
+(pbmmake -b 1 1)
+match
+match
+match
+match
+match
+match
+match
+match
+match
+match
+(pbmmake -w 1 1)
+match
+match
+match
+match
+match
+match
+match
+match
+match
+match
+(pbmmake -g 17 11)
+match
+match
+match
+match
+match
+match
+match
+match
+match
+match
+(ppmpat -argyle1 -randomseed=100 7 8)
+match
+match
+match
+match
+match
+match
+match
+match
+match
+match
diff --git a/test/pnmpad-flip.test b/test/pnmpad-flip.test
new file mode 100755
index 00000000..2013874c
--- /dev/null
+++ b/test/pnmpad-flip.test
@@ -0,0 +1,62 @@
+#! /bin/sh
+# This script tests: pnmpad
+# Also requires: pamflip pbmmake pbmnoise pgmnoise ppmpat
+
+# If any of the padding functions is altered, make sure to run this
+# test in a more thorough form.  Try more input images and more
+# values of d0, d1, d2, d3.
+
+tmpdir=${tmpdir:-/tmp}
+test_pnm=${tmpdir}/test.pnm
+padded_pnm=${tmpdir}/padded.pnm
+
+echo "Test 1.  Should print match sixteen (8x2) times"
+
+d0=1; d1=11; d2=10; d3=5;
+
+for generator in "pbmnoise -randomseed=100 11 16" \
+                 "pgmnoise -randomseed=100 31 41"
+    do
+    ${generator} > ${test_pnm}
+    echo "("${generator}")"
+    for method in "-black" "-white" "-color rgb:20/30/e0" "-extend-edge"
+    do
+      pnmpad ${method} -t ${d0} -r ${d1} -b ${d2} -l ${d3} ${test_pnm} > ${padded_pnm}
+
+      pamflip -lr ${test_pnm} |\
+        pnmpad ${method} -t ${d0} -l ${d1} -b ${d2} -r ${d3} | pamflip -lr |\
+        cmp -s ${padded_pnm} - && echo "match" || echo "no match"
+
+      pamflip -r90 ${test_pnm} |\
+         pnmpad ${method} -l ${d0} -t ${d1} -r ${d2} -b ${d3} | pamflip -r270 |\
+         cmp -s ${padded_pnm} - && echo "match" || echo "no match"
+
+    done
+done
+
+echo "Test 2.  Should print match forty (10x4) times"
+
+# Test images with all corners with the same colors
+
+for generator in "pbmmake -b 1 1" \
+                 "pbmmake -w 1 1" \
+                 "pbmmake -g 17 11" \
+                 "ppmpat -argyle1 -randomseed=100 7 8"
+    do
+    ${generator} > ${test_pnm}
+    echo "("${generator}")"
+    for method in "-black" "-white" "-color rgb:20/30/e0 -promote none" \
+                  "-detect-background" "-extend-edge"
+    do
+      pnmpad ${method} -t ${d0} -r ${d1} -b ${d2} -l ${d3} ${test_pnm} > ${padded_pnm}
+
+      pamflip -lr ${test_pnm} |\
+        pnmpad ${method} -t ${d0} -l ${d1} -b ${d2} -r ${d3} | pamflip -lr |\
+        cmp -s ${padded_pnm} - && echo "match" || echo "no match"
+
+      pamflip -r90 ${test_pnm} |\
+         pnmpad ${method} -l ${d0} -t ${d1} -r ${d2} -b ${d3} | pamflip -r270 |\
+         cmp -s ${padded_pnm} - && echo "match" || echo "no match"
+
+    done
+done
diff --git a/test/pnmpad-format.ok b/test/pnmpad-format.ok
new file mode 100644
index 00000000..9938a170
--- /dev/null
+++ b/test/pnmpad-format.ok
@@ -0,0 +1,135 @@
+Test 1. PBM infile
+Should print: PBM raw, 8 by 1 fourteen times
+stdin:	PBM raw, 8 by 1
+stdin:	PBM raw, 8 by 1
+stdin:	PBM raw, 8 by 1
+stdin:	PBM raw, 8 by 1
+stdin:	PBM raw, 8 by 1
+stdin:	PBM raw, 8 by 1
+stdin:	PBM raw, 8 by 1
+stdin:	PBM raw, 8 by 1
+stdin:	PBM raw, 8 by 1
+stdin:	PBM raw, 8 by 1
+stdin:	PBM raw, 8 by 1
+stdin:	PBM raw, 8 by 1
+stdin:	PBM raw, 8 by 1
+stdin:	PBM raw, 8 by 1
+Should print: PGM raw, 8 by 1  maxval 1 twice
+stdin:	PGM raw, 8 by 1  maxval 1
+stdin:	PGM raw, 8 by 1  maxval 1
+Should print: PGM raw, 8 by 1  maxval 255 twice
+stdin:	PGM raw, 8 by 1  maxval 255
+stdin:	PGM raw, 8 by 1  maxval 255
+Should print: PPM raw, 8 by 1  maxval 1 once
+stdin:	PPM raw, 8 by 1  maxval 1
+Should print: PPM raw, 8 by 1  maxval 255 twice
+stdin:	PPM raw, 8 by 1  maxval 255
+stdin:	PPM raw, 8 by 1  maxval 255
+
+Test 2. PGM maxval 127 infile
+Should print: PGM raw, 8 by 1  maxval 127 sixteen times
+stdin:	PGM raw, 8 by 1  maxval 127
+stdin:	PGM raw, 8 by 1  maxval 127
+stdin:	PGM raw, 8 by 1  maxval 127
+stdin:	PGM raw, 8 by 1  maxval 127
+stdin:	PGM raw, 8 by 1  maxval 127
+stdin:	PGM raw, 8 by 1  maxval 127
+stdin:	PGM raw, 8 by 1  maxval 127
+stdin:	PGM raw, 8 by 1  maxval 127
+stdin:	PGM raw, 8 by 1  maxval 127
+stdin:	PGM raw, 8 by 1  maxval 127
+stdin:	PGM raw, 8 by 1  maxval 127
+stdin:	PGM raw, 8 by 1  maxval 127
+stdin:	PGM raw, 8 by 1  maxval 127
+stdin:	PGM raw, 8 by 1  maxval 127
+stdin:	PGM raw, 8 by 1  maxval 127
+stdin:	PGM raw, 8 by 1  maxval 127
+Should print: PGM raw, 8 by 1  maxval 255 four times
+stdin:	PGM raw, 8 by 1  maxval 255
+stdin:	PGM raw, 8 by 1  maxval 255
+stdin:	PGM raw, 8 by 1  maxval 255
+stdin:	PGM raw, 8 by 1  maxval 255
+Should print: PPM raw, 8 by 1  maxval 127 once
+stdin:	PPM raw, 8 by 1  maxval 127
+Should print: PPM raw, 8 by 1  maxval 255 twice
+stdin:	PPM raw, 8 by 1  maxval 255
+stdin:	PPM raw, 8 by 1  maxval 255
+
+Test 3. PGM maxval 255 infile
+Should print: PGM raw, 8 by 1  maxval 255 eighteen times
+stdin:	PGM raw, 8 by 1  maxval 255
+stdin:	PGM raw, 8 by 1  maxval 255
+stdin:	PGM raw, 8 by 1  maxval 255
+stdin:	PGM raw, 8 by 1  maxval 255
+stdin:	PGM raw, 8 by 1  maxval 255
+stdin:	PGM raw, 8 by 1  maxval 255
+stdin:	PGM raw, 8 by 1  maxval 255
+stdin:	PGM raw, 8 by 1  maxval 255
+stdin:	PGM raw, 8 by 1  maxval 255
+stdin:	PGM raw, 8 by 1  maxval 255
+stdin:	PGM raw, 8 by 1  maxval 255
+stdin:	PGM raw, 8 by 1  maxval 255
+stdin:	PGM raw, 8 by 1  maxval 255
+stdin:	PGM raw, 8 by 1  maxval 255
+stdin:	PGM raw, 8 by 1  maxval 255
+stdin:	PGM raw, 8 by 1  maxval 255
+stdin:	PGM raw, 8 by 1  maxval 255
+stdin:	PGM raw, 8 by 1  maxval 255
+Should print: PPM raw, 8 by 1  maxval 255 three times
+stdin:	PPM raw, 8 by 1  maxval 255
+stdin:	PPM raw, 8 by 1  maxval 255
+stdin:	PPM raw, 8 by 1  maxval 255
+
+Test 4. PPM maxval 127 infile
+Should print: PPM raw, 8 by 1  maxval 127 seventeen times
+stdin:	PPM raw, 8 by 1  maxval 127
+stdin:	PPM raw, 8 by 1  maxval 127
+stdin:	PPM raw, 8 by 1  maxval 127
+stdin:	PPM raw, 8 by 1  maxval 127
+stdin:	PPM raw, 8 by 1  maxval 127
+stdin:	PPM raw, 8 by 1  maxval 127
+stdin:	PPM raw, 8 by 1  maxval 127
+stdin:	PPM raw, 8 by 1  maxval 127
+stdin:	PPM raw, 8 by 1  maxval 127
+stdin:	PPM raw, 8 by 1  maxval 127
+stdin:	PPM raw, 8 by 1  maxval 127
+stdin:	PPM raw, 8 by 1  maxval 127
+stdin:	PPM raw, 8 by 1  maxval 127
+stdin:	PPM raw, 8 by 1  maxval 127
+stdin:	PPM raw, 8 by 1  maxval 127
+stdin:	PPM raw, 8 by 1  maxval 127
+stdin:	PPM raw, 8 by 1  maxval 127
+Should print: PPM raw, 8 by 1  maxval 255 five times
+stdin:	PPM raw, 8 by 1  maxval 255
+stdin:	PPM raw, 8 by 1  maxval 255
+stdin:	PPM raw, 8 by 1  maxval 255
+stdin:	PPM raw, 8 by 1  maxval 255
+stdin:	PPM raw, 8 by 1  maxval 255
+
+Test 5. PPM maxval 511 infile
+Should print: PPM raw, 8 by 1  maxval 511 twenty-five times
+stdin:	PPM raw, 8 by 1  maxval 511
+stdin:	PPM raw, 8 by 1  maxval 511
+stdin:	PPM raw, 8 by 1  maxval 511
+stdin:	PPM raw, 8 by 1  maxval 511
+stdin:	PPM raw, 8 by 1  maxval 511
+stdin:	PPM raw, 8 by 1  maxval 511
+stdin:	PPM raw, 8 by 1  maxval 511
+stdin:	PPM raw, 8 by 1  maxval 511
+stdin:	PPM raw, 8 by 1  maxval 511
+stdin:	PPM raw, 8 by 1  maxval 511
+stdin:	PPM raw, 8 by 1  maxval 511
+stdin:	PPM raw, 8 by 1  maxval 511
+stdin:	PPM raw, 8 by 1  maxval 511
+stdin:	PPM raw, 8 by 1  maxval 511
+stdin:	PPM raw, 8 by 1  maxval 511
+stdin:	PPM raw, 8 by 1  maxval 511
+stdin:	PPM raw, 8 by 1  maxval 511
+stdin:	PPM raw, 8 by 1  maxval 511
+stdin:	PPM raw, 8 by 1  maxval 511
+stdin:	PPM raw, 8 by 1  maxval 511
+stdin:	PPM raw, 8 by 1  maxval 511
+stdin:	PPM raw, 8 by 1  maxval 511
+stdin:	PPM raw, 8 by 1  maxval 511
+stdin:	PPM raw, 8 by 1  maxval 511
+stdin:	PPM raw, 8 by 1  maxval 511
diff --git a/test/pnmpad-format.test b/test/pnmpad-format.test
new file mode 100755
index 00000000..73ea6d2b
--- /dev/null
+++ b/test/pnmpad-format.test
@@ -0,0 +1,245 @@
+#! /bin/sh
+# This script tests: pnmpad
+# Also requires: pbmmake pgmmake ppmmake pamfile
+
+tmpdir=${tmpdir:-/tmp}
+
+white_pbm=${tmpdir}/white.pbm
+#black_pbm=${tmpdir}/black.pbm
+test127_pgm=${tmpdir}/testimg1.pgm
+test255_pgm=${tmpdir}/testimg2.pgm
+test511_pgm=${tmpdir}/testimg3.pgm
+test127_ppm=${tmpdir}/testimg1.ppm
+test255_ppm=${tmpdir}/testimg2.ppm
+test511_ppm=${tmpdir}/testimg3.ppm
+
+BLACK="rgbi:0.0/0.0/0.0"
+WHITE="rgbi:1.0/1.0/1.0"
+LIGHTGRAY="rgbi:0.6/0.6/0.6"
+LIGHTGRAYv=0.6
+DARKGRAY="rgbi:0.01/0.01/0.01"
+DARKGRAYv=0.01
+PURPLE="rgb:A0/20/F0"
+YELLOW="rgb:FF/FF/00"
+
+pbmmake -w 3 1 > ${white_pbm}
+#pbmmake -b 3 1 > ${black_pbm}
+pgmmake 0.2 3 1 -maxval 127 > ${test127_pgm}
+pgmmake 0.2 3 1 -maxval 255 > ${test255_pgm}
+ppmmake ${YELLOW} 3 1 -maxval 127 > ${test127_ppm}
+ppmmake ${YELLOW} 3 1 -maxval 511 > ${test511_ppm}
+
+# define function
+ckfmt() { pamfile || echo "failure"; }
+
+size="-width 8"
+
+echo "Test 1. PBM infile"
+
+infile=${white_pbm}
+
+echo "Should print: PBM raw, 8 by 1 fourteen times"
+
+pnmpad ${size} ${infile} | ckfmt
+pnmpad ${size} -black ${infile} | ckfmt
+pnmpad ${size} -white ${infile} | ckfmt
+pnmpad ${size} -extend-edge ${infile} | ckfmt
+pnmpad ${size} -detect-background ${infile} | ckfmt
+
+pnmpad ${size} -color ${BLACK} ${infile} | ckfmt
+pnmpad ${size} -color ${BLACK} -promote none   ${infile} | ckfmt
+pnmpad ${size} -color ${BLACK} -promote format ${infile} | ckfmt
+
+pnmpad ${size} -color ${WHITE} ${infile} | ckfmt
+pnmpad ${size} -color ${WHITE} -promote none   ${infile} | ckfmt
+pnmpad ${size} -color ${WHITE} -promote format ${infile} | ckfmt
+
+pnmpad ${size} -color ${LIGHTGRAY} -promote none ${infile} | ckfmt
+pnmpad ${size} -color ${DARKGRAY} -promote none ${infile} | ckfmt
+pnmpad ${size} -color ${PURPLE}   -promote none ${infile} | ckfmt
+
+echo "Should print: PGM raw, 8 by 1  maxval 1 twice"
+
+pnmpad ${size} -color ${LIGHTGRAY} -promote format ${infile} | ckfmt
+pnmpad ${size} -color ${DARKGRAY} -promote format ${infile} | ckfmt
+
+echo "Should print: PGM raw, 8 by 1  maxval 255 twice"
+
+pnmpad ${size} -color ${LIGHTGRAY} ${infile} | ckfmt
+pnmpad ${size} -color ${DARKGRAY} ${infile} | ckfmt
+
+echo "Should print: PPM raw, 8 by 1  maxval 1 once"
+
+pnmpad ${size} -color ${PURPLE} -promote format ${infile} | ckfmt
+
+echo "Should print: PPM raw, 8 by 1  maxval 255 twice"
+
+pnmpad ${size} -color ${PURPLE} ${infile} | ckfmt
+pnmpad ${size} -color ${PURPLE} -promote all ${infile} | ckfmt
+
+rm ${infile}
+
+echo
+echo "Test 2. PGM maxval 127 infile"
+
+infile=${test127_pgm}
+
+echo "Should print: PGM raw, 8 by 1  maxval 127 sixteen times"
+
+pnmpad ${size} ${infile} | ckfmt
+pnmpad ${size} -black ${infile} | ckfmt
+pnmpad ${size} -white ${infile} | ckfmt
+pnmpad ${size} -extend-edge ${infile} | ckfmt
+pnmpad ${size} -detect-background ${infile} | ckfmt
+
+pnmpad ${size} -color ${BLACK} ${infile} | ckfmt
+pnmpad ${size} -color ${BLACK} -promote none   ${infile} | ckfmt
+pnmpad ${size} -color ${BLACK} -promote format ${infile} | ckfmt
+
+pnmpad ${size} -color ${WHITE} ${infile} | ckfmt
+pnmpad ${size} -color ${WHITE} -promote none   ${infile} | ckfmt
+pnmpad ${size} -color ${WHITE} -promote format ${infile} | ckfmt
+
+pnmpad ${size} -color ${LIGHTGRAY} -promote none ${infile} | ckfmt
+pnmpad ${size} -color ${LIGHTGRAY} -promote format ${infile} | ckfmt
+
+pnmpad ${size} -color ${DARKGRAY} -promote none ${infile} | ckfmt
+pnmpad ${size} -color ${DARKGRAY} -promote format ${infile} | ckfmt
+
+pnmpad ${size} -color ${PURPLE}   -promote none ${infile} | ckfmt
+
+echo "Should print: PGM raw, 8 by 1  maxval 255 four times"
+
+pnmpad ${size} -color ${LIGHTGRAY}              ${infile} | ckfmt
+pnmpad ${size} -color ${LIGHTGRAY} -promote all ${infile} | ckfmt
+pnmpad ${size} -color ${DARKGRAY}               ${infile} | ckfmt
+pnmpad ${size} -color ${DARKGRAY}  -promote all ${infile} | ckfmt
+
+echo "Should print: PPM raw, 8 by 1  maxval 127 once"
+
+pnmpad ${size} -color ${PURPLE} -promote format ${infile} | ckfmt
+
+echo "Should print: PPM raw, 8 by 1  maxval 255 twice"
+
+pnmpad ${size} -color ${PURPLE} ${infile} | ckfmt
+pnmpad ${size} -color ${PURPLE} -promote all ${infile} | ckfmt
+
+rm ${infile}
+
+echo
+echo "Test 3. PGM maxval 255 infile"
+
+infile=${test255_pgm}
+
+echo "Should print: PGM raw, 8 by 1  maxval 255 eighteen times"
+
+pnmpad ${size} ${infile} | ckfmt
+pnmpad ${size} -black ${infile} | ckfmt
+pnmpad ${size} -white ${infile} | ckfmt
+pnmpad ${size} -extend-edge ${infile} | ckfmt
+pnmpad ${size} -detect-background ${infile} | ckfmt
+
+pnmpad ${size} -color ${BLACK} ${infile} | ckfmt
+pnmpad ${size} -color ${BLACK} -promote none   ${infile} | ckfmt
+pnmpad ${size} -color ${BLACK} -promote format ${infile} | ckfmt
+pnmpad ${size} -color ${BLACK} -promote all    ${infile} | ckfmt
+
+pnmpad ${size} -color ${LIGHTGRAY} ${infile} | ckfmt
+pnmpad ${size} -color ${LIGHTGRAY} -promote none   ${infile} | ckfmt
+pnmpad ${size} -color ${LIGHTGRAY} -promote format ${infile} | ckfmt
+pnmpad ${size} -color ${LIGHTGRAY} -promote all    ${infile} | ckfmt
+
+
+pnmpad ${size} -color ${DARKGRAY} ${infile} | ckfmt
+pnmpad ${size} -color ${DARKGRAY} -promote none   ${infile} | ckfmt
+pnmpad ${size} -color ${DARKGRAY} -promote format ${infile} | ckfmt
+pnmpad ${size} -color ${DARKGRAY} -promote all    ${infile} | ckfmt
+
+pnmpad ${size} -color ${PURPLE}   -promote none   ${infile} | ckfmt
+
+echo "Should print: PPM raw, 8 by 1  maxval 255 three times"
+
+pnmpad ${size} -color ${PURPLE} ${infile} | ckfmt
+
+pnmpad ${size} -color ${PURPLE} -promote format ${infile} | ckfmt
+pnmpad ${size} -color ${PURPLE} -promote all    ${infile} | ckfmt
+
+rm ${infile}
+
+echo
+echo "Test 4. PPM maxval 127 infile"
+
+infile=${test127_ppm}
+
+echo "Should print: PPM raw, 8 by 1  maxval 127 seventeen times"
+
+pnmpad ${size} ${infile} | ckfmt
+pnmpad ${size} -black ${infile} | ckfmt
+pnmpad ${size} -white ${infile} | ckfmt
+pnmpad ${size} -extend-edge ${infile} | ckfmt
+pnmpad ${size} -detect-background ${infile} | ckfmt
+
+pnmpad ${size} -color ${BLACK} ${infile} | ckfmt
+pnmpad ${size} -color ${BLACK} -promote none   ${infile} | ckfmt
+pnmpad ${size} -color ${BLACK} -promote format ${infile} | ckfmt
+pnmpad ${size} -color ${WHITE} ${infile} | ckfmt
+pnmpad ${size} -color ${WHITE} -promote none   ${infile} | ckfmt
+pnmpad ${size} -color ${WHITE} -promote format ${infile} | ckfmt
+
+pnmpad ${size} -color ${LIGHTGRAY} -promote none   ${infile} | ckfmt
+pnmpad ${size} -color ${LIGHTGRAY} -promote format ${infile} | ckfmt
+pnmpad ${size} -color ${DARKGRAY} -promote none   ${infile} | ckfmt
+pnmpad ${size} -color ${DARKGRAY} -promote format ${infile} | ckfmt
+
+pnmpad ${size} -color ${PURPLE} -promote none   ${infile} | ckfmt
+pnmpad ${size} -color ${PURPLE} -promote format ${infile} | ckfmt
+
+echo "Should print: PPM raw, 8 by 1  maxval 255 five times"
+
+pnmpad ${size} -color ${LIGHTGRAY} ${infile} | ckfmt
+pnmpad ${size} -color ${DARKGRAY}  ${infile} | ckfmt
+pnmpad ${size} -color ${PURPLE}    ${infile} | ckfmt
+pnmpad ${size} -color ${LIGHTGRAY} -promote all ${infile} | ckfmt
+pnmpad ${size} -color ${PURPLE}    -promote all ${infile} | ckfmt
+
+rm ${infile}
+
+echo
+echo "Test 5. PPM maxval 511 infile"
+
+infile=${test511_ppm}
+
+echo "Should print: PPM raw, 8 by 1  maxval 511 twenty-five times"
+
+pnmpad ${size} ${infile} | ckfmt
+pnmpad ${size} -black ${infile} | ckfmt
+pnmpad ${size} -white ${infile} | ckfmt
+pnmpad ${size} -extend-edge ${infile} | ckfmt
+pnmpad ${size} -detect-background ${infile} | ckfmt
+
+pnmpad ${size} -color ${BLACK} ${infile} | ckfmt
+pnmpad ${size} -color ${BLACK} -promote none   ${infile} | ckfmt
+pnmpad ${size} -color ${BLACK} -promote format ${infile} | ckfmt
+pnmpad ${size} -color ${BLACK} -promote all    ${infile} | ckfmt
+
+pnmpad ${size} -color ${WHITE} ${infile} | ckfmt
+pnmpad ${size} -color ${WHITE} -promote none   ${infile} | ckfmt
+pnmpad ${size} -color ${WHITE} -promote format ${infile} | ckfmt
+pnmpad ${size} -color ${WHITE} -promote all    ${infile} | ckfmt
+
+pnmpad ${size} -color ${LIGHTGRAY} ${infile} | ckfmt
+pnmpad ${size} -color ${LIGHTGRAY} -promote none   ${infile} | ckfmt
+pnmpad ${size} -color ${LIGHTGRAY} -promote format ${infile} | ckfmt
+pnmpad ${size} -color ${LIGHTGRAY} -promote all    ${infile} | ckfmt
+
+pnmpad ${size} -color ${DARKGRAY} ${infile} | ckfmt
+pnmpad ${size} -color ${DARKGRAY} -promote none   ${infile} | ckfmt
+pnmpad ${size} -color ${DARKGRAY} -promote format ${infile} | ckfmt
+pnmpad ${size} -color ${DARKGRAY} -promote all    ${infile} | ckfmt
+
+pnmpad ${size} -color ${PURPLE} ${infile} | ckfmt
+pnmpad ${size} -color ${PURPLE} -promote none   ${infile} | ckfmt
+pnmpad ${size} -color ${PURPLE} -promote format ${infile} | ckfmt
+pnmpad ${size} -color ${PURPLE} -promote all    ${infile} | ckfmt
+
+rm ${infile}
diff --git a/test/pnmpad-pnmmargin.ok b/test/pnmpad-pnmmargin.ok
new file mode 100644
index 00000000..552c530f
--- /dev/null
+++ b/test/pnmpad-pnmmargin.ok
@@ -0,0 +1,15 @@
+Test 1.  Should print match three times
+match
+match
+match
+Test 2.  Should print match four times
+match
+match
+match
+match
+Test 3.  Should print match five times
+match
+match
+match
+match
+match
diff --git a/test/pnmpad-pnmmargin.test b/test/pnmpad-pnmmargin.test
new file mode 100755
index 00000000..8b23be35
--- /dev/null
+++ b/test/pnmpad-pnmmargin.test
@@ -0,0 +1,79 @@
+#! /bin/sh
+# This script tests: pnmpad pnmmargin
+# Also requires: pamcat pamcut pamenlarge pbmmake pnmmargin ppmmake ppmpat
+
+tmpdir=${tmpdir:-/tmp}
+padded_pbm=${tmpdir}/padded.pbm
+argyle_ppm=${tmpdir}/argyle.ppm
+padded_ppm=${tmpdir}/padded.ppm
+
+spacer_pnm=${tmpdir}/spacer.pnm
+
+# define function
+addmargin () {
+
+# This function takes 3 positional parameters:
+#   $1: color black white or gofigure
+#   $2: color string (ignore if black white or gofigure)
+#   $3: margin
+#   $4: filename
+
+    case $1 in
+        -color) ppmmake $2 $3 $3 > ${spacer_pnm}; infile=$4 ;;
+        -black) pbmmake -black $2 $2 > ${spacer_pnm}; infile=$3 ;;
+        -white) pbmmake -white $2 $2 > ${spacer_pnm}; infile=$3 ;;
+        *) pamcut -t 0 -l 0 -w 1 -h 1 $2 | pamenlarge $1 > ${spacer_pnm}; infile=$2 ;;
+    esac
+    pamcat -lr ${spacer_pnm} ${infile} ${spacer_pnm} |\
+        pamcat -tb ${spacer_pnm} - ${spacer_pnm}
+    rm ${spacer_pnm}
+}
+
+echo "Test 1.  Should print match three times"
+
+pnmmargin -black 5 maze.pbm > ${padded_pbm} 
+pnmmargin -black 1 maze.pbm | pnmpad -black -t 4 -b 4 -l 4 -r 4 |\
+    cmp -s ${padded_pbm} - && echo "match" || echo "no match"
+pnmmargin 1 maze.pbm | pnmpad -black -t 4 -b 4 -l 4 -r 4 |\
+    cmp -s ${padded_pbm} - && echo "match" || echo "no match"
+pnmmargin -black 1 maze.pbm | pnmpad -extend-edge -t 4 -b 4 -l 4 -r 4 |\
+    cmp -s ${padded_pbm} - && echo "match" || echo "no match"
+
+
+echo "Test 2.  Should print match four times"
+
+addmargin -black 5 maze.pbm |\
+    cmp -s ${padded_pbm} - && echo "match" || echo "no match"
+addmargin -black 1 maze.pbm | pnmpad -black -t 4 -b 4 -l 4 -r 4 |\
+    cmp -s ${padded_pbm} - && echo "match" || echo "no match"
+addmargin 1 maze.pbm | pnmpad -black -t 4 -b 4 -l 4 -r 4 |\
+    cmp -s ${padded_pbm} - && echo "match" || echo "no match"
+addmargin -black 1 maze.pbm | pnmpad -extend-edge -t 4 -b 4 -l 4 -r 4 |\
+    cmp -s ${padded_pbm} - && echo "match" || echo "no match"
+
+rm ${padded_pbm}
+
+echo "Test 3.  Should print match five times"
+
+ppmpat -argyle1 -color=rgb:20/30/ff,rgb:70/80/ff 30 20 > ${argyle_ppm}
+
+addmargin 3 ${argyle_ppm} > ${padded_ppm}
+
+addmargin -color rgb:20/30/ff 1 ${argyle_ppm} |\
+  pnmpad -color=rgb:20/30/ff -t 2 -b 2 -r 2 -l 2 |\
+    cmp -s ${padded_ppm} - && echo "match" || echo "no match"
+addmargin -color rgb:20/30/ff 1 ${argyle_ppm} |\
+  pnmpad -color=rgb:20/30/ff -t 2 -b 2 -r 2 -l 2 |\
+    cmp -s ${padded_ppm} - && echo "match" || echo "no match"
+addmargin 1 ${argyle_ppm} |\
+  pnmpad -extend-edge -t 2 -b 2 -r 2 -l 2 |\
+    cmp -s ${padded_ppm} - && echo "match" || echo "no match"
+
+pnmpad -color rgb:20/30/ff -t 3 -b 3 -r 3 -l 3 ${argyle_ppm} |\
+    cmp -s ${padded_ppm} - && echo "match" || echo "no match"
+
+pnmpad -detect-background -t 3 -b 3 -r 3 -l 3 ${argyle_ppm} |\
+    cmp -s ${padded_ppm} - && echo "match" || echo "no match"
+
+
+rm ${argyle_ppm} ${padded_ppm}
diff --git a/test/pnmpad-reportonly.ok b/test/pnmpad-reportonly.ok
new file mode 100644
index 00000000..2cf58f39
--- /dev/null
+++ b/test/pnmpad-reportonly.ok
@@ -0,0 +1,75 @@
+Test 1.  Should print 0 0 0 0 227 149 six times
+0 0 0 0 227 149
+0 0 0 0 227 149
+0 0 0 0 227 149
+0 0 0 0 227 149
+0 0 0 0 227 149
+0 0 0 0 227 149
+Test 2.  Should print 10 0 0 0 110 17 seven times
+10 0 0 0 110 17
+10 0 0 0 110 17
+10 0 0 0 110 17
+10 0 0 0 110 17
+10 0 0 0 110 17
+10 0 0 0 110 17
+10 0 0 0 110 17
+Test 3.  Should print 0 10 0 0 110 19 eight times
+0 10 0 0 110 19
+0 10 0 0 110 19
+0 10 0 0 110 19
+0 10 0 0 110 19
+0 10 0 0 110 19
+0 10 0 0 110 19
+0 10 0 0 110 19
+0 10 0 0 110 19
+Test 4.  Should print 10 10 0 0 120 19 four times
+10 10 0 0 120 19
+10 10 0 0 120 19
+10 10 0 0 120 19
+10 10 0 0 120 19
+Test 5.  Should print 0 0 10 0 27 110 seven times
+0 0 10 0 27 110
+0 0 10 0 27 110
+0 0 10 0 27 110
+0 0 10 0 27 110
+0 0 10 0 27 110
+0 0 10 0 27 110
+0 0 10 0 27 110
+Test 6.  Should print 0 0 0 10 19 110 eight times
+0 0 0 10 19 110
+0 0 0 10 19 110
+0 0 0 10 19 110
+0 0 0 10 19 110
+0 0 0 10 19 110
+0 0 0 10 19 110
+0 0 0 10 19 110
+0 0 0 10 19 110
+Test 7.  Should print 0 0 12 12 27 124 four times
+0 0 12 12 27 124
+0 0 12 12 27 124
+0 0 12 12 27 124
+0 0 12 12 27 124
+Test 8.  Should print 5 10 0 0 115 17 seven times
+5 10 0 0 115 17
+5 10 0 0 115 17
+5 10 0 0 115 17
+5 10 0 0 115 17
+5 10 0 0 115 17
+5 10 0 0 115 17
+5 10 0 0 115 17
+Test 9.  Should print 0 0 4 8 19 112 seven times
+0 0 4 8 19 112
+0 0 4 8 19 112
+0 0 4 8 19 112
+0 0 4 8 19 112
+0 0 4 8 19 112
+0 0 4 8 19 112
+0 0 4 8 19 112
+Test Invalid
+Expected failure 1 (no output)
+Expected failure 2 (no output)
+Expected failure 3 (no output)
+Expected failure 4 (no output)
+Expected failure 5 (no output)
+Expected failure 6 (no output)
+Expected failure 7 (no output)
diff --git a/test/pnmpad-reportonly.test b/test/pnmpad-reportonly.test
new file mode 100755
index 00000000..412cb8a2
--- /dev/null
+++ b/test/pnmpad-reportonly.test
@@ -0,0 +1,158 @@
+#! /bin/sh
+# This script tests: pnmpad
+# Also requires: pbmmake pgmmake ppmmake pamfile
+
+tmpdir=${tmpdir:-/tmp}
+
+test1_pbm=${tmpdir}/test1.pbm
+test2_pbm=${tmpdir}/test2.pbm
+test_pgm=${tmpdir}/test.pgm
+test_ppm=${tmpdir}/test.ppm
+
+testimg_size=$(pamfile -size testimg.ppm) 
+
+echo "Test 1.  Should print 0 0 0 0 ${testimg_size} six times" 
+
+for pad in "" "-left=0" "-right=0" "-top=0" "-bottom=0" \
+           "-left=0 -right=0 -top=0 -bottom=0"
+  do
+  pnmpad -reportonly ${pad} testimg.ppm || echo "failure"
+  done
+
+
+echo "Test 2.  Should print 10 0 0 0 110 17 seven times" 
+ 
+pbmmake -w 100 17 > ${test1_pbm}
+for pad in "-left=10" \
+           "-left=10 -right=0" \
+           "-left=10 -width=90" \
+           "-left=10 -width=105" \
+           "-left=10 -width=110" \
+           "-right=0 -width=110" \
+           "-halign=1.0 -width=110"
+  do
+  pnmpad -reportonly ${pad} ${test1_pbm} || echo "failure"
+  done
+
+
+echo "Test 3.  Should print 0 10 0 0 110 19 eight times" 
+pgmmake 0.5 100 19 > ${test_pgm}
+for pad in "-right=10" \
+           "-right=10 -left=0" \
+           "-right=10 -width=90" \
+           "-right=10 -width=105" \
+           "-right=10 -width=110" \
+           "-left=0 -width=110" \
+           "-halign=0.0 -width=110" \
+           "-right=1 -mwidth=11"
+  do
+  pnmpad -reportonly ${pad} ${test_pgm} || echo "failure"
+  done
+
+
+echo "Test 4.  Should print 10 10 0 0 120 19 four times" 
+for pad in "-left=10 -right=10" \
+           "-right=10 -width=120" \
+           "-halign=0.5 -width=120" \
+           "-left=1 -right=1 -mwidth=30"
+  do
+  pnmpad -reportonly ${pad} ${test_pgm} || echo "failure"
+  done
+
+
+echo "Test 5.  Should print 0 0 10 0 27 110 seven times" 
+ 
+pbmmake -w 27 100 > ${test2_pbm}
+for pad in "-top=10" \
+           "-top=10 -bottom=0" \
+           "-top=10 -height=50" \
+           "-top=10 -height=101" \
+           "-top=10 -height=110" \
+           "-bottom=0 -height=110" \
+           "-valign=1.0 -height=110"
+  do
+  pnmpad -reportonly ${pad} ${test2_pbm} || echo "failure"
+  done
+
+
+echo "Test 6.  Should print 0 0 0 10 19 110 eight times" 
+ppmmake rgb:33/44/55 19 100 > ${test_ppm}
+for pad in "-bottom=10" \
+           "-bottom=10 -top=0" \
+           "-bottom=10 -height=10" \
+           "-bottom=10 -height=107" \
+           "-bottom=10 -height=110" \
+           "-top=0 -height=110" \
+           "-valign=0.0 -height=110" \
+           "-bottom=1 -mheight=10"
+  do
+  pnmpad -reportonly ${pad} ${test_ppm} || echo "failure"
+  done
+
+
+echo "Test 7.  Should print 0 0 12 12 27 124 four times" 
+for pad in "-top=12 -bottom=12" \
+           "-top=12 -height=124" \
+           "-valign=0.5 -height=124" \
+           "-top=11 -bottom=11 -mheight=4"
+  do
+  pnmpad -reportonly ${pad} ${test2_pbm} || echo "failure"
+  done
+
+
+echo "Test 8.  Should print 5 10 0 0 115 17 seven times"
+for pad in "-l 5 -r 10 -w 115" \
+           "-l 5       -w 115" \
+           "     -r 10 -w 115" \
+           "-l 5 -r 10       " \
+           "-halign 0.333 -w 115 " \
+           "-l 2 -r 4 -mw 23" \
+           "-halign 0.333 -mw 23"
+  do
+  pnmpad -reportonly ${pad} ${test1_pbm} || echo "failure"
+  done
+
+
+echo "Test 9.  Should print 0 0 4 8 19 112 seven times"
+for pad in "-t 4 -b 8 -h 112" \
+           "-t 4      -h 112" \
+           "     -b 8 -h 112" \
+           "-t 4 -b 8       " \
+           "-t 4 -b 8 -mh 14" \
+           "-valign 0.333 -mh 14" \
+           "-valign 0.333 -h 112"
+  do
+  pnmpad -reportonly ${pad} ${test_ppm} || echo "failure"
+  done
+
+echo "Test Invalid"
+
+test_out=${tmpdir}/test_out
+n=1
+
+# define function
+invcmd () { $1 > ${test_out} || \
+  printf "Expected failure $n "
+  test -s ${test_out} && echo "unexpected output" || echo "(no output)"
+  rm -f ${test_out}
+  n=$(($n +1)); }
+
+echo 1>&2
+echo "Invalid command-line arguments." 1>&2
+echo "Error messages should appear below the line." 1>&2
+echo "-----------------------------------------------------------" 1>&2
+
+invcmd "pnmpad -reportonly -l 1 -r 1 -w 100 testgrid.pbm"
+invcmd "pnmpad -reportonly -t 1 -b 1 -h 100 testgrid.pbm"
+invcmd "pnmpad -reportonly -black -white -l 1 testgrid.pbm"
+invcmd "pnmpad -reportonly -color -l 1 testgrid.pbm"
+invcmd "pnmpad -reportonly -color rgbi:0/0/0 -white -l 1 testgrid.pbm"
+invcmd "pnmpad -reportonly -color rgbi:0/0/0 -extend-edge -l 1 testgrid.pbm"
+invcmd "pnmpad -reportonly -color rgbi:0/0/0 -detect-background -l 1 testgrid.pbm"
+
+# echo "Test Invalid.  Should print failure twice"
+# 
+# pnmpad -reportonly -l 1 -r 1 -w 100 testgrid.pbm && echo "unexpected success" || echo "failure" 
+# pnmpad -reportonly -t 1 -b 1 -h 100 testgrid.pbm && echo "unexpected success" || echo "failure"
+# 
+rm ${test1_pbm} ${test2_pbm} ${test_pgm} ${test_ppm}
diff --git a/test/pnmpaste-pbm.test b/test/pnmpaste-pbm.test
index b75797af..70f2b266 100755
--- a/test/pnmpaste-pbm.test
+++ b/test/pnmpaste-pbm.test
@@ -1,4 +1,4 @@
-#! /bin/bash
+#! /bin/sh
 # This script tests: pnmpaste
 # Also requires: pbmmake
 
diff --git a/test/pnmpsnr.ok b/test/pnmpsnr.ok
index 7042f86c..38bed0f3 100644
--- a/test/pnmpsnr.ok
+++ b/test/pnmpsnr.ok
@@ -8,7 +8,7 @@ Test 2
 match
 match
 Test Invalid
-Expected failure 1 1
-Expected failure 2 1
-Expected failure 3 1
-Expected failure 4 1
+Expected failure 1 (no output)
+Expected failure 2 (no output)
+Expected failure 3 (no output)
+Expected failure 4 (no output)
diff --git a/test/pnmpsnr.test b/test/pnmpsnr.test
index 7603459b..6ea05aed 100755
--- a/test/pnmpsnr.test
+++ b/test/pnmpsnr.test
@@ -1,4 +1,4 @@
-#! /bin/bash
+#! /bin/sh
 # This script tests: pnmpsnr
 # Also requires: pbmmake
 
@@ -27,21 +27,11 @@ pnmpsnr  testimg.ppm  testimg.ppm -target1=1000 -target2=1000 -target3=1000
 
 echo "Test Invalid"
 
-tmpdir=${tmpdir:-/tmp}
-test_out=${tmpdir}/test_out
-
-echo 1>&2
-echo "Invalid command-line argument combinations." 1>&2
-echo "Error messages should appear below the line." 1>&2
-echo "-----------------------------------------------------------" 1>&2
-
-pnmpsnr ${b_pbm} ${w_pbm} ${b_pbm}     > ${test_out} || \
-   echo -n "Expected failure 1"; test -s ${test_out}; echo " "$?
-pnmpsnr ${b_pbm}                       > ${test_out} || \
-   echo -n "Expected failure 2"; test -s ${test_out}; echo " "$?
-pnmpsnr ${b_pbm} ${w_pbm} -target1=100 > ${test_out} || \
-   echo -n "Expected failure 3"; test -s ${test_out}; echo " "$?
-pnmpsnr                   -machine     > ${test_out} || \
-   echo -n "Expected failure 4"; test -s ${test_out}; echo " "$?
-
-rm ${b_pbm} ${w_pbm} ${test_out}
+. ${srcdir}/test-invalid.inc
+
+invCmd "pnmpsnr ${b_pbm} ${w_pbm} ${b_pbm}    "
+invCmd "pnmpsnr ${b_pbm}                      "
+invCmd "pnmpsnr ${b_pbm} ${w_pbm} -target1=100"
+invCmd "pnmpsnr                   -machine    "
+
+rm ${b_pbm} ${w_pbm}
diff --git a/test/pnmquant.ok b/test/pnmquant.ok
index 407d42a3..f4229601 100644
--- a/test/pnmquant.ok
+++ b/test/pnmquant.ok
@@ -8,11 +8,11 @@ Test 1
 1 1
 1 1
 Test Invalid
-Expected failure 1 1
-Expected failure 2 1
-Expected failure 3 1
-Expected failure 4 1
-Expected failure 5 1
-Expected failure 6 1
-Expected failure 7 1
-Expected failure 8 1
+Expected failure 1 (no output)
+Expected failure 2 (no output)
+Expected failure 3 (no output)
+Expected failure 4 (no output)
+Expected failure 5 (no output)
+Expected failure 6 (no output)
+Expected failure 7 (no output)
+Expected failure 8 (no output)
diff --git a/test/pnmquant.test b/test/pnmquant.test
index 3a2ef906..4baff9a8 100755
--- a/test/pnmquant.test
+++ b/test/pnmquant.test
@@ -1,4 +1,4 @@
-#! /bin/bash
+#! /bin/sh
 # This script tests: pnmquant
 # Also requires: ppmhist
 
@@ -7,30 +7,30 @@ echo "Test 1"
 # Count colors in output image.
 
 pnmquant 256 testimg.ppm | ppmhist | \
-  awk 'NR==1 {print ($2 <= 256) , ($2 > 256 * 0.95)}' 
+  awk 'NR==1 {print ($2 <= 256) , ($2 > 256 * 0.95)}'
 
 pnmquant -center 256 testimg.ppm | ppmhist | \
-  awk 'NR==1 {print ($2 <= 256) , ($2 > 256 * 0.95)}' 
+  awk 'NR==1 {print ($2 <= 256) , ($2 > 256 * 0.95)}'
 
 pnmquant -spreadbrightness 256 testimg.ppm | ppmhist | \
-  awk 'NR==1 {print ($2 <= 256) , ($2 > 256 * 0.95)}' 
+  awk 'NR==1 {print ($2 <= 256) , ($2 > 256 * 0.95)}'
 
 pnmquant -spreadluminosity 128 testimg.ppm | ppmhist | \
-  awk 'NR==1 {print ($2 <= 128) , ($2 > 128 * 0.95)}' 
+  awk 'NR==1 {print ($2 <= 128) , ($2 > 128 * 0.95)}'
 
 pnmquant -floyd -randomseed=0 128 testimg.ppm | ppmhist | \
-  awk 'NR==1 {print ($2 <= 128) , ($2 > 128 * 0.95)}' 
+  awk 'NR==1 {print ($2 <= 128) , ($2 > 128 * 0.95)}'
 
 pnmquant 64 -meanpixel testimg.ppm | ppmhist | \
-  awk 'NR==1 {print ($2 <= 64) , ($2 > 64 * 0.9)}' 
+  awk 'NR==1 {print ($2 <= 64) , ($2 > 64 * 0.9)}'
 
 pnmquant 16 -meancolor testimg.ppm | ppmhist | \
-  awk 'NR==1 {print ($2 <= 16) , ($2 > 16 * 0.9)}' 
+  awk 'NR==1 {print ($2 <= 16) , ($2 > 16 * 0.9)}'
 
 
 pnmquant 2 testgrid.pbm | ppmhist | \
-  awk 'NR==1 {print ($2 <= 2) , ($2 == 2) }' 
- 
+  awk 'NR==1 {print ($2 <= 2) , ($2 == 2) }'
+
 echo "Test Invalid"
 
 echo 1>&2
@@ -42,20 +42,41 @@ tmpdir=${tmpdir:-/tmp}
 test_out=${tmpdir}/test_out
 
 pnmquant 0 testimg.ppm   > ${test_out} || \
-  echo -n "Expected failure 1"; test -s ${test_out}; echo " "$?
+  printf "Expected failure 1 "
+  test -s ${test_out} && echo "unexpected output" || echo "(no output)"
+  rm -f ${test_out}
+
 pnmquant testimg.ppm  > ${test_out} || \
-  echo -n "Expected failure 2"; test -s ${test_out}; echo " "$?
+  printf "Expected failure 2 "
+  test -s ${test_out} && echo "unexpected output" || echo "(no output)"
+  rm -f ${test_out}
+
 pnmquant 10.5 testimg.ppm > ${test_out} || \
-  echo -n "Expected failure 3"; test -s ${test_out}; echo " "$?
+  printf "Expected failure 3 "
+  test -s ${test_out} && echo "unexpected output" || echo "(no output)"
+  rm -f ${test_out}
+
 pnmquant -center -meancolor 16 testimg.ppm > ${test_out} || \
-  echo -n "Expected failure 4"; test -s ${test_out}; echo " "$?
+  printf "Expected failure 4 "
+  test -s ${test_out} && echo "unexpected output" || echo "(no output)"
+  rm -f ${test_out}
+
 pnmquant -center -meanpixel 16 testimg.ppm    > ${test_out} || \
-  echo -n "Expected failure 5"; test -s ${test_out}; echo " "$?
+  printf "Expected failure 5 "
+  test -s ${test_out} && echo "unexpected output" || echo "(no output)"
+  rm -f ${test_out}
+
 pnmquant -meancolor -meanpixel 16 testimg.ppm > ${test_out} || \
-  echo -n "Expected failure 6"; test -s ${test_out}; echo " "$?
+  printf "Expected failure 6 "
+  test -s ${test_out} && echo "unexpected output" || echo "(no output)"
+  rm -f ${test_out}
+
 pnmquant -spreadbrightness -spreadluminosity 16 testimg.ppm > ${test_out} || \
-  echo -n "Expected failure 7"; test -s ${test_out}; echo " "$?
-pnmquant -randomseed 1 -norandom 10 testimg.ppm > ${test_out} || \
-  echo -n "Expected failure 8"; test -s ${test_out}; echo " "$?
+  printf "Expected failure 7 "
+  test -s ${test_out} && echo "unexpected output" || echo "(no output)"
+  rm -f ${test_out}
 
-rm ${test_out}
+pnmquant -randomseed 1 -norandom 10 testimg.ppm > ${test_out} || \
+  printf "Expected failure 8 "
+  test -s ${test_out} && echo "unexpected output" || echo "(no output)"
+  rm -f ${test_out}
diff --git a/test/pnmquantall.ok b/test/pnmquantall.ok
index 5885d370..c7563d88 100644
--- a/test/pnmquantall.ok
+++ b/test/pnmquantall.ok
@@ -1,7 +1,14 @@
+Test 1.
 2373957371 33838
 3892560659 33838
 1383839923 33838
-1
+color count 20: success
+Test 2.
+452076937 33838
+452076937 33838
+452076937 33838
+color count 1: success
+Test Invalid
 Expected failure 1
 Expected failure 1.rm
 Expected failure 2
diff --git a/test/pnmquantall.test b/test/pnmquantall.test
index 4c1bb77f..7910d0fc 100755
--- a/test/pnmquantall.test
+++ b/test/pnmquantall.test
@@ -1,47 +1,71 @@
-#! /bin/bash
+#! /bin/sh
 # This script tests: pnmquantall
-# Also requires: ppmtorgb3 pgmhist pnmcat
+# Also requires: ppmtorgb3 pgmhist pamcat
 
 tmpdir=${tmpdir:-/tmp}
-test_ppm=${tmpdir}/testimg.ppm
+rose_ppm=${tmpdir}/rose.ppm
 
-cp testimg.ppm ${tmpdir} &&
-ppmtorgb3 ${test_ppm}
+cp testimg.ppm ${rose_ppm} &&
+ppmtorgb3 ${rose_ppm}
 
-test_red=${tmpdir}/testimg.red
-test_grn=${tmpdir}/testimg.grn
-test_blu=${tmpdir}/testimg.blu
+rose_red=${tmpdir}/rose.red
+rose_grn=${tmpdir}/rose.grn
+rose_blu=${tmpdir}/rose.blu
 
-pnmquantall 20 ${test_red} ${test_grn} ${test_blu}
+cp ${rose_red} ${rose_red}.1
+cp ${rose_grn} ${rose_grn}.1
+cp ${rose_blu} ${rose_blu}.1
 
-for i in ${test_red} ${test_grn} ${test_blu}
+echo "Test 1."
+
+pnmquantall 20 ${rose_red}.1 ${rose_grn}.1 ${rose_blu}.1
+
+for i in ${rose_red}.1 ${rose_grn}.1 ${rose_blu}.1
 do
 cat $i | cksum
 done
 
-# Should print 1
+pamcat ${rose_red}.1 ${rose_grn}.1 ${rose_blu}.1 -tb | \
+    pgmhist -m |\
+    awk '$2>0 {s++};
+         END { printf("color count %u: %s\n", s,
+                 (s==20) ? "success" : "failure") }'
 
-pnmcat ${test_red} ${test_grn} ${test_blu} -tb | \
-    pgmhist -m | awk '$2>0 {s++}; END { print (s<=20) }'
+rm ${rose_red}.1 ${rose_grn}.1 ${rose_blu}.1
 
+echo "Test 2."
 
-tmpdir=${tmpdir:-/tmp}
-test_out=${tmpdir}/test_out
+pnmquantall -ext .2 1 ${rose_red} ${rose_grn} ${rose_blu}
+
+for i in ${rose_red}.2 ${rose_grn}.2 ${rose_blu}.2
+do
+cat $i | cksum
+done
+
+pamcat ${rose_red}.2 ${rose_grn}.2 ${rose_blu}.2 -tb | \
+    pgmhist -m |\
+    awk '$2>0 {s++};
+         END { printf("color count %u: %s\n", s,
+                 (s==1) ? "success" : "failure") }'
+
+rm ${rose_red}.2 ${rose_grn}.2 ${rose_blu}.2
+
+echo "Test Invalid"
 
 echo 1>&2
 echo "Invalid command-line argument combinations." 1>&2
 echo "Error messages should appear below the line." 1>&2
 echo "-----------------------------------------------------------" 1>&2
 
-pnmquantall -ext xx 0 ${test_red} ${test_grn} ${test_blu} || \
+pnmquantall -ext xx 0 ${rose_red} ${rose_grn} ${rose_blu} || \
    echo "Expected failure 1"
-rm ${test_red}xx ${test_grn}xx ${test_blu}xx || \
+rm ${rose_red}xx ${rose_grn}xx ${rose_blu}xx || \
    echo "Expected failure 1.rm"
-pnmquantall -ext xx 1 ${test_red} ${test_grn} ${test_blu} || \
+pnmquantall -ext yy ${rose_red} ${rose_grn} ${rose_blu} || \
    echo "Expected failure 2"
-rm ${test_red}xx ${test_grn}xx ${test_blu}xx || \
+rm ${rose_red}yy ${rose_grn}yy ${rose_blu}yy || \
    echo "Expected failure 2.rm"
-pnmquantall -ext xx 2 || \
+pnmquantall -ext zz 2 || \
    echo "Expected failure 3"
 
-rm ${test_red} ${test_grn} ${test_blu} ${test_ppm}
\ No newline at end of file
+rm ${rose_red} ${rose_grn} ${rose_blu} ${rose_ppm}
diff --git a/test/pnmremap1.ok b/test/pnmremap1.ok
index 23a9dddd..0f511754 100644
--- a/test/pnmremap1.ok
+++ b/test/pnmremap1.ok
@@ -1,7 +1,7 @@
 3602410851 101482
-Expected failure 1 1
-Expected failure 2 1
-Expected failure 3 1
-Expected failure 4 1
-Expected failure 5 1
-Expected failure 6 1
+Expected failure 1 (no output)
+Expected failure 2 (no output)
+Expected failure 3 (no output)
+Expected failure 4 (no output)
+Expected failure 5 (no output)
+Expected failure 6 (no output)
diff --git a/test/pnmremap1.test b/test/pnmremap1.test
index 18debcb8..9c60460b 100755
--- a/test/pnmremap1.test
+++ b/test/pnmremap1.test
@@ -1,4 +1,4 @@
-#! /bin/bash
+#! /bin/sh
 # This script tests: pnmremap
 # Also requires: pamseq pamtopnm
 
@@ -33,17 +33,32 @@ tmpdir=${tmpdir:-/tmp}
 test_out=${tmpdir}/test_out
 
 pnmremap -mapfile=/dev/null testimg.ppm > ${test_out} || \
-  echo -n "Expected failure 1"; test -s ${test_out}; echo " "$?
+  printf "Expected failure 1 "
+  test -s ${test_out} && echo "unexpected output" || echo "(no output)"
+  rm -f ${test_out}
+
 pnmremap -mapfile=/dev/zero testimg.ppm > ${test_out} || \
-  echo -n "Expected failure 2"; test -s ${test_out}; echo " "$?
+  printf "Expected failure 2 "
+  test -s ${test_out} && echo "unexpected output" || echo "(no output)"
+  rm -f ${test_out}
+
 pnmremap testimg.ppm                    > ${test_out} || \
-  echo -n "Expected failure 3"; test -s ${test_out}; echo " "$?
+  printf "Expected failure 3 "
+  test -s ${test_out} && echo "unexpected output" || echo "(no output)"
+  rm -f ${test_out}
+
 pnmremap -fs -nofs testimg.ppm          > ${test_out} || \
-  echo -n "Expected failure 4"; test -s ${test_out}; echo " "$?
+  printf "Expected failure 4 "
+  test -s ${test_out} && echo "unexpected output" || echo "(no output)"
+  rm -f ${test_out}
+
 pnmremap -mapfile=testgrid.pbm -missingcolor=rgb:00/ff/00 testimg.ppm \
  > ${test_out} || \
-  echo -n "Expected failure 5"; test -s ${test_out}; echo " "$?
-pnmremap -mapfile=testgrid.pbm -firstisdefault testimg.ppm > ${test_out} || \
-  echo -n "Expected failure 6"; test -s ${test_out}; echo " "$?
+  printf "Expected failure 5 "
+  test -s ${test_out} && echo "unexpected output" || echo "(no output)"
+  rm -f ${test_out}
 
-rm ${test_out}
+pnmremap -mapfile=testgrid.pbm -firstisdefault testimg.ppm > ${test_out} || \
+  printf "Expected failure 6 "
+  test -s ${test_out} && echo "unexpected output" || echo "(no output)"
+  rm -f ${test_out}
diff --git a/test/pnmremap2.test b/test/pnmremap2.test
index 76c2d566..7eea2c4a 100755
--- a/test/pnmremap2.test
+++ b/test/pnmremap2.test
@@ -1,4 +1,4 @@
-#! /bin/bash
+#! /bin/sh
 # This script tests: pnmremap
 # Also requires: pamdepth pamseq pamtopnm
 
diff --git a/test/pnmshear.test b/test/pnmshear.test
index a19a9852..42e5c816 100755
--- a/test/pnmshear.test
+++ b/test/pnmshear.test
@@ -1,4 +1,4 @@
-#! /bin/bash
+#! /bin/sh
 # This script tests: pnmshear
 # Also requires: pbmmake pnmpad
 
diff --git a/test/pnmtile.ok b/test/pnmtile.ok
index 279251b8..572893df 100644
--- a/test/pnmtile.ok
+++ b/test/pnmtile.ok
@@ -1,6 +1,6 @@
 4228632379 259
-0 0 : 0
-Expected failure 1 1
-Expected failure 2 1
-Expected failure 3 1
-Expected failure 4 1
+0 0 0 : 0
+Expected failure 1 (no output)
+Expected failure 2 (no output)
+Expected failure 3 (no output)
+Expected failure 4 (no output)
diff --git a/test/pnmtile.test b/test/pnmtile.test
index 11f576bd..35addbec 100755
--- a/test/pnmtile.test
+++ b/test/pnmtile.test
@@ -1,6 +1,6 @@
 #! /bin/bash
 # This script tests: pnmtile
-# Also requires: pnmcat
+# Also requires: pamcat
 
 
 # Test 1.  Should print 4228632379 259
@@ -8,36 +8,22 @@ pnmtile 40 50 testgrid.pbm | cksum
 
 tmpdir=${tmpdir:-/tmp}
 
-# Test 2.  Compare 2x2 tile images produced by pnmtile and pnmcat
+# Test 2.  Compare 2x2 tile images produced by pnmtile and pamcat
 # Should print 0
 testimg2_ppm=${tmpdir}/testimg2.ppm
 testimg4_ppm=${tmpdir}/testimg4.ppm
 
 pnmtile 454 298 testimg.ppm > ${testimg4_ppm} &&
-pnmcat -lr testimg.ppm testimg.ppm > ${testimg2_ppm} &&
-pnmcat -tb ${testimg2_ppm} ${testimg2_ppm} | \
+pamcat -lr testimg.ppm testimg.ppm > ${testimg2_ppm} &&
+pamcat -tb ${testimg2_ppm} ${testimg2_ppm} | pamtopnm --assume |\
 cmp -s - ${testimg4_ppm}
 echo ${PIPESTATUS[@]} ":" $?
 
 rm ${testimg2_ppm} ${testimg4_ppm}
 
-test_out=${tmpdir}/test_out
+. ${srcdir}/test-invalid.inc
 
-echo 1>&2
-echo "Invalid command-line argument combinations." 1>&2
-echo "Error messages should appear below the line." 1>&2
-echo "-----------------------------------------------------------" 1>&2
-
-pnmtile 100 testgrid.pbm > ${test_out} || \
-   echo -n "Expected failure 1"; test -s ${test_out}; echo " "$?
-
-pnmtile 100 0 testgrid.pbm > ${test_out} || \
-   echo -n "Expected failure 2"; test -s ${test_out}; echo " "$?
-
-pnmtile 0 100 testgrid.pbm > ${test_out} || \
-   echo -n "Expected failure 3"; test -s ${test_out}; echo " "$?
-
-pnmtile 100 100 100 testgrid.pbm > ${test_out} || \
-   echo -n "Expected failure 4"; test -s ${test_out}; echo " "$?
-
-rm -f ${test_out}
\ No newline at end of file
+invCmd "pnmtile 100 testgrid.pbm"
+invCmd "pnmtile 100 0 testgrid.pbm"
+invCmd "pnmtile 0 100 testgrid.pbm"
+invCmd "pnmtile 100 100 100 testgrid.pbm"
diff --git a/test/pnmtojpeg-scans.ok b/test/pnmtojpeg-scans.ok
new file mode 100644
index 00000000..089dfebf
--- /dev/null
+++ b/test/pnmtojpeg-scans.ok
@@ -0,0 +1,20 @@
+success
+pnmtojpeg: Input file has format P6.
+It has 149 rows of 227 columns of pixels with max sample value of 255.
+pnmtojpeg: A scan script with 7 entries is being used:
+pnmtojpeg:     Scan  0: Ss= 0 Se= 0 Ah= 0 Al= 0  3 components
+pnmtojpeg:         Color component 0 index: 0
+pnmtojpeg:         Color component 1 index: 1
+pnmtojpeg:         Color component 2 index: 2
+pnmtojpeg:     Scan  1: Ss= 1 Se= 2 Ah= 0 Al= 0  1 components
+pnmtojpeg:         Color component 0 index: 0
+pnmtojpeg:     Scan  2: Ss= 3 Se= 5 Ah= 0 Al= 0  1 components
+pnmtojpeg:         Color component 0 index: 0
+pnmtojpeg:     Scan  3: Ss= 1 Se=63 Ah= 0 Al= 0  1 components
+pnmtojpeg:         Color component 0 index: 1
+pnmtojpeg:     Scan  4: Ss= 1 Se=63 Ah= 0 Al= 0  1 components
+pnmtojpeg:         Color component 0 index: 2
+pnmtojpeg:     Scan  5: Ss= 6 Se= 9 Ah= 0 Al= 0  1 components
+pnmtojpeg:         Color component 0 index: 0
+pnmtojpeg:     Scan  6: Ss=10 Se=63 Ah= 0 Al= 0  1 components
+pnmtojpeg:         Color component 0 index: 0
diff --git a/test/pnmtojpeg-scans.test b/test/pnmtojpeg-scans.test
new file mode 100755
index 00000000..ea17c8c0
--- /dev/null
+++ b/test/pnmtojpeg-scans.test
@@ -0,0 +1,32 @@
+#! /bin/bash
+# This script tests: pnmtojpeg
+# Also requires:
+
+tmpdir=${tmpdir:-/tmp}
+test_jpegscan=${tmpdir}/test.jpegscan
+err_out=${tmpdir}/err.out
+
+cat > ${test_jpegscan} << EOF
+# This is a example of a scan script to be used by 'pnmtojpeg' with -scan .
+# It should work with any color image.
+
+#Interleaved DC scan for Y, Cb, Cr:
+0, 1, 2: 0-0, 0, 0 ;
+
+# AC scans:
+0:  1- 2, 0, 0 ;
+0:  3- 5, 0, 0 ;
+1:  1-63, 0, 0 ;
+2:  1-63, 0, 0 ;
+0:  6- 9, 0, 0 ;
+0: 10-63, 0, 0 ;
+EOF
+
+pnmtojpeg testimg.ppm -scans=${test_jpegscan} -verbose \
+ > /dev/null 2> ${err_out} && echo "success" || echo "failure"
+
+cat ${err_out}
+
+rm ${err_out} ${test_jpegscan}
+
+# TODO test invalid scan script
diff --git a/test/pnmtopnm-plain.ok b/test/pnmtopnm-plain.ok
index 02d99f1e..640f0964 100644
--- a/test/pnmtopnm-plain.ok
+++ b/test/pnmtopnm-plain.ok
@@ -1,48 +1,51 @@
+Test.  Should print three identical images in plain format, twice each
 P1
-14 16
-10101010101010
-11111111111111
-10101010101010
-11111111111111
-10101010101010
-11111111111111
-10101010101010
-11111111111111
-10101010101010
-11111111111111
-10101010101010
-11111111111111
-10101010101010
-11111111111111
-10101010101010
-11111111111111
+5 5
+01010
+10101
+01010
+10101
+01010
+P1
+5 5
+01010
+10101
+01010
+10101
+01010
+P2
+8 8
+7
+0 0 1 1 2 2 3 3
+0 1 1 2 2 3 3 4
+1 1 2 2 3 3 4 4
+1 2 2 3 3 4 4 5
+2 2 3 3 4 4 5 5
+2 3 3 4 4 5 5 6
+3 3 4 4 5 5 6 6
+3 4 4 5 5 6 6 7
 P2
-14 16
+8 8
+7
+0 0 1 1 2 2 3 3 
+0 1 1 2 2 3 3 4 
+1 1 2 2 3 3 4 4 
+1 2 2 3 3 4 4 5 
+2 2 3 3 4 4 5 5 
+2 3 3 4 4 5 5 6 
+3 3 4 4 5 5 6 6 
+3 4 4 5 5 6 6 7 
+P3
+4 4
 255
-0 255 0 255 0 255 0 255 0 255 0 255 0 255 
-0 0 0 0 0 0 0 0 0 0 0 0 0 0 
-0 255 0 255 0 255 0 255 0 255 0 255 0 255 
-0 0 0 0 0 0 0 0 0 0 0 0 0 0 
-0 255 0 255 0 255 0 255 0 255 0 255 0 255 
-0 0 0 0 0 0 0 0 0 0 0 0 0 0 
-0 255 0 255 0 255 0 255 0 255 0 255 0 255 
-0 0 0 0 0 0 0 0 0 0 0 0 0 0 
-0 255 0 255 0 255 0 255 0 255 0 255 0 255 
-0 0 0 0 0 0 0 0 0 0 0 0 0 0 
-0 255 0 255 0 255 0 255 0 255 0 255 0 255 
-0 0 0 0 0 0 0 0 0 0 0 0 0 0 
-0 255 0 255 0 255 0 255 0 255 0 255 0 255 
-0 0 0 0 0 0 0 0 0 0 0 0 0 0 
-0 255 0 255 0 255 0 255 0 255 0 255 0 255 
-0 0 0 0 0 0 0 0 0 0 0 0 0 0 
+0 31 255  0 31 255  63 0 0  0 31 255
+0 31 255  0 31 255  0 31 255  63 0 0
+0 31 255  63 0 0  63 0 0  63 0 0
+63 0 0  0 31 255  63 0 0  63 0 0
 P3
-14 16
+4 4
 255
-0 0 0 255 255 255 0 0 0 255 255 255 0 0 0 255 255 255 0 0 0 255 255 255 
-0 0 0 255 255 255 0 0 0 255 255 255 0 0 0 255 255 255 
-0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 
-0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 
-0 0 0 255 255 255 0 0 0 255 255 255 0 0 0 255 255 255 0 0 0 255 255 255 
-0 0 0 255 255 255 0 0 0 255 255 255 0 0 0 255 255 255 
-0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 
-0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 
+0 31 255 0 31 255 63 0 0 0 31 255 
+0 31 255 0 31 255 0 31 255 63 0 0 
+0 31 255 63 0 0 63 0 0 63 0 0 
+63 0 0 0 31 255 63 0 0 63 0 0 
diff --git a/test/pnmtopnm-plain.test b/test/pnmtopnm-plain.test
index 5b7e4b48..87b74064 100755
--- a/test/pnmtopnm-plain.test
+++ b/test/pnmtopnm-plain.test
@@ -1,10 +1,14 @@
-#! /bin/bash
+#! /bin/sh
 # This script tests: pamtopnm
-# Also requires: pgmtopgm ppmtoppm
+# Also requires: pbmmake pgmramp ppmpat
 
-pamtopnm -plain testgrid.pbm
+echo "Test.  Should print three identical images in plain format, twice each"
 
-pgmtopgm < testgrid.pbm | pamtopnm -plain
+pbmmake -g 5 5 -plain
+pbmmake -g 5 5 | pamtopnm -plain
 
-ppmtoppm < testgrid.pbm | pamtopnm -plain | \
-  head -n11
+pgmramp -maxval 7 -diag 8 8 -plain
+pgmramp -maxval 7 -diag 8 8 | pamtopnm -plain
+
+ppmpat -g2 -color=rgb:00/1f/ff,rgb:3f/00/00 -mesh 4 4 -plain
+ppmpat -g2 -color=rgb:00/1f/ff,rgb:3f/00/00 -mesh 4 4 | pamtopnm -plain
diff --git a/test/ppmbrighten.ok b/test/ppmbrighten.ok
index 3895dbd0..95c90d24 100644
--- a/test/ppmbrighten.ok
+++ b/test/ppmbrighten.ok
@@ -4,8 +4,6 @@ Test 2: Should print 295150171 101484
 295150171 101484
 Test 3: Should print 1
 1
-Test Error: Should print 1 four times
-1
-1
-1
-1
+Test Invalid
+Expected failure 1 (no output)
+Expected failure 2 (no output)
diff --git a/test/ppmbrighten.test b/test/ppmbrighten.test
index 40fe08f6..8ae1d744 100755
--- a/test/ppmbrighten.test
+++ b/test/ppmbrighten.test
@@ -1,6 +1,6 @@
-#! /bin/bash
+#! /bin/sh
 # This script tests: ppmbrighten
-# Also requires: pnmnorm pambrighten pamsumm 
+# Also requires: pnmnorm pambrighten pamsumm
 
 # Failure message
 ## Ppmbrighten is sensitive to subtle differences in floating point math.
@@ -20,19 +20,11 @@ echo "Test 3: Should print 1"
 ppmbrighten -v 100 -normalize testimg.ppm | pamsumm --mean | \
  awk '{print ($NF > 132.0) && ($NF < 132.2)}'
 
-echo "Invalid command-line argument combinations." 1>&2
-echo "Error messages should appear below the line." 1>&2
-echo "-----------------------------------------------------------" 1>&2
 
-echo "Test Error: Should print 1 four times"
+echo "Test Invalid"
 
-output_ppm=${tmpdir}/output.ppm
+. ${srcdir}/test-invalid.inc
+
+invCmd "pambrighten -v -120 testimg.ppm"
+invCmd "pambrighten -s -120 testimg.ppm"
 
-pambrighten -v -120 testimg.ppm > ${output_ppm}
-echo $?
-test -s ${output_ppm}
-echo $?
-pambrighten -s -120 testimg.ppm > ${output_ppm}
-echo $?
-test -s ${output_ppm}
-echo $?
diff --git a/test/ppmchange-roundtrip.ok b/test/ppmchange-roundtrip.ok
index a676a1f2..4fb7d428 100644
--- a/test/ppmchange-roundtrip.ok
+++ b/test/ppmchange-roundtrip.ok
@@ -1,2 +1,2 @@
-2425386270 41
-2425386270 41
+281226646 481
+281226646 481
diff --git a/test/ppmchange-roundtrip.test b/test/ppmchange-roundtrip.test
index 78f5b548..5bd18150 100755
--- a/test/ppmchange-roundtrip.test
+++ b/test/ppmchange-roundtrip.test
@@ -1,12 +1,12 @@
-#! /bin/bash
+#! /bin/sh
 # This script tests: ppmchange
 # Also requires: pgmtopbm pnminvert ppmtopgm
 
 
-ppmchange black white white black testgrid.pbm | \
+ppmchange black white white black maze.pbm | \
 pnminvert | ppmtopgm | \
 pgmtopbm -th -val=0.5 | cksum
 
-ppmchange  black white white black testgrid.pbm | \
+ppmchange  black white white black maze.pbm | \
 ppmchange  black white white black | \
 ppmtopgm | pgmtopbm -th -val=0.5 | cksum
diff --git a/test/ppmchange.test b/test/ppmchange.test
index a749a5d2..a579631b 100755
--- a/test/ppmchange.test
+++ b/test/ppmchange.test
@@ -1,4 +1,4 @@
-#! /bin/bash
+#! /bin/sh
 # This script tests: ppmchange
 # Also requires: ppmrainbow pgmramp ppmhist
 
diff --git a/test/ppmcie.test b/test/ppmcie.test
index 0ce69dea..dd7f121f 100755
--- a/test/ppmcie.test
+++ b/test/ppmcie.test
@@ -1,4 +1,4 @@
-#! /bin/bash
+#! /bin/sh
 # This script tests: ppmcie
 # Also requires: pamsumm pamsharpness
 
diff --git a/test/ppmdfont.test b/test/ppmdfont.test
index 7d894789..e6b461f1 100755
--- a/test/ppmdfont.test
+++ b/test/ppmdfont.test
@@ -1,4 +1,4 @@
-#! /bin/bash
+#! /bin/sh
 # This script tests: ppmdmkfont ppmddumpfont ppmdcfont
 # Also requires:
 
diff --git a/test/ppmdim.test b/test/ppmdim.test
index 848e2e9f..48d9e891 100755
--- a/test/ppmdim.test
+++ b/test/ppmdim.test
@@ -1,4 +1,4 @@
-#! /bin/bash
+#! /bin/sh
 # This script tests: ppmdim
 # Also requires: pamfunc pamarith pamsumm
 
diff --git a/test/ppmdither.test b/test/ppmdither.test
index 7e32ef59..f82c34ff 100755
--- a/test/ppmdither.test
+++ b/test/ppmdither.test
@@ -1,4 +1,4 @@
-#! /bin/bash
+#! /bin/sh
 # This script tests: ppmdither
 # Also requires:
 
diff --git a/test/ppmforge-parameters.ok b/test/ppmforge-parameters.ok
index 37d89ccd..afb3e855 100644
--- a/test/ppmforge-parameters.ok
+++ b/test/ppmforge-parameters.ok
@@ -1,10 +1,14 @@
-Test 1
+Test 1: Should print 256 256
 256 256
-100 90
+Test 2: Should print 40 30
+40 30
+Test 3: Should print 90 90
 90 90
 Test Invalid
-Expected failure 1 1
-Expected failure 2 1
-Expected failure 3 1
-Expected failure 4 1
-Expected failure 5 1
+Expected failure 1 (no output)
+Expected failure 2 (no output)
+Expected failure 3 (no output)
+Expected failure 4 (no output)
+Expected failure 5 (no output)
+Expected failure 6 (no output)
+Expected failure 7 (no output)
diff --git a/test/ppmforge-parameters.test b/test/ppmforge-parameters.test
index 28a92916..0525e7af 100755
--- a/test/ppmforge-parameters.test
+++ b/test/ppmforge-parameters.test
@@ -1,39 +1,35 @@
-#! /bin/bash
+#! /bin/sh
 # This script tests: ppmforge
 # Also requires: pamfile
 
-echo "Test 1"
+echo "Test 1: Should print 256 256"
 
-# Should print 256 256
-ppmforge -night | pamfile -size
+# Default size is 256 256
+ppmforge -night -seed=1 | pamfile -size
+
+echo "Test 2: Should print 40 30"
 
 # Width is adjusted if not even
-# becomes 100 in this case
-ppmforge -night -width=99 -height=90 | pamfile -size
+# becomes 40 in this case
+ppmforge -night -seed=1 -width=39 -height=30 | pamfile -size
+
+echo "Test 3: Should print 90 90"
 
 # Width is adjusted if smaller than height
-# brought up to 100 in this case
-ppmforge -night -width=80 -height=90 | pamfile -size
+# brought up to 90 in this case
+ppmforge -night -seed=1 -width=80 -height=90 | pamfile -size
 
 echo "Test Invalid"
 
 tmpdir=${tmpdir:-/tmp}
 test_out=${tmpdir}/test_out
 
-echo 1>&2
-echo "Invalid command-line arguments." 1>&2
-echo "Error messages should appear below the line." 1>&2
-echo "-----------------------------------------------------------" 1>&2
-
-ppmforge -night  -dimension=0  > ${test_out} || \
-   echo -n "Expected failure 1"; test -s ${test_out}; echo " "$?
-ppmforge -clouds -mesh=1.99    > ${test_out} || \
-   echo -n "Expected failure 2"; test -s ${test_out}; echo " "$?
-ppmforge -clouds -power=0      > ${test_out} || \
-   echo -n "Expected failure 3"; test -s ${test_out}; echo " "$?
-ppmforge         -ice=0        > ${test_out} || \
-   echo -n "Expected failure 4"; test -s ${test_out}; echo " "$?
-ppmforge         -glaciers=0   > ${test_out} || \
-   echo -n "Expected failure 5"; test -s ${test_out}; echo " "$?
-
-rm ${test_out}
+. ${srcdir}/test-invalid.inc
+
+invCmd "ppmforge -seed=0 -night -dimension=0"
+invCmd "ppmforge -seed=0 -dimension=10"
+invCmd "ppmforge -seed=0 -dimension=-1"
+invCmd "ppmforge -seed=0 -clouds -mesh=1.99"
+invCmd "ppmforge -seed=0 -clouds -power=0"
+invCmd "ppmforge -seed=0 -ice=-1"
+invCmd "ppmforge -seed=0 -glaciers=-1"
diff --git a/test/ppmforge.ok b/test/ppmforge.ok
new file mode 100644
index 00000000..d2ed4a66
--- /dev/null
+++ b/test/ppmforge.ok
@@ -0,0 +1,10 @@
+Test 1. Should print: 547829788 196623  (Mersenne Twister)
+3820754824 196623
+Test 2.
+match
+Test 3.
+match
+Test 4.
+match
+Test 5.
+match
diff --git a/test/ppmforge.rand-ok b/test/ppmforge.rand-ok
deleted file mode 100644
index c8b3ac9f..00000000
--- a/test/ppmforge.rand-ok
+++ /dev/null
@@ -1,3 +0,0 @@
-000|0
-081|3634219838 196623
-082|3262664440 196623
diff --git a/test/ppmforge.test b/test/ppmforge.test
index 3ebea88c..2a120357 100755
--- a/test/ppmforge.test
+++ b/test/ppmforge.test
@@ -1,9 +1,50 @@
-#! /bin/bash
+#! /bin/sh
 # This script tests: ppmforge
-# Also requires:
+# Also requires: pnmpsnr
 
-# Use small x y values to avoid floating point issues.
-
-# Should print: 3634219838 196623 (Glibc)
-#               3262664440 196623 (MAC OS)
+echo "Test 1. Should print: 547829788 196623  (Mersenne Twister)" 
 ppmforge -night -seed 1 | cksum
+
+tmpdir=${tmpdir:-/tmp}
+test_ppm=${tmpdir}/test.ppm
+
+# Target values for following tests were determined by running the
+# ppmforge command pairs 1000 times with different seeds, finding
+# the minimum (or "poorest match") for each component and 
+# subtracting 0.01 dB.   As such these are weak tests.
+
+echo "Test 2."
+ppmforge -cloud -seed 110 -power 0.75 > ${test_ppm}
+ppmforge -cloud -seed 110 -power 0.74 | \
+  pnmpsnr -rgb -target1=40.53 -target2=40.53 -target3=999 - ${test_ppm}
+
+
+rm ${test_ppm}
+
+echo "Test 3."
+ppmforge -cloud -seed 111 -dimension 2.15 > ${test_ppm}
+ppmforge -cloud -seed 111 -dimension 2.16 | \
+  pnmpsnr -rgb -target1=40.34 -target2=40.34 -target3=999 - ${test_ppm}        
+
+  # Note that there should be no difference for the target3: blue.
+
+
+rm ${test_ppm}
+
+echo "Test 4."
+ppmforge -seed 200 -stars 0 -ice 0.01 -power 1.180 -hour 10 >  ${test_ppm}
+ppmforge -seed 200 -stars 0 -ice 0.01 -power 1.181 -hour 10 | \
+  pnmpsnr -rgb -target1=45.9 -target2=45.81 -target3=32.11 - ${test_ppm}
+
+rm ${test_ppm}
+
+
+echo "Test 5."
+ppmforge -seed 300 -stars 0 -ice 0.01 \
+    -inclination 9  -hour 12 -power 300 > ${test_ppm} 
+ppmforge -seed 300 -stars 0 -ice 0.01 \
+    -inclination 9.1 -hour 12 -power 300 | \
+  pnmpsnr -rgb -target1=44.86 -target2=44.86 -target3=42.43 - ${test_ppm}
+
+
+rm ${test_ppm}
diff --git a/test/ppmhist.ok b/test/ppmhist.ok
index 468bd317..a78540f1 100644
--- a/test/ppmhist.ok
+++ b/test/ppmhist.ok
@@ -20,6 +20,6 @@ Test 2
  Summary: 6 colors: 1 black, 0 white, 0 gray, 5 color
  Summary: 6 colors: 1 black, 1 white, 1 gray, 3 color
 Test Invalid
-Expected failure 1 1
-Expected failure 2 1
-Expected failure 3 1
+Expected failure 1 (no output)
+Expected failure 2 (no output)
+Expected failure 3 (no output)
diff --git a/test/ppmhist.test b/test/ppmhist.test
index 1983bd13..1e814eb7 100755
--- a/test/ppmhist.test
+++ b/test/ppmhist.test
@@ -1,4 +1,4 @@
-#! /bin/bash
+#! /bin/sh
 # This script tests: ppmhist
 # Also requires: pgmramp pamtopnm pbmmake pamseq ppmpat
 
@@ -27,19 +27,8 @@ ppmpat -madras --color=rgb:00/00/00,rgb:31/58/a3,rgb:ff/ff/ff 25 25 | \
 
 echo "Test Invalid"
 
-tmpdir=${tmpdir:-/tmp}
-test_out=${tmpdir}/test_out
+. ${srcdir}/test-invalid.inc
 
-echo 1>&2
-echo "Invalid command-line argument combinations." 1>&2
-echo "Error messages should appear below the line." 1>&2
-echo "-----------------------------------------------------------" 1>&2
-
-ppmhist -hexcolor -float testimg.ppm > ${test_out} || \
-   echo -n "Expected failure 1"; test -s ${test_out}; echo " "$?
-ppmhist -hexcolor -map   testimg.ppm > ${test_out} || \
-   echo -n "Expected failure 2"; test -s ${test_out}; echo " "$?
-ppmhist -float    -map   testimg.ppm > ${test_out} || \
-   echo -n "Expected failure 3"; test -s ${test_out}; echo " "$?
-
-rm ${test_out}
+invCmd "ppmhist -hexcolor -float testimg.ppm"
+invCmd "ppmhist -hexcolor -map   testimg.ppm"
+invCmd "ppmhist -float    -map   testimg.ppm"
diff --git a/test/ppmmake.ok b/test/ppmmake.ok
index 6d559c8d..e365bd9e 100644
--- a/test/ppmmake.ok
+++ b/test/ppmmake.ok
@@ -1,15 +1,23 @@
 Test 1
+P3
+1 1
+5
+0 0 0
+P3
+1 1
+65535
+65535 65535 65535
 2477651508 15012
-4294967295 0
+135932096 23
 2378991101 7513
 Test Invalid
-Expected failure 1 1
-Expected failure 2 1
-Expected failure 3 1
-Expected failure 4 1
-Expected failure 5 1
-Expected failure 6 1
-Expected failure 7 1
-Expected failure 8 1
-Expected failure 9 1
-Expected failure 10 1
+Expected failure 1 (no output)
+Expected failure 2 (no output)
+Expected failure 3 (no output)
+Expected failure 4 (no output)
+Expected failure 5 (no output)
+Expected failure 6 (no output)
+Expected failure 7 (no output)
+Expected failure 8 (no output)
+Expected failure 9 (no output)
+Expected failure 10 (no output)
diff --git a/test/ppmmake.test b/test/ppmmake.test
index f28249c7..295e0bf4 100755
--- a/test/ppmmake.test
+++ b/test/ppmmake.test
@@ -1,42 +1,27 @@
-#! /bin/bash
+#! /bin/sh
 # This script tests: ppmmake
 # Also requires:
 
 echo "Test 1"
 
-ppmmake rgb:ff/80/80 50 100 -maxval=5 | cksum
-ppmmake rgbi:0.5/1.0/0 2   | cksum
+ppmmake -maxval=5 -plain rgb:00/00/00 1 1
+ppmmake -maxval=65535 -plain rgb:ff/ff/ff 1 1
+ppmmake -maxval=5 rgb:ff/80/80 50 100 | cksum
+ppmmake rgbi:0.5/1.0/0 2 2 | cksum
 ppmmake red 50 50  | cksum
 
 echo "Test Invalid"
 
-tmpdir=${tmpdir:-/tmp}
-test_out=${tmpdir}/test_out
+. ${srcdir}/test-invalid.inc
 
-echo 1>&2
-echo "Invalid command-line argument combinations." 1>&2
-echo "Error messages should appear below the line." 1>&2
-echo "-----------------------------------------------------------" 1>&2
-
-ppmmake rgb:gg/00/00  2 2  > ${test_out} || \
-   echo -n "Expected failure 1"; test -s ${test_out}; echo " "$?
-ppmmake rgb:ff/ff/00  2    > ${test_out} || \
-   echo -n "Expected failure 2"; test -s ${test_out}; echo " "$?
-ppmmake rgbi:1.1/0/0  2 2  > ${test_out} || \
-   echo -n "Expected failure 3"; test -s ${test_out}; echo " "$?
-ppmmake rgbi:1.0/.5   2 2  > ${test_out} || \
-   echo -n "Expected failure 4"; test -s ${test_out}; echo " "$?
-ppmmake rainbow       2 2  > ${test_out} || \
-   echo -n "Expected failure 5"; test -s ${test_out}; echo " "$?
-ppmmake               2 2  > ${test_out} || \
-   echo -n "Expected failure 6"; test -s ${test_out}; echo " "$?
-ppmmake blue -maxval=0 2 2  > ${test_out} || \
-   echo -n "Expected failure 7"; test -s ${test_out}; echo " "$?
-ppmmake blue -maxval=-1 2 2  > ${test_out} || \
-   echo -n "Expected failure 8"; test -s ${test_out}; echo " "$?
-ppmmake blue -maxval=65536 2 2  > ${test_out} || \
-   echo -n "Expected failure 9"; test -s ${test_out}; echo " "$?
-RGBDEF=/dev/null ppmmake red 2 2 > ${test_out} || \
-   echo -n "Expected failure 10"; test -s ${test_out}; echo " "$?
-
-rm ${test_out}
+invCmd "ppmmake rgb:gg/00/00  2 2"
+invCmd "ppmmake rgb:ff/ff/00  2"
+invCmd "ppmmake rgbi:1.1/0/0  2 2"
+invCmd "ppmmake rgbi:1.0/.5   2 2"
+invCmd "ppmmake rainbow       2 2"
+invCmd "ppmmake               2 2"
+invCmd "ppmmake blue -maxval=0 2 2"
+invCmd "ppmmake blue -maxval=-1 2 2"
+invCmd "ppmmake blue -maxval=65536 2 2"
+export  RGBDEF=/dev/null
+invCmd "ppmmake red 2 2"
diff --git a/test/ppmmix.test b/test/ppmmix.test
index e1c6486b..c3900baf 100755
--- a/test/ppmmix.test
+++ b/test/ppmmix.test
@@ -1,4 +1,4 @@
-#! /bin/bash
+#! /bin/sh
 # This script tests: ppmmix
 # Also requires: pamdepth pamenlarge pamsumm pbmmake
 # Also requires: pgmtopgm pnminvert ppmtopgm
diff --git a/test/ppmpat-random.ok b/test/ppmpat-random.ok
new file mode 100644
index 00000000..71f631e5
--- /dev/null
+++ b/test/ppmpat-random.ok
@@ -0,0 +1,6 @@
+Test 1. Should print: 1366170000 36015
+1366170000 36015
+Test 2. Should print: 4073196212 16813
+4073196212 16813
+Test 3. Should print: 2292015301 16813
+2292015301 16813
diff --git a/test/ppmpat-random.rand-ok b/test/ppmpat-random.rand-ok
deleted file mode 100644
index eb8779ab..00000000
--- a/test/ppmpat-random.rand-ok
+++ /dev/null
@@ -1,7 +0,0 @@
-000|0
-081|2219119109 36015
-081|3436846137 16813
-081|908097729 16813
-082|3606254242 36015
-082|3615722579 16813
-082|1756684515 16813
diff --git a/test/ppmpat-random.test b/test/ppmpat-random.test
index a6daa982..4da0d77c 100755
--- a/test/ppmpat-random.test
+++ b/test/ppmpat-random.test
@@ -1,4 +1,4 @@
-#! /bin/bash
+#! /bin/sh
 # This script tests: ppmpat
 # Also requires:
 
@@ -7,16 +7,16 @@
 
 # These tests require random numbers.
 
-# Test 1. Should print: 2219119109 36015 (glibc)
-#                       3606254242 36015 (MAC OS)
+echo "Test 1. Should print: 1366170000 36015" # Mersenne Twister
+
 ppmpat --randomseed=0 -camo 100 120 | cksum
 
-# Test 2. Should print: 3436846137 16813 (glibc)
-#                       3615722579 16813 (MAC OS)
+echo "Test 2. Should print: 4073196212 16813" # Mersenne Twister
+
 ppmpat --randomseed=0 -anticamo 80 70 | cksum
 
-# Test 3. Should print: 908097729 16813 (glibc)
-#                       1756684515 16813 (MAC OS)
+echo "Test 3. Should print: 2292015301 16813" # Mersenne Twister 
+
 ppmpat --randomseed=0 --color \
   rgb:55/c0/34,rgb:0/ff/0,rgb:0/ee/0,rgb:0/cd/0,rgb:0/8b/0,rgb:4f/4f/2f \
   -camo 80 70 | cksum
diff --git a/test/ppmpat.ok b/test/ppmpat.ok
index 4a9cebd9..dc7922ed 100644
--- a/test/ppmpat.ok
+++ b/test/ppmpat.ok
@@ -1,39 +1,47 @@
-Test 1
+Test 1. Should print: 4008533639 781
 4008533639 781
-Test 2
+Test 2. Should print: 738714211 781
+738714211 781
+Test 3. Should print: 3805937800 9613
 3805937800 9613
-Test 3
+Test 4. Should print: 1586690955 9613
+1586690955 9613
+Test 5. Should print: 2698433077 1549
 2698433077 1549
-Test 4
+Test 6. Should print: 1526189097 1549
+1526189097 1549
+Test 7. Should print: 3705929501 781
 3705929501 781
-Test 5
+Test 8. Should print: 1996587666 781
+1996587666 781
+Test 9. Should print: 3057513592 661
 3057513592 661
-Test 6
+Test 10. Should print: 1861389287 661
 1861389287 661
 Test Invalid
-Expected failure 1 1
-Expected failure 2 1
-Expected failure 3 1
-Expected failure 4 1
-Expected failure 5 1
-Expected failure 6 1
-Expected failure 7 1
-Expected failure 8 1
-Expected failure 9 1
-Expected failure 10 1
-Expected failure 11 1
-Expected failure 12 1
-Expected failure 13 1
-Expected failure 14 1
-Expected failure 15 1
-Expected failure 16 1
-Expected failure 17 1
-Expected failure 18 1
-Expected failure 19 1
-Expected failure 20 1
-Expected failure 21 1
-Expected failure 22 1
-Expected failure 23 1
-Expected failure 24 1
-Expected failure 25 1
-Expected failure 26 1
+Expected failure 1 (no output)
+Expected failure 2 (no output)
+Expected failure 3 (no output)
+Expected failure 4 (no output)
+Expected failure 5 (no output)
+Expected failure 6 (no output)
+Expected failure 7 (no output)
+Expected failure 8 (no output)
+Expected failure 9 (no output)
+Expected failure 10 (no output)
+Expected failure 11 (no output)
+Expected failure 12 (no output)
+Expected failure 13 (no output)
+Expected failure 14 (no output)
+Expected failure 15 (no output)
+Expected failure 16 (no output)
+Expected failure 17 (no output)
+Expected failure 18 (no output)
+Expected failure 19 (no output)
+Expected failure 20 (no output)
+Expected failure 21 (no output)
+Expected failure 22 (no output)
+Expected failure 23 (no output)
+Expected failure 24 (no output)
+Expected failure 25 (no output)
+Expected failure 26 (no output)
diff --git a/test/ppmpat.test b/test/ppmpat.test
index 0a6127ca..00f8421e 100755
--- a/test/ppmpat.test
+++ b/test/ppmpat.test
@@ -1,107 +1,82 @@
-#! /bin/bash
+#! /bin/sh
 # This script tests: ppmpat
 # Also requires:
 
-# Test 1. Should print: 4008533639 781
-echo "Test 1"
-ppmpat -g2 --color=rgb:32/0d/b7,rgb:31/58/a3 16 16 | cksum
+echo "Test 1. Should print: 4008533639 781"
+ppmpat -gingham2 \
+       -color=rgb:32/0d/b7,rgb:31/58/a3 16 16 | cksum
 
-# Test 2. Should print: 3805937800 9613
-echo "Test 2"
-ppmpat -g3 --color=rgb:32/0d/b7,rgb:31/58/a3,rgb:e9/5e/d4 64 50 | cksum
+echo "Test 2. Should print: 738714211 781"
+ppmpat -g2 -mesh \
+       --color=rgb:32/0d/b7,rgb:31/58/a3 16 16 | cksum
 
-# Test 3. Should print: 2698433077 1549
-echo "Test 3"
-ppmpat -madras --color=rgb:32/0d/b7,rgb:31/58/a3,rgb:e9/5e/d4 32 16 | cksum
+echo "Test 3. Should print: 3805937800 9613"
+ppmpat -gingham3 \
+       -color=rgb:32/0d/b7,rgb:31/58/a3,rgb:e9/5e/d4 64 50 | cksum
 
-# Test 4. Should print: 3705929501 781
-echo "Test 4"
+echo "Test 4. Should print: 1586690955 9613"
+ppmpat -g3 -mesh \
+       -color=rgb:32/0d/b7,rgb:31/58/a3,rgb:e9/5e/d4 64 50 | cksum
+
+echo "Test 5. Should print: 2698433077 1549"
+ppmpat -madras \
+       --color=rgb:32/0d/b7,rgb:31/58/a3,rgb:e9/5e/d4 32 16 | cksum
+
+echo "Test 6. Should print: 1526189097 1549"
+ppmpat -madras -mesh \
+       --color=rgb:32/0d/b7,rgb:31/58/a3,rgb:e9/5e/d4 32 16 | cksum
+
+echo "Test 7. Should print: 3705929501 781"
 ppmpat -tartan --color=rgb:32/0d/b7,rgb:31/58/a3,rgb:e9/5e/d4 16 16 | cksum
 
-# Test 5. Should print: 3057513592 661
-echo "Test 5"
+echo "Test 8. Should print: 1996587666 781"
+ppmpat -tartan -mesh \
+       --color=rgb:32/0d/b7,rgb:31/58/a3,rgb:e9/5e/d4 16 16 | cksum
+
+echo "Test 9. Should print: 3057513592 661"
 ppmpat -argyle1 --color=rgb:ff/ff/ff,rgb:ff/0/0 12 18 | cksum
 
-# Test 6. Should print: 1861389287 661
-echo "Test 6"
+echo "Test 10. Should print: 1861389287 661"
 ppmpat -argyle2 --color=rgb:00/00/00,rgb:ff/80/80,rgb:e0/e0/e0 12 18 | cksum
 
-# Test 7.
 echo "Test Invalid"
 
-tmpdir=${tmpdir:-/tmp}
-test_out=${tmpdir}/test_out
-
-echo 1>&2
-echo "Invalid command-line argument combinations." 1>&2
-echo "Error messages should appear below the line." 1>&2
-echo "-----------------------------------------------------------" 1>&2
-
-ppmpat -g2 -g3 10 10 > ${test_out} || \
-   echo -n "Expected failure 1"; test -s ${test_out}; echo " "$?
-ppmpat -madras -tartan 10 10 > ${test_out} || \
-   echo -n "Expected failure 2"; test -s ${test_out}; echo " "$?
-ppmpat -poles -squig 10 10 > ${test_out} || \
-   echo -n "Expected failure 3"; test -s ${test_out}; echo " "$?
-ppmpat -camo -anticamo 10 10 > ${test_out} || \
-   echo -n "Expected failure 4"; test -s ${test_out}; echo " "$?
-ppmpat -argyle1 -argyle2 10 10 > ${test_out} || \
-   echo -n "Expected failure 5"; test -s ${test_out}; echo " "$?
-
-ppmpat 10 10 > ${test_out} || \
-   echo -n "Expected failure 6"; test -s ${test_out}; echo " "$?
-ppmpat -g2 10 > ${test_out} || \
-   echo -n "Expected failure 7"; test -s ${test_out}; echo " "$?
-ppmpat -g2 10 10 10 > ${test_out} || \
-   echo -n "Expected failure 8"; test -s ${test_out}; echo " "$?
-ppmpat -g2 10 > ${test_out} || \
-   echo -n "Expected failure 9"; test -s ${test_out}; echo " "$?
+. ${srcdir}/test-invalid.inc
+
+invCmd "ppmpat -g2 -g3 10 10"
+invCmd "ppmpat -madras -tartan 10 10"
+invCmd "ppmpat -poles -squig 10 10"
+invCmd "ppmpat -camo -anticamo 10 10"
+invCmd "ppmpat -argyle1 -argyle2 10 10"
+invCmd "ppmpat 10 10"
+invCmd "ppmpat -g2 10"
+invCmd "ppmpat -g2 10 10 10"
+invCmd "ppmpat -g2 10"
 
 clist1="-color=rgb:00/00/00"
 clist2="-color=rgb:00/00/00,rgb:00/00/ff"
 clist3="-color=rgb:00/00/00,rgb:00/00/ff,rgb:00/ff/ff"
 clist4="-color=rgb:00/00/00,rgb:00/00/ff,rgb:00/ff/ff,rgb:ff/ff/ff"
 
-# These patterns require exactly 2 colors 
-ppmpat -gingham2 ${clist1} 10 10 > ${test_out} || \
-   echo -n "Expected failure 10"; test -s ${test_out}; echo " "$?
-ppmpat -argyle1  ${clist1} 10 10 > ${test_out} || \
-   echo -n "Expected failure 11"; test -s ${test_out}; echo " "$?
-ppmpat -gingham2 ${clist3} 10 10 > ${test_out} || \
-   echo -n "Expected failure 12"; test -s ${test_out}; echo " "$?
-ppmpat -argyle1  ${clist3} 10 10 > ${test_out} || \
-   echo -n "Expected failure 13"; test -s ${test_out}; echo " "$?
-
-# These require exactly 3 colors 
-ppmpat -gingham3 ${clist2} 10 10 > ${test_out} || \
-   echo -n "Expected failure 14"; test -s ${test_out}; echo " "$?
-ppmpat -argyle2  ${clist2} 10 10 > ${test_out} || \
-   echo -n "Expected failure 15"; test -s ${test_out}; echo " "$?
-ppmpat -madras   ${clist2} 10 10 > ${test_out} || \
-   echo -n "Expected failure 16"; test -s ${test_out}; echo " "$?
-ppmpat -tartan   ${clist2} 10 10 > ${test_out} || \
-   echo -n "Expected failure 17"; test -s ${test_out}; echo " "$?
-ppmpat -gingham3 ${clist4} 10 10 > ${test_out} || \
-   echo -n "Expected failure 18"; test -s ${test_out}; echo " "$?
-ppmpat -argyle2  ${clist4} 10 10 > ${test_out} || \
-   echo -n "Expected failure 19"; test -s ${test_out}; echo " "$?
-ppmpat -madras   ${clist4} 10 10 > ${test_out} || \
-   echo -n "Expected failure 20"; test -s ${test_out}; echo " "$?
-ppmpat -tartan   ${clist4} 10 10 > ${test_out} || \
-   echo -n "Expected failure 21"; test -s ${test_out}; echo " "$?
-
-# These require at least 3 colors 
-ppmpat -squig    ${clist2} 10 10 > ${test_out} || \
-   echo -n "Expected failure 22"; test -s ${test_out}; echo " "$?
-ppmpat -camo     ${clist2} 10 10 > ${test_out} || \
-   echo -n "Expected failure 23"; test -s ${test_out}; echo " "$?
-ppmpat -anticamo ${clist2} 10 10 > ${test_out} || \
-   echo -n "Expected failure 24"; test -s ${test_out}; echo " "$?
-
-# The squig pattern has an aspect ratio restriction 
-ppmpat -squig ${clist3} 10 250  > ${test_out} || \
-   echo -n "Expected failure 25"; test -s ${test_out}; echo " "$?
-ppmpat -squig ${clist3} 500 20  > ${test_out} || \
-   echo -n "Expected failure 26"; test -s ${test_out}; echo " "$?
-
-rm ${test_out}
+# These patterns require exactly 2 colors
+invCmd "ppmpat -gingham2 ${clist1} 10 10"
+invCmd "ppmpat -argyle1  ${clist1} 10 10"
+invCmd "ppmpat -gingham2 ${clist3} 10 10"
+invCmd "ppmpat -argyle1  ${clist3} 10 10"
+
+# These require exactly 3 colors
+invCmd "ppmpat -gingham3 ${clist2} 10 10"
+invCmd "ppmpat -argyle2  ${clist2} 10 10"
+invCmd "ppmpat -madras   ${clist2} 10 10"
+invCmd "ppmpat -tartan   ${clist2} 10 10"
+invCmd "ppmpat -gingham3 ${clist4} 10 10"
+invCmd "ppmpat -argyle2  ${clist4} 10 10"
+invCmd "ppmpat -madras   ${clist4} 10 10"
+invCmd "ppmpat -tartan   ${clist4} 10 10"
+invCmd "ppmpat -squig    ${clist2} 10 10"
+invCmd "ppmpat -camo     ${clist2} 10 10"
+invCmd "ppmpat -anticamo ${clist2} 10 10"
+
+# The squig pattern has an aspect ratio restriction
+invCmd "ppmpat -squig ${clist3} 10 250"
+invCmd "ppmpat -squig ${clist3} 500 20"
diff --git a/test/ppmrelief.test b/test/ppmrelief.test
index 3467dcde..c7241663 100755
--- a/test/ppmrelief.test
+++ b/test/ppmrelief.test
@@ -1,4 +1,4 @@
-#! /bin/bash
+#! /bin/sh
 # This script tests: ppmrelief
 # Also requires: pbmmake pgmramp pamflip
 
diff --git a/test/ppmrough-parameters.ok b/test/ppmrough-parameters.ok
new file mode 100644
index 00000000..473ace05
--- /dev/null
+++ b/test/ppmrough-parameters.ok
@@ -0,0 +1,25 @@
+Test Invalid
+Expected failure 1 (no output)
+Expected failure 2 (no output)
+Expected failure 3 (no output)
+Expected failure 4 (no output)
+Expected failure 5 (no output)
+Expected failure 6 (no output)
+Expected failure 7 (no output)
+Expected failure 8 (no output)
+Expected failure 9 (no output)
+Expected failure 10 (no output)
+Expected failure 11 (no output)
+Expected failure 12 (no output)
+Expected failure 13 (no output)
+Expected failure 14 (no output)
+Expected failure 15 (no output)
+Expected failure 16 (no output)
+Expected failure 17 (no output)
+Expected failure 20 (no output)
+Expected failure 18 (no output)
+Expected failure 19 (no output)
+Expected failure 20 (no output)
+Expected failure 21 (no output)
+Expected failure 22 (no output)
+Expected failure 23 (no output)
diff --git a/test/ppmrough-parameters.test b/test/ppmrough-parameters.test
new file mode 100755
index 00000000..fb67424e
--- /dev/null
+++ b/test/ppmrough-parameters.test
@@ -0,0 +1,145 @@
+#! /bin/sh
+# This script tests: ppmrough
+# Also requires:
+
+tmpdir=${tmpdir:-/tmp}
+test_out=${tmpdir}/test_out
+
+
+# Test Invalid
+echo "Test Invalid"
+
+echo 1>&2
+echo "Invalid command-line argument combinations." 1>&2
+echo "Error messages should appear below the line." 1>&2
+echo "-----------------------------------------------------------" 1>&2
+
+ppmrough -h 10 -w 10 -top -1 > ${test_out} || \
+  printf "Expected failure 1 "
+  test -s ${test_out} && echo "unexpected output" || echo "(no output)"
+  rm -f ${test_out}
+
+ppmrough -h 10 -w 100 -top 11 > ${test_out} || \
+  printf "Expected failure 2 "
+  test -s ${test_out} && echo "unexpected output" || echo "(no output)"
+  rm -f ${test_out}
+
+
+ppmrough -h 10 -w 10 -bottom -1 > ${test_out} || \
+  printf "Expected failure 3 "
+  test -s ${test_out} && echo "unexpected output" || echo "(no output)"
+  rm -f ${test_out}
+
+ppmrough -h 10 -w 1000 -bottom 11 > ${test_out} || \
+  printf "Expected failure 4 "
+  test -s ${test_out} && echo "unexpected output" || echo "(no output)"
+  rm -f ${test_out}
+
+ppmrough -h 10 -w 10 -left -1 > ${test_out} || \
+  printf "Expected failure 5 "
+  test -s ${test_out} && echo "unexpected output" || echo "(no output)"
+  rm -f ${test_out}
+
+ppmrough -h 10 -w 100 -left 101 > ${test_out} || \
+  printf "Expected failure 6 "
+  test -s ${test_out} && echo "unexpected output" || echo "(no output)"
+  rm -f ${test_out}
+
+
+ppmrough -h 10 -w 10 -right -1 > ${test_out} || \
+  printf "Expected failure 7 "
+  test -s ${test_out} && echo "unexpected output" || echo "(no output)"
+  rm -f ${test_out}
+
+ppmrough -h 10 -w 1000 -right 1001 > ${test_out} || \
+  printf "Expected failure 8 "
+  test -s ${test_out} && echo "unexpected output" || echo "(no output)"
+  rm -f ${test_out}
+
+
+ppmrough -width 0.1 > ${test_out} || \
+  printf "Expected failure 9 "
+  test -s ${test_out} && echo "unexpected output" || echo "(no output)"
+  rm -f ${test_out}
+
+ppmrough -width -1 > ${test_out} || \
+  printf "Expected failure 10 "
+  test -s ${test_out} && echo "unexpected output" || echo "(no output)"
+  rm -f ${test_out}
+
+ppmrough -width > ${test_out} || \
+  printf "Expected failure 11 "
+  test -s ${test_out} && echo "unexpected output" || echo "(no output)"
+  rm -f ${test_out}
+
+
+ppmrough -height 0.1 > ${test_out} || \
+  printf "Expected failure 12 "
+  test -s ${test_out} && echo "unexpected output" || echo "(no output)"
+  rm -f ${test_out}
+
+ppmrough -height -1 > ${test_out} || \
+  printf "Expected failure 13 "
+  test -s ${test_out} && echo "unexpected output" || echo "(no output)"
+  rm -f ${test_out}
+
+ppmrough -height > ${test_out} || \
+  printf "Expected failure 14 "
+  test -s ${test_out} && echo "unexpected output" || echo "(no output)"
+  rm -f ${test_out}
+
+
+ppmrough -randomseed 0.1 > ${test_out} || \
+  printf "Expected failure 15 "
+  test -s ${test_out} && echo "unexpected output" || echo "(no output)"
+  rm -f ${test_out}
+
+ppmrough -randomseed -1 > ${test_out} || \
+  printf "Expected failure 16 "
+  test -s ${test_out} && echo "unexpected output" || echo "(no output)"
+  rm -f ${test_out}
+
+ppmrough -randomseed > ${test_out} || \
+  printf "Expected failure 17 "
+  test -s ${test_out} && echo "unexpected output" || echo "(no output)"
+  rm -f ${test_out}
+
+
+
+ppmrough -var A > ${test_out} || \
+  printf "Expected failure 20 "
+  test -s ${test_out} && echo "unexpected output" || echo "(no output)"
+  rm -f ${test_out}
+
+ppmrough -var -1 > ${test_out} || \
+  printf "Expected failure 18 "
+  test -s ${test_out} && echo "unexpected output" || echo "(no output)"
+  rm -f ${test_out}
+
+ppmrough -var > ${test_out} || \
+  printf "Expected failure 19 "
+  test -s ${test_out} && echo "unexpected output" || echo "(no output)"
+  rm -f ${test_out}
+
+
+ppmrough -bg redmint > ${test_out} || \
+  printf "Expected failure 20 "
+  test -s ${test_out} && echo "unexpected output" || echo "(no output)"
+  rm -f ${test_out}
+
+ppmrough -bg > ${test_out} || \
+  printf "Expected failure 21 "
+  test -s ${test_out} && echo "unexpected output" || echo "(no output)"
+  rm -f ${test_out}
+
+
+ppmrough -fg redmint > ${test_out} || \
+  printf "Expected failure 22 "
+  test -s ${test_out} && echo "unexpected output" || echo "(no output)"
+  rm -f ${test_out}
+
+ppmrough -fg > ${test_out} || \
+  printf "Expected failure 23 "
+  test -s ${test_out} && echo "unexpected output" || echo "(no output)"
+  rm -f ${test_out}
+
diff --git a/test/ppmrough.ok b/test/ppmrough.ok
new file mode 100644
index 00000000..4beff006
--- /dev/null
+++ b/test/ppmrough.ok
@@ -0,0 +1,24 @@
+Test 1. Should print 378403602 30015
+378403602 30015
+Test 2. Should print 378403602 30015
+378403602 30015
+Test 3. Should print 535171440 30015
+535171440 30015
+Test 4. Should print 937167683 30015
+937167683 30015
+Test 5. Should print 1927474861 30015
+1927474861 30015
+Test 6. Should print 3596045345 30015
+3596045345 30015
+Test 7. Should print 198510149 30015
+198510149 30015
+Test 8. Should print 1128371780 30015
+1128371780 30015
+Test 9. Should print 2909877411 30015
+2909877411 30015
+Test 10. Should print 2820370592 30015
+2820370592 30015
+Test 11. Should print 2028409204 30015
+2028409204 30015
+Test 12. Should print 4234304830 30015
+4234304830 30015
diff --git a/test/ppmrough.rand-ok b/test/ppmrough.rand-ok
deleted file mode 100644
index 216545c7..00000000
--- a/test/ppmrough.rand-ok
+++ /dev/null
@@ -1,3 +0,0 @@
-000|0
-081|378403602 30015
-082|378403602 30015
diff --git a/test/ppmrough.test b/test/ppmrough.test
index bd4211a3..e1d720d5 100755
--- a/test/ppmrough.test
+++ b/test/ppmrough.test
@@ -1,6 +1,48 @@
-#! /bin/bash
+#! /bin/sh
 # This script tests: ppmrough
 # Also requires:
 
-# Should print: 378403602 30015 (Glibc and MAC OS)
-ppmrough  -randomseed 1 | cksum
+defaultopts="-randomseed 1 -bg rgb:00/ff/ff -fg rgb:ff/ff/00 -w 100 -h 100"
+
+# No border
+
+echo "Test 1. Should print 378403602 30015"
+ppmrough -randomseed 1 | cksum
+
+echo "Test 2. Should print 378403602 30015"
+ppmrough -randomseed 1 -var 0 | cksum
+
+# Vertical border
+
+echo "Test 3. Should print 535171440 30015"
+ppmrough ${defaultopts} -left 20 | cksum
+
+echo "Test 4. Should print 937167683 30015"
+ppmrough ${defaultopts} -right 20 | cksum
+
+echo "Test 5. Should print 1927474861 30015"
+ppmrough ${defaultopts} -left 50 | cksum
+
+echo "Test 6. Should print 3596045345 30015"
+ppmrough ${defaultopts} -right 50 | cksum
+
+echo "Test 7. Should print 198510149 30015"
+ppmrough ${defaultopts} -right 20 -var 0 | cksum
+
+# Horizontal border
+
+echo "Test 8. Should print 1128371780 30015"
+ppmrough ${defaultopts} -top 30 | cksum
+
+echo "Test 9. Should print 2909877411 30015"
+ppmrough ${defaultopts} -bottom 25 | cksum
+
+echo "Test 10. Should print 2820370592 30015"
+ppmrough ${defaultopts} -top 50 | cksum
+
+echo "Test 11. Should print 2028409204 30015"
+ppmrough ${defaultopts} -bottom 50 | cksum
+
+echo "Test 12. Should print 4234304830 30015"
+ppmrough ${defaultopts} -bottom 10 -var 0 | cksum
+
diff --git a/test/ppmshift.ok b/test/ppmshift.ok
new file mode 100644
index 00000000..735ac445
--- /dev/null
+++ b/test/ppmshift.ok
@@ -0,0 +1,23 @@
+Test 1. Should print: 3705777303 101484
+3705777303 101484
+Test 2. Should print: 202790723 685
+202790723 685
+Test 3. Should print: 0 0 : 0
+0 0 : 0
+Test 4.  Should print: 0 0 : 0
+0 0 : 0
+Test 5. (1) Should print: 1 twice
+1
+1
+Test 5. (15) Should print: 1 twice
+1
+1
+Test 5. (16) Should print: 1 twice
+1
+1
+Test 5. (20) Should print: 1 twice
+1
+1
+Test 5. (1000) Should print: 1 twice
+1
+1
diff --git a/test/ppmshift.test b/test/ppmshift.test
new file mode 100755
index 00000000..fff193b3
--- /dev/null
+++ b/test/ppmshift.test
@@ -0,0 +1,42 @@
+#! /bin/bash
+# This script tests: ppmshift
+# Also requires: pgmtoppm
+
+echo "Test 1. Should print: 3705777303 101484"
+ppmshift -seed=1 10 testimg.ppm | cksum
+
+echo "Test 2. Should print: 202790723 685"
+ppmshift -seed=1 1 testgrid.pbm | cksum
+
+echo "Test 3. Should print: 0 0 : 0"
+ppmshift -seed=1 0 testimg.ppm | cmp -s - testimg.ppm
+  echo ${PIPESTATUS[@]} ":" $?
+
+tmpdir=${tmpdir:-/tmp}
+test0_ppm=${tmpdir}/test0.ppm
+test14_ppm=${tmpdir}/test14.ppm
+
+pgmtoppm < maze.pbm > ${test0_ppm}
+
+echo "Test 4.  Should print: 0 0 : 0"
+  ppmshift -seed=2 0 maze.pbm | cmp -s - ${test0_ppm}
+    echo ${PIPESTATUS[@]} ":" $?
+
+ppmshift -seed=2 14 maze.pbm > ${test14_ppm}
+
+for i in 1 15 16 20 1000
+  do
+  echo "Test 5. ("$i") Should print: 1 twice"
+  ppmshift -seed=2 $i maze.pbm | cmp -s - ${test0_ppm}
+    echo $?
+  ppmshift -seed=2 $i maze.pbm | cmp -s - ${test14_ppm}
+    echo $?
+  done
+
+# In Test 5 the image files are not supposed to match.
+# When cmp finds a difference, it may terminate and stop reading input from
+# the pipe at that point.  This may cause a "broken pipe" exception; however
+# this does not always happen.  The broken pipe shows up as a non-zero value
+# for ${PIPESTATUS[0]}.
+
+rm ${test0_ppm} ${test14_ppm}
diff --git a/test/ppmspread.ok b/test/ppmspread.ok
new file mode 100644
index 00000000..40f44465
--- /dev/null
+++ b/test/ppmspread.ok
@@ -0,0 +1,12 @@
+Test 1.
+stdin: PPM RAW 227 149 3 255 RGB
+stdin: PPM RAW 227 149 3 255 RGB
+Test 2.
+57 59
+57 59
+Test 3. Should print 281226646 481
+281226646 481
+Test 4. Should print 639729144 101484
+639729144 101484
+Test 5. Should print 3278353642 685
+3278353642 685
diff --git a/test/ppmspread.test b/test/ppmspread.test
new file mode 100755
index 00000000..d7e0fb37
--- /dev/null
+++ b/test/ppmspread.test
@@ -0,0 +1,28 @@
+#! /bin/sh
+# This script tests: ppmspread
+# Also requires: pamfile ppmtopgm pgmtopbm
+
+# Input/output size does not change
+
+echo "Test 1."
+cat testimg.ppm | pamfile -machine
+ppmspread -randomseed=100 20 testimg.ppm | pamfile -machine
+
+echo "Test 2."
+pamfile -size maze.pbm
+ppmspread -randomseed=100 20 maze.pbm | pamfile -size
+
+# No change when spread distance value is 0
+
+echo "Test 3. Should print 281226646 481"
+ppmspread -randomseed=1 0 maze.pbm | ppmtopgm | pgmtopbm | cksum
+
+# The following tests will fail when changes are made to the random
+# number generator
+
+echo "Test 4. Should print 639729144 101484"
+ppmspread -randomseed=1 10 testimg.ppm | cksum
+
+echo "Test 5. Should print 3278353642 685"
+ppmspread -randomseed=1 1 testgrid.pbm | cksum
+
diff --git a/test/ppmtoapplevol.ok b/test/ppmtoapplevol.ok
new file mode 100644
index 00000000..daed172c
--- /dev/null
+++ b/test/ppmtoapplevol.ok
@@ -0,0 +1,6 @@
+Test: should print 1518149010 3065
+1518149010 3065
+Test Invalid
+Expected failure 1 (no output)
+Expected failure 2 (no output)
+Expected failure 3 (no output)
diff --git a/test/ppmtoapplevol.test b/test/ppmtoapplevol.test
new file mode 100755
index 00000000..a11e6aa6
--- /dev/null
+++ b/test/ppmtoapplevol.test
@@ -0,0 +1,30 @@
+#! /bin/sh
+# This script tests: ppmtoapplevol 
+# Also requires: ppmmake pbmmake
+
+echo "Test: should print 1518149010 3065"
+ppmmake rgb:0/0/0 255 12 | ppmtoapplevol | cksum
+
+echo "Invalid input." 1>&2
+echo "Error messages should appear below the line." 1>&2
+echo "-----------------------------------------------------------" 1>&2
+
+echo "Test Invalid"
+
+tmpdir=${tmpdir:-/tmp}
+test_out=${tmpdir}/test_out
+
+pbmmake 10 11 | ppmtoapplevol > ${test_out} || \
+  printf "Expected failure 1 "
+  test -s ${test_out} && echo "unexpected output" || echo "(no output)"
+  rm -f ${test_out}
+ 
+pbmmake 10 13 | ppmtoapplevol > ${test_out} || \
+  printf "Expected failure 2 "
+  test -s ${test_out} && echo "unexpected output" || echo "(no output)"
+  rm -f ${test_out}
+ 
+pbmmake 256 12 | ppmtoapplevol > ${test_out} || \
+  printf "Expected failure 3 "
+  test -s ${test_out} && echo "unexpected output" || echo "(no output)"
+  rm -f ${test_out}
diff --git a/test/ppmtoarbtxt-roundtrip.test b/test/ppmtoarbtxt-roundtrip.test
index dff78250..f63aabe2 100755
--- a/test/ppmtoarbtxt-roundtrip.test
+++ b/test/ppmtoarbtxt-roundtrip.test
@@ -1,4 +1,4 @@
-#! /bin/bash
+#! /bin/sh
 # This script tests: ppmtoarbtxt
 # Also requires: pnminvert pamtopnm
 
@@ -30,5 +30,4 @@ ppmtoarbtxt ${bodyskl} -hd ${headskl} testimg.ppm | tee ${inv_ppm} |
 
 cat ${inv_ppm} | ppmtoarbtxt ${bodyskl} -hd ${headskl} | pamtopnm | cksum
 
-
-rm ${bodyskl} ${headskl}
+rm ${inv_ppm} ${bodyskl} ${headskl}
diff --git a/test/ppmtomitsu.ok b/test/ppmtomitsu.ok
new file mode 100644
index 00000000..812b2ffa
--- /dev/null
+++ b/test/ppmtomitsu.ok
@@ -0,0 +1,14 @@
+Test 0. Should print 668243897 101532
+668243897 101532
+Test 1. Should print 3110813682 101562
+3110813682 101562
+Test 2. Should print 825518840 34209
+825518840 34209
+Test 3. Should print 3201293405 310
+3201293405 310
+Test 4. Should print 3354679572 752
+3354679572 752
+Test 5. Should print 3999654426 101549
+3999654426 101549
+Test 6. Should print 3103038403 101549
+3103038403 101549
diff --git a/test/ppmtomitsu.test b/test/ppmtomitsu.test
new file mode 100755
index 00000000..31cd936f
--- /dev/null
+++ b/test/ppmtomitsu.test
@@ -0,0 +1,31 @@
+#! /bin/sh
+# This script tests: ppmtomitsu
+# Also requires: pamseq pamdepth
+
+tmpdir=${tmpdir:-/tmp}
+testimg216_ppm=${tmpdir}/testimg216.ppm
+
+echo "Test 0. Should print 668243897 101532"
+
+pamseq 3 5 -tupletype=RGB | pamdepth 255 | pnmremap -nofloyd -mapfile=- testimg.ppm |\
+  tee ${testimg216_ppm} | cksum
+
+echo "Test 1. Should print 3110813682 101562"
+ppmtomitsu testimg.ppm | cksum
+
+echo "Test 2. Should print 825518840 34209"
+ppmtomitsu ${testimg216_ppm} | cksum
+
+echo "Test 3. Should print 3201293405 310"
+ppmtomitsu testgrid.pbm | cksum
+
+echo "Test 4. Should print 3354679572 752"
+ppmtomitsu -tiny testgrid.pbm | cksum
+
+echo "Test 5. Should print 3999654426 101549"
+ppmtomitsu -tiny testimg.ppm | cksum
+
+echo "Test 6. Should print 3103038403 101549"
+ppmtomitsu -tiny ${testimg216_ppm} | cksum
+
+rm ${testimg216_ppm}
diff --git a/test/ppmtopgm.test b/test/ppmtopgm.test
index 8503194b..696b660c 100755
--- a/test/ppmtopgm.test
+++ b/test/ppmtopgm.test
@@ -1,4 +1,4 @@
-#! /bin/bash
+#! /bin/sh
 # This script tests: ppmtopgm
 # Also requires:
 
diff --git a/test/ppmtoppm.ok b/test/ppmtoppm.ok
index 764a3464..2b4ad9f8 100644
--- a/test/ppmtoppm.ok
+++ b/test/ppmtoppm.ok
@@ -1 +1,23 @@
-829921912 685
+Test 1.  Should print a simple 4 x 3 pattern
+P3
+4 3
+255
+255 255 255  0 0 0  255 255 255  0 0 0
+0 0 0  255 255 255  0 0 0  255 255 255
+255 255 255  0 0 0  255 255 255  0 0 0
+Test 2.  Should print a simple 6 x 8 pattern
+P3
+6 8
+5
+0 0 0  0 0 0  0 0 0  1 1 1  1 1 1  2 2 2
+0 0 0  0 0 0  1 1 1  1 1 1  2 2 2  2 2 2
+0 0 0  1 1 1  1 1 1  2 2 2  2 2 2  2 2 2
+1 1 1  1 1 1  2 2 2  2 2 2  2 2 2  3 3 3
+1 1 1  2 2 2  2 2 2  2 2 2  3 3 3  3 3 3
+2 2 2  2 2 2  2 2 2  3 3 3  3 3 3  4 4 4
+2 2 2  2 2 2  3 3 3  3 3 3  4 4 4  4 4 4
+2 2 2  3 3 3  3 3 3  4 4 4  4 4 4  5 5 5
+Test 3.  Should print 669206373 10102
+669206373 10102
+Test 4.  Should print 1926073387 101484
+1926073387 101484
diff --git a/test/ppmtoppm.test b/test/ppmtoppm.test
index 797c733d..90ff2ddf 100755
--- a/test/ppmtoppm.test
+++ b/test/ppmtoppm.test
@@ -1,6 +1,15 @@
-#! /bin/bash
+#! /bin/sh
 # This script tests: ppmtoppm
-# Also requires:
+# Also requires: pbmmake pgmramp
 
+echo "Test 1.  Should print a simple 4 x 3 pattern"
+pbmmake -g 4 3 | ppmtoppm -plain
 
-ppmtoppm < testgrid.pbm | cksum
+echo "Test 2.  Should print a simple 6 x 8 pattern"
+pgmramp -diagonal -maxval=5 6 8 | ppmtoppm -plain
+
+echo "Test 3.  Should print 669206373 10102"
+ppmtoppm < maze.pbm | cksum
+
+echo "Test 4.  Should print 1926073387 101484"
+ppmtoppm < testimg.ppm | cksum
\ No newline at end of file
diff --git a/test/ppmwheel.ok b/test/ppmwheel.ok
index 0b0a7746..525bee2c 100644
--- a/test/ppmwheel.ok
+++ b/test/ppmwheel.ok
@@ -2,7 +2,8 @@ Test 1.
 1537578995 59
 875938089 86
 Test Invalid.
-Expected failure 1 1
-Expected failure 2 1
-Expected failure 3 1
-Expected failure 4 1
+Expected failure 1 (no output)
+Expected failure 2 (no output)
+Expected failure 3 (no output)
+Expected failure 4 (no output)
+Expected failure 5 (no output)
diff --git a/test/ppmwheel.test b/test/ppmwheel.test
index fd401951..ca439bea 100755
--- a/test/ppmwheel.test
+++ b/test/ppmwheel.test
@@ -1,4 +1,4 @@
-#! /bin/bash
+#! /bin/sh
 # This script tests: ppmwheel
 # Also requires:
 
@@ -122,15 +122,26 @@ echo "Error messages should appear below the line." 1>&2
 echo "-----------------------------------------------------------" 1>&2
 
 ppmwheel 10 -huevalue -huesaturation > ${test_out} || \
-   echo -n "Expected failure 1"; test -s ${test_out}; echo " "$?
+  printf "Expected failure 1 "
+  test -s ${test_out} && echo "unexpected output" || echo "(no output)"
+  rm -f ${test_out}
 
 ppmwheel 0 > ${test_out} || \
-   echo -n "Expected failure 2"; test -s ${test_out}; echo " "$?
+  printf "Expected failure 2 "
+  test -s ${test_out} && echo "unexpected output" || echo "(no output)"
+  rm -f ${test_out}
+
+ppmwheel 3 > ${test_out} || \
+  printf "Expected failure 3 "
+  test -s ${test_out} && echo "unexpected output" || echo "(no output)"
+  rm -f ${test_out}
 
 ppmwheel > ${test_out} || \
-   echo -n "Expected failure 3"; test -s ${test_out}; echo " "$?
+  printf "Expected failure 4 "
+  test -s ${test_out} && echo "unexpected output" || echo "(no output)"
+  rm -f ${test_out}
 
 ppmwheel 10 10 > ${test_out} || \
-   echo -n "Expected failure 4"; test -s ${test_out}; echo " "$?
-
-rm -f ${test_out}
\ No newline at end of file
+  printf "Expected failure 5 "
+  test -s ${test_out} && echo "unexpected output" || echo "(no output)"
+  rm -f ${test_out}
diff --git a/test/ps-alt-roundtrip.ok b/test/ps-alt-roundtrip.ok
index 2deba38d..a23005f9 100644
--- a/test/ps-alt-roundtrip.ok
+++ b/test/ps-alt-roundtrip.ok
@@ -1,2 +1,4 @@
+Test 1.  Should print: 281226646 481
 2425386270 41
-2916080186 235
+Test 2.  Should print: 2154092425 3374
+2154092425 3374
diff --git a/test/ps-alt-roundtrip.test b/test/ps-alt-roundtrip.test
index 8fc08f2b..bdecaffd 100755
--- a/test/ps-alt-roundtrip.test
+++ b/test/ps-alt-roundtrip.test
@@ -1,4 +1,4 @@
-#! /bin/bash
+#! /bin/sh
 # This script tests: pbmtoepsi pbmtopsg3 psidtopgm pstopnm
 # Also requires: gs pnmcrop
 
@@ -24,7 +24,9 @@
 # pstopnm does not use libnetpbm functions for output.
 # Output is filtered through at least one Netpbm program.
 
-# Test 1. Should print: 2425386270 41
+echo "Test 1.  Should print: 281226646 481"
+
+tmpdir=${tmpdir:-/tmp}
 testgrid1_ps=${tmpdir}/testgrid1.ps
 
 pbmtopsg3 -dpi=72 testgrid.pbm \
@@ -36,13 +38,12 @@ pstopnm -xborder=0 -yborder=0 -llx=0 -lly=-16 -urx=14 \
 rm ${testgrid1_ps}
 
 
-
-# Test 2. Should print: 2916080186 235
+echo "Test 2.  Should print: 2154092425 3374"
 # Output is pgm maxval=1 with black and white inverted.
-#
+
 testgrid_epsi=${tmpdir}/testgrid.epsi
 
-pbmtoepsi testgrid.pbm > ${testgrid_epsi} && \
+pbmtoepsi maze.pbm > ${testgrid_epsi} && \
 xysizebps=`awk  '/BeginPreview/ {print $2,$3,$4}' \
     ${testgrid_epsi}` && \
 awk '/^%%BeginPreview:/ { p=1; next } /^%%EndImage/ { p=0; next } \
diff --git a/test/ps-flate-roundtrip.ok b/test/ps-flate-roundtrip.ok
index 57fb124f..0fdf23f2 100644
--- a/test/ps-flate-roundtrip.ok
+++ b/test/ps-flate-roundtrip.ok
@@ -1,3 +1,5 @@
+Test 1.  Should print: 1926073387 101484 twice
 1926073387 101484
 1926073387 101484
-1386192571 507420
+Test 2. Should print 1831481505 608904
+1831481505 608904
diff --git a/test/ps-flate-roundtrip.test b/test/ps-flate-roundtrip.test
index 08d1500c..9fc24ddb 100755
--- a/test/ps-flate-roundtrip.test
+++ b/test/ps-flate-roundtrip.test
@@ -1,4 +1,4 @@
-#! /bin/bash
+#! /bin/sh
 # This script tests: pnmtops pstopnm
 # Also requires: pamtopnm gs zlib
 
@@ -17,7 +17,7 @@ tmpdir=${tmpdir:-/tmp}
 # pstopnm does not use libnetpbm functions for output.
 # Output is filtered through pamtopnm.
 
-# Test 1.  Should print: 1926073387 101484 twice
+echo "Test 1.  Should print: 1926073387 101484 twice"
 test1_ps=${tmpdir}/testimg1.ps
 
 for flag in "-ps -flate" "-ps -rle -ascii -flate"
@@ -32,16 +32,17 @@ for flag in "-ps -flate" "-ps -rle -ascii -flate"
 
 rm ${test1_ps}
 
-# Test 2. Should print: 1386192571 507420
+echo "Test 2. Should print 1831481505 608904"
 # See comments in ps-roundtrip.test
 
 test3_ps=${tmpdir}/testimg3.ps
 flag="-ps -bitspersample=12 -flate -rle -vmreclaim"
-cat testimg.ppm testimg.ppm testimg.ppm testgrid.pbm testgrid.pbm | \
-pnmtops -nocenter -equalpixels -dpi 72 -noturn -setpage ${flag} \
-  > ${test3_ps} &&
+cat testimg.ppm testimg.ppm testimg.ppm maze.pbm \
+  testgrid.pbm testgrid.pbm | \
+  pnmtops -nocenter -equalpixels -dpi 72 -noturn -setpage ${flag} \
+    > ${test3_ps} &&
 xysize3=`awk  '/BoundingBox/ {print "-xsize="$4,"-ysize="$5 ; exit}' \
-  ${test3_ps}` &&
+    ${test3_ps}` &&
 pstopnm -portrait -xborder=0 -yborder=0 $xysize3 -stdout  ${test3_ps} | \
   pamtopnm | cksum
 
diff --git a/test/ps-roundtrip.ok b/test/ps-roundtrip.ok
index 5ef66cc4..1a69224d 100644
--- a/test/ps-roundtrip.ok
+++ b/test/ps-roundtrip.ok
@@ -1,7 +1,9 @@
+Test 1.  Should print 1926073387 101484 four times
 1926073387 101484
 1926073387 101484
 1926073387 101484
 1926073387 101484
+Test 2.  Should print 2918318199 62 seven times
 2918318199 62
 2918318199 62
 2918318199 62
@@ -9,6 +11,7 @@
 2918318199 62
 2918318199 62
 2918318199 62
-1386192571 507420
-1386192571 507420
-1386192571 507420
+Test 3. Should print 1831481505 608904 three times
+1831481505 608904
+1831481505 608904
+1831481505 608904
diff --git a/test/ps-roundtrip.test b/test/ps-roundtrip.test
index 207646cc..5d7b7d65 100755
--- a/test/ps-roundtrip.test
+++ b/test/ps-roundtrip.test
@@ -1,6 +1,6 @@
-#! /bin/bash
+#! /bin/sh
 # This script tests: pnmtops pstopnm
-# Also requires: pamtopnm gs pbmmake pnmshear pnmpad pnmcat
+# Also requires: pamtopnm gs pbmmake pnmshear pnmpad pamcat
 
 
 # Failure message
@@ -11,7 +11,7 @@ tmpdir=${tmpdir:-/tmp}
 # pstopnm does not use libnetpbm functions for output.
 # Output is filtered through pamtopnm.
 
-# Test 1.  Should print: 1926073387 101484 four times
+echo "Test 1.  Should print 1926073387 101484 four times"
 test1_ps=${tmpdir}/testimg1.ps
 
 for flag in "" "-ps" "-rle" "-ps -ascii"
@@ -25,9 +25,9 @@ for flag in "" "-ps" "-rle" "-ps -ascii"
   done
 
 rm ${test1_ps}
-# Test 2.  Should print: 2918318199 62 seven times
+
+echo "Test 2.  Should print 2918318199 62 seven times"
 # Test image designed to detect problems with run-length compression
-#
 
 g_pbm=${tmpdir}/g.pbm
 t_pbm=${tmpdir}/t.pbm
@@ -37,7 +37,7 @@ pbmmake -g 2 2 > ${g_pbm}
 pbmmake -g 8 4 | \
   pnmshear 45 -noantialias -background=black | \
   pnmpad -right 60 | \
-  pnmcat -tb -jright - ${g_pbm} > ${t_pbm} &&
+  pamcat -tb -jright - ${g_pbm} > ${t_pbm} &&
 for flag in "" "-rle" "-ps -rle -ascii" \
             "-bitspersample=2 -rle" "-ps -bitspersample=4 -rle" \
             "-bitspersample=8 -rle" "-ps -bitspersample=12 -rle -dict"
@@ -52,8 +52,8 @@ for flag in "" "-rle" "-ps -rle -ascii" \
 
 rm ${grid_ps} ${g_pbm} ${t_pbm}
 
-#Test 3. Should print: 1386192571 507420 three times
-#
+echo "Test 3. Should print 1831481505 608904 three times"
+
 # Special care is needed when conducting round-trips with multiple-image
 # files as input.
 # (1) pnmtops: -setpage is mandatory
@@ -61,16 +61,16 @@ rm ${grid_ps} ${g_pbm} ${t_pbm}
 #          Subsequent BoundingBox values are ignored.
 # (3) pstopnm: input must be an ordinary file.  Input from stdin
 #     (by pipe or input redirection: "< file" ) does not work.
-#
 
 test3_ps=${tmpdir}/testimg3.ps
 
 for flag in "" "-ps" \
             "-ps -bitspersample=12 -rle -vmreclaim"
   do
-cat testimg.ppm testimg.ppm testimg.ppm testgrid.pbm testgrid.pbm | \
-pnmtops -nocenter -equalpixels -dpi 72 -noturn -setpage ${flag} \
-  > ${test3_ps} &&
+cat testimg.ppm testimg.ppm testimg.ppm maze.pbm \
+  testgrid.pbm testgrid.pbm | \
+  pnmtops -nocenter -equalpixels -dpi 72 -noturn -setpage ${flag} \
+    > ${test3_ps} &&
 xysize3=`awk  '/BoundingBox/ {print "-xsize="$4,"-ysize="$5 ; exit}' \
   ${test3_ps}` &&
 pstopnm -portrait -xborder=0 -yborder=0 $xysize3 -stdout  ${test3_ps} | \
diff --git a/test/qoi-roundtrip.ok b/test/qoi-roundtrip.ok
new file mode 100644
index 00000000..66e25bd8
--- /dev/null
+++ b/test/qoi-roundtrip.ok
@@ -0,0 +1,34 @@
+Test 1.  Should print 1.N 0 0
+1.0 0 0
+1.1 0 0
+1.2 0 0
+1.3 0 0
+1.4 0 0
+Test 2.  Should print 2.N 0 0
+2.0 0 0
+2.1 0 0
+2.2 0 0
+2.3 0 0
+2.4 0 0
+Test 3.  Should print 3.N 0 0
+3.0 0 0
+3.1 0 0
+3.2 0 0
+3.3 0 0
+3.4 0 0
+Test Invalid
+Should print: Expected failure N (no output)
+Expected failure 1 (no output)
+Expected failure 2 (no output)
+Expected failure 3 (no output)
+Expected failure 4 (no output)
+Expected failure 5 (no output)
+Expected failure 6 (no output)
+Expected failure 7 (no output)
+Expected failure 8 (no output)
+------------------------------
+Should print: Expected failure N (output produced)
+Expected failure 9 (output produced)
+Expected failure 10 (output produced)
+Expected failure 11 (output produced)
+Expected failure 12 (output produced)
diff --git a/test/qoi-roundtrip.test b/test/qoi-roundtrip.test
new file mode 100755
index 00000000..52396e39
--- /dev/null
+++ b/test/qoi-roundtrip.test
@@ -0,0 +1,254 @@
+#! /bin/sh
+# This script tests: qoitopam pamtoqoi
+# Also requires: pamdepth pamfile pamseq pamstack pamtopnm pbmmake
+# Also requires: pgmnoise ppmpat ppmtopgm
+
+# Ensure that sed operates in original narrow-character mode
+
+LANG=C
+LC_ALL=C
+export LANG LC_ALL
+
+tmpdir=${tmpdir:-/tmp}
+
+maze_qoi=${tmpdir}/maze.qoi
+maze_bw_alpha=${tmpdir}/maze_bw_alpha.pam
+maze_rgb=${tmpdir}/maze_rgb.pam
+maze_rgb_alpha=${tmpdir}/maze_rgb_alpha.pam
+
+echo "Test 1.  Should print 1.N 0 0"
+
+pbmmake -g $(pamfile -size maze.pbm) |\
+  pamstack -tupletype="BLACKANDWHITE_ALPHA" maze.pbm - > ${maze_bw_alpha}
+
+pbmmake -g $(pamfile -size maze.pbm) |\
+  pamstack -tupletype="RGB" maze.pbm maze.pbm maze.pbm |\
+  pamdepth 255 > ${maze_rgb}
+printf "1.0 $? "
+
+pbmmake -g $(pamfile -size maze.pbm) |\
+  pamstack -tupletype="RGB_ALPHA" maze.pbm maze.pbm maze.pbm - |\
+  pamdepth 255 > ${maze_rgb_alpha}
+echo $?
+
+# PBM, PBM + alpha
+
+pamtoqoi maze.pbm | tee ${maze_qoi} | qoitopam | cmp -s - ${maze_rgb}
+printf "1.1 $? "
+test -s ${maze_qoi}
+echo $?
+
+pamdepth 8 maze.pbm | pamtoqoi | qoitopam | cmp -s - ${maze_rgb}
+printf "1.2 $? "
+test -s ${maze_rgb}
+echo $?
+
+pamtoqoi ${maze_bw_alpha} | qoitopam | cmp -s - ${maze_rgb_alpha}
+printf "1.3 $? "
+test -s ${maze_bw_alpha}
+echo $?
+
+pamdepth 2 ${maze_bw_alpha} | pamstack -tupletype="GRAYSCALE_ALPHA" |\
+  pamtoqoi | qoitopam | cmp -s - ${maze_rgb_alpha}
+printf "1.4 $? "
+test -s ${maze_rgb_alpha}
+echo $?
+
+rm ${maze_rgb} ${maze_rgb_alpha} ${maze_bw_alpha}
+
+echo "Test 2.  Should print 2.N 0 0"
+
+# ---- PGM, PGM + alpha
+
+noise1_pgm=${tmpdir}/noise1.pgm
+noise2_pgm=${tmpdir}/noise2.pgm
+test_gray_alpha=${tmpdir}/test_gray_alpha.pam
+res_gray_alpha=${tmpdir}/res_gray_alpha.pam
+
+pgmnoise --randomseed=0 20 20 > ${noise1_pgm}
+pgmnoise --randomseed=1 20 20 | tee ${noise2_pgm} |\
+  pamstack -tupletype="GRAYSCALE_ALPHA" ${noise1_pgm} - \
+  > ${test_gray_alpha}
+printf "2.0 $? "
+
+pamstack -tupletype="RGB_ALPHA" \
+  ${noise1_pgm} ${noise1_pgm} ${noise1_pgm} ${noise2_pgm} > ${res_gray_alpha}
+echo $?
+
+rm ${noise2_pgm}
+
+pamtoqoi ${noise1_pgm} | qoitopam | pamtopnm | ppmtopgm |\
+  cmp -s - ${noise1_pgm}
+printf "2.1 $? "
+test -s ${noise1_pgm}
+echo $?
+
+
+pamdepth 65535 ${noise1_pgm} | pamtoqoi | qoitopam | pamtopnm | ppmtopgm |\
+  cmp -s - ${noise1_pgm}
+printf "2.2 $? "
+test -s ${noise1_pgm}
+echo $?
+
+pamtoqoi ${test_gray_alpha} | qoitopam | cmp -s - ${res_gray_alpha}
+printf "2.3 $? "
+test -s ${test_gray_alpha}
+echo $?
+
+pamdepth 4095 ${test_gray_alpha} | pamtoqoi | qoitopam |\
+  cmp -s - ${res_gray_alpha}
+printf "2.4 $? "
+test -s ${res_gray_alpha}
+echo $?
+
+rm ${test_gray_alpha} ${res_gray_alpha}
+
+echo "Test 3.  Should print 3.N 0 0"
+
+# rgb rgb-alpha
+
+tartan_ppm=${tmpdir}/tartan.ppm
+tartan_qoi=${tmpdir}/tartan.qoi
+test_rgb_alpha=${tmpdir}/test_rgb_alpha.pam
+
+ppmpat -tartan 20 20 | tee ${tartan_ppm} |\
+  pamstack -tupletype="RGB_ALPHA" - ${noise1_pgm} > ${test_rgb_alpha}
+printf "3.0 $? "
+test -s ${tartan_ppm}
+echo $?
+
+pamtoqoi ${tartan_ppm} | tee ${tartan_qoi} | qoitopam | pamtopnm |\
+  cmp -s - ${tartan_ppm}
+printf "3.1 $? "
+test -s ${tartan_qoi}
+echo $?
+rm ${tartan_qoi}
+
+pamdepth 4095 ${tartan_ppm} | pamtoqoi | tee ${tartan_qoi} |\
+  qoitopam | pamtopnm | cmp -s - ${tartan_ppm}
+printf "3.2 $? "
+test -s ${tartan_qoi}
+echo $?
+rm ${tartan_qoi}
+
+pamtoqoi ${test_rgb_alpha} | qoitopam | cmp -s - ${test_rgb_alpha}
+printf "3.3 $? "
+test -s ${test_rgb_alpha}
+echo $?
+
+pamdepth 511 ${test_rgb_alpha} | pamtoqoi | qoitopam |\
+  cmp -s - ${test_rgb_alpha}
+printf "3.4 $? "
+test -s ${test_rgb_alpha}
+echo $?
+
+rm ${noise1_pgm} ${tartan_ppm} ${test_rgb_alpha}
+
+
+echo "Test Invalid"
+
+test_out=${tmpdir}/test.out
+maze_qoi_size=$(cat ${maze_qoi} | wc -c)
+
+echo 1>&2
+echo "Invalid command-line argument combinations." 1>&2
+echo "Error messages should appear below the line." 1>&2
+echo "-----------------------------------------------------------" 1>&2
+
+echo "Should print: Expected failure N (no output)"
+
+pamseq -tupletype="void" 1 1 | pamtoqoi > \
+  ${test_out} || \
+  printf "Expected failure 1 "
+  test -s ${test_out} && echo "unexpected output" || echo "(no output)"
+  rm -f ${test_out}
+
+( echo "P1"; echo "400000001 1" ;
+  head -c 400000001 /dev/zero ) | pamtoqoi > \
+  ${test_out} || \
+  printf "Expected failure 2 "
+  test -s ${test_out} && echo "unexpected output" || echo "(no output)"
+  rm -f ${test_out}
+
+# Replace fields in the qoi file header with invalid values
+  
+( printf "qojf"
+  tail -c +5 ${maze_qoi} ) | qoitopam > \
+  ${test_out} || \
+  printf "Expected failure 3 "
+  test -s ${test_out} && echo "unexpected output" || echo "(no output)"
+  rm -f ${test_out}
+
+( head -c 4 ${maze_qoi}
+  head -c 4 /dev/zero
+  tail -c +9 ${maze_qoi} ) | qoitopam > \
+  ${test_out} || \
+  printf "Expected failure 4 "
+  test -s ${test_out} && echo "unexpected output" || echo "(no output)"
+  rm -f ${test_out}
+
+( head -c 8 ${maze_qoi}
+  head -c 4 /dev/zero
+  tail -c +13 ${maze_qoi} ) | qoitopam > \
+  ${test_out} || \
+  printf "Expected failure 5 "
+  test -s ${test_out} && echo "unexpected output" || echo "(no output)"
+  rm -f ${test_out}
+
+# Following sed construct means: "replace first 8 bytes of input
+# stream."  echo -e -n and printf may be straightforward but
+# unfortunately they are not portable.  Is there any better solution?
+# Suggestions welcome.
+
+( head -c 4 ${maze_qoi}
+  tail -c +5 ${maze_qoi} | \
+  sed '1s/^......../\x00\x00\x4F\xFF\x00\x00\x4F\xFF/' ) | qoitopam > \
+  ${test_out} || \
+  printf "Expected failure 6 "
+  test -s ${test_out} && echo "unexpected output" || echo "(no output)"
+  rm -f ${test_out}
+
+( head -c 12 ${maze_qoi}
+  tail -c +13 ${maze_qoi} | sed '1s/^./\x01/' ) | qoitopam > \
+  ${test_out} || \
+  printf "Expected failure 7 "
+  test -s ${test_out} && echo "unexpected output" || echo "(no output)"
+  rm -f ${test_out}
+
+( head -c 13 ${maze_qoi}
+  tail -c +14 ${maze_qoi} | sed '1s/^./\x02/' ) | qoitopam > \
+  ${test_out} || \
+  printf "Expected failure 8 "
+  test -s ${test_out} && echo "unexpected output" || echo "(no output)"
+  rm -f ${test_out}
+
+echo "------------------------------"
+echo "Should print: Expected failure N (output produced)"
+
+( head -c $(( ${maze_qoi_size} - 9 )) ${maze_qoi}
+  tail -c 9 ${maze_qoi} |   sed '1s/^./\xfd/' ) | qoitopam > \
+  ${test_out} || \
+  printf "Expected failure 9 "
+  test -s ${test_out} && echo "(output produced)"|| echo "no output"
+  rm -f ${test_out}
+
+head -c $(( ${maze_qoi_size} - 1 )) ${maze_qoi} | qoitopam > \
+  ${test_out} || \
+  printf "Expected failure 10 "
+  test -s ${test_out} && echo "(output produced)"|| echo "no output"
+  rm -f ${test_out}
+
+( head -c $(( ${maze_qoi_size} - 1 )) ${maze_qoi}
+  printf '1' ) | qoitopam > \
+  ${test_out} || \
+  printf "Expected failure 11 "
+  test -s ${test_out} && echo "(output produced)"|| echo "no output"
+  rm -f ${test_out}
+
+( cat ${maze_qoi}; printf '1' ) | qoitopam > \
+  ${test_out} || \
+  printf "Expected failure 12 "
+  test -s ${test_out} && echo "(output produced)"|| echo "no output"
+  rm -f ${test_out}
+
+rm ${maze_qoi}
diff --git a/test/random-generator.ok b/test/random-generator.ok
new file mode 100644
index 00000000..e137d901
--- /dev/null
+++ b/test/random-generator.ok
@@ -0,0 +1,219 @@
+Test 1: Should produce:
+P2
+12 1
+1023
+720 296 192 858 101 57 298 629 804 1019 64 617
+Above output is for Mersenne Twister
+P2
+12 1
+1023
+720 296 192 858 101 57 298 629 804 1019 64 617
+
+Test 2: Mersenne Twister random number generator
+Should produce:
+3499211612  581869302 3890346734 3586334585  545404204
+4161255391 3922919429  949333985 2715962298 1323567403
+ ... 
+ 297480282 1101405687 1473439254 2634793792 1341017984
+ Total 1000 integers, 200 lines
+
+3499211612  581869302 3890346734 3586334585  545404204 
+4161255391 3922919429  949333985 2715962298 1323567403 
+ 418932835 2350294565 1196140740  809094426 2348838239 
+4264392720 4112460519 4279768804 4144164697 4156218106 
+ 676943009 3117454609 4168664243 4213834039 4111000746 
+ 471852626 2084672536 3427838553 3437178460 1275731771 
+ 609397212   20544909 1811450929  483031418 3933054126 
+2747762695 3402504553 3772830893 4120988587 2163214728 
+2816384844 3427077306  153380495 1551745920 3646982597 
+ 910208076 4011470445 2926416934 2915145307 1712568902 
+3254469058 3181055693 3191729660 2039073006 1684602222 
+1812852786 2815256116  746745227  735241234 1296707006 
+3032444839 3424291161  136721026 1359573808 1189375152 
+3747053250  198304612  640439652  417177801 4269491673 
+3536724425 3530047642 2984266209  537655879 1361931891 
+3280281326 4081172609 2107063880  147944788 2850164008 
+1884392678  540721923 1638781099  902841100 3287869586 
+ 219972873 3415357582  156513983  802611720 1755486969 
+2103522059 1967048444 1913778154 2094092595 2775893247 
+3410096536 3046698742 3955127111 3241354600 3468319344 
+1185518681 3031277329 2919300778   12105075 2813624502 
+3052449900  698412071 2765791248  511091141 1958646067 
+2140457296 3323948758 4122068897 2464257528 1461945556 
+3765644424 2513705832 3471087299  961264978   76338300 
+3226667454 3527224675 1095625157 3525484323 2173068963 
+4037587209 3002511655 1772389185 3826400342 1817480335 
+4120125281 2495189930 2350272820  678852156  595387438 
+3271610651  641212874  988512770 1105989508 3477783405 
+3610853094 4245667946 1092133642 1427854500 3497326703 
+1287767370 1045931779   58150106 3991156885  933029415 
+1503168825 3897101788  844370145 3644141418 1078396938 
+4101769245 2645891717 3345340191 2032760103 4241106803 
+1510366103  290319951 3568381791 3408475658 2513690134 
+2553373352 2361044915 3147346559 3939316793 2986002498 
+1227669233 2919803768 3252150224 1685003584 3237241796 
+2411870849 1634002467  893645500 2438775379 2265043167 
+ 325791709 1736062366  231714000 1515103006 2279758133 
+2546159170 3346497776 1530490810 4011545318 4144499009 
+ 557942923  663307952 2443079012 1696117849 2016017442 
+1663423246   51119001 3122246755 1447930741 1668894615 
+ 696567687 3983551422 3411426125 1873110678 1336658413 
+3705174600 2270032533 2664425968  711455903  513451233 
+2585492744 2027039028 1129453058 1461232481 2809248324 
+2275654012 2960153730 3075629128 3213286615 4245057188 
+1935061435 3094495853  360010077 3919490483  983448591 
+2171099548 3922754098 2397746050  654458600 2161184684 
+3546856898 1986311591 2312163142 2347594600 4278366025 
+1922360368  335761339 3669839044 1901288696 2595154464 
+ 458070173 2141230976 4131320786 4208748424   19903848 
+ 147391738 3328215103 4196191786 3510290616 1559873971 
+3731015357 2918514861  362649214 1487061100 1717053387 
+3675955720 1116134897  193529268 3436267940 2835191639 
+1852908272 3220971953 3911201640  571213604  781027019 
+4219206494 1133024903  409547355  625085180 1214072539 
+ 584409985 3445042528 3733581611  333104904 2489812253 
+2694595213 2361631596   34763086  622576118 2921810672 
+3663740744 2293225236 2671706445 1884059696 1507329019 
+ 857065948 2204390003  592711182 1725752375 1642107460 
+ 326274448 3274574484 1030432041  173822100  529650788 
+1086437636  789877945 2167974914 1030588245 3533061365 
+1792148406 4216468704  213264131 3536714075 3877136173 
+1296338417 4057830103  205919137 2108245233 1064497347 
+2101324080 2336703164 1450493809 3812754708 3865701845 
+1476779561 1585902852  142887412  477612192  699530444 
+3351157089 3768249319 1673915577  903239649 1038056164 
+1171465372 1734789440 2115022236  414269055  959581346 
+ 566820984 2105828892 4046076449 4101450561 4106566571 
+2800184123 2470502098 3253453343  256751188 1869365987 
+1008372035 2374606708 1516804538  228288551 3527001547 
+1385173098   66157275 1739381798  184785808 3901692666 
+ 725806641 3475217997 2787929747 1109372433 3142723729 
+ 557686578 2782047723 2118822689 1936702581 1625646963 
+2349385293 3085804937 1272688179 1236112995 3198431244 
+2677635414  811555596 3486972196 2949678043 1342211552 
+ 788174404 1656614077 1582629285 1477167035 2687011245 
+3503701453 3351051324 2874557775  348432514 1629591495 
+3991682351 1969229192 3331660584 1304012077 2090754125 
+3910846836 1871998370 2098597104 1918921592 3246092887 
+1315760974  464122393 2184028058 1690455542 2193747147 
+3737423698 3511684278 1549884962 3413774919 3938991454 
+2767325310 2335626851 1626114941  601913200 3485711542 
+ 858447440 2288468476 4075602213 1506361431 4252489875 
+4032981007 1031118352 3762145731   70955369 2362903502 
+1669089455 2673510137 3348740333 2521337794 2047144929 
+ 892246357 2319875070 1293843163   79245769 2022600352 
+3866257397  989939126  835351312 3626278636 3805332945 
+ 836506264 1895040349  970326679  634920763  733185481 
+1028655248  977810701 3434484235 1871311609 2031584214 
+1336174158  385787519 3965885375 2768323462 1847726660 
+2718987737  793780050 2509902580 3886434164 3120956802 
+4207987247 1523159183 1884932179 2922324286  477253416 
+3037922812 1108379444  697195677 1755438379  574393398 
+2555059183 1930828628 1126190880  180621093 2589191337 
+3424652760 3054648512  719646637  952394946 3570038180 
+ 504304985 1395707758 1274213163 2816553213 1369142370 
+1804702100 1821782344 3358274235 2181234724  486158240 
+ 367287522 4267199121 1127352639  779850007 3440331597 
+3276765484  125500149 1142120513 3989398167 1048565860 
+3136747194  432668526 2098559576 1478877150 2484746208 
+1209580219 1019125185 4160278734 1970740713  918146921 
+4136433784 2602441845 2348512686  973030509 2238261365 
+ 815637919  994690313 1724736366 2099799816 1775069742 
+2680317667  730798472 2916864943 1284417767 1698724919 
+2733611686 1578128411  651006053 4243350375 3303874296 
+ 162087183 3796616231 3801767645 4119825424 3922537059 
+  77594039 3419583692 2503306160  423966005 3293613218 
+1124728190 1407880681 1440346680  554334954 2919409323 
+1253962019  586491243 3638308238 3097648541  991125519 
+ 458538714 2155963569 2807866455    6862945 2122460897 
+  53853750 3346001678 1230879976 3071060893  423909157 
+3881450262 1652511030 3826483009 1526211009 1435219366 
+3092251623 3001090498  281084412  849586749 2207008400 
+ 131172352 1820973075 3195774605 2962673849 2147580010 
+1090677336 2061249893 1724513375 3885752424 1135918139 
+2619357288 4012575714 2652856935 2029480458 3691276589 
+2623865075 3459550738 2097670126 2477000057 2209844713 
+ 785646024 1052349661 1030500157 1430246618 3807539761 
+2157629976  123154542 2560049331 2104110449 1332109867 
+ 721241591 4136042859 4203401395  998151922 3060999432 
+3207929139 2149509272 1385268511 2023309182 1366796638 
+ 256061060 4090836236 2929047008 2296609403  182240337 
+3744374619  306855912 4014087816 2240468995 2865233169 
+ 415452309 1244206523 3513921306  281425419 3511338031 
+ 995954022 3102854413 3026765331  643667197  837979907 
+2832983005 1813414171 2227348307 4020325887 4178893912 
+ 610818241 2787397224 2762441380 3437393657 2030369078 
+1949046312 1876612561 1857107382 1049344864 3544695775 
+2172907342  358500115 3895295219  571965125  328582064 
+ 744698407 3066193991 1679065087 2650874932 3570748805 
+ 812110431 3450423805 1705023874  259721746 1192558045 
+1714799045 3685508436 2262914445 3903852862 1790140070 
+2651193482 2821191752  776610414 2697125035 2212010032 
+1254062056 3541766210 1853927671 1543286708   66516686 
+3505195914 4226521519 1260092911  717982876  739240369 
+ 456195732 2116515161 1599487648  838913496  850912042 
+3712172413 2103192411  877020153 1458113119 2646869271 
+4087221703 3771198399 3952796001 1685641891  226245966 
+4065518354 3169076409  715963611 1155859114 4174181651 
+1816065125 2422210778 2353087594 2569974907 4049024520 
+ 563593555 1794197249 2434290377 4222178191 2381045132 
+1294739153 1333544226 3011196239  518183212 2861903570 
+3168787443 2315530531 1042490149 2998340365 3534153126 
+2862715604  796613230  765073073 1342937225  549817636 
+3786981820 4291017601 2895722553  734959362 3175258828 
+ 140019477  268621172 2410334776  565052604 3787587805 
+ 386344800 2874086067   35710270  817904650 1960697289 
+1584484509 2724312018 1978802819 2275314726 4216102886 
+2138332912  671754166 1442240992 3674442465 1085868016 
+2769242611 1003628378 1616076847  743729558  820011032 
+2559719034 1839332599 3121982280 2070268989 3769147733 
+ 518022934 3037227899 2531915367 1008310588  971468687 
+2052976098 1651926578   78218926 2503907441 3209763057 
+1081499040 2812016370 1247433164  335294964 2650385171 
+2030527826 1139372809 4279827824 3540669095 2285341455 
+4220507154 3863048231 3136394663 3319584205 1476940506 
+ 875141230 2508558662 3896001866  462864388 1609807693 
+3892563868 3642514037 3778083990 1403162576 3512254868 
+1403323269 1119818229 2831288053 2552740643 2520136409 
+  96690857  210381252 1826474872 3306977352 1343117402 
+2112059492  693571694 2096734379  767794921 1843084587 
+1816280216 1695342628  404711915 3334843684 2570639553 
+4186538211 2022604264 3214805180 2989079529 2725165355 
+3005995436  310011850 2742468706 2720274646  144327376 
+2271696819  295519962 1272030376 1372670420 1397272558 
+2280044719 2710639434 2810822904 4271368265 1750711132 
+2216408539 3521792518 3111505866 3085328191 1054735512 
+4160317205 1427385632 2282061755 3215251668 1396490078 
+2933318719  453673969 2926038256 2624047458  338625410 
+3344930154 1971116345 1818716442 2998517928  390083048 
+ 291563131 1144486353  296954266  659950561 2263631666 
+1206908601 1125491020 1890151284 2076080514 2264060846 
+ 561805191 1964622705  405620012 3759692386  517035386 
+2225016848 4165419081 4052828294 3248204933 2738939733 
+1151808775 4113264137 3113447491 1033828852 1785686386 
+2903923175 2038900010 1241522880  238119113 2885394101 
+2636011022 2985605703 2107193353  292026696 3884689974 
+1094315383 4016714705  962244585 3943968050 2868319718 
+1304919603 3626636694 3393461291 1479454799  971639318 
+3352306399 1928233566 2900529135 2190901098   28842068 
+ 990556577 2586302532 3057504668 1661169605 4228191763 
+3934152427 2814119472    4943754 1171095774 1986204006 
+2014406505 1822565279   12890078 1979620724 1917376192 
+3307810835 4170173371 1385005883 1308519769 3370429606 
+ 923886311 2024463563 1063369787  153599761 3463680785 
+ 755374878 2088947962 3099927142 1750207400 2033606872 
+ 926120766  655932557 2320365045 1465119024 3105365454 
+2608716819 1218456091  823539591 2331574954 3171519129 
+3246671799 1043031086 1425831588 3940307546 3443545749 
+1155610704 3681098065 3287797558   63959365  810297004 
+3800799806 1234795257 2547289014  391329364  370300179 
+2474800443 3972311925 2935022755 3924395679 2347599539 
+4212318274 1828491430 3865565525 2767860661 4078993078 
+2781496513 4013741232 2916354756   35752471 2730683119 
+3340599926 4059491907  111492530  897368671 2524912702 
+3046341697 2790787159 1014602604 1409764839  512802978 
+ 477082227 2608350570  533747000 1933326657 4182933327 
+1970210993 2290203137 2843031053 2844558050 3308351089 
+3041943368 1504174920  295229952 2843309586  884572473 
+1787387521 1861566286 3616058184   48071792 3577350513 
+ 297480282 1101405687 1473439254 2634793792 1341017984 
diff --git a/test/random-generator.test b/test/random-generator.test
new file mode 100755
index 00000000..351b982e
--- /dev/null
+++ b/test/random-generator.test
@@ -0,0 +1,83 @@
+#! /bin/sh
+# This script tests: pgmnoise
+# Also requires:
+
+# These tests are for examining the integrity of the random number
+# generator.  There is some overlap between the tests here and tests
+# in pgmnoise.test, but the tests here are better focused for
+# diagnosing problems with the random number generator.
+#
+# Test 1 is for determining the kind of random number generator in
+# use.
+#
+# Test 2 prints random numbers in an output format close to what the
+# test in the original Mersenne Twister code produces.
+#
+# If these tests fail, subsequent tests which depend on random numbers
+# will fail too.  There is no provision (beyond remarks in the script
+# files) for generators other than the Mersenne Twister in those
+# tests.
+
+echo "Test 1: Should produce:"
+
+echo "P2"
+echo "12 1"
+echo "1023"
+echo "720 296 192 858 101 57 298 629 804 1019 64 617"
+echo "Above output is for Mersenne Twister"
+
+pgmnoise -maxval=1023 -randomseed=3791 -plain 12 1
+
+echo
+echo "Test 2: Mersenne Twister random number generator"
+echo "Should produce:"
+
+echo "3499211612  581869302 3890346734 3586334585  545404204"
+echo "4161255391 3922919429  949333985 2715962298 1323567403"
+echo " ... "
+echo " 297480282 1101405687 1473439254 2634793792 1341017984"
+echo " Total 1000 integers, 200 lines"
+echo
+
+# Use perl to avoid mawk limitation
+# (cannot convert 32 bit integers)
+
+perlPgmProcessorProgram='
+  if (($#F+1) == 10) {
+    for (my $i = 0; $i <= 9; $i += 2) {
+      my $r = $F[$i + 1] * 65536 + $F[$i];
+      printf "%10u ", $r;
+    }
+    print "";
+  }
+'
+
+pgmnoise -randomseed=5489 -plain -maxval=65535 10 200 | \
+  perl -walne "$perlPgmProcessorProgram"
+
+# The above outputs (10 * 200 / 2) = 1000 samples.
+
+#    Method to generate output for Test 2 from original
+#    Mersenne Twister source code
+#
+# Download Mersenne Twister code.  See lib/util/randmersenne.c for URL.
+# Edit mt19937ar.c:
+#   In function main() at bottom of file, replace
+#     init_by_array(init, length);
+#   with
+#     init_genrand(5489UL);
+#
+# We need only the output of genrand_int32().
+# Remove the second loop which produces double-precision floating point
+# random numbers with genrand_real2().
+#
+# Compile: gcc mt19937ar.c -o mt1000
+# Execute: ./mt1000
+
+# 1000 may seem like a large number of samples but there is a reason
+# for this.  The generator produces random integers in batches of 624.
+# The number of samples must be larger than 624 to ensure proper
+# generation in batches after the first.
+
+# If you encounter problems, adjust the 200 (rows) above and tweak
+# the code in mt19937ar.c accordingly to produce more random numbers.
diff --git a/test/rgb3-roundtrip.ok b/test/rgb3-roundtrip.ok
index 367e5429..cbdb369c 100644
--- a/test/rgb3-roundtrip.ok
+++ b/test/rgb3-roundtrip.ok
@@ -1,6 +1,12 @@
+Test 1.  Should print 1926073387 101484
 1926073387 101484
+Test 2.  Should print 3744829044 101514
 3744829044 101514
-2425386270 41
+Test 3.  Should print 281226646 481 twice
+281226646 481
+281226646 481
+Test 4.  Should print 0 twice
 0
 0
+Test 5.  Should print 0 0 : 0
 0 0 : 0
diff --git a/test/rgb3-roundtrip.test b/test/rgb3-roundtrip.test
index 42fd822f..76bd90f1 100755
--- a/test/rgb3-roundtrip.test
+++ b/test/rgb3-roundtrip.test
@@ -10,37 +10,45 @@
 tmpdir=${tmpdir:-/tmp}
 
 # Test 1.  PPM (color) input
-testimg_ppm=${tmpdir}/testimg.ppm
-testimg_red=${tmpdir}/testimg.red
-testimg_grn=${tmpdir}/testimg.grn
-testimg_blu=${tmpdir}/testimg.blu
-
-cp testimg.ppm ${tmpdir} &&
-ppmtorgb3 ${testimg_ppm} &&
-rgb3toppm ${testimg_red} ${testimg_grn} ${testimg_blu} | cksum
-
-cat ${testimg_red} ${testimg_grn} ${testimg_blu} | cksum
-
-rm ${testimg_ppm} ${testimg_red} ${testimg_grn} ${testimg_blu}
-
-# Test 2.  PBM (monochrome) input
-testgrid_pbm=${tmpdir}/testgrid.pbm
-testgrid_red=${tmpdir}/testgrid.red
-testgrid_grn=${tmpdir}/testgrid.grn
-testgrid_blu=${tmpdir}/testgrid.blu
-
-cp testgrid.pbm ${tmpdir} &&
-ppmtorgb3 ${testgrid_pbm} &&
-rgb3toppm ${testgrid_red} ${testgrid_grn} ${testgrid_blu} | \
+echo "Test 1.  Should print 1926073387 101484"
+rose_ppm=${tmpdir}/rose.ppm
+rose_red=${tmpdir}/rose.red
+rose_grn=${tmpdir}/rose.grn
+rose_blu=${tmpdir}/rose.blu
+
+cp testimg.ppm ${rose_ppm} &&
+ppmtorgb3 ${rose_ppm} &&
+rgb3toppm ${rose_red} ${rose_grn} ${rose_blu} | cksum
+
+# Simple cat of three planes
+echo "Test 2.  Should print 3744829044 101514"
+cat ${rose_red} ${rose_grn} ${rose_blu} | cksum
+
+rm ${rose_ppm} ${rose_red} ${rose_grn} ${rose_blu}
+
+# Test 3.  PBM (monochrome) input
+echo "Test 3.  Should print 281226646 481 twice"
+maze_pbm=${tmpdir}/maze.pbm
+maze_red=${tmpdir}/maze.red
+maze_grn=${tmpdir}/maze.grn
+maze_blu=${tmpdir}/maze.blu
+
+cp maze.pbm ${tmpdir} &&
+ppmtorgb3 ${maze_pbm} &&
+rgb3toppm ${maze_red} ${maze_grn} ${maze_blu} | \
   ppmtopgm | pgmtopbm -th -val=0.5 | cksum
+pgmtopbm -th -val=0.5 ${maze_red} | cksum
 
-# Test 3.
+# Test 4.
 # With PGM or PBM input, the three monochrome planes should be
 # identical.  Test for this.
 
-cmp -s ${testgrid_red} ${testgrid_grn} ; echo $?
-cmp -s ${testgrid_grn} ${testgrid_blu} ; echo $?
-pgmtopgm < testgrid.pbm | cmp -s - ${testgrid_red}
+echo "Test 4.  Should print 0 twice"
+cmp -s ${maze_red} ${maze_grn} ; echo $?
+cmp -s ${maze_grn} ${maze_blu} ; echo $?
+
+echo "Test 5.  Should print 0 0 : 0"
+pgmtopgm < maze.pbm | cmp -s - ${maze_red}
   echo ${PIPESTATUS[@]} ":" $?
 
-rm ${testgrid_pbm} ${testgrid_red} ${testgrid_grn} ${testgrid_blu}
+rm ${maze_pbm} ${maze_red} ${maze_grn} ${maze_blu}
diff --git a/test/sbig-roundtrip.test b/test/sbig-roundtrip.test
index 1fdaccfd..2611fa89 100755
--- a/test/sbig-roundtrip.test
+++ b/test/sbig-roundtrip.test
@@ -1,4 +1,4 @@
-#! /bin/bash
+#! /bin/sh
 # This script tests: pgmtosbig sbigtopgm
 # Also requires: pamchannel pamtopnm
 
diff --git a/test/sgi-roundtrip.ok b/test/sgi-roundtrip.ok
index b1bd5ba6..3c3f022a 100644
--- a/test/sgi-roundtrip.ok
+++ b/test/sgi-roundtrip.ok
@@ -1,8 +1,13 @@
+Test 1.  Should produce 1926073387 101484 twice
 1926073387 101484
 1926073387 101484
+Test 2.  Should produce 1926073387 101484 twice
 1926073387 101484
 1926073387 101484
-538848130 235
-538848130 235
-2394972481 463
-2394972481 463
+Test 3.  Should produce 281226646 481 twice
+281226646 481
+281226646 481
+Test 4. Should produce 4155890407 6741 three times
+4155890407 6741
+4155890407 6741
+4155890407 6741
diff --git a/test/sgi-roundtrip.test b/test/sgi-roundtrip.test
index 5052bb81..50a9fbc2 100755
--- a/test/sgi-roundtrip.test
+++ b/test/sgi-roundtrip.test
@@ -1,14 +1,14 @@
-#! /bin/bash
+#! /bin/sh
 # This script tests: pnmtosgi sgitopnm
-# Also requires: rgb3toppm pamdepth pamtopnm
-
+# Also requires: rgb3toppm pamdepth pamtopnm pgmtopbm
 
+tmpdir=${tmpdir:-/tmp}
 a_sgi=${tmpdir}/a.sgi
 a_red=${tmpdir}/a.red
 a_grn=${tmpdir}/a.grn
 a_blu=${tmpdir}/a.blu
 
-# Test 1.  Should produce 1926073387 101484 twice
+echo "Test 1.  Should produce 1926073387 101484 twice"
 pnmtosgi -rle testimg.ppm | tee ${a_sgi} | sgitopnm  | cksum
 sgitopnm -channel=0  ${a_sgi} > ${a_red}
 sgitopnm -channel=1  ${a_sgi} > ${a_grn}
@@ -21,7 +21,7 @@ b_red=${tmpdir}/b.red
 b_grn=${tmpdir}/b.grn
 b_blu=${tmpdir}/b.blu
 
-# Test 2.  Should produce 1926073387 101484 twice
+echo "Test 2.  Should produce 1926073387 101484 twice"
 pnmtosgi -verbatim testimg.ppm | tee ${b_sgi} | sgitopnm  | cksum
 sgitopnm -channel=0  ${b_sgi} > ${b_red}
 sgitopnm -channel=1  ${b_sgi} > ${b_grn}
@@ -29,15 +29,16 @@ sgitopnm -channel=2  ${b_sgi} > ${b_blu}
 rgb3toppm ${b_red} ${b_grn} ${b_blu} | cksum
 rm ${b_sgi} ${b_red} ${b_grn} ${b_blu}
 
-# Test 3.  Should produce 2425386270 41 twice
-pnmtosgi testgrid.pbm | sgitopnm | cksum             # Defaults to -rle
-pnmtosgi -verbatim testgrid.pbm | sgitopnm | cksum
-
+echo "Test 3.  Should produce 281226646 481 twice"
+pnmtosgi maze.pbm | sgitopnm | pgmtopbm -threshold -value=0.5 | cksum 
+# Defaults to -rle
+pnmtosgi -verbatim maze.pbm | sgitopnm | \
+  pgmtopbm -threshold -value=0.5 | cksum 
 
-testgrid_pgm=${tmpdir}/testgrid.pgm
+maze_pgm=${tmpdir}/maze.pgm
 
-# Test 4. Should produce 2394972481 463 twice
-pamdepth 65535 testgrid.pbm | pamtopnm | tee ${testgrid_pgm} | \
-  pnmtosgi -rle | sgitopnm | cksum
-pnmtosgi -verbatim ${testgrid_pgm} | sgitopnm | cksum
-rm ${testgrid_pgm}
+echo "Test 4. Should produce 4155890407 6741 three times"
+pamdepth 65535 maze.pbm | pamtopnm | tee ${maze_pgm} | cksum
+pnmtosgi -rle ${maze_pgm} | sgitopnm | cksum
+pnmtosgi -verbatim ${maze_pgm} | sgitopnm | cksum
+rm ${maze_pgm}
diff --git a/test/st4-roundtrip.test b/test/st4-roundtrip.test
index ffe8f348..f2e15078 100755
--- a/test/st4-roundtrip.test
+++ b/test/st4-roundtrip.test
@@ -1,4 +1,4 @@
-#! /bin/bash
+#! /bin/sh
 # This script tests: pgmtost4 st4topgm
 # Also requires: pamchannel pamtopnm pamcut
 
diff --git a/test/stdin-pam1.ok b/test/stdin-pam1.ok
new file mode 100644
index 00000000..10e48622
--- /dev/null
+++ b/test/stdin-pam1.ok
@@ -0,0 +1,44 @@
+pamaddnoise -seed=1: 0 0 0 0
+pamaltsat -strength=1: 0 0 0 0
+pambackground: 0 0 0 0
+pambayer -type=2: 0 0 0 0
+pambrighten: 0 0 0 0
+pamcat -topbottom: 0 0 0 0
+pamcut: 0 0 0 0
+pamdeinterlace: 0 0 0 0
+pamdepth 15: 0 0 0 0
+pamditherbw -threshold: 0 0 0 0
+pamedge: 0 0 0 0
+pamexec cat: 0 0 0 0
+pamfile -size: 0 0 0 0
+pamfind -target=1: 0 0 0 0
+pamfix: 0 0 0 0
+pamflip -lr: 0 0 0 0
+pamfunc -not: 0 0 0 0
+pamhomography -from 0,0,0,1,1,0,1,1: 0 0 0 0
+pamhue -huechange=60: 0 0 0 0
+pamlevels -f1 rgb:0/0/0 -t1 rgb:0/0/0 -f2 rgb:ff/ff/ff -t2 rgb:ff/ff/ff: 0 0 0 0
+pammixinterlace: 0 0 0 0
+pammosaicknit: 0 0 0 0
+pamoil: 0 0 0 0
+pamperspective 0 0 0 1 1 0 1 1: 0 0 0 0
+pamrecolor: 0 0 0 0
+pamrestack: 0 0 0 0
+pamrubber -quad 1 1 2 2: 0 0 0 0
+pamscale 2: 0 0 0 0
+pamshadedrelief: 0 0 0 0
+pamsharpness: 0 0 0 0
+pamshuffle -randomseed=1: 0 0 0 0
+pamsistoaglyph: 0 0 0 0
+pamslice -row=1: 0 0 0 0
+pamstack: 0 0 0 0
+pamstereogram -randomseed=1: 0 0 0 0
+pamstretch 1: 0 0 0 0
+pamstretch-gen 1: 0 0 0 0
+pamsumm -max: 0 0 0 0
+pamsummcol -mean: 0 0 0 0
+pamtable: 0 0 0 0
+pamthreshold: 0 0 0 0
+pamtilt: 0 0 0 0
+pamtopnm: 0 0 0 0
+pamwipeout -tb: 0 0 0 0
diff --git a/test/stdin-pam1.test b/test/stdin-pam1.test
new file mode 100755
index 00000000..2ab7b11c
--- /dev/null
+++ b/test/stdin-pam1.test
@@ -0,0 +1,75 @@
+#! /bin/sh
+# This script tests: pamaddnoise pamaltsat pambackground pambayer
+# This script tests: pambrighten pamcat pamcut pamdeinterlace pamdepth pamditherbw
+# This script tests: pamedge pamexec pamfile pamfind pamfix pamflip
+# This script tests: pamfunc pamhomography pamhue pamlevels
+# This script tests: pammixinterlace pammosaicknit pamoil
+# This script tests: pamperspective pamrecolor pamrestack pamrubber pamscale
+# This script tests: pamshadedrelief pamsharpness pamshuffle pamsistoaglyph
+# This script tests: pamslice pamstack pamstereogram pamstretch
+# This script tests: pamstretch-gen pamsumm pamsummcol pamtable pamthreshold
+# This script tests: pamtilt pamtopnm pamwipeout
+# Also requires: pbmmake
+
+tmpdir=${tmpdir:-/tmp}
+out1=${tmpdir}/out1
+out2=${tmpdir}/out2
+small_pbm=${tmpdir}/small.pbm
+
+pbmmake -g 5 5 > ${small_pbm}
+
+for testprog in \
+    "pamaddnoise -seed=1" \
+    "pamaltsat -strength=1" \
+    pambackground \
+    "pambayer -type=2" \
+    pambrighten \
+    "pamcat -topbottom" \
+    pamcut \
+    pamdeinterlace \
+    "pamdepth 15" \
+    "pamditherbw -threshold" \
+    pamedge \
+    "pamexec cat" \
+    "pamfile -size" \
+    "pamfind -target=1" \
+    pamfix \
+    "pamflip -lr" \
+    "pamfunc -not" \
+    "pamhomography -from 0,0,0,1,1,0,1,1" \
+    "pamhue -huechange=60" \
+    "pamlevels -f1 rgb:0/0/0 -t1 rgb:0/0/0 -f2 rgb:ff/ff/ff -t2 rgb:ff/ff/ff" \
+    pammixinterlace \
+    pammosaicknit \
+    pamoil \
+    "pamperspective 0 0 0 1 1 0 1 1" \
+    pamrecolor \
+    pamrestack \
+    "pamrubber -quad 1 1 2 2" \
+    "pamscale 2" \
+    pamshadedrelief \
+    pamsharpness \
+    "pamshuffle -randomseed=1" \
+    pamsistoaglyph \
+    "pamslice -row=1" \
+    pamstack \
+    "pamstereogram -randomseed=1" \
+    "pamstretch 1" \
+    "pamstretch-gen 1" \
+    "pamsumm -max" \
+    "pamsummcol -mean" \
+    pamtable \
+    pamthreshold \
+    pamtilt \
+    pamtopnm \
+    "pamwipeout -tb"
+  do
+  ${testprog} ${small_pbm} > ${out1};      status1=$?
+  ${testprog} < ${small_pbm} > ${out2};    status2=$?
+  test -s ${out1};                         status3=$?
+  cmp -s ${out1} ${out2}
+  echo ${testprog}": "${status1} ${status2} ${status3} $?
+  rm ${out1} ${out2}
+  done
+
+rm ${small_pbm}
diff --git a/test/stdin-pam2.ok b/test/stdin-pam2.ok
new file mode 100644
index 00000000..dd3148e8
--- /dev/null
+++ b/test/stdin-pam2.ok
@@ -0,0 +1,5 @@
+pammasksharpen: 0 0 0 0
+pammixmulti: 0 0 0 0
+pamdice: 0 0 0 0
+pamlookup: 0 0 0 0
+pamunlookup: 0 0 0 0
diff --git a/test/stdin-pam2.test b/test/stdin-pam2.test
new file mode 100755
index 00000000..10713c77
--- /dev/null
+++ b/test/stdin-pam2.test
@@ -0,0 +1,70 @@
+#! /bin/sh
+# This script tests: pammasksharpen pammixmulti pamdice
+# This script tests: pamlookup pamunlookup
+# Also requires: pbmmake
+
+tmpdir=${tmpdir:-/tmp}
+out1=${tmpdir}/out1
+out2=${tmpdir}/out2
+out3=${tmpdir}/out3
+out4=${tmpdir}/out4
+small_pbm=${tmpdir}/small.pbm
+
+pbmmake -g 3 3 > ${small_pbm}
+
+for testprog in \
+    pammasksharpen \
+    pammixmulti
+  do
+  ${testprog} ${small_pbm}   ${small_pbm} > ${out1};   status1=$?
+  ${testprog} ${small_pbm} < ${small_pbm} > ${out2};   status2=$?
+  test -s ${out1};                                     status3=$?
+  cmp -s ${out1} ${out2}
+  echo ${testprog}": "${status1} ${status2} ${status3} $?
+  rm ${out1} ${out2}
+done
+
+
+  dicestem=${tmpdir}/dice
+
+  testprog="pamdice -outstem=${dicestem}"
+  ${testprog} ${small_pbm};   status1=$?
+  cat ${dicestem}_*_*.pbm > ${out1}
+  rm ${dicestem}_*_*.pbm
+  ${testprog} < ${small_pbm}; status2=$?
+  cat ${dicestem}_*_*.pbm > ${out2}
+  rm ${dicestem}_*_*.pbm
+  test -s ${out1};            status3=$?
+  cmp -s ${out1} ${out2}
+  echo pamdice: ${status1} ${status2} ${status3} $?
+  # Do not use testprog, which contains a variable, in the above
+  # Same for pamlookup, pamunlookup
+  rm ${out1} ${out2}
+
+lookup_ppm=${tmpdir}/lookup.ppm
+
+cat > ${lookup_ppm} <<EOF
+P3
+2 1
+2
+0 0 0
+0 1 2
+EOF
+
+  testprog="pamlookup -lookupfile=${lookup_ppm}"
+  ${testprog}   ${small_pbm} > ${out1}; status1=$?
+  ${testprog} < ${small_pbm} > ${out2}; status2=$?
+  test -s ${out1};                      status3=$?
+  cmp -s ${out1} ${out2}
+  echo pamlookup": "${status1} ${status2} ${status3} $?
+  rm ${out2}
+
+  testprog="pamunlookup -lookupfile=${lookup_ppm}"
+  ${testprog}   ${out1} > ${out3}; status1=$?
+  ${testprog} < ${out1} > ${out4}; status2=$?
+  test -s ${out1};                 status3=$?
+  cmp -s ${out3} ${out4}
+  echo pamunlookup": "${status1} ${status2} ${status3} $?
+  rm ${out1} ${out3} ${out4}
+
+rm ${lookup_ppm} ${small_pbm}
diff --git a/test/stdin-pam3.ok b/test/stdin-pam3.ok
new file mode 100644
index 00000000..516e9554
--- /dev/null
+++ b/test/stdin-pam3.ok
@@ -0,0 +1,34 @@
+Test.  Should print (command): 0 0 0 0
+The following are exceptions: should print (command): 0 0 0 1
+pamtotga, pamtotiff
+
+pamtoavs: 0 0 0 0
+avstopam: 0 0 0 0
+pamtohdiff: 0 0 0 0
+hdifftopam: 0 0 0 0
+pamtojpeg2k: 0 0 0 0
+jpeg2ktopam: 0 0 0 0
+pamtopdbimg -fixedtime: 0 0 0 0
+pdbimgtopam: 0 0 0 0
+pamtopfm: 0 0 0 0
+pfmtopam: 0 0 0 0
+pamtopng: 0 0 0 0
+pngtopam: 0 0 0 0
+pamtoqoi: 0 0 0 0
+qoitopam: 0 0 0 0
+pamtosrf: 0 0 0 0
+srftopam: 0 0 0 0
+pamtosvg: 0 0 0 0
+svgtopam: 0 0 0 0
+pamtowinicon: 0 0 0 0
+winicontopam: 0 0 0 0
+pamtotga: 0 0 0 1
+tgatoppm: 0 0 0 0
+pamtoxvmini: 0 0 0 0
+xvminitoppm: 0 0 0 0
+pamtofits: 0 0 0 0
+fitstopnm: 0 0 0 0
+pamtogif: 0 0 0 0
+giftopnm: 0 0 0 0
+pamtotiff: 0 0 0 1
+tifftopnm: 0 0 0 0
diff --git a/test/stdin-pam3.test b/test/stdin-pam3.test
new file mode 100755
index 00000000..40155671
--- /dev/null
+++ b/test/stdin-pam3.test
@@ -0,0 +1,75 @@
+#! /bin/sh
+# This script tests: pamtoavs avstopam
+# This script tests: pamtohdiff hdifftopam
+# This script tests: pamtojpeg2k jpeg2ktopam
+# This script tests: pamtopdbimg pdbimgtopam
+# This script tests: pamtopfm pfmtopam
+# This script tests: pamtopng pngtopam
+# This script tests: pamtoqoi qoitopam
+# This script tests: pamtosrf srftopam
+# This script tests: pamtosvg svgtopam
+# This script tests: pamtowinicon winicontopam
+# This script tests: pamtotga tgatoppm
+# This script tests: pamtoxvmini xvminitoppm
+# This script tests: pamtofits fitstopnm
+# This script tests: pamtogif giftopnm
+# This script tests: pamtotiff tifftopnm
+# Also requires: pgmmake
+
+tmpdir=${tmpdir:-/tmp}
+test_pgm=${tmpdir}/test.pgm
+out1=${tmpdir}/out1
+out2=${tmpdir}/out2
+out3=${tmpdir}/out3
+out4=${tmpdir}/out4
+
+pgmmake -maxval 3 0.25 32 32 > ${test_pgm}
+
+echo "Test.  Should print (command): 0 0 0 0"
+echo "The following are exceptions: should print (command): 0 0 0 1"
+echo "pamtotga, pamtotiff"
+echo
+
+for fmt in \
+    avs \
+    hdiff \
+    jpeg2k \
+    pdbimg \
+    pfm \
+    png \
+    qoi \
+    srf \
+    svg \
+    winicon \
+    tga \
+    xvmini \
+    fits \
+    gif \
+    tiff
+  do
+
+  if [ ${fmt} = pdbimg ]
+      then testprog1="pamtopdbimg -fixedtime";
+      else testprog1="pamto"${fmt};
+  fi
+
+  case $fmt in
+      "tga" | "xvmini")        testprog2=${fmt}"toppm";;
+      "fits" | "gif" | "tiff") testprog2=${fmt}"topnm";;
+      *) testprog2=${fmt}"topam";
+  esac
+
+  ${testprog1} ${test_pgm} > ${out1};      status1=$?
+  ${testprog1} < ${test_pgm} > ${out2};    status2=$?
+  test -s ${out1};                         status3=$?
+  cmp -s ${out1} ${out2}
+  echo ${testprog1}": "${status1} ${status2} ${status3} $?
+
+  ${testprog2} ${out1} > ${out3};      status4=$?
+  ${testprog2} < ${out1} > ${out4};    status5=$?
+  test -s ${out3};                     status6=$?
+  cmp -s ${out3} ${out4}
+  echo ${testprog2}": "${status4} ${status5} ${status6} $?
+  done
+
+rm ${test_pgm} ${out1} ${out2} ${out3} ${out4}
diff --git a/test/stdin-pbm1.ok b/test/stdin-pbm1.ok
new file mode 100644
index 00000000..0dd83466
--- /dev/null
+++ b/test/stdin-pbm1.ok
@@ -0,0 +1,9 @@
+pbmclean: 0 0 0 0
+pbmlife: 0 0 0 0
+pbmmask: 0 0 0 0
+pbmminkowski: 0 0 0 0
+pbmtoepsi: 0 0 0 0
+pbmtopsg3: 0 0 0 0
+pbmpscale 1 : 0 0 0 0
+pbmreduce -threshold 2 : 0 0 0 0
+pbmtopgm 2 2 : 0 0 0 0
diff --git a/test/stdin-pbm1.test b/test/stdin-pbm1.test
new file mode 100755
index 00000000..4e99ba0b
--- /dev/null
+++ b/test/stdin-pbm1.test
@@ -0,0 +1,45 @@
+#! /bin/sh
+# This script tests: pbmclean pbmlife pbmmask pbmminkowski pbmtoepsi
+# This script tests: pbmtopsg3 pbmpscale pbmreduce pbmtopgm
+# Also requires: pbmmake
+
+# Tests whether output is unchanged when
+# (1) input is a named file: pbm-command input-file
+# (2) input is from stdin:   pbm-command < input-file
+
+tmpdir=${tmpdir:-/tmp}
+out1=${tmpdir}/out1
+out2=${tmpdir}/out2
+out3=${tmpdir}/out3
+out4=${tmpdir}/out4
+small_pbm=${tmpdir}/small.pbm
+
+pbmmake -b 3 3 > ${small_pbm}
+
+for testprog in \
+        pbmclean \
+        pbmlife \
+        pbmmask \
+        pbmminkowski \
+        pbmtoepsi \
+        pbmtopsg3 \
+        "pbmpscale 1 " \
+        "pbmreduce -threshold 2 " \
+        "pbmtopgm 2 2 "
+  do
+  ${testprog} ${small_pbm} > ${out1};      status1=$?
+  ${testprog} < ${small_pbm} > ${out2};    status2=$?
+  test -s ${out1};                         status3=$?
+  cmp -s ${out1} ${out2}
+  echo ${testprog}": "${status1} ${status2} ${status3} $?
+  rm ${out1} ${out2}
+  done
+
+rm ${small_pbm}
+
+# For Pbm converters not tested here see pbm-misc-converters.test
+
+# These programs do not have a converter in the opposite direction:
+# Brushtopbm
+# Ddbugtopbm
+# Thinkjettopbm (?)
diff --git a/test/stdin-pbm2.ok b/test/stdin-pbm2.ok
new file mode 100644
index 00000000..c77f7b13
--- /dev/null
+++ b/test/stdin-pbm2.ok
@@ -0,0 +1,28 @@
+pbmtoatk: 0 0 0 0
+atktopbm: 0 0 0 0
+pbmtocis: 0 0 0 0
+cistopbm: 0 0 0 0
+pbmtocmuwm: 0 0 0 0
+cmuwmtopbm: 0 0 0 0
+pbmtoescp2: 0 0 0 0
+escp2topbm: 0 0 0 0
+pbmtog3: 0 0 0 0
+g3topbm: 0 0 0 0
+pbmtogem: 0 0 0 0
+gemtopnm: 0 0 0 0
+pbmtomacp: 0 0 0 0
+macptopbm: 0 0 0 0
+pbmtomda: 0 0 0 0
+mdatopbm: 0 0 0 0
+pbmtomgr: 0 0 0 0
+mgrtopbm: 0 0 0 0
+pbmtomrf: 0 0 0 0
+mrftopbm: 0 0 0 0
+pbmtopi3: 0 0 0 0
+pi3topbm: 0 0 0 0
+pbmtosunicon: 0 0 0 0
+sunicontopnm: 0 0 0 0
+pbmtowbmp: 0 0 0 0
+wbmptopbm: 0 0 0 0
+pbmtoybm: 0 0 0 0
+ybmtopbm: 0 0 0 0
diff --git a/test/stdin-pbm2.test b/test/stdin-pbm2.test
new file mode 100755
index 00000000..ba585516
--- /dev/null
+++ b/test/stdin-pbm2.test
@@ -0,0 +1,78 @@
+#! /bin/sh
+# This script tests: atktopbm pbmtoatk
+# This script tests: cistopbm pbmtocis
+# This script tests: cmuwmtopbm pbmtocmuwm
+# This script tests: escp2topbm pbmtoescp2
+# This script tests: g3topbm pbmtog3
+# This script tests: gemtopnm pbmtogem
+# This script tests: macptopbm pbmtomacp
+# This script tests: mdatopbm pbmtomda
+# This script tests: mgrtopbm pbmtomgr
+# This script tests: mrftopbm pbmtomrf
+# This script tests: pi3topbm pbmtopi3
+# This script tests: sunicontopnm pbmtosunicon
+# This script tests: wbmptopbm pbmtowbmp
+# This script tests: ybmtopbm pbmtoybm
+# Also requires:
+
+tmpdir=${tmpdir:-/tmp}
+out1=${tmpdir}/out1
+out2=${tmpdir}/out2
+out3=${tmpdir}/out3
+out4=${tmpdir}/out4
+
+for fmt in  \
+        atk \
+        cis \
+        cmuwm \
+        escp2 \
+        g3 \
+        gem \
+        macp \
+        mda \
+        mgr \
+        mrf \
+        pi3 \
+        sunicon \
+        wbmp \
+        ybm
+  do
+  testprog1="pbmto"${fmt}
+
+  if [ ${fmt} = "sunicon" -o ${fmt} = "gem" ];
+    then testprog2=${fmt}"topnm";
+    else testprog2=${fmt}"topbm";
+  fi
+
+  ${testprog1} testgrid.pbm > ${out1};     status1=$?
+  ${testprog1} < testgrid.pbm > ${out2};   status2=$?
+  test -s ${out1};                         status3=$?
+  cmp -s ${out1} ${out2}
+  echo ${testprog1}": "${status1} ${status2} ${status3} $?
+  rm ${out2}
+
+  ${testprog2} ${out1} > ${out3};      status3=$?
+  ${testprog2} < ${out1} > ${out4};    status4=$?
+
+  if [ ${fmt} = "xbm" ];
+    then sed -i '3s/noname/testgrid/' ${out3};
+  fi
+
+  test -s ${out3};                         status5=$?
+  cmp -s ${out3} ${out4}
+  echo ${testprog2}": "${status3} ${status4} ${status5} $?
+  rm ${out1} ${out3} ${out4}
+  done
+
+# We don't test Pbmtopgm Pgmtopbm Asciitopbm Asciitopgm here
+
+# Pbmtopk Pktopbm require resolution output pk file, tk file
+#            some conditions apply to input image dimensions
+
+# These three programs embed the input file name in the output
+# If the input is from stdin, "noname"
+# Pbmtolps tested in lps-roundtrip.test
+# Pbmtoxbm           xbm-roundtrip.test
+# Pbmtozinc          pbm-misc-converters.test
+
+# Icontopbm Pbmtoicon Pbmtox10bm are legacy
diff --git a/test/stdin-pgm1.ok b/test/stdin-pgm1.ok
new file mode 100644
index 00000000..b3159517
--- /dev/null
+++ b/test/stdin-pgm1.ok
@@ -0,0 +1,11 @@
+pgmabel: 0 0 0 0
+pgmbentley: 0 0 0 0
+pgmdeshadow: 0 0 0 0
+pgmenhance: 0 0 0 0
+pgmhist: 0 0 0 0
+pgmmedian: 0 0 0 0
+pgmminkowski: 0 0 0 0
+pgmtexture: 0 0 0 0
+pgmtopbm -th : 0 0 0 0
+pgmtoppm rgb:00/00/00 : 0 0 0 0
+rawtopgm -headerskip 11 3 3 : 0 0 0 0
diff --git a/test/stdin-pgm1.test b/test/stdin-pgm1.test
new file mode 100755
index 00000000..f5980cdc
--- /dev/null
+++ b/test/stdin-pgm1.test
@@ -0,0 +1,47 @@
+#! /bin/sh
+# This script tests: pgmabel pgmbentley pgmdeshadow pgmenhance pgmhist
+# This script tests: pgmmedian pgmminkowski pgmtexture pgmtopbm pgmtoppm
+# This script tests: rawtopgm
+# Also requires: pgmmake
+
+tmpdir=${tmpdir:-/tmp}
+small_pgm=${tmpdir}/small.pgm
+out1=${tmpdir}/out1
+out2=${tmpdir}/out2
+out3=${tmpdir}/out3
+out4=${tmpdir}/out4
+
+pgmmake 0.5 3 3 > ${small_pgm}
+
+for testprog in  \
+        pgmabel \
+        pgmbentley \
+        pgmdeshadow \
+        pgmenhance \
+        pgmhist \
+        pgmmedian \
+        pgmminkowski \
+        pgmtexture \
+        "pgmtopbm -th " \
+        "pgmtoppm rgb:00/00/00 " \
+	"rawtopgm -headerskip 11 3 3 "
+  do
+  ${testprog} ${small_pgm} > ${out1};      status1=$?
+  ${testprog} < ${small_pgm} > ${out2};    status2=$?
+  test -s ${out1};                         status3=$?
+  cmp -s ${out1} ${out2}
+  echo ${testprog}": "${status1} ${status2} ${status3} $?
+  rm ${out1} ${out2}
+  done
+
+rm ${small_pgm}
+
+
+# Pgmtopgm accepts input only from stdin
+
+# These three programs are legacy
+# Pgmedge
+# Pgmnorm
+# Pgmoil
+
+# Pgmmorphconv needs template file
diff --git a/test/stdin-pgm2.ok b/test/stdin-pgm2.ok
new file mode 100644
index 00000000..ee6d8082
--- /dev/null
+++ b/test/stdin-pgm2.ok
@@ -0,0 +1,6 @@
+pgmtofs : 0 0 0 0
+fstopgm : 0 0 0 0
+pgmtolispm : 0 0 0 0
+lispmtopgm : 0 0 0 0
+pgmtost4 : 0 0 0 0
+st4topgm : 0 0 0 0
diff --git a/test/stdin-pgm2.test b/test/stdin-pgm2.test
new file mode 100755
index 00000000..3a6220d8
--- /dev/null
+++ b/test/stdin-pgm2.test
@@ -0,0 +1,49 @@
+#! /bin/sh
+# This script tests: pgmtofs fstopgm
+# This script tests: pgmtolispm lispmtopgm
+# This script tests: pgmtost4 st4topgm
+# Also requires: pgmmake
+
+tmpdir=${tmpdir:-/tmp}
+test_pgm=${tmpdir}/test.pgm
+out1=${tmpdir}/out1
+out2=${tmpdir}/out2
+out3=${tmpdir}/out3
+out4=${tmpdir}/out4
+
+pgmmake 0.75 192 165 > ${test_pgm}
+
+for fmt in  \
+        fs \
+        lispm \
+	st4
+  do
+  testprog1="pgmto"${fmt}
+  testprog2=${fmt}"topgm"
+
+  ${testprog1} ${test_pgm} > ${out1};   status1=$?
+  ${testprog1} < ${test_pgm} > ${out2}; status2=$?
+  test -s ${out1};                      status3=$?
+  cmp -s ${out1} ${out2}
+  echo ${testprog1}" :" ${status1} ${status2} ${status3} $?
+  rm ${out2}
+
+  ${testprog2} ${out1} > ${out3};     status4=$?
+  ${testprog2} < ${out1} > ${out4};   status5=$?
+  test -s ${out3};                    status6=$?
+  cmp -s ${out3} ${out4}
+  echo ${testprog2}" :" ${status4} ${status5} ${status6} $?
+
+  rm ${out1} ${out3} ${out4}
+  done
+
+rm ${test_pgm}
+
+# pgmtost4 size must be 192 x 165
+
+# The following programs do not have converters in the opposite direction:
+# Bioradtopgm
+# Hipstopgm
+# Psidtopgm
+# Rawtopgm
+# Spottopgm
diff --git a/test/stdin-pnm1.ok b/test/stdin-pnm1.ok
new file mode 100644
index 00000000..9f427b23
--- /dev/null
+++ b/test/stdin-pnm1.ok
@@ -0,0 +1,22 @@
+pnmalias: 0 0 0 0
+pnmcolormap all : 0 0 0 0
+pnmconvol -matrix=-1,3,-1 : 0 0 0 0
+pnmcrop: 0 0 0 0
+pnmgamma -ungamma 0.5 : 0 0 0 0
+pnmhisteq: 0 0 0 0
+pnmhistmap: 0 0 0 0
+pnminvert: 0 0 0 0
+pnmmargin 2 : 0 0 0 0
+pnmmercator: 0 0 0 0
+pnmmontage: 0 0 0 0
+pnmnlfilt 0.5 0.5 : 0 0 0 0
+pnmnorm: 0 0 0 0
+pnmpad: 0 0 0 0
+pnmquant 64 : 0 0 0 0
+pnmrotate 90 : 0 0 0 0
+pnmscalefixed 1 : 0 0 0 0
+pnmshear 45 : 0 0 0 0
+pnmsmooth: 0 0 0 0
+pnmtile 4 4 : 0 0 0 0
+pnmtoddif: 0 0 0 0
+pnmtopclxl -colorok : 0 0 0 0
diff --git a/test/stdin-pnm1.test b/test/stdin-pnm1.test
new file mode 100755
index 00000000..20902d41
--- /dev/null
+++ b/test/stdin-pnm1.test
@@ -0,0 +1,59 @@
+#! /bin/sh
+# This script tests: pnmalias pnmcolormap pnmconvol pnmcrop pnmgamma
+# This script tests: pnmhisteq pnmhistmap pnminvert pnmmargin pnmmercator
+# This script tests: pnmmontage pnmnlfilt pnmnorm pnmpad pnmquant pnmrotate
+# This script tests: pnmscalefixed pnmshear pnmsmooth pnmtile pnmtoddif
+# This script tests: pnmtopclxl
+# Also requires: ppmpat
+
+tmpdir=${tmpdir:-/tmp}
+small_ppm=${tmpdir}/test.ppm
+out1=${tmpdir}/out1
+out2=${tmpdir}/out2
+
+ppmpat -g2 -color=rgb:00/00/ff,rgb:ff/00/00 -mesh 4 4 > ${small_ppm}
+
+for testprog in  \
+        pnmalias \
+        "pnmcolormap all " \
+        "pnmconvol -matrix=-1,3,-1 " \
+        pnmcrop \
+        "pnmgamma -ungamma 0.5 " \
+        pnmhisteq \
+        pnmhistmap \
+        pnminvert \
+        "pnmmargin 2 " \
+        pnmmercator \
+        pnmmontage \
+        "pnmnlfilt 0.5 0.5 " \
+        pnmnorm \
+        pnmpad \
+        "pnmquant 64 " \
+        "pnmrotate 90 " \
+        "pnmscalefixed 1 " \
+        "pnmshear 45 " \
+        pnmsmooth \
+        "pnmtile 4 4 " \
+	pnmtoddif \
+	"pnmtopclxl -colorok "
+  do
+  ${testprog} ${small_ppm} > ${out1};      status1=$?
+  ${testprog} < ${small_ppm} > ${out2};    status2=$?
+  test -s ${out1};                         status3=$?
+  cmp -s ${out1} ${out2}
+  echo ${testprog}": "${status1} ${status2} ${status3} $?
+  rm ${out1} ${out2}
+  done
+
+
+rm ${small_ppm}
+
+# Pnmquantall: overwrites input files
+# Pnmremap: requires -mapfile=file
+# Pnmpsnr : compares two input files
+# Pnmindex: no input from stdin
+# Pnmpaste: requires two input files
+# Pnmstitch: requires two input files
+
+# pnmmargin: uses pamflip
+# pnmsmooth: uses pnmconvol
diff --git a/test/stdin-pnm2.ok b/test/stdin-pnm2.ok
new file mode 100644
index 00000000..093ff3f7
--- /dev/null
+++ b/test/stdin-pnm2.ok
@@ -0,0 +1,28 @@
+Test.  Should print (command): 0 0 0
+The following are exceptions: should print (command): 0 0 0 1
+pnmtops, pstopnm, pnmtoxwd, pnmtotiffcmyk
+
+pnmtofiasco --progress-meter 0 : 0 0 0 0
+fiascotopnm: 0 0 0 0
+pnmtojbig: 0 0 0 0
+jbigtopnm: 0 0 0 0
+pnmtojpeg: 0 0 0 0
+jpegtopnm: 0 0 0 0
+pnmtopalm: 0 0 0 0
+palmtopnm: 0 0 0 0
+pnmtopng: 0 0 0 0
+pngtopam: 0 0 0 0
+pnmtops: 0 0 0 1
+pstopnm -stdout : 0 0 0 1
+pnmtorast: 0 0 0 0
+rasttopnm: 0 0 0 0
+pnmtorle: 0 0 0 0
+rletopnm: 0 0 0 0
+pnmtosgi: 0 0 0 0
+sgitopnm: 0 0 0 0
+pnmtosir: 0 0 0 0
+sirtopnm: 0 0 0 0
+pnmtoxwd: 0 0 0 1
+xwdtopnm: 0 0 0 0
+pnmtotiffcmyk: 0 0 0 1
+tifftopnm: 0 0 0 0
diff --git a/test/stdin-pnm2.test b/test/stdin-pnm2.test
new file mode 100755
index 00000000..7622c279
--- /dev/null
+++ b/test/stdin-pnm2.test
@@ -0,0 +1,91 @@
+#! /bin/sh
+# This script tests: pnmtofiasco fiascotopnm
+# This script tests: pnmtojbig jbigtopnm
+# This script tests: pnmtojpeg jpegtopnm
+# This script tests: pnmtopalm palmtopnm
+# This script tests: pnmtopng pngtopam
+# This script tests: pnmtops pstopnm
+# This script tests: pnmtorast rasttopnm
+# This script tests: pnmtorle rletopnm
+# This script tests: pnmtosgi sgitopnm
+# This script tests: pnmtosir sirtopnm
+# This script tests: pnmtoxwd xwdtopnm
+# This script tests: pnmtotiffcmyk tifftopnm
+# Also requires: pgmramp
+
+tmpdir=${tmpdir:-/tmp}
+test_pgm=${tmpdir}/test.pgm
+out1=${tmpdir}/out1
+out2=${tmpdir}/out2
+out3=${tmpdir}/out3
+out4=${tmpdir}/out4
+
+pgmramp -diag 32 32 > ${test_pgm}
+
+echo "Test.  Should print (command): 0 0 0"
+echo "The following are exceptions: should print (command): 0 0 0 1"
+echo "pnmtops, pstopnm, pnmtoxwd, pnmtotiffcmyk"
+echo
+
+export NO_ADD_RLE_HISTORY=1
+# Suppress command-line sequence, execution time in pnmtorle header
+
+for fmt in  \
+        fiasco \
+        jbig \
+        jpeg \
+        palm \
+        png \
+        ps \
+        rast \
+        rle \
+        sgi \
+        sir \
+        xwd \
+	tiffcmyk
+  do
+
+  if [ ${fmt} = "fiasco" ]
+    then testprog1="pnmto"${fmt}" --progress-meter 0 ";
+  else
+      testprog1="pnmto"${fmt};
+  fi
+
+  if [ ${fmt} = "png" ]
+    then testprog2="pngtopam";
+  elif [ ${fmt} = "ps" ]
+    then testprog2="pstopnm -stdout ";
+  elif [ ${fmt} = "tiffcmyk" ]
+    then testprog2="tifftopnm";
+  else
+    testprog2=${fmt}"topnm";
+  fi
+
+  ${testprog1} ${test_pgm} > ${out1};   status1=$?
+  ${testprog1} < ${test_pgm} > ${out2}; status2=$?
+  test -s ${out1};                      status3=$?
+  cmp -s ${out1} ${out2}
+  echo ${testprog1}": "${status1} ${status2} ${status3} $?
+  rm ${out2}
+
+  ${testprog2} ${out1} > ${out3};       status4=$?
+  ${testprog2} < ${out1} > ${out4};     status5=$?
+  test -s ${out3};                      status6=$?
+  cmp -s ${out3} ${out4}
+  echo ${testprog2}": "${status4} ${status5} ${status6} $?
+  rm ${out1} ${out3} ${out4}
+
+  done
+
+rm ${test_pgm}
+
+
+# pnmtofiasco  width, height must be even and at least 32
+#              use --progressmeter option to suppress progress meter
+#
+# pnmtojbig    input must be bilevel black-white or gray
+# pnmtops      input file name embedded in output
+# pnmtotiffcmyk  input file name embedded in output
+#                "Standard input" if from stdin
+# pnmtoxwd     input file name embedded in output
+#              "stdin" if from stdin
diff --git a/test/stdin-ppm1.ok b/test/stdin-ppm1.ok
new file mode 100644
index 00000000..e84a31ea
--- /dev/null
+++ b/test/stdin-ppm1.ok
@@ -0,0 +1,15 @@
+ppmchange: 0 0 0 0
+ppmcolormask -color=rgb:0/0/ff : 0 0 0 0
+ppmdim 0.5 : 0 0 0 0
+ppmdist: 0 0 0 0
+ppmdither: 0 0 0 0
+ppmflash 0.5 : 0 0 0 0
+ppmglobe 12 : 0 0 0 0
+ppmhist: 0 0 0 0
+ppmlabel: 0 0 0 0
+ppmntsc: 0 0 0 0
+ppmrelief: 0 0 0 0
+ppmshadow: 0 0 0 0
+ppmshift 2 -seed=1 : 0 0 0 0
+ppmspread 2 -randomseed=1 : 0 0 0 0
+ppmtv 0.5 : 0 0 0 0
diff --git a/test/stdin-ppm1.test b/test/stdin-ppm1.test
new file mode 100755
index 00000000..84614326
--- /dev/null
+++ b/test/stdin-ppm1.test
@@ -0,0 +1,58 @@
+#! /bin/sh
+# This script tests: ppmchange ppmcolormask ppmdim ppmdist ppmdither ppmflash
+# This script tests: ppmglobe ppmhist ppmlabel ppmntsc ppmrelief ppmshadow
+# This script tests: ppmshift ppmspread ppmtv
+# Also requires: ppmpat
+
+tmpdir=${tmpdir:-/tmp}
+test_ppm=${tmpdir}/test.ppm
+out1=${tmpdir}/out1
+out2=${tmpdir}/out2
+
+ppmpat -g2 -color=rgb:00/00/ff,rgb:ff/00/00 -mesh 12 12 > ${test_ppm}
+
+for testprog in  \
+        ppmchange \
+        "ppmcolormask -color=rgb:0/0/ff " \
+        "ppmdim 0.5 " \
+        ppmdist \
+        ppmdither \
+        "ppmflash 0.5 " \
+        "ppmglobe 12 " \
+        ppmhist \
+        ppmlabel \
+        ppmntsc \
+        ppmrelief \
+        ppmshadow \
+        "ppmshift 2 -seed=1 " \
+        "ppmspread 2 -randomseed=1 " \
+        "ppmtv 0.5 "
+  do
+  ${testprog} ${test_ppm} > ${out1};      status1=$?
+  ${testprog} < ${test_ppm} > ${out2};    status2=$?
+  test -s ${out1};                        status3=$?
+  cmp -s ${out1} ${out2}
+  echo ${testprog}": "${status1} ${status2} ${status3} $?
+  rm ${out1} ${out2}
+  done
+
+rm ${test_ppm}
+
+# These utlities do not have a counterpart "ppmto*" program
+
+# Gouldtoppm
+# Imgtoppm
+# Mtvtoppm
+# Pc1toppm
+# Pgmtoppm
+# Qrttoppm
+# Rawtoppm
+# Sldtoppm
+# Spctoppm
+# Ximtoppm
+
+# Tgatoppm -> Pamtotga
+# Xvminitoppm -> Pamtoxvmini
+
+# Ppm3d and Ppmmix require input two files
+# Ppmfade produces a series of output files
diff --git a/test/stdin-ppm2.ok b/test/stdin-ppm2.ok
new file mode 100644
index 00000000..e1335bfb
--- /dev/null
+++ b/test/stdin-ppm2.ok
@@ -0,0 +1,11 @@
+ppmtoacad: 0 0 0 0
+ppmtoapplevol: 0 0 0 0
+ppmtoascii: 0 0 0 0
+ppmtoicr -windowname testimage: 0 0 0 0
+ppmtolj: 0 0 0 0
+ppmtomitsu: 0 0 0 0
+ppmtopgm: 0 0 0 0
+ppmtopuzz: 0 0 0 0
+ppmtosixel: 0 0 0 0
+ppmtoterm: 0 0 0 0
+ppmtoyuvsplit: 0 0 0 0
diff --git a/test/stdin-ppm2.test b/test/stdin-ppm2.test
new file mode 100755
index 00000000..e43b6d4c
--- /dev/null
+++ b/test/stdin-ppm2.test
@@ -0,0 +1,58 @@
+#! /bin/sh
+# This script tests: ppmtoacad ppmtoapplevol ppmtoascii ppmtolj ppmtomitsu
+# This script tests: ppmtopgm ppmtopuzz ppmtosixel ppmtoterm
+# This script tests: ppmtoicr ppmtoyuvsplit
+# Also requires: ppmpat
+
+tmpdir=${tmpdir:-/tmp}
+test_ppm=${tmpdir}/test.ppm
+out1=${tmpdir}/out1
+out2=${tmpdir}/out2
+
+ppmpat -g2 -color=rgb:00/00/ff,rgb:ff/00/00 -mesh 12 12 > ${test_ppm}
+
+# These converters do not have counterparts in the reverse direction
+
+for testprog in  \
+        ppmtoacad \
+        ppmtoapplevol \
+        ppmtoascii \
+        "ppmtoicr -windowname testimage" \
+        ppmtolj \
+        ppmtomitsu \
+        ppmtopgm \
+        ppmtopuzz \
+        ppmtosixel \
+        ppmtoterm
+  do
+  ${testprog} ${test_ppm} > ${out1};      status1=$?
+  ${testprog} < ${test_ppm} > ${out2};    status2=$?
+  test -s ${out1};                        status3=$?
+  cmp -s ${out1} ${out2}
+  echo ${testprog}": "${status1} ${status2} ${status3} $?
+  rm ${out1} ${out2}
+  done
+
+rm ${test_ppm}
+
+testprog=ppmtoyuvsplit
+
+# Produces three output files
+
+  ${testprog} ${tmpdir}/base testgrid.pbm;     status1=$?
+  cat ${tmpdir}/base.Y  ${tmpdir}/base.U  ${tmpdir}/base.V > ${out1}
+  rm ${tmpdir}/base.Y  ${tmpdir}/base.U  ${tmpdir}/base.V
+
+  ${testprog} ${tmpdir}/base < testgrid.pbm;   status2=$?
+  cat ${tmpdir}/base.Y  ${tmpdir}/base.U  ${tmpdir}/base.V > ${out2}
+  rm ${tmpdir}/base.Y  ${tmpdir}/base.U  ${tmpdir}/base.V
+  test -s ${out1};                             status3=$?
+  cmp -s ${out1} ${out2}
+  echo ${testprog}": "${status1} ${status2} ${status3} $?
+  rm ${out1} ${out2}
+
+# Ppmtoppm input is from standard input
+
+# Ppmtoapplevol height must be 12
+# Ppmtoarbtxt needs body template file
+# Ppmtompeg parameter file must be given
diff --git a/test/stdin-ppm3.ok b/test/stdin-ppm3.ok
new file mode 100644
index 00000000..42932e92
--- /dev/null
+++ b/test/stdin-ppm3.ok
@@ -0,0 +1,20 @@
+ppmtobmp: 0 0 0 0
+bmptopnm: 0 0 0 0
+ppmtoilbm: 0 0 0 0
+ilbmtoppm: 0 0 0 0
+ppmtoleaf: 0 0 0 0
+leaftoppm: 0 0 0 0
+ppmtoneo: 0 0 0 0
+neotoppm: 0 0 0 0
+ppmtopcx: 0 0 0 0
+pcxtoppm: 0 0 0 0
+ppmtopi1: 0 0 0 0
+pi1toppm: 0 0 0 0
+ppmtopict: 0 0 0 0
+picttoppm: 0 0 0 0
+ppmtopj: 0 0 0 0
+pjtoppm: 0 0 0 0
+ppmtospu: 0 0 0 0
+sputoppm: 0 0 0 0
+ppmtoxpm -name small: 0 0 0 0
+xpmtoppm: 0 0 0 0
diff --git a/test/stdin-ppm3.test b/test/stdin-ppm3.test
new file mode 100755
index 00000000..1313ac40
--- /dev/null
+++ b/test/stdin-ppm3.test
@@ -0,0 +1,75 @@
+#! /bin/sh
+# This script tests: ppmtobmp bmptopnm
+# This script tests: ppmtoilbm ilbmtoppm
+# This script tests: ppmtoleaf leaftoppm
+# This script tests: ppmtoneo neotoppm
+# This script tests: ppmtopcx pcxtoppm
+# This script tests: ppmtopi1 pi1toppm
+# This script tests: ppmtopict picttoppm
+# This script tests: ppmtopj pjtoppm
+# This script tests: ppmtospu sputoppm
+# This script tests: ppmtoxpm xpmtoppm
+# Also requires: ppmmake
+
+tmpdir=${tmpdir:-/tmp}
+small_ppm=${tmpdir}/small.ppm
+large_ppm=${tmpdir}/large.ppm
+out1=${tmpdir}/out1
+out2=${tmpdir}/out2
+out3=${tmpdir}/out3
+out4=${tmpdir}/out4
+
+ppmmake -maxval 65535 rgb:00/00/00 8 3 > ${small_ppm}
+ppmmake -maxval 7 rgb:00/00/00 320 200 > ${large_ppm}
+
+for fmt in \
+        bmp \
+        ilbm \
+        leaf \
+        neo \
+        pcx \
+        pi1 \
+        pict \
+        pj \
+        spu \
+        xpm
+do
+  if [ ${fmt} = "xpm" ]
+    then testprog1="ppmto${fmt} -name small";
+  else 	 testprog1="ppmto${fmt}";
+  fi
+  if [ ${fmt} = "bmp" ]
+    then testprog2=${fmt}"topnm";
+  else   testprog2=${fmt}"toppm";
+  fi
+
+  if [ ${fmt} = "spu" ]
+    then test_ppm=${large_ppm};
+  else   test_ppm=${small_ppm};
+  fi
+
+  ${testprog1} ${test_ppm} > ${out1};    status1=$?
+  ${testprog1} < ${test_ppm} > ${out2};  status2=$?
+  test -s ${out1};                       status3=$?
+  cmp -s ${out1} ${out2}
+  echo ${testprog1}": "${status1} ${status2} ${status3} $?
+  rm ${out2}
+
+  ${testprog2} ${out1} > ${out3};      status4=$?
+  ${testprog2} < ${out1} > ${out4};    status5=$?
+  test -s ${out1};                     status6=$?
+  cmp -s ${out3} ${out4}
+  echo ${testprog2}": "${status4} ${status5} ${status6} $?
+  rm ${out1} ${out3} ${out4}
+  done
+
+rm ${small_ppm} ${large_ppm}
+
+# ppmtopict width must be 8 or more
+
+# ppmtospu sputoppm width=320 height=200 fixed
+
+# Eyuvtoppm, Yuvtoppm width, height are mandatory
+
+# Ppmtowinicon Winicontoppm legacy
+# Winicontoppm max size 255 255
diff --git a/test/sunicon-roundtrip.ok b/test/sunicon-roundtrip.ok
index 845be5fb..8bfdc3a0 100644
--- a/test/sunicon-roundtrip.ok
+++ b/test/sunicon-roundtrip.ok
@@ -1 +1,4 @@
-2425386270 41
+Test.  Should print 0 three times
+0
+0
+0
diff --git a/test/sunicon-roundtrip.test b/test/sunicon-roundtrip.test
index a52fda68..38513ea8 100755
--- a/test/sunicon-roundtrip.test
+++ b/test/sunicon-roundtrip.test
@@ -1,8 +1,26 @@
-#! /bin/bash
+#! /bin/sh
 # This script tests: pbmtosunicon sunicontopnm
-# Also requires: pamcut
+# Also requires: pbmnoise
 
-# Width of Sun icons are multiples of 8.
+# Width of a Sun icon is always a multiple of 8.
 
-# Test.  Should print: 2425386270 41
-pbmtosunicon testgrid.pbm | sunicontopnm | pamcut 1 0 14 16 | cksum
+tmpdir=${tmpdir:-/tmp}
+
+noise16_pbm=${tmpdir}/noise16.pbm
+noise32_pbm=${tmpdir}/noise32.pbm
+noise64_pbm=${tmpdir}/noise64.pbm
+
+echo "Test.  Should print 0 three times"
+pbmnoise -randomseed=1 16 16 > ${noise16_pbm} && \
+  pbmtosunicon ${noise16_pbm} | sunicontopnm | cmp -s - ${noise16_pbm}
+  echo $?
+
+pbmnoise -randomseed=1 32 32 > ${noise32_pbm} && \
+  pbmtosunicon ${noise32_pbm} | sunicontopnm | cmp -s - ${noise32_pbm}
+  echo $?
+
+pbmnoise -randomseed=1 64 64 > ${noise64_pbm} && \
+  pbmtosunicon ${noise64_pbm} | sunicontopnm | cmp -s - ${noise64_pbm}
+  echo $?
+
+rm ${noise16_pbm} ${noise32_pbm} ${noise64_pbm}
\ No newline at end of file
diff --git a/test/sunrast-roundtrip.test b/test/sunrast-roundtrip.test
index a5cfa8c7..dfe68402 100755
--- a/test/sunrast-roundtrip.test
+++ b/test/sunrast-roundtrip.test
@@ -1,4 +1,4 @@
-#! /bin/bash
+#! /bin/sh
 # This script tests: pnmtorast rasttopnm
 # Also requires:
 
diff --git a/test/symmetry.ok b/test/symmetry.ok
index a5945014..111f09cf 100644
--- a/test/symmetry.ok
+++ b/test/symmetry.ok
@@ -1,5 +1,8 @@
+Test 1.
 ok
+Test 2.
 ok
+Test 3.  Should print ok 7 times
 ok
 ok
 ok
@@ -7,7 +10,9 @@ ok
 ok
 ok
 ok
+Test 4.
 ok
+Test 5.  Should print ok 7 times.
 ok
 ok
 ok
@@ -15,4 +20,5 @@ ok
 ok
 ok
 ok
+Test 6.
 ok
diff --git a/test/symmetry.test b/test/symmetry.test
index 52ba6388..3c495778 100755
--- a/test/symmetry.test
+++ b/test/symmetry.test
@@ -1,4 +1,4 @@
-#! /bin/bash
+#! /bin/sh
 # This script tests: pgmramp pamgauss pgmkernel pbmmake pbmpscale
 # Also requires: pamflip
 
@@ -25,7 +25,7 @@
 
 tmpdir=${tmpdir:-/tmp}
 
-# Test 1.
+echo "Test 1."
 rect_pgm=${tmpdir}/rect.pgm
 
 pgmramp -rect 31 31 > ${rect_pgm}
@@ -37,7 +37,8 @@ pgmramp -rect 31 31 > ${rect_pgm}
 
 rm ${rect_pgm}
 
-# Test 2.
+
+echo "Test 2."
 circle_pgm=${tmpdir}/circle.pgm
 pgmramp -ell 63 63 > ${circle_pgm}
 
@@ -48,7 +49,8 @@ pgmramp -ell 63 63 > ${circle_pgm}
 
 rm ${circle_pgm}
 
-# Test 3.  Should print "ok" 7 times
+
+echo "Test 3.  Should print ok 7 times"
 gauss_pgm=${tmpdir}/gauss.pgm
 for size in 3 4 5 8 13 21 25
 do
@@ -63,7 +65,7 @@ rm ${gauss_pgm}
 done
 
 
-# Test 4.
+echo "Test 4."
 kernel_pgm=${tmpdir}/kernel.pgm
 pgmkernel 15 15 > ${kernel_pgm}
 
@@ -74,12 +76,12 @@ pgmkernel 15 15 > ${kernel_pgm}
 
 rm ${kernel_pgm}
 
-# Test 5.
-# Should print "ok" 7 times.
+
+echo "Test 5.  Should print ok 7 times."
 pscale_pbm=${tmpdir}/pscale.pbm
-for size in `seq 1 7`
-do
-pbmmake -g 5 5 | pbmpscale $size > ${pscale_pbm}
+for size in 1 2 3 4 5 6 7  # for size in `seq 7`
+  do
+  pbmmake -g 5 5 | pbmpscale ${size} > ${pscale_pbm}
 
 ( for op in -null -tb -lr -r90
     do pamflip $op ${pscale_pbm} | cksum
@@ -89,7 +91,8 @@ pbmmake -g 5 5 | pbmpscale $size > ${pscale_pbm}
 rm ${pscale_pbm}
 done
 
-# Test 6.
+
+echo "Test 6."
 ell_pgm=${tmpdir}/ell.pgm
 pgmramp -ell 101 33 > ${ell_pgm}
 
diff --git a/test/targa-roundtrip.ok b/test/targa-roundtrip.ok
index 514f970f..beb6700e 100644
--- a/test/targa-roundtrip.ok
+++ b/test/targa-roundtrip.ok
@@ -1,15 +1,15 @@
-Test 1
-2425386270 41
-2425386270 41
-2425386270 41
-2425386270 41
-2425386270 41
-2425386270 41
-2425386270 41
-2425386270 41
-2425386270 41
-2425386270 41
-Test 2
+Test 1:  Should print 281226646 481 ten times
+281226646 481
+281226646 481
+281226646 481
+281226646 481
+281226646 481
+281226646 481
+281226646 481
+281226646 481
+281226646 481
+281226646 481
+Test 2:  Should produce 1571496937 33838 ten times
 1571496937 33838
 1571496937 33838
 1571496937 33838
@@ -20,19 +20,19 @@ Test 2
 1571496937 33838
 1571496937 33838
 1571496937 33838
-Test 3
+Test 3.  Should print 1926073387 101484 four times
 1926073387 101484
 1926073387 101484
 1926073387 101484
 1926073387 101484
-Test 4
+Test 4.  Should print 0 0 0 : 0 six times
 0 0 0 : 0
 0 0 0 : 0
 0 0 0 : 0
 0 0 0 : 0
 0 0 0 : 0
 0 0 0 : 0
-Test 5
+Test 4.  Should print 0 0 0 : 0 twice, then 0 0 0 0 : 0 six times
 0 0 0 : 0
 0 0 0 : 0
 0 0 0 0 : 0
diff --git a/test/targa-roundtrip.test b/test/targa-roundtrip.test
index 79b01b61..2dd04e91 100755
--- a/test/targa-roundtrip.test
+++ b/test/targa-roundtrip.test
@@ -4,25 +4,21 @@
 
 tmpdir=${tmpdir:-/tmp}
 
-#Test 1: Should print 2425386270 41, cksum of testgrid.pbm, ten times
-
-echo "Test 1"
+echo "Test 1:  Should print 281226646 481 ten times"
 
 for mode in "-mono" "-mono -norle" \
             "-cmap" "-cmap -norle" "-cmap16" "-cmap16 -norle" \
             "-rgb"  "-rgb  -norle" "" "-norle"
   do
-  pamtotga ${mode} testgrid.pbm | \
+  pamtotga ${mode} maze.pbm | \
     tgatoppm | ppmtopgm | \
     pgmtopbm -threshold -val 0.5 | cksum
   done
 
-#Test 2:  Should produce 1571496937 33838, cksum of testimg.red, ten times
-
-echo "Test 2"
+echo "Test 2:  Should produce 1571496937 33838 ten times"
 
 test_pam=${tmpdir}/testimg.pgm
-pamchannel -infile=testimg.ppm -tupletype="GRAYSCALE" 0 > ${test_pam}
+pamchannel -infile=testimg.ppm -tupletype="GRAYSCALE" 0 > ${test_pam} 
 
 for mode in "-mono" "-mono -norle" \
             "-cmap" "-cmap -norle" "-cmap16" "-cmap16 -norle" \
@@ -33,19 +29,14 @@ for mode in "-mono" "-mono -norle" \
 
 rm ${test_pam}
 
-
-#Test 3: Should print 1926073387 101484, cksum of testimg.ppm, four times
-
-echo "Test 3"
+echo "Test 3.  Should print 1926073387 101484 four times"
 
 for mode in "-rgb" "-rgb -norle" "" "-norle"
   do
   pamtotga ${mode} testimg.ppm | tgatoppm | cksum
   done
 
-#Test 4: Should print 0 six times
-
-echo "Test 4"
+echo "Test 4.  Should print 0 0 0 : 0 six times"
 
 test256_ppm=${tmpdir}/test256.ppm
 pnmquant 256 testimg.ppm > ${test256_ppm} || echo "pnmquant failed"
@@ -57,10 +48,7 @@ for mode in "-rgb" "-rgb -norle" "-cmap" "-cmap -norle" "" "-norle"
   echo ${PIPESTATUS[@]} ":" $?
 done
 
-
-#Test 5: Should print 0 eight times
-
-echo "Test 5"
+echo "Test 4.  Should print 0 0 0 : 0 twice, then 0 0 0 0 : 0 six times"
 
 test256_31_ppm=${tmpdir}/test256-31.ppm
 pamdepth 31 ${test256_ppm} > ${test256_31_ppm} || echo "pamdepth failed"
diff --git a/test/test-invalid.inc b/test/test-invalid.inc
new file mode 100644
index 00000000..e24cfd3f
--- /dev/null
+++ b/test/test-invalid.inc
@@ -0,0 +1,16 @@
+echo 1>&2
+echo "Invalid command-line argument combination(s)." 1>&2
+echo "Error message(s) should appear below the line." 1>&2
+echo "-----------------------------------------------------------" 1>&2
+
+tmpdir=${tmpdir:-/tmp}
+test_out=${tmpdir}/test_out
+
+# define function
+invCmd () { $1 > ${test_out} && \
+  printf "Unexpected success ${testcnt} " || printf "Expected failure ${testcnt} "
+  test -s ${test_out} && echo "unexpected output" || echo "(no output)"
+  rm -f ${test_out}
+  testcnt=$(($testcnt +1)); }
+
+testcnt=1
diff --git a/test/test1.info b/test/test1.info
new file mode 100644
index 00000000..5510d8e8
--- /dev/null
+++ b/test/test1.info
Binary files differdiff --git a/test/test2.info b/test/test2.info
new file mode 100644
index 00000000..7ddb5a6b
--- /dev/null
+++ b/test/test2.info
Binary files differdiff --git a/test/tiff-flate-lzw-roundtrip.ok b/test/tiff-flate-lzw-roundtrip.ok
index 4d5597cc..b3b0e1e7 100644
--- a/test/tiff-flate-lzw-roundtrip.ok
+++ b/test/tiff-flate-lzw-roundtrip.ok
@@ -1,7 +1,9 @@
+Test 1.  Should print 1079668603 10237 six times
 1079668603 10237
 1079668603 10237
 1079668603 10237
 1079668603 10237
 1079668603 10237
 1079668603 10237
-2425386270 41
+Test 2.  Should print 281226646 481
+281226646 481
diff --git a/test/tiff-flate-lzw-roundtrip.test b/test/tiff-flate-lzw-roundtrip.test
index 59d4c483..2b0a4536 100755
--- a/test/tiff-flate-lzw-roundtrip.test
+++ b/test/tiff-flate-lzw-roundtrip.test
@@ -1,4 +1,4 @@
-#! /bin/bash
+#! /bin/sh
 # This script tests: pamtotiff tifftopnm
 # Also requires: ppmpat
 
@@ -8,11 +8,11 @@
 ## features.
 
 tmpdir=${tmpdir:-/tmp}
-
 tartan_ppm=${tmpdir}/testimg40.ppm
 
 # Make a test image with reduced colors which compresses better
-# cksum is 1079668603 10237
+
+echo "Test 1.  Should print 1079668603 10237 six times"
 
 ppmpat -tartan --color=rgb:32/0d/b7,rgb:31/58/a3,rgb:e9/5e/d4 71 48 | \
   tee ${tartan_ppm} | cksum
@@ -28,7 +28,9 @@ pamtotiff -adobeflate ${tartan_ppm} | tifftopnm | cksum
 pamtotiff -lzw ${tartan_ppm} | tifftopnm | cksum
 pamtotiff -lzw -predictor=1 ${tartan_ppm} | tifftopnm | cksum
 
-# PBM image: test flate compression
-pamtotiff -flate testgrid.pbm | tifftopnm | cksum
-
 rm ${tartan_ppm}
+
+echo "Test 2.  Should print 281226646 481"
+
+# PBM image: test flate compression
+pamtotiff -flate maze.pbm | tifftopnm | cksum
diff --git a/test/tiff-roundtrip.ok b/test/tiff-roundtrip.ok
index 14258de2..dec662ed 100644
--- a/test/tiff-roundtrip.ok
+++ b/test/tiff-roundtrip.ok
@@ -1,36 +1,36 @@
-PPM-rose
+Test 1:PPM-rose  Should print 1926073387 101484 five times
 1926073387 101484
 1926073387 101484
 1926073387 101484
 1926073387 101484
 1926073387 101484
-PPM-6
+Test 2:PPM-6  Should print 1646869394 29498 four times
 1646869394 29498
 1646869394 29498
 1646869394 29498
 1646869394 29498
-PPM-2
+Test 3:PPM-2  Should print 3743909631 14836 four times
 3743909631 14836
 3743909631 14836
 3743909631 14836
 3743909631 14836
-PPM-gray
+Test 4:PPM-gray  Should print 603974118 4954 six times
 603974118 4954
 603974118 4954
 603974118 4954
 603974118 4954
 603974118 4954
 603974118 4954
-PPM-bilevel-black-white
+Test 5:PPM-bilevel-black-white  Should print 1001018459 4954 four times
 1001018459 4954
 1001018459 4954
 1001018459 4954
 1001018459 4954
-PBM
-2425386270 41
-2425386270 41
-2425386270 41
-Extract from multi-image TIFF
+Test 6:PBM  Should print 281226646 481 three times
+281226646 481
+281226646 481
+281226646 481
+Test 7:Extract from multi-image TIFF
 1926073387 101484
 1646869394 29498
 3743909631 14836
diff --git a/test/tiff-roundtrip.test b/test/tiff-roundtrip.test
index 55aba278..c33ee904 100755
--- a/test/tiff-roundtrip.test
+++ b/test/tiff-roundtrip.test
@@ -1,4 +1,4 @@
-#! /bin/bash
+#! /bin/sh
 # This script tests: pamtotiff tifftopnm
 # Also requires: ppmpat pampick ppmtopgm
 
@@ -13,9 +13,8 @@ argylegray_ppm=${tmpdir}/argyle2.ppm
 multiimage_tiff=${tmpdir}/multiimage.ppm
 
 # PPM image
-# Should print 1926073387 101484 five times
 
-echo PPM-rose
+echo "Test 1:PPM-rose  Should print 1926073387 101484 five times"
 pamtotiff testimg.ppm | tifftopnm -headerdump | cksum
 pamtotiff -truecolor testimg.ppm -output ${multiimage_tiff} && \
   tifftopnm ${multiimage_tiff} -byrow | cksum
@@ -25,9 +24,8 @@ pamtotiff -truecolor -lsb2msb  testimg.ppm | \
   tifftopnm -respectfillorder | cksum
 
 # PPM image with six colors
-# Should print 1646869394 29498 four times
 
-echo PPM-6
+echo "Test 2:PPM-6  Should print 1646869394 29498 four times"
 ppmpat -tartan -color=rgb:0/8/8,rgb:8/f/8,rgb:f/f/0 108 91 | \
   tee ${tartan_ppm} | cksum
 pamtotiff -truecolor ${tartan_ppm} | tifftopnm | cksum
@@ -37,12 +35,12 @@ pamtotiff ${tartan_ppm} -append -output ${multiimage_tiff} && \
 
 
 # PPM image with two colors
-# Should print 3743909631 14836 four times
 
-echo PPM-2
+echo "Test 3:PPM-2  Should print 3743909631 14836 four times"
 ppmpat -argyle2 -color=rgb:0/0/0,rgb:f/8/f,rgb:0/0/0 61 81 | \
   tee ${argylecolor_ppm} | cksum
-pamtotiff -indexbits=2 ${argylecolor_ppm} -append -output ${multiimage_tiff} && \
+pamtotiff -indexbits=2 ${argylecolor_ppm} -append \
+  -output ${multiimage_tiff} && \
   tifftopnm ${multiimage_tiff} | pampick 2 | cksum
 pamtotiff -indexbits=1 ${argylecolor_ppm} | tifftopnm | cksum
 pamtotiff -indexbits=1 -g4 ${argylecolor_ppm} | tifftopnm | cksum
@@ -51,9 +49,8 @@ pamtotiff -indexbits=1 -g4 ${argylecolor_ppm} | tifftopnm | cksum
 # pamtotiff detects the absence of colors and produces a grayscale
 # tiff image unless -color is specified
 # Pipeline output is PGM unless -color is specified
-# Should print 603974118 4954 six times
 
-echo PPM-gray
+echo "Test 4:PPM-gray  Should print 603974118 4954 six times"
 ppmpat -gingham3 -color=rgb:0/0/0,rgb:ff/ff/ff,rgb:0/0/0 61 81 | \
   tee ${gingham_ppm} | ppmtopgm | cksum
 pamtotiff -color ${gingham_ppm} | tifftopnm | cksum
@@ -67,9 +64,8 @@ pamtotiff -mb ${gingham_ppm} -append -output ${multiimage_tiff} && \
 # pamtotiff detects the absence of colors and produces a grayscale
 # tiff image unless -color is specified
 # Pipeline output is PGM unless -color is specified
-# Should print 1001018459 4954 four times
 
-echo PPM-bilevel-black-white
+echo "Test 5:PPM-bilevel-black-white  Should print 1001018459 4954 four times"
 ppmpat -argyle2 -color=rgb:0/0/0,rgb:ff/ff/ff,rgb:0/0/0 61 81 | \
   tee ${argylegray_ppm} | ppmtopgm | cksum
 pamtotiff -color -fill ${argylegray_ppm} | tifftopnm | cksum
@@ -78,17 +74,17 @@ pamtotiff -mb ${argylegray_ppm} -append -output ${multiimage_tiff} && \
   tifftopnm ${multiimage_tiff} | pampick 4 | cksum
 
 # PBM image
-# Should print 2425386270 41 three times
 
-echo PBM
-pamtotiff testgrid.pbm | tifftopnm | cksum
-pamtotiff -g3 -fill testgrid.pbm | tifftopnm | cksum
-pamtotiff -g4 -mb testgrid.pbm -append -output ${multiimage_tiff} && \
+
+echo "Test 6:PBM  Should print 281226646 481 three times"
+pamtotiff maze.pbm | tifftopnm | cksum
+pamtotiff -g3 -fill maze.pbm | tifftopnm | cksum
+pamtotiff -g4 -mb maze.pbm -append -output ${multiimage_tiff} && \
   tifftopnm ${multiimage_tiff} | pampick 5 | cksum
 
 # Extract individual images from multi-image tiff file
 
-echo "Extract from multi-image TIFF"
+echo "Test 7:Extract from multi-image TIFF"
 tifftopnm ${multiimage_tiff} | pampick 0 | cksum
 tifftopnm ${multiimage_tiff} | pampick 1 | cksum
 tifftopnm ${multiimage_tiff} | pampick 2 | cksum
diff --git a/test/tiffcmyk-roundtrip.test b/test/tiffcmyk-roundtrip.test
index 133c81b7..ebbc5666 100755
--- a/test/tiffcmyk-roundtrip.test
+++ b/test/tiffcmyk-roundtrip.test
@@ -1,4 +1,4 @@
-#! /bin/bash
+#! /bin/sh
 # This script tests: pnmtotiffcmyk tifftopnm
 # Also requires: pnmpsnr
 
diff --git a/test/utahrle-roundtrip.test b/test/utahrle-roundtrip.test
index 17f1a6c4..4dce0b40 100755
--- a/test/utahrle-roundtrip.test
+++ b/test/utahrle-roundtrip.test
@@ -1,4 +1,4 @@
-#! /bin/bash
+#! /bin/sh
 # This script tests: pnmtorle rletopnm
 # Also requires: pamchannel pamtopnm
 
diff --git a/test/wbmp-roundtrip.ok b/test/wbmp-roundtrip.ok
index 845be5fb..5168378d 100644
--- a/test/wbmp-roundtrip.ok
+++ b/test/wbmp-roundtrip.ok
@@ -1 +1 @@
-2425386270 41
+281226646 481
diff --git a/test/wbmp-roundtrip.test b/test/wbmp-roundtrip.test
index b651c3d0..cf747487 100755
--- a/test/wbmp-roundtrip.test
+++ b/test/wbmp-roundtrip.test
@@ -1,7 +1,7 @@
-#! /bin/bash
+#! /bin/sh
 # This script tests: pbmtowbmp wbmptopbm
 # Also requires:
 
 
-# Should print 2425386270 41, cksum of testgrid.pbm
-pbmtowbmp testgrid.pbm | wbmptopbm | cksum
+# Should print 281226646 481, cksum of maze.pbm
+pbmtowbmp maze.pbm | wbmptopbm | cksum
diff --git a/test/winicon-roundtrip.ok b/test/winicon-roundtrip.ok
index 4ba2606e..73e5030c 100644
--- a/test/winicon-roundtrip.ok
+++ b/test/winicon-roundtrip.ok
@@ -3,10 +3,10 @@ Test 1. Should print 4241318573 6973 four times
 4241318573 6973
 4241318573 6973
 4241318573 6973
-Test 1. Should print 819454437 1093 six times
-819454437 1093
-819454437 1093
-819454437 1093
-819454437 1093
-819454437 1093
-819454437 1093
+Test 1. Should print 1009647580 1093 six times
+1009647580 1093
+1009647580 1093
+1009647580 1093
+1009647580 1093
+1009647580 1093
+1009647580 1093
diff --git a/test/winicon-roundtrip.test b/test/winicon-roundtrip.test
index 00c78400..31fb89aa 100755
--- a/test/winicon-roundtrip.test
+++ b/test/winicon-roundtrip.test
@@ -1,6 +1,7 @@
-#! /bin/bash
+#! /bin/sh
 # This script tests: pamtowinicon ppmtowinicon winicontopam
-# Also requires: pamchannel pamcut pamdepth pamtopam pngtopam pnmtile pnmtopng
+# Also requires: pamchannel pamcut pamdepth pamtopam
+# Also requires: pngtopam pnmtopng
 
 tmpdir=${tmpdir:-/tmp}
 test_pam=${tmpdir}/testimg.pam
@@ -18,9 +19,9 @@ pamtowinicon -pngthreshold=1   ${test_pam} | winicontopam | \
 
 rm ${test_pam}
 
-echo "Test 1. Should print 819454437 1093 six times"
+echo "Test 1. Should print 1009647580 1093 six times"
 
-pnmtile 32 32 testgrid.pbm | pamtopam | \
+pamcut -top=0 -left=0 -width=32 -height=32 maze.pbm | pamtopam | \
   tee ${test_pam} | cksum
 pamtowinicon ${test_pam} | winicontopam | \
   pamdepth 1 | pamchannel -tupletype="BLACKANDWHITE" 0 | cksum
@@ -33,5 +34,6 @@ pamtowinicon -pngthreshold=1   ${test_pam} | winicontopam |
 
 rm ${test_pam}
 
-pnmtile 32 32 testgrid.pbm | ppmtowinicon | winicontopam | \
+pamcut -top=0 -left=0 -width=32 -height=32 maze.pbm | \
+  ppmtowinicon | winicontopam | \
   pamdepth 1 | pamchannel -tupletype="BLACKANDWHITE" 0 | cksum
diff --git a/test/winicon-roundtrip2.ok b/test/winicon-roundtrip2.ok
index bb8c77d8..54ba54e6 100644
--- a/test/winicon-roundtrip2.ok
+++ b/test/winicon-roundtrip2.ok
@@ -1,3 +1,4 @@
+Should print: former checksum values
 16 24 32 48 64 : 1 plane
 Should print 2588356089 8591 or 3783949470 69390 four times
 2588356089 8591
@@ -38,6 +39,7 @@ Should print 2704877198 33359 or 1699833476 276750 four times
 Should print 2567279592 41655 or 4154838752 345902 twice
 2567279592 41655
 2567279592 41655
+Should print: latter checksum values
 16 32 48 256 : 1 plane
 Should print 2588356089 8591 or 3783949470 69390 four times
 3783949470 69390
diff --git a/test/winicon-roundtrip2.test b/test/winicon-roundtrip2.test
index ec074055..de40446e 100755
--- a/test/winicon-roundtrip2.test
+++ b/test/winicon-roundtrip2.test
@@ -1,13 +1,13 @@
-#! /bin/bash
+#! /bin/sh
 # This script tests: pamtowinicon winicontopam
-# Also requires: pamchannel pamdepth pamstack pamtopam pbmmake pngtopam
-# Also requires: pnmtopng ppmpat
+# Also requires: pamchannel pamdepth pamstack pamtopam pbmmake ppmpat
+# Also requires: pngtopam pnmtopng
 
 tmpdir=${tmpdir:-/tmp}
 test_pam=${tmpdir}/testimg.pam
 test1_pam=${tmpdir}/testimg1.pam
 test2_pam=${tmpdir}/testimg2.pam
-#test3_pam=${tmpdir}/testimg3.pam
+
 test4_pam=${tmpdir}/testimg4.pam
 test5_pam=${tmpdir}/testimg5.pam
 black_pam=${tmpdir}/black.pam
@@ -19,6 +19,10 @@ gray_pam=${tmpdir}/gray.pam
 
 for sizes in "16 24 32 48 64" "16 32 48 256"
   do
+  if  echo $sizes | awk '{exit !($NF==64)}' ;
+  then echo "Should print: former checksum values";
+  else echo "Should print: latter checksum values";
+  fi
 
   for size in ${sizes}
     do
@@ -65,11 +69,11 @@ for sizes in "16 24 32 48 64" "16 32 48 256"
   pamstack ${gray_pam} ${gray_pam} | \
   pamchannel -tupletype="GRAYSCALE_ALPHA" 0 1 | tee ${test2_pam} | cksum
   pamtowinicon ${test2_pam} | winicontopam -allimages | \
-    pamchannel -tupletype="GRAYSCALE_ALPHA" 0 1 | cksum
+    pamchannel -tupletype="GRAYSCALE_ALPHA" 0 1 | pamdepth 255 | cksum
   pamtowinicon -pngthreshold=300 ${test2_pam} | winicontopam -allimages | \
     pamchannel -tupletype="GRAYSCALE_ALPHA" 0 1 | cksum
   pamtowinicon -pngthreshold=1   ${test2_pam} | winicontopam -allimages | \
-    pamchannel -tupletype="GRAYSCALE_ALPHA" 0 1 | cksum
+    pamchannel -tupletype="GRAYSCALE_ALPHA" 0 1 | pamdepth 255 | cksum
 
   rm ${test2_pam}
 
diff --git a/test/xbm-roundtrip.ok b/test/xbm-roundtrip.ok
index a676a1f2..82c6b5d8 100644
--- a/test/xbm-roundtrip.ok
+++ b/test/xbm-roundtrip.ok
@@ -1,2 +1,3 @@
-2425386270 41
-2425386270 41
+Test.  Should print 281226646 481 twice
+281226646 481
+281226646 481
diff --git a/test/xbm-roundtrip.test b/test/xbm-roundtrip.test
index e84d6fc3..a8754150 100755
--- a/test/xbm-roundtrip.test
+++ b/test/xbm-roundtrip.test
@@ -1,7 +1,8 @@
-#! /bin/bash
+#! /bin/sh
 # This script tests: pbmtoxbm xbmtopbm
 # Also requires:
 
+echo "Test.  Should print 281226646 481 twice"
 
-pbmtoxbm testgrid.pbm | xbmtopbm | cksum
-pbmtoxbm -x10 testgrid.pbm | xbmtopbm | cksum
+pbmtoxbm maze.pbm | xbmtopbm | cksum
+pbmtoxbm -x10 < maze.pbm | xbmtopbm | cksum
diff --git a/test/xpm-roundtrip.ok b/test/xpm-roundtrip.ok
index 845be5fb..2083dc10 100644
--- a/test/xpm-roundtrip.ok
+++ b/test/xpm-roundtrip.ok
@@ -1 +1,4 @@
-2425386270 41
+Test 1. Should print 1926073387 101484
+1926073387 101484
+Test 2. Should print 281226646 481
+281226646 481
diff --git a/test/xpm-roundtrip.test b/test/xpm-roundtrip.test
index fd0253b1..c016c8c3 100755
--- a/test/xpm-roundtrip.test
+++ b/test/xpm-roundtrip.test
@@ -1,9 +1,11 @@
-#! /bin/bash
+#! /bin/sh
 # This script tests: ppmtoxpm xpmtoppm
 # Also requires: pgmtopbm ppmtopgm
 
+echo "Test 1. Should print 1926073387 101484"
+ppmtoxpm -hexonly testimg.ppm | \
+  xpmtoppm  | cksum
 
-#ppmtoxpm -hexonly testimg.ppm | \
-# xpmtoppm  | cksum
-ppmtoxpm testgrid.pbm | xpmtoppm | \
+echo "Test 2. Should print 281226646 481"
+ppmtoxpm maze.pbm | xpmtoppm | \
   ppmtopgm | pgmtopbm -th -value=0.5 | cksum
diff --git a/test/xv-roundtrip.test b/test/xv-roundtrip.test
index d73933a1..70b298df 100755
--- a/test/xv-roundtrip.test
+++ b/test/xv-roundtrip.test
@@ -1,4 +1,4 @@
-#! /bin/bash
+#! /bin/sh
 # This script tests: pamtoxvmini xvminitoppm
 # Also requires: pamdepth
 
diff --git a/test/xwd-roundtrip.ok b/test/xwd-roundtrip.ok
index 25d3d871..31dcba3e 100644
--- a/test/xwd-roundtrip.ok
+++ b/test/xwd-roundtrip.ok
@@ -1,3 +1,9 @@
+Test 1.  Should produce 1571496937 33838, cksum of testimg.red twice
 1571496937 33838
+1571496937 33838
+Test 2.  Should produce 1926073387 101484
 1926073387 101484
-2425386270 41
+Test 3.  Should produce 281226646 481 three times
+281226646 481
+281226646 481
+281226646 481
diff --git a/test/xwd-roundtrip.test b/test/xwd-roundtrip.test
index cd0d38ad..1583cd68 100755
--- a/test/xwd-roundtrip.test
+++ b/test/xwd-roundtrip.test
@@ -1,16 +1,22 @@
-#! /bin/bash
+#! /bin/sh
 # This script tests: pnmtoxwd xwdtopnm
-# Also requires: pamchannel pamtopnm pamdepth
+# Also requires: pamchannel pamtopnm pamdepth ppmtopgm
 
-
-# Test 1.  Should produce 1571496937 33838, cksum of testimg.red
+echo "Test 1.  Should produce 1571496937 33838, cksum of testimg.red twice"
 pamchannel -infile=testimg.ppm -tupletype="GRAYSCALE" 0 | pamtopnm | \
   pnmtoxwd | xwdtopnm | pamdepth 255 | cksum
 
-# Test 2.  Should produce 1926073387 101484
-pnmtoxwd --quiet  testimg.ppm | \
+pamchannel -infile=testimg.ppm -tupletype="GRAYSCALE" 0 | pamtopnm | \
+  pnmtoxwd -direct | xwdtopnm -quiet | pamdepth 255 | ppmtopgm | cksum
+
+echo "Test 2.  Should produce 1926073387 101484"
+pnmtoxwd --quiet testimg.ppm | \
   xwdtopnm --quiet | pamdepth 255 | cksum
 
-# Test 3.  Should produce 2425386270 41
-pnmtoxwd --quiet  testgrid.pbm | \
-  xwdtopnm | cksum
+echo "Test 3.  Should produce 281226646 481 three times"
+pnmtoxwd --quiet maze.pbm | xwdtopnm | cksum
+
+pnmtoxwd --quiet -pseudodepth 1 maze.pbm | xwdtopnm | cksum
+
+pnmtoxwd --quiet -pseudodepth 16 maze.pbm | xwdtopnm | cksum
+
diff --git a/test/ybm-roundtrip.ok b/test/ybm-roundtrip.ok
new file mode 100644
index 00000000..3873d097
--- /dev/null
+++ b/test/ybm-roundtrip.ok
@@ -0,0 +1,2 @@
+Test.  Should print 281226646 481
+281226646 481
diff --git a/test/ybm-roundtrip.test b/test/ybm-roundtrip.test
new file mode 100755
index 00000000..b53d2ba0
--- /dev/null
+++ b/test/ybm-roundtrip.test
@@ -0,0 +1,7 @@
+#! /bin/sh
+# This script tests: pbmtoybm xbmtopbm
+# Also requires:
+
+echo "Test.  Should print 281226646 481"
+
+pbmtoybm maze.pbm | ybmtopbm | cksum
diff --git a/test/yuv-roundtrip.test b/test/yuv-roundtrip.test
index e339b418..68f459e8 100755
--- a/test/yuv-roundtrip.test
+++ b/test/yuv-roundtrip.test
@@ -1,4 +1,4 @@
-#! /bin/bash
+#! /bin/sh
 # This script tests: ppmtoyuv yuvtoppm
 # Also requires: pamgradient
 
diff --git a/urt/Makefile b/urt/Makefile
index 0aef5290..8c85dab4 100644
--- a/urt/Makefile
+++ b/urt/Makefile
@@ -10,10 +10,10 @@ default: all
 include $(BUILDDIR)/config.mk
 
 LIBOBJECTS = Runput.o cmd_name.o \
-	rle_addhist.o rle_error.o rle_getcom.o rle_getrow.o rle_getskip.o \
+	rle_addhist.o rle_getcom.o rle_getrow.o rle_getskip.o \
 	rle_global.o rle_hdr.o rle_open_f.o rle_putcom.o rle_putrow.o \
-        rle_row_alc.o \
-        scanargs.o vaxshort.o     
+	rle_row_alc.o \
+	vaxshort.o     
 
 MERGE_OBJECTS =
 
diff --git a/urt/README b/urt/README
index dc68889d..2cfbb3e2 100644
--- a/urt/README
+++ b/urt/README
@@ -18,3 +18,8 @@ in its initializer in the original.  But GNU C Library Version 2
 defines stdout as a variable, so that wouldn't compile.  So I changed
 it to NULL and added a line to rle_hdr_init to set that field to
 'stdout' dynamically.  2000.06.02 BJH.
+
+---
+
+Cleanup by Akira F Urushibata 2022.03.06
+Unused functions removed.
\ No newline at end of file
diff --git a/urt/Runput.c b/urt/Runput.c
index 3bc562ac..d4281bb9 100644
--- a/urt/Runput.c
+++ b/urt/Runput.c
@@ -1,14 +1,14 @@
 /*
  * This software is copyrighted as noted below.  It may be freely copied,
- * modified, and redistributed, provided that the copyright notice is 
+ * modified, and redistributed, provided that the copyright notice is
  * preserved on all copies.
- * 
+ *
  * There is no warranty or other guarantee of fitness for this software,
  * it is provided solely "as is".  Bug reports or fixes may be sent
  * to the author, who may or may not act on them as he desires.
  *
  * You may not include this software in a program or other software product
- * without supplying the source, or without informing the end-user that the 
+ * without supplying the source, or without informing the end-user that the
  * source is available for no extra charge.
  *
  * If you modify this software, you should include a notice giving the
@@ -18,339 +18,390 @@
  *  Modified at BRL 16-May-88 by Mike Muuss to avoid Alliant STDC desire
  *  to have all "void" functions so declared.
  */
-/* 
+/*
  * Runput.c - General purpose Run Length Encoding.
- * 
- * Author:	Spencer W. Thomas
- * 		Computer Science Dept.
- * 		University of Utah
- * Date:	Mon Aug  9 1982
+ *
+ * Author:      Spencer W. Thomas
+ *              Computer Science Dept.
+ *              University of Utah
+ * Date:        Mon Aug  9 1982
  * Copyright (c) 1982,1986 Spencer W. Thomas
- * 
+ *
  * $Id: Runput.c,v 3.0.1.1 1992/01/28 18:17:40 spencer Exp $
- * 
- * Modified by:	Todd W. Fuqua
- * 	Date:	Jul 22 1984
+ *
+ * Modified by: Todd W. Fuqua
+ *      Date:   Jul 22 1984
  * convert to new RLE format to make room for larger frame buffers
  */
 
 /* THIS IS WAY OUT OF DATE.  See rle.5.
  * The output file format is:
- * 
- * Word 0:	A "magic" number.  The top byte of the word contains
- *		the letter 'R' or the letter 'W'.  'W' indicates that
- *		only black and white information was saved.  The bottom
- *		byte is one of the following:
- *	' ':	Means a straight "box" save, -S flag was given.
- *	'B':	Image saved with background color, clear screen to
- *		background before restoring image.
- *	'O':	Image saved in overlay mode.
- * 
- * Words 1-6:	The structure
- * {     short   xpos,			Lower left corner
+ *
+ * Word 0:      A "magic" number.  The top byte of the word contains
+ *              the letter 'R' or the letter 'W'.  'W' indicates that
+ *              only black and white information was saved.  The bottom
+ *              byte is one of the following:
+ *      ' ':    Means a straight "box" save, -S flag was given.
+ *      'B':    Image saved with background color, clear screen to
+ *              background before restoring image.
+ *      'O':    Image saved in overlay mode.
+ *
+ * Words 1-6:   The structure
+ * {     short   xpos,                  Lower left corner
  *             ypos,
- *             xsize,			Size of saved box
+ *             xsize,                   Size of saved box
  *             ysize;
- *     char    rgb[3];			Background color
- *     char    map;			flag for map presence
+ *     char    rgb[3];                  Background color
+ *     char    map;                     flag for map presence
  * }
- * 
- * If the map flag is non-zero, then the color map will follow as 
+ *
+ * If the map flag is non-zero, then the color map will follow as
  * 3*256 16 bit words, first the red map, then the green map, and
  * finally the blue map.
- * 
+ *
  * Following the setup information is the Run Length Encoded image.
  * Each instruction consists of a 4-bit opcode, a 12-bit datum and
  * possibly one or more following words (all words are 16 bits).  The
  * instruction opcodes are:
- * 
+ *
  * SkipLines (1):   The bottom 10 bits are an unsigned number to be added to
- *		    current Y position.
- * 
+ *                  current Y position.
+ *
  * SetColor (2):    The datum indicates which color is to be loaded with
- * 		    the data described by the following ByteData and
- * 		    RunData instructions.  0->red, 1->green, 2->blue.  The
- * 		    operation also resets the X position to the initial
- * 		    X (i.e. a carriage return operation is performed).
- * 
+ *                  the data described by the following ByteData and
+ *                  RunData instructions.  0->red, 1->green, 2->blue.  The
+ *                  operation also resets the X position to the initial
+ *                  X (i.e. a carriage return operation is performed).
+ *
  * SkipPixels (3):  The bottom 10 bits are an unsigned number to be
- * 		    added to the current X position.
- * 
+ *                  added to the current X position.
+ *
  * ByteData (5):    The datum is one less than the number of bytes of
- * 		    color data following.  If the number of bytes is
- * 		    odd, a filler byte will be appended to the end of
- * 		    the byte string to make an integral number of 16-bit
- * 		    words.  The bytes are in PDP-11 order.  The X
- * 		    position is incremented to follow the last byte of
- * 		    data.
- * 
- * RunData (6):	    The datum is one less than the run length.  The
- * 		    following word contains (in its lower 8 bits) the
- * 		    color of the run.  The X position is incremented to
- * 		    follow the last byte in the run.
+ *                  color data following.  If the number of bytes is
+ *                  odd, a filler byte will be appended to the end of
+ *                  the byte string to make an integral number of 16-bit
+ *                  words.  The bytes are in PDP-11 order.  The X
+ *                  position is incremented to follow the last byte of
+ *                  data.
+ *
+ * RunData (6):     The datum is one less than the run length.  The
+ *                  following word contains (in its lower 8 bits) the
+ *                  color of the run.  The X position is incremented to
+ *                  follow the last byte in the run.
  */
 
-#include    <string.h>
-#include	<stdio.h>
+#include <assert.h>
+#include <string.h>
+#include <stdio.h>
+
+#include "mallocvar.h"
+#include "pm.h"
 
-#include	"rle_put.h"
-#include	"rle.h"
-#include	"rle_code.h"
-#include    "vaxshort.h"
-#include    "Runput.h"
+#include "rle_put.h"
+#include "rle.h"
+#include "rle_code.h"
+#include "vaxshort.h"
+#include "Runput.h"
 
-#define UPPER 255			/* anything bigger ain't a byte */
+#define UPPER 255                       /* anything bigger ain't a byte */
 
 /*
  * Macros to make writing instructions with correct byte order easier.
  */
 /* Write a two-byte value in little_endian order. */
-#define	put16(a)    (putc((a)&0xff,rle_fd),putc((char)(((a)>>8)&0xff),rle_fd))
+#define put16(a)   (putc((a)&0xff,rle_fd),putc((char)(((a)>>8)&0xff),rle_fd))
 
 /* short instructions */
-#define mk_short_1(oper,a1)		/* one argument short */ \
+#define mk_short_1(oper,a1)             /* one argument short */ \
     putc(oper,rle_fd), putc((char)a1,rle_fd)
 
-#define mk_short_2(oper,a1,a2)		/* two argument short */ \
+#define mk_short_2(oper,a1,a2)          /* two argument short */ \
     putc(oper,rle_fd), putc((char)a1,rle_fd), put16(a2)
 
 /* long instructions */
-#define mk_long_1(oper,a1)		/* one argument long */ \
+#define mk_long_1(oper,a1)              /* one argument long */ \
     putc((char)(LONG|oper),rle_fd), putc('\0', rle_fd), put16(a1)
 
-#define mk_long_2(oper,a1,a2)		/* two argument long */ \
-    putc((char)(LONG|oper),rle_fd), putc('\0', rle_fd), \
-    put16(a1), put16(a2)
+#define mk_long_2(oper,a1,a2)           /* two argument long */ \
+    putc((char)(LONG|oper),rle_fd), putc('\0', rle_fd),        \
+            put16(a1), put16(a2)
 
 /* choose between long and short format instructions */
 /* NOTE: these macros can only be used where a STATEMENT is legal */
 
-#define mk_inst_1(oper,a1)		/* one argument inst */ \
+#define mk_inst_1(oper,a1)              /* one argument inst */ \
     if (a1>UPPER) (mk_long_1(oper,a1)); else (mk_short_1(oper,a1))
 
-#define mk_inst_2(oper,a1,a2)		/* two argument inst */ \
+#define mk_inst_2(oper,a1,a2)           /* two argument inst */ \
     if (a1>UPPER) (mk_long_2(oper,a1,a2)); else (mk_short_2(oper,a1,a2))
 
-/* 
+/*
  * Opcode definitions
  */
-#define	    RSkipLines(n)   	    mk_inst_1(RSkipLinesOp,(n))
+#define     RSkipLines(n)           mk_inst_1(RSkipLinesOp,(n))
 
-#define	    RSetColor(c)	    mk_short_1(RSetColorOp,(c))
-				    /* has side effect of performing */
-				    /* "carriage return" action */
+#define     RSetColor(c)            mk_short_1(RSetColorOp,(c))
+                                    /* has side effect of performing */
+                                    /* "carriage return" action */
 
-#define	    RSkipPixels(n)	    mk_inst_1(RSkipPixelsOp,(n))
+#define     RSkipPixels(n)          mk_inst_1(RSkipPixelsOp,(n))
 
-#define	    RNewLine		    RSkipLines(1)
+#define     RNewLine                RSkipLines(1)
 
-#define	    RByteData(n)	    mk_inst_1(RByteDataOp,n)
-					/* followed by ((n+1)/2)*2 bytes */
-					/* of data.  If n is odd, last */
-					/* byte will be ignored */
-					/* "cursor" is left at pixel */
-					/* following last pixel written */
+#define     RByteData(n)            mk_inst_1(RByteDataOp,n)
+                                        /* followed by ((n+1)/2)*2 bytes */
+                                        /* of data.  If n is odd, last */
+                                        /* byte will be ignored */
+                                        /* "cursor" is left at pixel */
+                                        /* following last pixel written */
 
-#define	    RRunData(n,c)	    mk_inst_2(RRunDataOp,(n),(c))
-					/* next word contains color data */
-					/* "cursor" is left at pixel after */
-					/* end of run */
+#define     RRunData(n,c)           mk_inst_2(RRunDataOp,(n),(c))
+                                        /* next word contains color data */
+                                        /* "cursor" is left at pixel after */
+                                        /* end of run */
+
+#define     REOF                    mk_inst_1(REOFOp,0)
+                                        /* Really opcode only */
 
-#define     REOF		    mk_inst_1(REOFOp,0)
-					/* Really opcode only */
 
-/*****************************************************************
- * TAG( RunSetup )
- * Put out initial setup data for RLE files.
- */
 void
-RunSetup(rle_hdr * the_hdr)
-{
+RunSetup(rle_hdr * const hdrP) {
+/*----------------------------------------------------------------------------
+  Put out initial setup data for RLE files.
+-----------------------------------------------------------------------------*/
+    FILE * const rle_fd = hdrP->rle_file;
+
     struct XtndRsetup setup;
-    register FILE * rle_fd = the_hdr->rle_file;
 
-    put16( RLE_MAGIC );
+    put16(RLE_MAGIC);
 
-    if ( the_hdr->background == 2 )
-	setup.h_flags = H_CLEARFIRST;
-    else if ( the_hdr->background == 0 )
-	setup.h_flags = H_NO_BACKGROUND;
+    if (hdrP->background == 2)
+        setup.h_flags = H_CLEARFIRST;
+    else if (hdrP->background == 0)
+        setup.h_flags = H_NO_BACKGROUND;
     else
-	setup.h_flags = 0;
-    if ( the_hdr->alpha )
-	setup.h_flags |= H_ALPHA;
-    if ( the_hdr->comments != NULL && *the_hdr->comments != NULL )
-	setup.h_flags |= H_COMMENT;
-
-    setup.h_ncolors = the_hdr->ncolors;
-    setup.h_pixelbits = 8;		/* Grinnell dependent */
-    if ( the_hdr->ncmap > 0 && the_hdr->cmap == NULL )
-    {
-	fprintf( stderr,
-       "%s: Color map of size %d*%d specified, but not supplied, writing %s\n",
-		 the_hdr->cmd, the_hdr->ncmap, (1 << the_hdr->cmaplen),
-		 the_hdr->file_name );
-	the_hdr->ncmap = 0;
+        setup.h_flags = 0;
+
+    if (hdrP->alpha)
+        setup.h_flags |= H_ALPHA;
+
+    if (hdrP->comments != NULL && *hdrP->comments != NULL)
+        setup.h_flags |= H_COMMENT;
+
+    if (hdrP->ncolors > 255)
+        pm_error("Too many colors (%u) for RLE format.  Maximum is 255",
+                 hdrP->ncolors);
+
+    setup.h_ncolors = (unsigned char)hdrP->ncolors;
+    setup.h_pixelbits = 8;              /* Grinnell dependent */
+
+    if ((hdrP->cmaplen) > sizeof(UINT_MAX) * 8 - 1) {
+        pm_error("Color map size logarithm (%u) "
+                 "is too large for computation.  Maximum is %lu",
+                 hdrP->cmaplen, sizeof(UINT_MAX) * 8 - 2);
     }
-    setup.h_cmaplen = the_hdr->cmaplen;	/* log2 of color map size */
-    setup.h_ncmap = the_hdr->ncmap;	/* no of color channels */
-    vax_pshort(setup.hc_xpos,the_hdr->xmin);
-    vax_pshort(setup.hc_ypos,the_hdr->ymin);
-    vax_pshort(setup.hc_xlen,the_hdr->xmax - the_hdr->xmin + 1);
-    vax_pshort(setup.hc_ylen,the_hdr->ymax - the_hdr->ymin + 1);
-    fwrite((char *)&setup, SETUPSIZE, 1, rle_fd);
-    if ( the_hdr->background != 0 )
-    {
-	register int i;
-	register rle_pixel *background =
-	    (rle_pixel *)malloc( (unsigned)(the_hdr->ncolors + 1) );
-	register int *bg_color;
-	/* 
-	 * If even number of bg color bytes, put out one more to get to 
-	 * 16 bit boundary.
-	 */
-	bg_color = the_hdr->bg_color;
-	for ( i = 0; i < the_hdr->ncolors; i++ )
-	    background[i] =  *bg_color++;
-	/* Extra byte, if written, should be 0. */
-	background[i] = 0;
-	fwrite((char *)background, (the_hdr->ncolors / 2) * 2 + 1, 1, rle_fd);
-	free( background );
+    /* We need to be able to count 2 bytes for each channel of each entry
+       in the color map:
+    */
+    if (hdrP->ncmap > 0 && 1 << hdrP->cmaplen > UINT_MAX/2/hdrP->ncmap) {
+        pm_error("Color map length %u and number of color channels in the "
+                 "color map %u are too large for computation",
+                 1 << hdrP->cmaplen, hdrP->ncmap);
     }
-    else
-	putc( '\0', rle_fd );
-    if (the_hdr->ncmap > 0)
-    {
-	/* Big-endian machines are harder */
-	register int i, nmap = (1 << the_hdr->cmaplen) *
-			       the_hdr->ncmap;
-	register char *h_cmap = (char *)malloc( nmap * 2 );
-	if ( h_cmap == NULL )
-	{
-	    fprintf( stderr,
-	     "%s: Malloc failed for color map of size %d, writing %s\n",
-		     the_hdr->cmd, nmap, the_hdr->file_name );
-	    exit( 1 );
-	}
-	for ( i = 0; i < nmap; i++ )
-	    vax_pshort( &h_cmap[i*2], the_hdr->cmap[i] );
-
-	fwrite( h_cmap, nmap, 2, rle_fd );
-	free( h_cmap );
+
+    if (hdrP->ncmap > 255)
+        pm_error("Too many color channels in the color map (%u) "
+                 "for the RLE format.  Maximum is 255", hdrP->ncmap);
+    setup.h_ncmap = hdrP->ncmap;     /* no of color channels */
+
+    if (hdrP->ncmap > 0 && hdrP->cmap == NULL) {
+        pm_message("Warning: "
+                   "Color map of size %d*%d specified, but not supplied, "
+                   "writing '%s'",
+                   hdrP->ncmap, (1 << hdrP->cmaplen), hdrP->file_name);
+        hdrP->ncmap = 0;
+    }
+    setup.h_cmaplen = (unsigned char)hdrP->cmaplen;
+
+    vax_pshort(setup.hc_xpos,hdrP->xmin);
+    vax_pshort(setup.hc_ypos,hdrP->ymin);
+    vax_pshort(setup.hc_xlen,hdrP->xmax - hdrP->xmin + 1);
+    vax_pshort(setup.hc_ylen,hdrP->ymax - hdrP->ymin + 1);
+
+    fwrite((char *)&setup, SETUPSIZE, 1, rle_fd);
+
+    if (hdrP->background != 0) {
+        unsigned int i;
+        rle_pixel * background;
+        int * bg_color;
+
+        assert(hdrP->ncolors < UINT_MAX);
+
+        MALLOCARRAY_NOFAIL(background, hdrP->ncolors + 1);
+
+        /* If even number of bg color bytes, put out one more to get to
+           16 bit boundary.
+        */
+
+        for (i = 0, bg_color = hdrP->bg_color; i < hdrP->ncolors; ++i)
+            background[i] =  *bg_color++;
+
+        /* Extra byte; if written, should be 0. */
+        background[i] = 0;
+
+        fwrite(background, (hdrP->ncolors / 2) * 2 + 1, 1, rle_fd);
+
+        free(background);
+    } else
+        putc('\0', rle_fd);
+
+    if (hdrP->ncmap > 0) {
+        /* Big-endian machines are harder */
+        unsigned int const nmap = (1 << hdrP->cmaplen) * hdrP->ncmap;
+
+        unsigned char * h_cmap;
+        unsigned int i;
+
+        MALLOCARRAY(h_cmap, nmap * 2);
+
+        if (!h_cmap) {
+            pm_error("Failed to allocate memory for color map of size %u, "
+                     "writing '%s'",
+                     nmap, hdrP->file_name);
+        }
+        for (i = 0; i < nmap; ++i)
+            vax_pshort(&h_cmap[i*2], hdrP->cmap[i]);
+
+        fwrite(h_cmap, nmap, 2, rle_fd);
+
+        free(h_cmap);
     }
 
     /* Now write out comments if given */
-    if ( setup.h_flags & H_COMMENT )
-    {
-	int comlen;
-	register CONST_DECL char ** com_p;
-
-	/* Get the total length of comments */
-	comlen = 0;
-	for ( com_p = the_hdr->comments; *com_p != NULL; com_p++ )
-	    comlen += 1 + strlen( *com_p );
-
-	put16( comlen );
-	for ( com_p = the_hdr->comments; *com_p != NULL; com_p++ )
-	    fwrite( *com_p, 1, strlen( *com_p ) + 1, rle_fd );
-
-	if ( comlen & 1 )	/* if odd length, round up */
-	    putc( '\0', rle_fd );
+    if (setup.h_flags & H_COMMENT) {
+        unsigned int comlen;
+        const char ** comP;
+
+        /* Get the total length of comments */
+        for (comP = hdrP->comments, comlen = 0; *comP != NULL; ++comP)
+            comlen += 1 + strlen(*comP);
+
+        put16(comlen);
+
+        for (comP = hdrP->comments; *comP != NULL; ++comP)
+            fwrite(*comP, 1, strlen(*comP) + 1, rle_fd);
+
+        if (comlen & 0x1)       /* if odd length, round up */
+            putc('\0', rle_fd);
     }
 }
 
-/*****************************************************************
- * TAG( RunSkipBlankLines )
- * Skip one or more blank lines in the RLE file.
- */
+
+
 void
-RunSkipBlankLines(int nblank, rle_hdr * the_hdr)
-{
-    register FILE * rle_fd = the_hdr->rle_file;
+RunSkipBlankLines(unsigned int const nblank,
+                  rle_hdr *    const hdrP) {
+/*----------------------------------------------------------------------------
+  Skip one or more blank lines in the RLE file.
+-----------------------------------------------------------------------------*/
+    FILE * const rle_fd = hdrP->rle_file;
+
     RSkipLines(nblank);
 }
 
-/*****************************************************************
- * TAG( RunSetColor )
- * Select a color and do carriage return.
- * color: 0 = Red, 1 = Green, 2 = Blue.
- */
+
+
 void
-RunSetColor(int c, rle_hdr * the_hdr)
-{
-    register FILE * rle_fd = the_hdr->rle_file;
+RunSetColor(int       const c,
+            rle_hdr * const hdrP) {
+/*----------------------------------------------------------------------------
+  Select a color and do carriage return.
+  color: 0 = Red, 1 = Green, 2 = Blue.
+-----------------------------------------------------------------------------*/
+    FILE * const rle_fd = hdrP->rle_file;
+
     RSetColor(c);
 }
 
-/*****************************************************************
- * TAG( RunSkipPixels )
- * Skip a run of background.
- */
 
-/* ARGSUSED */
+
 void
-RunSkipPixels(int nskip, int last, int wasrun, rle_hdr * the_hdr)
-{
-    register FILE * rle_fd = the_hdr->rle_file;
-    if (! last && nskip > 0)
-    {
-	RSkipPixels(nskip);
+RunSkipPixels(unsigned int const nskip,
+              int          const last,
+              int          const wasrun,
+              rle_hdr *    const hdrP) {
+/*----------------------------------------------------------------------------
+  Skip a run of background.
+-----------------------------------------------------------------------------*/
+    FILE * const rle_fd = hdrP->rle_file;
+
+    if (!last && nskip > 0) {
+        RSkipPixels(nskip);
     }
 }
 
-/*****************************************************************
- * TAG( RunNewScanLine )
- * Perform a newline action.  Since CR is implied by the Set Color
- * operation, only generate code if the newline flag is true.
- */
+
+
 void
-RunNewScanLine(int flag, rle_hdr * the_hdr)
-{
-    register FILE * rle_fd = the_hdr->rle_file;
-    if (flag)
-    {
-	RNewLine;
+RunNewScanLine(int       const flag,
+               rle_hdr * const hdrP) {
+/*----------------------------------------------------------------------------
+  Perform a newline action.  Since CR is implied by the Set Color operation,
+  only generate code if the newline flag is true.
+-----------------------------------------------------------------------------*/
+    FILE * const rle_fd = hdrP->rle_file;
+
+    if (flag) {
+        RNewLine;
     }
 }
 
-/*****************************************************************
- * TAG( Runputdata )
- * Put one or more pixels of byte data into the output file.
- */
+
+
 void
-Runputdata(rle_pixel * buf, int n, rle_hdr * the_hdr)
-{
-    register FILE * rle_fd = the_hdr->rle_file;
-    if (n == 0)
-	return;
-
-    RByteData(n-1);
-    fwrite((char *)buf, n, 1, rle_fd);
-    if ( n & 1 )
-	putc( 0, rle_fd );
+Runputdata(rle_pixel *  const buf,
+           unsigned int const n,
+           rle_hdr *    const hdrP) {
+/*----------------------------------------------------------------------------
+  Put one or more pixels of byte data into the output file.
+-----------------------------------------------------------------------------*/
+    FILE * const rle_fd = hdrP->rle_file;
+
+    if (n != 0) {
+        RByteData(n - 1);
+
+        fwrite(buf, n, 1, rle_fd);
+
+        if (n & 0x1)
+            putc(0, rle_fd);
+    }
 }
 
-/*****************************************************************
- * TAG( Runputrun )
- * Output a single color run.
- */
 
-/* ARGSUSED */
+
 void
-Runputrun(int color, int n, int last, rle_hdr * the_hdr)
-{
-    register FILE * rle_fd = the_hdr->rle_file;
-    RRunData(n-1,color);
+Runputrun(int          const color,
+          unsigned int const n,
+          int          const last,
+          rle_hdr *    const hdrP) {
+/*----------------------------------------------------------------------------
+  Output a single color run.
+-----------------------------------------------------------------------------*/
+    FILE * const rle_fd = hdrP->rle_file;
+
+    RRunData(n - 1, color);
 }
 
 
-/*****************************************************************
- * TAG( RunputEof )
- * Output an EOF opcode
- */
+
 void
-RunputEof(rle_hdr * the_hdr)
-{
-    register FILE * rle_fd = the_hdr->rle_file;
+RunputEof(rle_hdr * const hdrP) {
+/*----------------------------------------------------------------------------
+  Output an EOF opcode
+-----------------------------------------------------------------------------*/
+    FILE * const rle_fd = hdrP->rle_file;
+
     REOF;
 }
+
+
diff --git a/urt/Runput.h b/urt/Runput.h
index 776e3ec5..57a45564 100644
--- a/urt/Runput.h
+++ b/urt/Runput.h
@@ -1,23 +1,39 @@
-void 
-RunSetup(rle_hdr * the_hdr);
+#ifndef RUNPUT_H_INCLUDED
+#define RUNPUT_H_INCLUDED
 
 void
-RunSkipBlankLines(int nblank, rle_hdr * the_hdr);
+RunSetup(rle_hdr * const hdrP);
 
 void
-RunSetColor(int c, rle_hdr * the_hdr);
+RunSkipBlankLines(unsigned int const nblank,
+                  rle_hdr *    const hdrP);
 
 void
-RunSkipPixels(int nskip, int last, int wasrun, rle_hdr * the_hdr);
+RunSetColor(int       const c,
+            rle_hdr * const hdrP);
 
 void
-RunNewScanLine(int flag, rle_hdr * the_hdr);
+RunSkipPixels(unsigned int const nskip,
+              int          const last,
+              int          const wasrun,
+              rle_hdr *    const hdrP);
 
 void
-Runputdata(rle_pixel * buf, int n, rle_hdr * the_hdr);
+RunNewScanLine(int       const flag,
+               rle_hdr * const hdrP);
 
 void
-Runputrun(int color, int n, int last, rle_hdr * the_hdr);
+Runputdata(rle_pixel *  const buf,
+           unsigned int const n,
+           rle_hdr *    const hdrP);
 
 void
-RunputEof(rle_hdr * the_hdr);
+Runputrun(int          const color,
+          unsigned int const n,
+          int          const last,
+          rle_hdr *    const hdrP);
+
+void
+RunputEof(rle_hdr * const hdrP);
+
+#endif
diff --git a/urt/cmd_name.c b/urt/cmd_name.c
index 31fe5f42..6d48a63b 100644
--- a/urt/cmd_name.c
+++ b/urt/cmd_name.c
@@ -1,27 +1,27 @@
 /*
  * This software is copyrighted as noted below.  It may be freely copied,
- * modified, and redistributed, provided that the copyright notice is 
+ * modified, and redistributed, provided that the copyright notice is
  * preserved on all copies.
- * 
+ *
  * There is no warranty or other guarantee of fitness for this software,
  * it is provided solely "as is".  Bug reports or fixes may be sent
  * to the author, who may or may not act on them as he desires.
  *
  * You may not include this software in a program or other software product
- * without supplying the source, or without informing the end-user that the 
+ * without supplying the source, or without informing the end-user that the
  * source is available for no extra charge.
  *
  * If you modify this software, you should include a notice giving the
  * name of the person performing the modification, the date of modification,
  * and the reason for such modification.
  */
-/* 
+/*
  * cmd_name.c - Extract command name from argv[0].
- * 
- * Author:	Spencer W. Thomas
- * 		EECS Dept.
- * 		University of Michigan
- * Date:	Wed Jun 27 1990
+ *
+ * Author:      Spencer W. Thomas
+ *              EECS Dept.
+ *              University of Michigan
+ * Date:        Wed Jun 27 1990
  * Copyright (c) 1990, University of Michigan
  */
 
@@ -35,23 +35,26 @@ char *
 cmd_name( argv )
 char **argv;
 {
-    register char *cp, *a;
+    char *cp, *a;
 
     /* Be paranoid. */
     if ( !argv || !(a = *argv) )
-	return no_name;
+        return no_name;
 
     /* Find end of file name. */
     for ( cp = a; *cp; cp++ )
-	;
+        ;
 
     /* Find last / or beginning of command name. */
     for ( cp--; *cp != '/' && cp > a; cp-- )
-	;
-    
+        ;
+
     /* If it's a /, skip it. */
     if ( *cp == '/' )
-	cp++;
+        cp++;
 
     return cp;
 }
+
+
+
diff --git a/urt/rle.h b/urt/rle.h
index 00717748..ee9eb379 100644
--- a/urt/rle.h
+++ b/urt/rle.h
@@ -50,19 +50,19 @@ typedef unsigned short rle_map;
 /*
  * Defines for traditional channel numbers.
  */
-#define RLE_RED     0   /* Red channel traditionally here. */
-#define RLE_GREEN   1   /* Green channel traditionally here. */
-#define RLE_BLUE    2   /* Blue channel traditionally here. */
-#define RLE_ALPHA      -1   /* Alpha channel here. */
+#define RLE_RED    0   /* Red channel traditionally here. */
+#define RLE_GREEN  1   /* Green channel traditionally here. */
+#define RLE_BLUE   2   /* Blue channel traditionally here. */
+#define RLE_ALPHA -1   /* Alpha channel here. */
 
 /*
  * Return values from rle_get_setup.
  */
-#define RLE_SUCCESS  0
-#define RLE_NOT_RLE -1
-#define RLE_NO_SPACE    -2
-#define RLE_EMPTY   -3
-#define RLE_EOF     -4
+#define RLE_SUCCESS   0
+#define RLE_NOT_RLE  -1
+#define RLE_NO_SPACE -2
+#define RLE_EMPTY    -3
+#define RLE_EOF      -4
 
 /*
  * "Magic" value for is_init field.  Pi * 2^29.
@@ -80,7 +80,7 @@ typedef
 #endif
     struct rle_hdr {
         enum rle_dispatch dispatch;  /* Type of file to create. */
-        int       ncolors;    /* Number of color channels. */
+        unsigned int ncolors;    /* Number of color channels. */
         int *     bg_color;   /* Pointer to bg color vector. */
         int       alpha;      /* If !0, save alpha channel. */
         int       background; /* 0->just save all pixels, */
@@ -103,7 +103,7 @@ typedef
          *      bits[c/8] & (1 << (c%8))
          */
 #define RLE_SET_BIT(glob,bit) \
-        ((glob).bits[((bit)&0xff)/8] |= (1<<((bit)&0x7)))
+            ((glob).bits[((bit)&0xff)/8] |= (1<<((bit)&0x7)))
 #define RLE_CLR_BIT(glob,bit) \
             ((glob).bits[((bit)&0xff)/8] &= ~(1<<((bit)&0x7)))
 #define RLE_BIT(glob,bit) \
@@ -167,13 +167,6 @@ extern int rle_get_error( int code,
 
 /* From rle_getrow.c */
 
-/*****************************************************************
- * TAG( rle_debug )
- *
- * Turn RLE debugging on or off.
- */
-extern void rle_debug( int on_off );
-
 int
 rle_get_setup(rle_hdr * const the_hdr);
 
@@ -239,16 +232,6 @@ extern void rle_hdr_clear( rle_hdr *the_hdr );
 
 /* From rle_putrow.c. */
 
-/*****************************************************************
- * TAG( rgb_to_bw )
- *
- * Converts RGB data to gray data via the NTSC Y transform.
- */
-extern void rgb_to_bw( rle_pixel *red_row,
-                       rle_pixel *green_row,
-                       rle_pixel *blue_row,
-                       rle_pixel *bw_row,
-                       int rowlen );
 
 /*****************************************************************
  * TAG( rle_puteof )
@@ -285,13 +268,6 @@ extern void rle_put_setup( rle_hdr * the_hdr );
  */
 extern void rle_skiprow( rle_hdr *the_hdr, int nrow );
 
-/* From rle_cp.c */
-/*****************************************************************
- * TAG( rle_cp )
- * Copy image data from input to output with minimal interpretation.
- */
-extern void rle_cp( rle_hdr *in_hdr, rle_hdr *out_hdr );
-
 /* From rle_row_alc.c. */
 /*****************************************************************
  * TAG( rle_row_alloc )
@@ -308,14 +284,6 @@ extern int rle_row_alloc( rle_hdr * the_hdr,
      */
 extern void rle_row_free( rle_hdr *the_hdr, rle_pixel **scanp );
 
-/* From buildmap.c. */
-/*
- * buildmap - build a more usable colormap from data in the_hdr struct.
-     */
-extern rle_pixel **buildmap( rle_hdr *the_hdr,
-                             int minmap,
-                             double orig_gamma,
-                             double new_gamma );
 
 /* From rle_getcom.c. */
 /*****************************************************************
@@ -329,55 +297,11 @@ rle_getcom(const char * const name,
 
 /* From rle_putcom.c. */
 
-/* Delete a specific comment from the image comments. */
-const char *
-rle_delcom(const char * const name,
-           rle_hdr *    const the_hdr);
-
 /* Put (or replace) a comment into the image comments. */
 const char *
 rle_putcom(const char * const value,
            rle_hdr *    const the_hdr);
 
-/* From dither.c. */
-/*****************************************************************
- * TAG( bwdithermap )
- * Create a color map for ordered dithering in grays.
- */
-extern void bwdithermap( int levels, double gamma, int bwmap[],
-                         int divN[256], int modN[256], int magic[16][16] );
-/*****************************************************************
- * TAG( ditherbw )
- * Dither a gray-scale value.
- */
-extern int ditherbw( int x, int y, int val,
-                     int divN[256], int modN[256], int magic[16][16] );
-/*****************************************************************
- * TAG( dithergb )
- * Dither a color value.
- */
-extern int dithergb( int x, int y, int r, int g, int b,
-                     int divN[256], int modN[256], int magic[16][16] );
-/*****************************************************************
- * TAG( dithermap )
- * Create a color map for ordered dithering in color.
- */
-extern void dithermap( int levels, double gamma, int rgbmap[][3],
-                       int divN[256], int modN[256], int magic[16][16] );
-/*****************************************************************
- * TAG( make_square )
- * Make a 16x16 magic square for ordered dithering.
- */
-extern void make_square( double N, int divN[256], int modN[256],
-                         int magic[16][16] );
-
-/* From float_to_exp.c. */
-/*****************************************************************
- * TAG( float_to_exp )
- * Convert a list of floating point numbers to "exp" format.
- */
-extern void float_to_exp( int count, float * floats, rle_pixel * pixels );
-
 /* From rle_open_f.c. */
 /*****************************************************************
  * TAG( rle_open_f )
@@ -398,32 +322,14 @@ rle_open_f_noexit(const char * const prog_name,
                   const char * const file_name,
                   const char * const mode);
 
-/*****************************************************************
- * TAG( rle_close_f )
- *
- * Close a file opened by rle_open_f.  If the file is stdin or stdout,
- * it will not be closed.
- */
-extern void
-rle_close_f( FILE *fd );
-
-/* From colorquant.c. */
-/*****************************************************************
- * TAG( colorquant )
- * Compute a colormap for quantizing an image to a limited set of colors.
- */
-extern int colorquant( rle_pixel *red, rle_pixel *green, rle_pixel *blue,
-                       unsigned long pixels, rle_pixel *colormap[3],
-                       int colors, int bits,
-                       rle_pixel *rgbmap, int fast, int otherimages );
 
 /* From rle_addhist.c. */
 
 /* Append history information to the HISTORY comment. */
 void
-rle_addhist(char *          argv[],
-            rle_hdr * const in_hdr,
-            rle_hdr * const out_hdr);
+rle_addhist(const char ** const argv,
+            rle_hdr *     const in_hdr,
+            rle_hdr *     const out_hdr);
 
 /* From cmd_name.c. */
 /*****************************************************************
@@ -432,38 +338,5 @@ rle_addhist(char *          argv[],
  */
 extern char *cmd_name( char **argv );
 
-/* From scanargs.c. */
-/*****************************************************************
- * TAG( scanargs )
- * Scan command argument list and parse arguments.
- */
-extern int scanargs( int argc,
-                     char **argv,
-                     const char *format,
-                     ... );
-
-/* From hilbert.c */
-/*****************************************************************
- * TAG( hilbert_i2c )
- * Convert an index into a Hilbert curve to a set of coordinates.
- */
-extern void hilbert_c2i( int n, int m, int a[], long int *r );
-
-/*****************************************************************
- * TAG( hilbert_c2i )
- * Convert coordinates of a point on a Hilbert curve to its index.
- */
-extern void hilbert_i2c( int n, int m, long int r, int a[] );
-
-/* From inv_cmap.c */
-/*****************************************************************
- * TAG( inv_cmap )
- * Compute an inverse colormap efficiently.
- */
-extern void inv_cmap( int colors,
-                      unsigned char *colormap[3],
-                      int bits,
-                      unsigned long *dist_buf,
-                      unsigned char *rgbmap );
 
 #endif /* RLE_H */
diff --git a/urt/rle_addhist.c b/urt/rle_addhist.c
index b1651754..f319a40e 100644
--- a/urt/rle_addhist.c
+++ b/urt/rle_addhist.c
@@ -1,25 +1,25 @@
 /*
  * This software is copyrighted as noted below.  It may be freely copied,
- * modified, and redistributed, provided that the copyright notice is 
+ * modified, and redistributed, provided that the copyright notice is
  * preserved on all copies.
- * 
+ *
  * There is no warranty or other guarantee of fitness for this software,
  * it is provided solely "as is".  Bug reports or fixes may be sent
  * to the author, who may or may not act on them as he desires.
  *
  * You may not include this software in a program or other software product
- * without supplying the source, or without informing the end-user that the 
+ * without supplying the source, or without informing the end-user that the
  * source is available for no extra charge.
  *
  * If you modify this software, you should include a notice giving the
  * name of the person performing the modification, the date of modification,
  * and the reason for such modification.
  */
-/* 
+/*
  * rle_addhist.c - Add to the HISTORY comment in header
- * 
+ *
  * Author:  Andrew Marriott.
- *      School of Computer Science 
+ *      School of Computer Science
  *      Curtin University of Technology
  * Date:    Mon Sept 10 1988
  * Copyright (c) 1988, Curtin University of Technology
@@ -30,80 +30,119 @@
 #include <time.h>
 
 #include "netpbm/mallocvar.h"
+
 #include "rle.h"
 
 
-/*****************************************************************
- * TAG( rle_addhist )
- * 
- * Put a history comment into the header struct.
- * Inputs:
- *  argv:       Command line history to add to comments.
- *  in_hdr:     Incoming header struct to use.
- * Outputs:
- *  out_hdr:    Outgoing header struct to add to.
- * Assumptions:
- *  If no incoming struct then value is NULL.
- * Algorithm:
- *  Calculate length of all comment strings, malloc and then set via
- *  rle_putcom.
- */
 
-void
-rle_addhist(char *          argv[],
-            rle_hdr * const in_hdr,
-            rle_hdr * const out_hdr) {
-
-    const char * const histoire = "HISTORY";
-    const char * const padding = "\t";
-
-    int length;
-    int i;
-    time_t  temp;
-    /* padding must give number of characters in histoire   */
-    /*     plus one for "="                 */
-    char * timedate;
-    const char * old;
-    static char * newc;
-
-    if (getenv("NO_ADD_RLE_HISTORY"))
-        return;
-    
-    length = 0;
-    for (i = 0; argv[i]; ++i)
-        length += strlen(argv[i]) +1;   /* length of each arg plus space. */
-
-    time(&temp);
-    timedate = ctime(&temp);
-    length += strlen(timedate);        /* length of date and time in ASCII. */
+static unsigned int
+newCommentLen(const char *  const histoire,
+              const char *  const old,
+              const char ** const argv,
+              const char *  const timedate,
+              const char *  const padding) {
+
+    unsigned int length;
+    unsigned int i;
+
+    length = 0;  /* initial value */
 
+    /* Add length of each arg plus space. */
+
+    for (i = 0; argv[i]; ++i) {
+        size_t const thisArgLen = strlen(argv[i]);
+        if (thisArgLen < UINT_MAX - length - 100) {
+            length += thisArgLen;
+            length += 1;  /* For the space */
+        }
+    }
+
+    /* Add length of date and time in ASCII. */
+    length += strlen(timedate);
+
+    /* Add length of padding, "on ", and length of history name plus "="*/
     length += strlen(padding) + 3 + strlen(histoire) + 1;
-        /* length of padding, "on "  and length of history name plus "="*/
-    if (in_hdr) /* if we are interested in the old comments... */
-        old = rle_getcom(histoire, in_hdr);     /* get old comment. */
-    else
-        old = NULL;
-    
+
     if (old && *old)
         length += strlen(old);       /* add length if there. */
 
-    ++length;                               /*Cater for the null. */
+    ++length;     /* Add size of terminating NUL. */
 
-    MALLOCARRAY(newc, length);
+    return length;
+}
 
-    if (newc == NULL)
-        return;
 
-    strcpy(newc,histoire);(void)strcat(newc,"=");
-    if (old && *old)
-        strcat(newc, old); /* add old string if there. */
-    for (i=0;argv[i];i++) {
-        strcat(newc, argv[i]);
-        strcat(newc, " ");
+
+void
+rle_addhist(const char ** const argv,
+            rle_hdr *     const inHdrP,
+            rle_hdr *     const outHdrP) {
+/*----------------------------------------------------------------------------
+  Put a history comment into the header struct.
+  Inputs:
+   argv:        Command line history to add to comments.
+   *inHdrP:     Incoming header struct to use.
+  Outputs:
+   *outHdrP:    Outgoing header struct to add to.
+  Assumptions:
+   If no incoming struct then value is NULL.
+  Algorithm:
+   Calculate length of all comment strings, malloc and then set via
+   rle_putcom.
+  If we run out of memory, don't put the history comment in.
+-----------------------------------------------------------------------------*/
+    if (!getenv("NO_ADD_RLE_HISTORY")) {
+        const char * const histoire = "HISTORY";
+        const char * const padding = "\t";
+
+        unsigned int length;
+            /* length of combined comment - the history comment we are adding
+               and any history comment that is already there (to which we
+               append)
+            */
+        time_t  nowTime;
+        /* padding must give number of characters in histoire   */
+        /*     plus one for "="                 */
+        const char * timedate;
+        const char * old;
+        char * newc;
+
+        if (inHdrP) /* if we are interested in the old comments... */
+            old = rle_getcom(histoire, inHdrP);     /* get old comment. */
+        else
+            old = NULL;
+
+        time(&nowTime);
+        timedate = ctime(&nowTime);
+
+        length = newCommentLen(histoire, old, argv, timedate, padding);
+
+        MALLOCARRAY(newc, length);
+
+        if (newc) {
+            unsigned int i;
+
+            strcpy(newc, histoire);
+            strcat(newc, "=");
+
+            if (old)
+                strcat(newc, old); /* add old string if there. */
+
+            for (i = 0; argv[i]; ++i) {
+                strcat(newc, argv[i]);
+                strcat(newc, " ");
+            }
+            strcat(newc, "on ");
+            strcat(newc, timedate);         /* \n supplied by 'ctime'. */
+            strcat(newc, padding);          /* to line up multiple histories.*/
+
+            rle_putcom(newc, outHdrP);
+                /* Creates reference to 'newc', may destroy reference to
+                   previous comment memory, which will thereby leak.
+                */
+        }
     }
-    strcat(newc,"on ");
-    strcat(newc,timedate);         /* \n supplied by time. */
-    strcat(newc,padding);          /* to line up multiple histories.*/
-    
-    rle_putcom(newc, out_hdr);
 }
+
+
+
diff --git a/urt/rle_code.h b/urt/rle_code.h
index 955e7d42..525066d4 100644
--- a/urt/rle_code.h
+++ b/urt/rle_code.h
@@ -1,70 +1,70 @@
 /*
  * This software is copyrighted as noted below.  It may be freely copied,
- * modified, and redistributed, provided that the copyright notice is 
+ * modified, and redistributed, provided that the copyright notice is
  * preserved on all copies.
- * 
+ *
  * There is no warranty or other guarantee of fitness for this software,
  * it is provided solely "as is".  Bug reports or fixes may be sent
  * to the author, who may or may not act on them as he desires.
  *
  * You may not include this software in a program or other software product
- * without supplying the source, or without informing the end-user that the 
+ * without supplying the source, or without informing the end-user that the
  * source is available for no extra charge.
  *
  * If you modify this software, you should include a notice giving the
  * name of the person performing the modification, the date of modification,
  * and the reason for such modification.
  */
-/* 
+/*
  * rle_code.h - Definitions for Run Length Encoding.
- * 
- * Author:	Spencer W. Thomas
- * 		Computer Science Dept.
- * 		University of Utah
- * Date:	Mon Aug  9 1982
+ *
+ * Author:      Spencer W. Thomas
+ *              Computer Science Dept.
+ *              University of Utah
+ * Date:        Mon Aug  9 1982
  * Copyright (c) 1982 Spencer W. Thomas
- * 
+ *
  * $Header: /usr/users/spencer/src/urt/include/RCS/rle_code.h,v 3.0 90/08/03 15:19:48 spencer Exp $
  */
 
 #ifndef RLE_MAGIC
 
-/* 
+/*
  * Opcode definitions
  */
 
 #define     LONG                0x40
-#define	    RSkipLinesOp	1
-#define	    RSetColorOp		2
-#define	    RSkipPixelsOp	3
-#define	    RByteDataOp		5
-#define	    RRunDataOp		6
-#define	    REOFOp		7
+#define     RSkipLinesOp        1
+#define     RSetColorOp         2
+#define     RSkipPixelsOp       3
+#define     RByteDataOp         5
+#define     RRunDataOp          6
+#define     REOFOp              7
+
+#define     H_CLEARFIRST        0x1   /* clear framebuffer flag */
+#define     H_NO_BACKGROUND     0x2   /* if set, no bg color supplied */
+#define     H_ALPHA             0x4   /* if set, alpha channel (-1) present */
+#define     H_COMMENT           0x8   /* if set, comments present */
 
-#define     H_CLEARFIRST        0x1	/* clear framebuffer flag */
-#define	    H_NO_BACKGROUND	0x2	/* if set, no bg color supplied */
-#define	    H_ALPHA		0x4   /* if set, alpha channel (-1) present */
-#define	    H_COMMENT		0x8	/* if set, comments present */
+struct XtndRsetup {
+    /* This maps the layout of the header text in the file */
 
-struct XtndRsetup
-{
-    char    hc_xpos[2],
-            hc_ypos[2],
-            hc_xlen[2],
-            hc_ylen[2];
-    char    h_flags,
-            h_ncolors,
-	    h_pixelbits,
-	    h_ncmap,
-	    h_cmaplen;
+    unsigned char hc_xpos[2];
+    unsigned char hc_ypos[2];
+    unsigned char hc_xlen[2];
+    unsigned char hc_ylen[2];
+    unsigned char h_flags;
+    unsigned char h_ncolors;
+    unsigned char h_pixelbits;
+    unsigned char h_ncmap;
+    unsigned char h_cmaplen;   /* log2 of color map size */
 };
-#define	    SETUPSIZE	((4*2)+5)
+#define     SETUPSIZE   ((4*2)+5)
 
 /* "Old" RLE format magic numbers */
-#define	    RMAGIC	('R' << 8)	/* top half of magic number */
-#define	    WMAGIC	('W' << 8)	/* black&white rle image */
+#define     RMAGIC      ('R' << 8)      /* top half of magic number */
+#define     WMAGIC      ('W' << 8)      /* black&white rle image */
 
-#define	    RLE_MAGIC	((short)0xcc52)	/* RLE file magic number */
+#define     RLE_MAGIC   ((short)0xcc52) /* RLE file magic number */
 
 #endif /* RLE_MAGIC */
-
diff --git a/urt/rle_config.h b/urt/rle_config.h
index 57126a18..5923c00d 100644
--- a/urt/rle_config.h
+++ b/urt/rle_config.h
@@ -49,7 +49,7 @@
 
 /* Typedef for void * so we can use it consistently. */
 #ifdef VOID_STAR
-typedef	void *void_star;
+typedef void *void_star;
 #else
 typedef char *void_star;
 #endif
@@ -59,7 +59,7 @@ typedef char *void_star;
  * before including this file.
  */
 #ifndef NO_DECLARE_MALLOC
-#   include <sys/types.h>	/* For size_t. */
+#   include <sys/types.h>       /* For size_t. */
     extern void_star malloc( size_t );
     extern void_star calloc( size_t, size_t );
     extern void_star realloc( void_star, size_t );
@@ -75,12 +75,12 @@ extern char *getenv( CONST_DECL char *name );
      * TAG( bstring bzero )
      * 'Byte string' functions.
      */
-#   define bzero( _str, _n )		memset( _str, '\0', _n )
-#   define bcopy( _from, _to, _count )	memcpy( _to, _from, _count )
+#   define bzero( _str, _n )            memset( _str, '\0', _n )
+#   define bcopy( _from, _to, _count )  memcpy( _to, _from, _count )
 #endif
 
 #ifdef NEED_SETLINEBUF
-#   define setlinebuf( _s )	setvbuf( (_s), NULL, _IOLBF, 0 )
+#   define setlinebuf( _s )     setvbuf( (_s), NULL, _IOLBF, 0 )
 #endif
 
 #endif
diff --git a/urt/rle_error.c b/urt/rle_error.c
deleted file mode 100644
index 801eee17..00000000
--- a/urt/rle_error.c
+++ /dev/null
@@ -1,89 +0,0 @@
-/*
- * This software is copyrighted as noted below.  It may be freely copied,
- * modified, and redistributed, provided that the copyright notice is
- * preserved on all copies.
- *
- * There is no warranty or other guarantee of fitness for this software,
- * it is provided solely "as is".  Bug reports or fixes may be sent
- * to the author, who may or may not act on them as he desires.
- *
- * You may not include this software in a program or other software product
- * without supplying the source, or without informing the end-user that the
- * source is available for no extra charge.
- *
- * If you modify this software, you should include a notice giving the
- * name of the person performing the modification, the date of modification,
- * and the reason for such modification.
- */
-/*
- * rle_error.c - Error message stuff for URT.
- *
- * Author:	Spencer W. Thomas
- * 		EECS Dept.
- * 		University of Michigan
- * Date:	Mon Mar  2 1992
- * Copyright (c) 1992, University of Michigan
- */
-
-#include <string.h>
-
-#include "rle_config.h"
-#include "rle.h"
-
-/*****************************************************************
- * TAG( rle_get_error )
- *
- * Print an error message for the return code from rle_get_setup
- * Inputs:
- * 	code:		The return code from rle_get_setup.
- *	pgmname:	Name of this program (argv[0]).
- *	fname:		Name of the input file.
- * Outputs:
- * 	Prints an error message on standard output.
- *	Returns code.
- */
-int
-rle_get_error( code, pgmname, fname )
-    int code;
-    CONST_DECL char *pgmname;
-    CONST_DECL char *fname;
-{
-    if (! fname || strcmp( fname, "-" ) == 0 )
-        fname = "Standard Input";
-
-    switch( code )
-    {
-    case RLE_SUCCESS:		/* success */
-        break;
-
-    case RLE_NOT_RLE:		/* Not an RLE file */
-        fprintf( stderr, "%s: %s is not an RLE file\n",
-                 pgmname, fname );
-        break;
-
-    case RLE_NO_SPACE:			/* malloc failed */
-        fprintf( stderr,
-                 "%s: Malloc failed reading header of file %s\n",
-                 pgmname, fname );
-        break;
-
-    case RLE_EMPTY:
-        fprintf( stderr, "%s: %s is an empty file\n",
-                 pgmname, fname );
-        break;
-
-    case RLE_EOF:
-        fprintf( stderr,
-                 "%s: RLE header of %s is incomplete (premature EOF)\n",
-                 pgmname, fname );
-        break;
-
-    default:
-        fprintf( stderr, "%s: Error encountered reading header of %s\n",
-                 pgmname, fname );
-        break;
-    }
-    return code;
-}
-
-
diff --git a/urt/rle_getcom.c b/urt/rle_getcom.c
index 4226eaaf..a85daa97 100644
--- a/urt/rle_getcom.c
+++ b/urt/rle_getcom.c
@@ -1,27 +1,27 @@
 /*
  * This software is copyrighted as noted below.  It may be freely copied,
- * modified, and redistributed, provided that the copyright notice is 
+ * modified, and redistributed, provided that the copyright notice is
  * preserved on all copies.
- * 
+ *
  * There is no warranty or other guarantee of fitness for this software,
  * it is provided solely "as is".  Bug reports or fixes may be sent
  * to the author, who may or may not act on them as he desires.
  *
  * You may not include this software in a program or other software product
- * without supplying the source, or without informing the end-user that the 
+ * without supplying the source, or without informing the end-user that the
  * source is available for no extra charge.
  *
  * If you modify this software, you should include a notice giving the
  * name of the person performing the modification, the date of modification,
  * and the reason for such modification.
  */
-/* 
+/*
  * rle_getcom.c - Get specific comments from the_hdr structure.
- * 
- * Author:	Spencer W. Thomas
- * 		Computer Science Dept.
- * 		University of Utah
- * Date:	Sun Jan 25 1987
+ *
+ * Author:      Spencer W. Thomas
+ *              Computer Science Dept.
+ *              University of Utah
+ * Date:        Sun Jan 25 1987
  * Copyright (c) 1987, University of Utah
  */
 
@@ -31,21 +31,21 @@
 
 /*****************************************************************
  * TAG( match )
- * 
+ *
  * Match a name against a test string for "name=value" or "name".
  * If it matches name=value, return pointer to value part, if just
  * name, return pointer to NUL at end of string.  If no match, return NULL.
  *
  * Inputs:
- * 	n:	Name to match.  May also be "name=value" to make it easier
- *		to replace comments.
- *	v:	Test string.
+ *      n:      Name to match.  May also be "name=value" to make it easier
+ *              to replace comments.
+ *      v:      Test string.
  * Outputs:
- * 	Returns pointer as above.
+ *      Returns pointer as above.
  * Assumptions:
- *	[None]
+ *      [None]
  * Algorithm:
- *	[None]
+ *      [None]
  */
 static const char *
 match(const char * const nArg,
@@ -69,17 +69,17 @@ match(const char * const nArg,
 
 /*****************************************************************
  * TAG( rle_getcom )
- * 
+ *
  * Return a pointer to the value part of a name=value pair in the comments.
  * Inputs:
- * 	name:		Name part of the comment to search for.
- *	the_hdr:	rle_dflt_hdr structure.
+ *      name:           Name part of the comment to search for.
+ *      the_hdr:        rle_dflt_hdr structure.
  * Outputs:
- * 	Returns pointer to value part of comment or NULL if no match.
+ *      Returns pointer to value part of comment or NULL if no match.
  * Assumptions:
- *	[None]
+ *      [None]
  * Algorithm:
- *	[None]
+ *      [None]
  */
 const char *
 rle_getcom(const char * const name,
@@ -98,3 +98,5 @@ rle_getcom(const char * const name,
     return NULL;
 }
 
+
+
diff --git a/urt/rle_getrow.c b/urt/rle_getrow.c
index ae220f5b..6a25c987 100644
--- a/urt/rle_getrow.c
+++ b/urt/rle_getrow.c
@@ -1,14 +1,14 @@
 /*
  * This software is copyrighted as noted below.  It may be freely copied,
- * modified, and redistributed, provided that the copyright notice is 
+ * modified, and redistributed, provided that the copyright notice is
  * preserved on all copies.
- * 
+ *
  * There is no warranty or other guarantee of fitness for this software,
  * it is provided solely "as is".  Bug reports or fixes may be sent
  * to the author, who may or may not act on them as he desires.
  *
  * You may not include this software in a program or other software product
- * without supplying the source, or without informing the end-user that the 
+ * without supplying the source, or without informing the end-user that the
  * source is available for no extra charge.
  *
  * If you modify this software, you should include a notice giving the
@@ -18,15 +18,15 @@
  *  Modified at BRL 16-May-88 by Mike Muuss to avoid Alliant STDC desire
  *  to have all "void" functions so declared.
  */
-/* 
+/*
  * rle_getrow.c - Read an RLE file in.
- * 
+ *
  * Author:  Spencer W. Thomas
  *      Computer Science Dept.
  *      University of Utah
  * Date:    Wed Apr 10 1985
  * Copyright (c) 1985 Spencer W. Thomas
- * 
+ *
  * $Id: rle_getrow.c,v 3.0.1.5 1992/03/04 19:33:08 spencer Exp spencer $
  */
 
@@ -43,7 +43,7 @@
 /* Read a two-byte "short" that started in VAX (LITTLE_ENDIAN) order */
 #define VAXSHORT( var, fp )\
     { var = fgetc(fp)&0xFF; var |= (fgetc(fp)) << 8; }
-  
+
 /* Instruction format -- first byte is opcode, second is datum. */
 
 #define OPCODE(inst) (inst[0] & ~LONG)
@@ -52,14 +52,74 @@
 
 static int     debug_f;     /* If non-zero, print debug info. */
 
+
+
+static void
+readComments(rle_hdr * const hdrP) {
+
+    FILE * ifP = hdrP->rle_file;
+
+    /* There are comments */
+    short comlen;
+    char * cp;
+
+    VAXSHORT(comlen, ifP); /* get comment length */
+
+    if (comlen < 0)
+        pm_error("Negative comment length in RLE header");
+    else if (comlen > 0) {
+        unsigned int const evenlen = (comlen + 1) & ~1;    /* make it even */
+
+        char * commentHeap;
+        unsigned int i;
+
+        MALLOCARRAY(commentHeap, evenlen);
+
+        if (commentHeap == NULL) {
+            pm_error("Malloc failed for comment buffer of size %u "
+                     "in rle_get_setup, reading '%s'",
+                     evenlen, hdrP->file_name );
+        }
+        fread(commentHeap, 1, evenlen, ifP);
+        /* Count the comments */
+        for (i = 0, cp = commentHeap; cp < commentHeap + comlen; ++cp) {
+            if (*cp == '\0')
+                ++i;
+        }
+        ++i;            /* extra for NULL pointer at end */
+        /* Get space to put pointers to comments */
+        MALLOCARRAY(hdrP->comments, i);
+        if (hdrP->comments == NULL) {
+            pm_error("Malloc failed for %d comment pointers "
+                     "in rle_get_setup, reading '%s'",
+                     i, hdrP->file_name );
+        }
+        /* Set comment heap */
+        hdrP->comments[0] = commentHeap;
+
+        /* Set pointers to individual comments in the heap as
+          hdrP->comments[1], hdrP->comments[2], etc.
+        */
+        for (i = 1, cp = commentHeap + 1;
+             cp < commentHeap + comlen;
+             ++cp)
+            if (*(cp - 1) == '\0')
+                hdrP->comments[i++] = cp;
+        hdrP->comments[i] = NULL;
+    } else
+        hdrP->comments = NULL;
+}
+
+
+
 int
-rle_get_setup(rle_hdr * const the_hdr) {
+rle_get_setup(rle_hdr * const hdrP) {
 /*-----------------------------------------------------------------------------
   Read the initialization information from an RLE file.
   Inputs:
-    the_hdr:    Contains pointer to the input file.
+    hdrP:    Contains pointer to the input file.
   Outputs:
-    the_hdr:    Initialized with information from the input file.
+    hdrP:    Initialized with information from the input file.
   Returns
      0  on success,
      -1 if the file is not an RLE file,
@@ -67,251 +127,148 @@ rle_get_setup(rle_hdr * const the_hdr) {
      -3 if an immediate EOF is hit (empty input file)
      -4 if an EOF is encountered reading the setup information.
   Assumptions:
-    infile points to the "magic" number in an RLE file (usually  byte 0
-    in the file).
+    input file is positioned to the "magic" number in an RLE file (usually
+    first byte of the file).
   Algorithm:
-    Read in the setup info and fill in the_hdr.
+    Read in the setup info and fill in *hdrP.
 ---------------------------------------------------------------------------- */
     struct XtndRsetup setup;
     short magic;
-    FILE * infile = the_hdr->rle_file;
+    FILE * ifP = hdrP->rle_file;
     int i;
-    char * comment_buf;
-    
+
     /* Clear old stuff out of the header. */
-    rle_hdr_clear(the_hdr);
-    if (the_hdr->is_init != RLE_INIT_MAGIC)
-        rle_names(the_hdr, "Urt", "some file", 0);
-    ++the_hdr->img_num;     /* Count images. */
+    rle_hdr_clear(hdrP);
+    if (hdrP->is_init != RLE_INIT_MAGIC)
+        rle_names(hdrP, "Urt", "some file", 0);
+    ++hdrP->img_num;     /* Count images. */
 
-    VAXSHORT(magic, infile);
-    if (feof(infile))
+    VAXSHORT(magic, ifP);
+    if (feof(ifP))
         return RLE_EMPTY;
     if (magic != RLE_MAGIC)
         return RLE_NOT_RLE;
-    fread(&setup, 1, SETUPSIZE, infile);  /* assume VAX packing */
-    if (feof( infile))
+    fread(&setup, 1, SETUPSIZE, ifP);  /* assume VAX packing */
+    if (feof( ifP))
         return RLE_EOF;
 
     /* Extract information from setup */
-    the_hdr->ncolors = setup.h_ncolors;
-    for (i = 0; i < the_hdr->ncolors; ++i)
-        RLE_SET_BIT(*the_hdr, i);
+    hdrP->ncolors = setup.h_ncolors;
+    for (i = 0; i < hdrP->ncolors; ++i)
+        RLE_SET_BIT(*hdrP, i);
 
     if (!(setup.h_flags & H_NO_BACKGROUND) && setup.h_ncolors > 0) {
         rle_pixel * bg_color;
 
-        MALLOCARRAY(the_hdr->bg_color, setup.h_ncolors);
-        if (!the_hdr->bg_color)
+        MALLOCARRAY(hdrP->bg_color, setup.h_ncolors);
+        if (!hdrP->bg_color)
             pm_error("Failed to allocation array for %u background colors",
                      setup.h_ncolors);
         MALLOCARRAY(bg_color, 1 + (setup.h_ncolors / 2) * 2);
         if (!bg_color)
             pm_error("Failed to allocation array for %u background colors",
                      1+(setup.h_ncolors / 2) * 2);
-        fread((char *)bg_color, 1, 1 + (setup.h_ncolors / 2) * 2, infile);
+        fread((char *)bg_color, 1, 1 + (setup.h_ncolors / 2) * 2, ifP);
         for (i = 0; i < setup.h_ncolors; ++i)
-            the_hdr->bg_color[i] = bg_color[i];
+            hdrP->bg_color[i] = bg_color[i];
         free(bg_color);
     } else {
-        getc(infile);   /* skip filler byte */
-        the_hdr->bg_color = NULL;
+        getc(ifP);   /* skip filler byte */
+        hdrP->bg_color = NULL;
     }
 
     if (setup.h_flags & H_NO_BACKGROUND)
-        the_hdr->background = 0;
+        hdrP->background = 0;
     else if (setup.h_flags & H_CLEARFIRST)
-        the_hdr->background = 2;
+        hdrP->background = 2;
     else
-        the_hdr->background = 1;
+        hdrP->background = 1;
     if (setup.h_flags & H_ALPHA) {
-        the_hdr->alpha = 1;
-        RLE_SET_BIT( *the_hdr, RLE_ALPHA );
+        hdrP->alpha = 1;
+        RLE_SET_BIT( *hdrP, RLE_ALPHA );
     } else
-        the_hdr->alpha = 0;
+        hdrP->alpha = 0;
+
+    hdrP->xmin = vax_gshort(setup.hc_xpos);
+    hdrP->ymin = vax_gshort(setup.hc_ypos);
+    hdrP->xmax = hdrP->xmin + vax_gshort(setup.hc_xlen) - 1;
+    hdrP->ymax = hdrP->ymin + vax_gshort(setup.hc_ylen) - 1;
 
-    the_hdr->xmin = vax_gshort(setup.hc_xpos);
-    the_hdr->ymin = vax_gshort(setup.hc_ypos);
-    the_hdr->xmax = the_hdr->xmin + vax_gshort(setup.hc_xlen) - 1;
-    the_hdr->ymax = the_hdr->ymin + vax_gshort(setup.hc_ylen) - 1;
+    hdrP->ncmap = setup.h_ncmap;
+    hdrP->cmaplen = setup.h_cmaplen;
 
-    the_hdr->ncmap = setup.h_ncmap;
-    the_hdr->cmaplen = setup.h_cmaplen;
-    if (the_hdr->ncmap > 0) {
-        int const maplen = the_hdr->ncmap * (1 << the_hdr->cmaplen);
+    if (hdrP->ncmap > 0) {
+        int const maplen = hdrP->ncmap * (1 << hdrP->cmaplen);
 
-        int i;
-        char *maptemp;
+        unsigned int i;
+        unsigned char *maptemp;
 
-        MALLOCARRAY(the_hdr->cmap, maplen);
+        MALLOCARRAY(hdrP->cmap, maplen);
         MALLOCARRAY(maptemp, 2 * maplen);
-        if (the_hdr->cmap == NULL || maptemp == NULL) {
+        if (hdrP->cmap == NULL || maptemp == NULL) {
             pm_error("Malloc failed for color map of size %d*%d "
                      "in rle_get_setup, reading '%s'",
-                     the_hdr->ncmap, (1 << the_hdr->cmaplen),
-                     the_hdr->file_name );
+                     hdrP->ncmap, (1 << hdrP->cmaplen),
+                     hdrP->file_name );
             return RLE_NO_SPACE;
         }
-        fread(maptemp, 2, maplen, infile);
+        fread(maptemp, 2, maplen, ifP);
         for (i = 0; i < maplen; ++i)
-            the_hdr->cmap[i] = vax_gshort(&maptemp[i * 2]);
+            hdrP->cmap[i] = vax_gshort(&maptemp[i * 2]);
         free(maptemp);
     }
 
-    /* Check for comments */
-    if (setup.h_flags & H_COMMENT) {
-        short comlen, evenlen;
-        char * cp;
-
-        VAXSHORT(comlen, infile); /* get comment length */
-        evenlen = (comlen + 1) & ~1;    /* make it even */
-        if (evenlen) {
-            MALLOCARRAY(comment_buf, evenlen);
-    
-            if (comment_buf == NULL) {
-                pm_error("Malloc failed for comment buffer of size %d "
-                         "in rle_get_setup, reading '%s'",
-                         comlen, the_hdr->file_name );
-                return RLE_NO_SPACE;
-            }
-            fread(comment_buf, 1, evenlen, infile);
-            /* Count the comments */
-            for (i = 0, cp = comment_buf; cp < comment_buf + comlen; ++cp)
-                if (*cp == '\0')
-                    ++i;
-            ++i;            /* extra for NULL pointer at end */
-            /* Get space to put pointers to comments */
-            MALLOCARRAY(the_hdr->comments, i);
-            if (the_hdr->comments == NULL) {
-                pm_error("Malloc failed for %d comment pointers "
-                         "in rle_get_setup, reading '%s'",
-                         i, the_hdr->file_name );
-                return RLE_NO_SPACE;
-            }
-            /* Get pointers to the comments */
-            *the_hdr->comments = comment_buf;
-            for (i = 1, cp = comment_buf + 1;
-                 cp < comment_buf + comlen;
-                 ++cp)
-                if (*(cp - 1) == '\0')
-                    the_hdr->comments[i++] = cp;
-            the_hdr->comments[i] = NULL;
-        } else
-            the_hdr->comments = NULL;
-    } else
-        the_hdr->comments = NULL;
+    if (setup.h_flags & H_COMMENT)
+        readComments(hdrP);
+    else
+        hdrP->comments = NULL;
 
     /* Initialize state for rle_getrow */
-    the_hdr->priv.get.scan_y = the_hdr->ymin;
-    the_hdr->priv.get.vert_skip = 0;
-    the_hdr->priv.get.is_eof = 0;
-    the_hdr->priv.get.is_seek = ftell(infile) > 0;
+    hdrP->priv.get.scan_y = hdrP->ymin;
+    hdrP->priv.get.vert_skip = 0;
+    hdrP->priv.get.is_eof = 0;
+    hdrP->priv.get.is_seek = ftell(ifP) > 0;
     debug_f = 0;
 
-    if (!feof(infile))
+    if (!feof(ifP))
         return RLE_SUCCESS; /* success! */
     else {
-        the_hdr->priv.get.is_eof = 1;
+        hdrP->priv.get.is_eof = 1;
         return RLE_EOF;
     }
 }
 
 
 
-void
-rle_get_setup_ok(rle_hdr *    const the_hdr,
-                 const char * const prog_name,
-                 const char * const file_name) {
-/*-----------------------------------------------------------------------------
-  Read the initialization information from an RLE file.
-
-  Inputs:
-   the_hdr:    Contains pointer to the input file.
-   prog_name:  Program name to be printed in the error message.
-       file_name:  File name to be printed in the error message.
-                   If NULL, the string "stdin" is generated.
-
-  Outputs:
-   the_hdr:    Initialized with information from the input file.
-       If reading the header fails, it prints an error message
-       and exits with the appropriate status code.
-  Algorithm:
-   rle_get_setup does all the work.
----------------------------------------------------------------------------- */
-    int code;
-
-    /* Backwards compatibility: if is_init is not properly set, 
-     * initialize the header.
-     */
-    if (the_hdr->is_init != RLE_INIT_MAGIC) {
-        FILE * const f = the_hdr->rle_file;
-        rle_hdr_init( the_hdr );
-        the_hdr->rle_file = f;
-        rle_names(the_hdr, prog_name, file_name, 0);
-    }
-
-    code = rle_get_error(rle_get_setup(the_hdr),
-                         the_hdr->cmd, the_hdr->file_name);
-    if (code)
-        exit(code);
-}
-
-
-
-void
-rle_debug( on_off )
-    int on_off;
-{
-/*-----------------------------------------------------------------------------
-  Turn RLE debugging on or off.
-  Inputs:
-   on_off:     if 0, stop debugging, else start.
-  Outputs:
-   Sets internal debug flag.
-  Assumptions:
-   [None]
-  Algorithm:
-   [None]
----------------------------------------------------------------------------- */
-    debug_f = on_off;
-
-    /* Set line buffering on stderr.  Character buffering is the default, and
-     * it is SLOOWWW for large amounts of output.
-     */
-    setvbuf(stderr, NULL, _IOLBF, 0);
-}
-
-
-
 int
-rle_getrow(rle_hdr *    const the_hdr,
+rle_getrow(rle_hdr *    const hdrP,
            rle_pixel ** const scanline) {
 /*-----------------------------------------------------------------------------
   Get a scanline from the input file.
   Inputs:
-   the_hdr:    Header structure containing information about 
+   hdrP:    Header structure containing information about
            the input file.
   Outputs:
    scanline:   an array of pointers to the individual color
            scanlines.  Scanline is assumed to have
-           the_hdr->ncolors pointers to arrays of rle_pixel,
-           each of which is at least the_hdr->xmax+1 long.
+           hdrP->ncolors pointers to arrays of rle_pixel,
+           each of which is at least hdrP->xmax+1 long.
    Returns the current scanline number.
   Assumptions:
    rle_get_setup has already been called.
   Algorithm:
    If a vertical skip is being executed, and clear-to-background is
-   specified (the_hdr->background is true), just set the
+   specified (hdrP->background is true), just set the
    scanlines to the background color.  If clear-to-background is
    not set, just increment the scanline number and return.
-  
+
    Otherwise, read input until a vertical skip is encountered,
    decoding the instructions into scanline data.
- 
+
    If ymax is reached (or, somehow, passed), continue reading and
    discarding input until end of image.
 ---------------------------------------------------------------------------- */
-    FILE * const infile = the_hdr->rle_file;
+    FILE * const ifP = hdrP->rle_file;
 
     rle_pixel * scanc;
 
@@ -323,73 +280,73 @@ rle_getrow(rle_hdr *    const the_hdr,
     short word, long_data;
     char inst[2];
 
-    scan_x = the_hdr->xmin; /* initial value */
-    max_x = the_hdr->xmax;  /* initial value */
+    scan_x = hdrP->xmin; /* initial value */
+    max_x = hdrP->xmax;  /* initial value */
     channel = 0; /* initial value */
     /* Clear to background if specified */
-    if (the_hdr->background != 1) {
-        if (the_hdr->alpha && RLE_BIT( *the_hdr, -1))
-            memset((char *)scanline[-1] + the_hdr->xmin, 0,
-                   the_hdr->xmax - the_hdr->xmin + 1);
-        for (nc = 0; nc < the_hdr->ncolors; ++nc) {
-            if (RLE_BIT( *the_hdr, nc)) {
+    if (hdrP->background != 1) {
+        if (hdrP->alpha && RLE_BIT( *hdrP, -1))
+            memset((char *)scanline[-1] + hdrP->xmin, 0,
+                   hdrP->xmax - hdrP->xmin + 1);
+        for (nc = 0; nc < hdrP->ncolors; ++nc) {
+            if (RLE_BIT( *hdrP, nc)) {
                 /* Unless bg color given explicitly, use 0. */
-                if (the_hdr->background != 2 || the_hdr->bg_color[nc] == 0)
-                    memset((char *)scanline[nc] + the_hdr->xmin, 0,
-                           the_hdr->xmax - the_hdr->xmin + 1);
+                if (hdrP->background != 2 || hdrP->bg_color[nc] == 0)
+                    memset((char *)scanline[nc] + hdrP->xmin, 0,
+                           hdrP->xmax - hdrP->xmin + 1);
                 else
-                    memset((char *)scanline[nc] + the_hdr->xmin,
-                           the_hdr->bg_color[nc],
-                           the_hdr->xmax - the_hdr->xmin + 1);
+                    memset((char *)scanline[nc] + hdrP->xmin,
+                           hdrP->bg_color[nc],
+                           hdrP->xmax - hdrP->xmin + 1);
             }
         }
     }
 
     /* If skipping, then just return */
-    if (the_hdr->priv.get.vert_skip > 0) {
-        --the_hdr->priv.get.vert_skip;
-        ++the_hdr->priv.get.scan_y;
-        if (the_hdr->priv.get.vert_skip > 0) {
-            if (the_hdr->priv.get.scan_y >= the_hdr->ymax) {
-                int const y = the_hdr->priv.get.scan_y;
-                while (rle_getskip(the_hdr) != 32768)
+    if (hdrP->priv.get.vert_skip > 0) {
+        --hdrP->priv.get.vert_skip;
+        ++hdrP->priv.get.scan_y;
+        if (hdrP->priv.get.vert_skip > 0) {
+            if (hdrP->priv.get.scan_y >= hdrP->ymax) {
+                int const y = hdrP->priv.get.scan_y;
+                while (rle_getskip(hdrP) != 32768)
                     ;
                 return y;
             } else
-                return the_hdr->priv.get.scan_y;
+                return hdrP->priv.get.scan_y;
         }
     }
 
     /* If EOF has been encountered, return also */
-    if (the_hdr->priv.get.is_eof)
-        return ++the_hdr->priv.get.scan_y;
+    if (hdrP->priv.get.is_eof)
+        return ++hdrP->priv.get.scan_y;
 
     /* Otherwise, read and interpret instructions until a skipLines
        instruction is encountered.
     */
-    if (RLE_BIT(*the_hdr, channel))
+    if (RLE_BIT(*hdrP, channel))
         scanc = scanline[channel] + scan_x;
     else
         scanc = NULL;
     for (;;) {
-        inst[0] = getc(infile);
-        inst[1] = getc(infile);
-        if (feof(infile)) {
-            the_hdr->priv.get.is_eof = 1;
+        inst[0] = getc(ifP);
+        inst[1] = getc(ifP);
+        if (feof(ifP)) {
+            hdrP->priv.get.is_eof = 1;
             break;      /* <--- one of the exits */
         }
 
         switch(OPCODE(inst)) {
         case RSkipLinesOp:
             if (LONGP(inst)) {
-                VAXSHORT(the_hdr->priv.get.vert_skip, infile);
+                VAXSHORT(hdrP->priv.get.vert_skip, ifP);
             } else
-                the_hdr->priv.get.vert_skip = DATUM(inst);
+                hdrP->priv.get.vert_skip = DATUM(inst);
             if (debug_f)
                 pm_message("Skip %d Lines (to %d)",
-                           the_hdr->priv.get.vert_skip,
-                           the_hdr->priv.get.scan_y +
-                           the_hdr->priv.get.vert_skip);
+                           hdrP->priv.get.vert_skip,
+                           hdrP->priv.get.scan_y +
+                           hdrP->priv.get.vert_skip);
 
             break;          /* need to break for() here, too */
 
@@ -397,8 +354,8 @@ rle_getrow(rle_hdr *    const the_hdr,
             channel = DATUM(inst);  /* select color channel */
             if (channel == 255)
                 channel = -1;
-            scan_x = the_hdr->xmin;
-            if (RLE_BIT(*the_hdr, channel))
+            scan_x = hdrP->xmin;
+            if (RLE_BIT(*hdrP, channel))
                 scanc = scanline[channel]+scan_x;
             if (debug_f)
                 pm_message("Set color to %d (reset x to %d)",
@@ -407,7 +364,7 @@ rle_getrow(rle_hdr *    const the_hdr,
 
         case RSkipPixelsOp:
             if (LONGP(inst)) {
-                VAXSHORT(long_data, infile);
+                VAXSHORT(long_data, ifP);
                 scan_x += long_data;
                 scanc += long_data;
                 if (debug_f)
@@ -422,40 +379,40 @@ rle_getrow(rle_hdr *    const the_hdr,
 
         case RByteDataOp:
             if (LONGP(inst)) {
-                VAXSHORT(nc, infile);
+                VAXSHORT(nc, ifP);
             } else
                 nc = DATUM(inst);
             ++nc;
             if (debug_f) {
-                if (RLE_BIT(*the_hdr, channel))
+                if (RLE_BIT(*hdrP, channel))
                     pm_message("Pixel data %d (to %d):", nc, scan_x + nc);
                 else
                     pm_message("Pixel data %d (to %d)", nc, scan_x + nc);
             }
-            if (RLE_BIT(*the_hdr, channel)) {
+            if (RLE_BIT(*hdrP, channel)) {
                 /* Don't fill past end of scanline! */
                 if (scan_x + nc > max_x) {
                     ns = scan_x + nc - max_x - 1;
                     nc -= ns;
                 } else
                     ns = 0;
-                fread((char *)scanc, 1, nc, infile);
+                fread((char *)scanc, 1, nc, ifP);
                 while (ns-- > 0)
-                    getc(infile);
+                    getc(ifP);
                 if (nc & 0x1)
-                    getc(infile);   /* throw away odd byte */
+                    getc(ifP);   /* throw away odd byte */
             } else {
-                if (the_hdr->priv.get.is_seek)
-                    fseek(infile, ((nc + 1) / 2) * 2, 1);
+                if (hdrP->priv.get.is_seek)
+                    fseek(ifP, ((nc + 1) / 2) * 2, 1);
                 else {
                     int ii;
                     for (ii = ((nc + 1) / 2) * 2; ii > 0; --ii)
-                        getc(infile);  /* discard it */
+                        getc(ifP);  /* discard it */
                 }
             }
             scanc += nc;
             scan_x += nc;
-            if (debug_f && RLE_BIT(*the_hdr, channel)) {
+            if (debug_f && RLE_BIT(*hdrP, channel)) {
                 rle_pixel * cp;
                 for (cp = scanc - nc; nc > 0; --nc)
                     fprintf(stderr, "%02x", *cp++);
@@ -465,17 +422,17 @@ rle_getrow(rle_hdr *    const the_hdr,
 
         case RRunDataOp:
             if (LONGP(inst)) {
-                VAXSHORT(nc, infile);
+                VAXSHORT(nc, ifP);
             } else
                 nc = DATUM(inst);
             ++nc;
             scan_x += nc;
 
-            VAXSHORT(word, infile);
+            VAXSHORT(word, ifP);
             if (debug_f)
                 pm_message("Run length %d (to %d), data %02x",
                            nc, scan_x, word);
-            if (RLE_BIT(*the_hdr, channel)) {
+            if (RLE_BIT(*hdrP, channel)) {
                 if (scan_x > max_x) {
                     ns = scan_x - max_x - 1;
                     nc -= ns;
@@ -492,29 +449,28 @@ rle_getrow(rle_hdr *    const the_hdr,
             break;
 
         case REOFOp:
-            the_hdr->priv.get.is_eof = 1;
+            hdrP->priv.get.is_eof = 1;
             if (debug_f)
                 pm_message("End of Image");
             break;
 
         default:
             pm_error("rle_getrow: Unrecognized opcode: %d, reading %s",
-                     inst[0], the_hdr->file_name);
+                     inst[0], hdrP->file_name);
         }
         if (OPCODE(inst) == RSkipLinesOp || OPCODE(inst) == REOFOp)
             break;          /* <--- the other loop exit */
     }
 
     /* If at end, skip the rest of a malformed image. */
-    if (the_hdr->priv.get.scan_y >= the_hdr->ymax) {
-        int const y = the_hdr->priv.get.scan_y;
-        while (rle_getskip(the_hdr) != 32768 )
+    if (hdrP->priv.get.scan_y >= hdrP->ymax) {
+        int const y = hdrP->priv.get.scan_y;
+        while (rle_getskip(hdrP) != 32768 )
             ;
         return y;
     }
 
-    return the_hdr->priv.get.scan_y;
+    return hdrP->priv.get.scan_y;
 }
 
 
-
diff --git a/urt/rle_getskip.c b/urt/rle_getskip.c
index 1366e162..2482f2bf 100644
--- a/urt/rle_getskip.c
+++ b/urt/rle_getskip.c
@@ -1,27 +1,27 @@
 /*
  * This software is copyrighted as noted below.  It may be freely copied,
- * modified, and redistributed, provided that the copyright notice is 
+ * modified, and redistributed, provided that the copyright notice is
  * preserved on all copies.
- * 
+ *
  * There is no warranty or other guarantee of fitness for this software,
  * it is provided solely "as is".  Bug reports or fixes may be sent
  * to the author, who may or may not act on them as he desires.
  *
  * You may not include this software in a program or other software product
- * without supplying the source, or without informing the end-user that the 
+ * without supplying the source, or without informing the end-user that the
  * source is available for no extra charge.
  *
  * If you modify this software, you should include a notice giving the
  * name of the person performing the modification, the date of modification,
  * and the reason for such modification.
  */
-/* 
+/*
  * rle_getskip.c - Skip scanlines on input.
- * 
- * Author:	Spencer W. Thomas
- * 		EECS Dept.
- * 		University of Michigan
- * Date:	Wed Jun 27 1990
+ *
+ * Author:      Spencer W. Thomas
+ *              EECS Dept.
+ *              University of Michigan
+ * Date:        Wed Jun 27 1990
  * Copyright (c) 1990, University of Michigan
  */
 
@@ -32,133 +32,136 @@
 
 /* Read a two-byte "short" that started in VAX (LITTLE_ENDIAN) order */
 #define VAXSHORT( var, fp )\
-	{ var = fgetc(fp)&0xFF; var |= (fgetc(fp)) << 8; }
-  
+        { var = fgetc(fp)&0xFF; var |= (fgetc(fp)) << 8; }
+
 /* Instruction format -- first byte is opcode, second is datum. */
 
 #define OPCODE(inst) (inst[0] & ~LONG)
 #define LONGP(inst) (inst[0] & LONG)
-#define DATUM(inst) (inst[1] & 0xff)	/* Make sure it's unsigned. */
+#define DATUM(inst) (inst[1] & 0xff)    /* Make sure it's unsigned. */
 
 /*****************************************************************
  * TAG( rle_getskip )
- * 
+ *
  * Skip the next scanline with data on it.
  * Most useful for skipping to end-of-image.
  * Inputs:
- * 	the_hdr:	Describes input image.
+ *      the_hdr:        Describes input image.
  * Outputs:
- * 	Returns the number of the next scanline.  At EOF returns 32768.
+ *      Returns the number of the next scanline.  At EOF returns 32768.
  * Assumptions:
- * 	rle_get_setup has been called.
+ *      rle_get_setup has been called.
  * Algorithm:
- * 	Read input to the beginning of the next scanline, or to EOF or
- * 	end of image.
+ *      Read input to the beginning of the next scanline, or to EOF or
+ *      end of image.
  */
 unsigned int
 rle_getskip( the_hdr )
 rle_hdr *the_hdr;
 {
     unsigned char inst[2];
-    register FILE *infile = the_hdr->rle_file;
+    FILE *infile = the_hdr->rle_file;
     int nc;
 
     /* Add in vertical skip from last scanline */
-    if ( the_hdr->priv.get.vert_skip > 0) 
-	the_hdr->priv.get.scan_y += the_hdr->priv.get.vert_skip;
+    if ( the_hdr->priv.get.vert_skip > 0)
+        the_hdr->priv.get.scan_y += the_hdr->priv.get.vert_skip;
     the_hdr->priv.get.vert_skip = 0;
 
     if ( the_hdr->priv.get.is_eof )
-	return 32768;		/* too big for 16 bits, signal EOF */
-    
+        return 32768;           /* too big for 16 bits, signal EOF */
+
     /* Otherwise, read and interpret instructions until a skipLines
      * instruction is encountered.
      */
     for (;;)
     {
         inst[0] = getc( infile );
-	inst[1] = getc( infile );
-	if ( feof(infile) )
-	{
-	    the_hdr->priv.get.is_eof = 1;
-	    break;		/* <--- one of the exits */
-	}
-
-	switch( OPCODE(inst) )
-	{
-	case RSkipLinesOp:
-	    if ( LONGP(inst) )
-	    {
-		VAXSHORT( the_hdr->priv.get.vert_skip, infile );
-	    }
-	    else
-		the_hdr->priv.get.vert_skip = DATUM(inst);
-	    break;			/* need to break for() here, too */
-
-	case RSetColorOp:
-	    /* No-op here. */
-	    break;
-
-	case RSkipPixelsOp:
-	    if ( LONGP(inst) )
-	    {
-		(void)getc( infile );
-		(void)getc( infile );
-	    }
-	    break;
-
-	case RByteDataOp:
-	    if ( LONGP(inst) )
-	    {
-	        VAXSHORT( nc, infile );
-	    }
-	    else
-		nc = DATUM(inst);
-	    nc++;
-	    if ( the_hdr->priv.get.is_seek )
-		fseek( infile, ((nc + 1) / 2) * 2, 1 );
-	    else
-	    {
-		register int ii;
-		for ( ii = ((nc + 1) / 2) * 2; ii > 0; ii-- )
-		    (void) getc( infile );	/* discard it */
-	    }
-
-	    break;
-
-	case RRunDataOp:
-	    if ( LONGP(inst) )
-	    {
-		(void)getc( infile );
-		(void)getc( infile );
-	    }
-	    (void)getc( infile );
-	    (void)getc( infile );
-	    break;
-
-	case REOFOp:
-	    the_hdr->priv.get.is_eof = 1;
-	    break;
-
-	default:
-	    fprintf( stderr,
-		     "%s: rle_getskip: Unrecognized opcode: %d, reading %s\n",
-		     the_hdr->cmd, OPCODE(inst), the_hdr->file_name );
-	    exit(1);
-	}
-	if ( OPCODE(inst) == REOFOp )
-	    break;			/* <--- the other loop exit */
-	if ( OPCODE(inst) == RSkipLinesOp )
-	    break;
+        inst[1] = getc( infile );
+        if ( feof(infile) )
+        {
+            the_hdr->priv.get.is_eof = 1;
+            break;              /* <--- one of the exits */
+        }
+
+        switch( OPCODE(inst) )
+        {
+        case RSkipLinesOp:
+            if ( LONGP(inst) )
+            {
+                VAXSHORT( the_hdr->priv.get.vert_skip, infile );
+            }
+            else
+                the_hdr->priv.get.vert_skip = DATUM(inst);
+            break;                      /* need to break for() here, too */
+
+        case RSetColorOp:
+            /* No-op here. */
+            break;
+
+        case RSkipPixelsOp:
+            if ( LONGP(inst) )
+            {
+                (void)getc( infile );
+                (void)getc( infile );
+            }
+            break;
+
+        case RByteDataOp:
+            if ( LONGP(inst) )
+            {
+                VAXSHORT( nc, infile );
+            }
+            else
+                nc = DATUM(inst);
+            nc++;
+            if ( the_hdr->priv.get.is_seek )
+                fseek( infile, ((nc + 1) / 2) * 2, 1 );
+            else
+            {
+                int ii;
+                for ( ii = ((nc + 1) / 2) * 2; ii > 0; ii-- )
+                    (void) getc( infile );      /* discard it */
+            }
+
+            break;
+
+        case RRunDataOp:
+            if ( LONGP(inst) )
+            {
+                (void)getc( infile );
+                (void)getc( infile );
+            }
+            (void)getc( infile );
+            (void)getc( infile );
+            break;
+
+        case REOFOp:
+            the_hdr->priv.get.is_eof = 1;
+            break;
+
+        default:
+            fprintf( stderr,
+                     "%s: rle_getskip: Unrecognized opcode: %d, reading %s\n",
+                     the_hdr->cmd, OPCODE(inst), the_hdr->file_name );
+            exit(1);
+        }
+        if ( OPCODE(inst) == REOFOp )
+            break;                      /* <--- the other loop exit */
+        if ( OPCODE(inst) == RSkipLinesOp )
+            break;
     }
 
     /* Return the number of the NEXT scanline. */
     the_hdr->priv.get.scan_y +=
-	the_hdr->priv.get.vert_skip;
+        the_hdr->priv.get.vert_skip;
     the_hdr->priv.get.vert_skip = 0;
 
     if ( the_hdr->priv.get.is_eof )
-	return 32768;		/* too big for 16 bits, signal EOF */
+        return 32768;           /* too big for 16 bits, signal EOF */
     else
-	return the_hdr->priv.get.scan_y;
+        return the_hdr->priv.get.scan_y;
 }
+
+
+
diff --git a/urt/rle_global.c b/urt/rle_global.c
index 6014a229..f7228ea9 100644
--- a/urt/rle_global.c
+++ b/urt/rle_global.c
@@ -1,14 +1,14 @@
 /*
  * This software is copyrighted as noted below.  It may be freely copied,
- * modified, and redistributed, provided that the copyright notice is 
+ * modified, and redistributed, provided that the copyright notice is
  * preserved on all copies.
- * 
+ *
  * There is no warranty or other guarantee of fitness for this software,
  * it is provided solely "as is".  Bug reports or fixes may be sent
  * to the author, who may or may not act on them as he desires.
  *
  * You may not include this software in a program or other software product
- * without supplying the source, or without informing the end-user that the 
+ * without supplying the source, or without informing the end-user that the
  * source is available for no extra charge.
  *
  * If you modify this software, you should include a notice giving the
@@ -18,15 +18,15 @@
  *  Modified at BRL 16-May-88 by Mike Muuss to avoid Alliant STDC desire
  *  to have all "void" functions so declared.
  */
-/* 
+/*
  * rle_global.c - Global variable initialization for rle routines.
- * 
- * Author:	Spencer W. Thomas
- * 		Computer Science Dept.
- * 		University of Utah
- * Date:	Thu Apr 25 1985
+ *
+ * Author:      Spencer W. Thomas
+ *              Computer Science Dept.
+ *              University of Utah
+ * Date:        Thu Apr 25 1985
  * Copyright (c) 1985,1986 Spencer W. Thomas
- * 
+ *
  * $Id: rle_global.c,v 3.0.1.1 1992/01/28 18:23:03 spencer Exp $
  */
 
@@ -39,40 +39,40 @@
 
 struct rle_dispatch_tab rle_DTable[] = {
     {
-	" OB",
-	RunSetup,
-	RunSkipBlankLines,
-	RunSetColor,
-	RunSkipPixels,
-	RunNewScanLine,
-	Runputdata,
-	Runputrun,
-	DefaultBlockHook,
-	RunputEof
+        " OB",
+        RunSetup,
+        RunSkipBlankLines,
+        RunSetColor,
+        RunSkipPixels,
+        RunNewScanLine,
+        Runputdata,
+        Runputrun,
+        DefaultBlockHook,
+        RunputEof
     },
 };
 
 static int bg_color[3] = { 0, 0, 0 };
 
 rle_hdr rle_dflt_hdr = {
-    RUN_DISPATCH,		/* dispatch value */
-    3,				/* 3 colors */
-    bg_color,			/* background color */
-    0,				/* (alpha) if 1, save alpha channel */
-    2,				/* (background) 0->just save pixels, */
-				/* 1->overlay, 2->clear to bg first */
-    0, 511,			/* (xmin, xmax) X bounds to save */
-    0, 511,			/* (ymin, ymax) Y bounds to save */
-    0,				/* ncmap (if != 0, save color map) */
-    8,				/* cmaplen (log2 of length of color map) */
-    NULL,			/* pointer to color map */
-    NULL,			/* pointer to comment strings */
-    NULL,			/* output file -- must be set dynamically */
-    { 7 },			/* RGB channels only */
-    0L,				/* Can't free name and file fields. */
-    "Urt",			/* Default "program name". */
-    "no file",			/* No file name given. */
-    0				/* First image. */
+    RUN_DISPATCH,               /* dispatch value */
+    3,                          /* 3 colors */
+    bg_color,                   /* background color */
+    0,                          /* (alpha) if 1, save alpha channel */
+    2,                          /* (background) 0->just save pixels, */
+                                /* 1->overlay, 2->clear to bg first */
+    0, 511,                     /* (xmin, xmax) X bounds to save */
+    0, 511,                     /* (ymin, ymax) Y bounds to save */
+    0,                          /* ncmap (if != 0, save color map) */
+    8,                          /* cmaplen (log2 of length of color map) */
+    NULL,                       /* pointer to color map */
+    NULL,                       /* pointer to comment strings */
+    NULL,                       /* output file -- must be set dynamically */
+    { 7 },                      /* RGB channels only */
+    0L,                         /* Can't free name and file fields. */
+    "Urt",                      /* Default "program name". */
+    "no file",                  /* No file name given. */
+    0                           /* First image. */
     /* Can't initialize the union */
 };
 
@@ -82,6 +82,6 @@ void
 NullputEof(the_hdr)
 rle_hdr * the_hdr;
 {
-				/* do nothing */
+                                /* do nothing */
 }
 #endif
diff --git a/urt/rle_hdr.c b/urt/rle_hdr.c
index bdb728d2..8ceaa9eb 100644
--- a/urt/rle_hdr.c
+++ b/urt/rle_hdr.c
@@ -40,7 +40,7 @@ rle_names(rle_hdr *    const hdrP,
           const char * const pgmname,
           const char * const fname,
           int          const imgNum) {
-/*---------------------------------------------------------------------------- 
+/*----------------------------------------------------------------------------
  * Load program and file names into header.
  * Inputs:
  *  hdrP:      Header to modify.
diff --git a/urt/rle_open_f.c b/urt/rle_open_f.c
index 1aeb6448..834a0c6d 100644
--- a/urt/rle_open_f.c
+++ b/urt/rle_open_f.c
@@ -226,7 +226,6 @@ dealWithSubprocess(const char *  const file_name,
 
 
 
-
 /*
  *  Purpose : Open a file for input or output as controlled by the mode
  *  parameter.  If no file name is specified (ie. file_name is null) then
@@ -323,30 +322,4 @@ rle_open_f(const char * prog_name, const char * file_name, const char * mode)
 }
 
 
-/*****************************************************************
- * TAG( rle_close_f )
- *
- * Close a file opened by rle_open_f.  If the file is stdin or stdout,
- * it will not be closed.
- * Inputs:
- *  fd: File to close.
- * Outputs:
- *  None.
- * Assumptions:
- *  fd is open.
- * Algorithm:
- *  If fd is NULL, just return.
- *  If fd is stdin or stdout, don't close it.  Otherwise, call fclose.
- */
-void
-rle_close_f( fd )
-    FILE *fd;
-{
-    if ( fd == NULL || fd == stdin || fd == stdout )
-        return;
-    else
-        fclose( fd );
-}
-
-
 
diff --git a/urt/rle_put.h b/urt/rle_put.h
index 1f8cc85b..015a15f3 100644
--- a/urt/rle_put.h
+++ b/urt/rle_put.h
@@ -1,29 +1,29 @@
 /*
  * This software is copyrighted as noted below.  It may be freely copied,
- * modified, and redistributed, provided that the copyright notice is 
+ * modified, and redistributed, provided that the copyright notice is
  * preserved on all copies.
- * 
+ *
  * There is no warranty or other guarantee of fitness for this software,
  * it is provided solely "as is".  Bug reports or fixes may be sent
  * to the author, who may or may not act on them as he desires.
  *
  * You may not include this software in a program or other software product
- * without supplying the source, or without informing the end-user that the 
+ * without supplying the source, or without informing the end-user that the
  * source is available for no extra charge.
  *
  * If you modify this software, you should include a notice giving the
  * name of the person performing the modification, the date of modification,
  * and the reason for such modification.
  */
-/* 
+/*
  * rle_put.h - Definitions and a few global variables for rle_putrow/putraw.
- * 
- * Author:	Spencer W. Thomas
- * 		Computer Science Dept.
- * 		University of Utah
- * Date:	Mon Aug  9 1982
+ *
+ * Author:      Spencer W. Thomas
+ *              Computer Science Dept.
+ *              University of Utah
+ * Date:        Mon Aug  9 1982
  * Copyright (c) 1982 Spencer W. Thomas
- * 
+ *
  * $Id: rle_put.h,v 3.0.1.2 1992/02/27 21:14:35 spencer Exp $
  */
 
@@ -35,7 +35,7 @@
  */
 #ifdef __cplusplus        /* Cfront 2.0  or g++ */
 #ifndef c_plusplus
-#define c_plusplus        
+#define c_plusplus
 #endif
 extern "C" {
 #endif
@@ -52,13 +52,13 @@ typedef int rle_fn( ARB_ARGS );
 struct rle_dispatch_tab {
     CONST_DECL char   *magic;   /* magic type flags */
     void (*setup)(rle_hdr * the_hdr);          /* startup function */
-    void (*skipBlankLines)(int nblank, rle_hdr * the_hdr);
+    void (*skipBlankLines)(unsigned int nblank, rle_hdr * the_hdr);
     void(*setColor)(int c, rle_hdr * the_hdr);
-    void(*skipPixels)(int nskip, int last, int wasrun, rle_hdr * the_hdr);
+    void(*skipPixels)(unsigned int nskip, int last, int wasrun, rle_hdr * the_hdr);
     void(*newScanLine)(int flag, rle_hdr * the_hdr);
-    void(*putdat)(rle_pixel * buf, int n, rle_hdr * the_hdr);
+    void(*putdat)(rle_pixel * buf, unsigned int n, rle_hdr * the_hdr);
         /* put a set of differing pixels */
-    void(*putrn)(int color, int n, int last, rle_hdr * the_hdr);
+    void(*putrn)(int color, unsigned int n, int last, rle_hdr * the_hdr);
         /* put a run all the same */
     void (*blockHook)(rle_hdr * the_hdr);
         /* hook called at start of new output block */
@@ -67,38 +67,38 @@ struct rle_dispatch_tab {
 
 extern struct rle_dispatch_tab rle_DTable[];
 
-/* 
+/*
  * These definitions presume the existence of a variable called
  * "fileptr", declared "long * fileptr".  *fileptr should be
  * initialized to 0 before calling Setup().
  * A pointer "the_hdr" declared "rle_hdr * the_hdr" is also
  * presumed to exist.
  */
-#define	    rle_magic		(rle_DTable[(int)the_hdr->dispatch].magic)
-#define	    Setup()		(*rle_DTable[(int)the_hdr->dispatch].setup)(the_hdr)
-#define	    SkipBlankLines(n)	(*rle_DTable[(int)the_hdr->dispatch].skipBlankLines)(n, the_hdr)
-#define	    SetColor(c)		(*rle_DTable[(int)the_hdr->dispatch].setColor)(c, the_hdr)
-#define	    SkipPixels(n, l, r)	(*rle_DTable[(int)the_hdr->dispatch].skipPixels)(n,l,r, the_hdr)
-#define	    NewScanLine(flag)	(*rle_DTable[(int)the_hdr->dispatch].newScanLine)(flag, the_hdr)
-#define	    putdata(buf, len)	(*rle_DTable[(int)the_hdr->dispatch].putdat)(buf, len, the_hdr)
-#define	    putrun(val, len, f)	(*rle_DTable[(int)the_hdr->dispatch].putrn)(val,len,f, the_hdr)
-#define	    BlockHook()		(*rle_DTable[(int)the_hdr->dispatch].blockHook)(the_hdr)
-#define	    PutEof()		(*rle_DTable[(int)the_hdr->dispatch].putEof)(the_hdr)
+#define     rle_magic           (rle_DTable[(int)the_hdr->dispatch].magic)
+#define     Setup()             (*rle_DTable[(int)the_hdr->dispatch].setup)(the_hdr)
+#define     SkipBlankLines(n)   (*rle_DTable[(int)the_hdr->dispatch].skipBlankLines)(n, the_hdr)
+#define     SetColor(c)         (*rle_DTable[(int)the_hdr->dispatch].setColor)(c, the_hdr)
+#define     SkipPixels(n, l, r) (*rle_DTable[(int)the_hdr->dispatch].skipPixels)(n,l,r, the_hdr)
+#define     NewScanLine(flag)   (*rle_DTable[(int)the_hdr->dispatch].newScanLine)(flag, the_hdr)
+#define     putdata(buf, len)   (*rle_DTable[(int)the_hdr->dispatch].putdat)(buf, len, the_hdr)
+#define     putrun(val, len, f) (*rle_DTable[(int)the_hdr->dispatch].putrn)(val,len,f, the_hdr)
+#define     BlockHook()         (*rle_DTable[(int)the_hdr->dispatch].blockHook)(the_hdr)
+#define     PutEof()            (*rle_DTable[(int)the_hdr->dispatch].putEof)(the_hdr)
 
 void
 DefaultBlockHook(rle_hdr * the_hdr);
-/* 
+/*
  * States for run detection
  */
-#define	DATA	0
-#define	RUN1	1
-#define RUN2	2
-#define	RUN3	3
-#define RUN4	4
-#define RUN5	5
-#define RUN6	6
-#define RUN7	7
-#define	INRUN	-1
+#define DATA    0
+#define RUN1    1
+#define RUN2    2
+#define RUN3    3
+#define RUN4    4
+#define RUN5    5
+#define RUN6    6
+#define RUN7    7
+#define INRUN  -1
 
 #ifdef __cplusplus
 }
diff --git a/urt/rle_putcom.c b/urt/rle_putcom.c
index ab2eb208..ff27cb20 100644
--- a/urt/rle_putcom.c
+++ b/urt/rle_putcom.c
@@ -1,23 +1,23 @@
 /*
  * This software is copyrighted as noted below.  It may be freely copied,
- * modified, and redistributed, provided that the copyright notice is 
+ * modified, and redistributed, provided that the copyright notice is
  * preserved on all copies.
- * 
+ *
  * There is no warranty or other guarantee of fitness for this software,
  * it is provided solely "as is".  Bug reports or fixes may be sent
  * to the author, who may or may not act on them as he desires.
  *
  * You may not include this software in a program or other software product
- * without supplying the source, or without informing the end-user that the 
+ * without supplying the source, or without informing the end-user that the
  * source is available for no extra charge.
  *
  * If you modify this software, you should include a notice giving the
  * name of the person performing the modification, the date of modification,
  * and the reason for such modification.
  */
-/* 
+/*
  * rle_putcom.c - Add a picture comment to the header struct.
- * 
+ *
  * Author:  Spencer W. Thomas
  *      Computer Science Dept.
  *      University of Utah
@@ -25,34 +25,35 @@
  * Copyright (c) 1987, University of Utah
  */
 
+#include <limits.h>
+#include <assert.h>
 #include <stdio.h>
 
 #include "netpbm/mallocvar.h"
 #include "netpbm/pm.h"
 #include "rle.h"
 
-/*****************************************************************
- * TAG( match )
- * 
- * Match a name against a test string for "name=value" or "name".
- * If it matches name=value, return pointer to value part, if just
- * name, return pointer to NUL at end of string.  If no match, return NULL.
- *
- * Inputs:
- *  n:  Name to match.  May also be "name=value" to make it easier
- *      to replace comments.
- *  v:  Test string.
- * Outputs:
- *  Returns pointer as above.
- * Assumptions:
- *  [None]
- * Algorithm:
- *  [None]
- */
+
+
 static const char *
 match(const char * const nArg,
       const char * const vArg) {
-
+/*----------------------------------------------------------------------------
+  Match a name against a test string for "name=value" or "name".
+  If it matches name=value, return pointer to value part, if just
+  name, return pointer to NUL at end of string.  If no match, return NULL.
+
+  Inputs:
+   n:  Name to match.  May also be "name=value" to make it easier
+       to replace comments.
+   v:  Test string.
+  Outputs:
+   Returns pointer as above.
+  Assumptions:
+   [None]
+  Algorithm:
+   [None]
+-----------------------------------------------------------------------------*/
     const char * n;
     const char * v;
 
@@ -70,56 +71,59 @@ match(const char * const nArg,
 
 
 
-/*****************************************************************
- * TAG( rle_putcom )
- * 
- * Put a comment into the header struct.
- * Inputs:
- *  value:      Value to add to comments.
- *  the_hdr:    Header struct to add to.
- * Outputs:
- *  the_hdr:    Modified header struct.
- *  Returns previous value;
- * Assumptions:
- *  value pointer can be used as is (data is NOT copied).
- * Algorithm:
- *  Find match if any, else add at end (realloc to make bigger).
- */
 const char *
 rle_putcom(const char * const value,
-           rle_hdr *    const the_hdr) {
-
-    if ( the_hdr->comments == NULL) {
-        MALLOCARRAY_NOFAIL(the_hdr->comments, 2);
-        the_hdr->comments[0] = value;
-        the_hdr->comments[1] = NULL;
+           rle_hdr *    const hdrP) {
+/*----------------------------------------------------------------------------
+  Put a comment into the header struct, replacing the existing one
+    that has the same key, if there is one.
+  Inputs:
+   value:      Value to add to comments.
+   *hdrP:    Header struct to add to.
+  Outputs:
+   *hdrP:    Modified header struct.
+   Returns previous comment having the same key; NULL if none
+  Assumptions:
+   value pointer can be used as is (data is NOT copied).
+  Algorithm:
+   Find match if any, else add at end (realloc to make bigger).
+-----------------------------------------------------------------------------*/
+    if ( hdrP->comments == NULL) {
+        MALLOCARRAY_NOFAIL(hdrP->comments, 2);
+        hdrP->comments[0] = value;
+        hdrP->comments[1] = NULL;
     } else {
         const char ** cp;
         const char * v;
-        const char ** old_comments;
-        int i;
-        for (i = 2, cp = the_hdr->comments; *cp != NULL; ++i, ++cp)
+        const char ** oldComments;
+        unsigned int i;
+
+        for (i = 2, cp = hdrP->comments;
+             *cp != NULL && i < UINT_MAX;
+             ++i, ++cp) {
             if (match(value, *cp) != NULL) {
                 v = *cp;
                 *cp = value;
                 return v;
             }
+        }
         /* Not found */
         /* Can't realloc because somebody else might be pointing to this
          * comments block.  Of course, if this were true, then the
          * assignment above would change the comments for two headers.
-         * But at least, that won't crash the program.  Realloc will.
+         * But at least that won't crash the program.  Realloc will.
          * This would work a lot better in C++, where hdr1 = hdr2
          * could copy the pointers, too.
          */
-        old_comments = the_hdr->comments;
-        MALLOCARRAY(the_hdr->comments, i);
-        if (the_hdr->comments == NULL)
+        oldComments = hdrP->comments;
+        MALLOCARRAY(hdrP->comments, i);
+        if (hdrP->comments == NULL)
             pm_error("Unable to allocate memory for comments");
-        the_hdr->comments[--i] = NULL;
-        the_hdr->comments[--i] = value;
-        for (--i; i >= 0; --i)
-            the_hdr->comments[i] = old_comments[i];
+        assert(i >= 2);
+        hdrP->comments[--i] = NULL;
+        hdrP->comments[--i] = value;
+        for (; i > 0; --i)
+            hdrP->comments[i-1] = oldComments[i-1];
     }
 
     return NULL;
@@ -127,43 +131,3 @@ rle_putcom(const char * const value,
 
 
 
-/*****************************************************************
- * TAG( rle_delcom )
- * 
- * Delete a comment from header struct.
- * Inputs:
- *  name:       Name of comment to delete.
- *  the_hdr:    Header to delete comment from.
- * Outputs:
- *  the_hdr:    Modified header struct.
- *  Returns original comment value.
- * Assumptions:
- *  [None]
- * Algorithm:
- *  [None]
- */
-const char *
-rle_delcom(const char * const name,
-           rle_hdr *    const the_hdr) {
-
-    const char * v = NULL;
-
-    if (the_hdr->comments == NULL)
-        v = NULL;
-    else {
-        const char ** cp;
-
-        for (cp = the_hdr->comments; *cp != NULL; ++cp)
-            if (match(name, *cp) != NULL) {
-                v = *cp;
-                for ( ; *cp != NULL; ++cp)
-                    *cp = cp[1];
-                break;
-            }
-        /* Not found */
-        if (*the_hdr->comments == NULL)
-            the_hdr->comments = NULL;
-    }
-
-    return v;
-}
diff --git a/urt/rle_putrow.c b/urt/rle_putrow.c
index 399633e4..31a596c8 100644
--- a/urt/rle_putrow.c
+++ b/urt/rle_putrow.c
@@ -1,14 +1,14 @@
 /*
  * This software is copyrighted as noted below.  It may be freely copied,
- * modified, and redistributed, provided that the copyright notice is 
+ * modified, and redistributed, provided that the copyright notice is
  * preserved on all copies.
- * 
+ *
  * There is no warranty or other guarantee of fitness for this software,
  * it is provided solely "as is".  Bug reports or fixes may be sent
  * to the author, who may or may not act on them as he desires.
  *
  * You may not include this software in a program or other software product
- * without supplying the source, or without informing the end-user that the 
+ * without supplying the source, or without informing the end-user that the
  * source is available for no extra charge.
  *
  * If you modify this software, you should include a notice giving the
@@ -18,60 +18,57 @@
  *  Modified at BRL 16-May-88 by Mike Muuss to avoid Alliant STDC desire
  *  to have all "void" functions so declared.
  */
-/* 
+/*
  * rle_putrow.c - Save a row of the fb to a file.
- * 
- * Author:	Spencer W. Thomas
- * 		Computer Science Dept.
- * 		University of Utah
- * Date:	1 April 1981
+ *
+ * Author:      Spencer W. Thomas
+ *              Computer Science Dept.
+ *              University of Utah
+ * Date:        1 April 1981
  * Copyright (c) 1981,1986 Spencer W. Thomas
  *
  * $Id: rle_putrow.c,v 3.0.1.2 1992/01/28 18:29:22 spencer Exp $
  */
- 
+
 #include <stdio.h>
 
 #include "rle_put.h"
 #include "rle.h"
 
 
-#define FASTRUNS		/* Faster run finding */
-#ifdef vax
-#define LOCC			/* Use vax instructions for more speed */
-#endif
+#define FASTRUNS                /* Faster run finding */
 
-#define	FALSE	0
-#define	TRUE	1
+#define FALSE   0
+#define TRUE    1
 
 /* Save some typing. */
 #define PBRUN the_hdr->priv.put.brun
 
 /*****************************************************************
  * TAG( findruns )
- * 
+ *
  * Find runs not a given color in the row.
  * Inputs:
- * 	row:		Row of pixel values
- *	rowlen:		Number of pixels in the row.
- *	color:		Color to compare against.
- *	nrun:		Number of runs already found (in different colors).
- *	brun:		Runs found in other color channels already.
+ *      row:            Row of pixel values
+ *      rowlen:         Number of pixels in the row.
+ *      color:          Color to compare against.
+ *      nrun:           Number of runs already found (in different colors).
+ *      brun:           Runs found in other color channels already.
  * Outputs:
- * 	brun:		Modified to reflect merging of runs in this color.
- *	Returns number of runs in brun.
+ *      brun:           Modified to reflect merging of runs in this color.
+ *      Returns number of runs in brun.
  * Assumptions:
  *
  * Algorithm:
- * 	Search for occurrences of pixels not of the given color outside
- *	the runs already found.  When some are found, add a new run or
- *	extend an existing one.  Adjacent runs with fewer than two
- *	pixels intervening are merged.
+ *      Search for occurrences of pixels not of the given color outside
+ *      the runs already found.  When some are found, add a new run or
+ *      extend an existing one.  Adjacent runs with fewer than two
+ *      pixels intervening are merged.
  */
 static int
-findruns(rle_pixel * const row, 
-         int         const rowlen, 
-         int         const color, 
+findruns(rle_pixel * const row,
+         int         const rowlen,
+         int         const color,
          int         const nrunAlready,
          short    (* const brun)[2]) {
 
@@ -99,9 +96,9 @@ findruns(rle_pixel * const row,
         /* Assert: 0 <= i <= rowlen
          * brun[i] is the run following the "blank" space being
          * searched.  If i == rowlen, search after brun[i-1].
-	 */
+         */
 
-	/* get lower and upper bounds of search */
+        /* get lower and upper bounds of search */
 
         if ( i == 0 )
             lower = 0;
@@ -118,15 +115,13 @@ findruns(rle_pixel * const row,
                  i, lower, upper );
 #endif
         /* Search for beginning of run != color */
-#if  defined(LOCC)&defined(vax)
-        s = upper - skpc( (char *)row + lower, upper - lower + 1, color ) + 1;
-#else
+
         for ( s = lower; s <= upper; s++ )
             if ( row[s] != color )
                 break;
-#endif
 
-        if ( s <= upper )	/* found a new run? */
+
+        if ( s <= upper )       /* found a new run? */
         {
             if ( s > lower + 1 || i == 0 ) /* disjoint from preceding run? */
             {
@@ -144,19 +139,16 @@ findruns(rle_pixel * const row,
             }
             else
             {
-                i--;		/* just add to preceding run */
+                i--;            /* just add to preceding run */
 #ifdef DEBUG
                 fprintf( stderr, "Adding to previous run\n" );
 #endif
             }
 
-#if defined(LOCC)&defined(vax)
-            s = upper - locc( (char *)row + s, upper - s + 1, color ) + 1;
-#else
             for ( ; s <= upper; s++ )
                 if ( row[s] == color )
                     break;
-#endif
+
             brun[i][1] = s - 1;
 
 #ifdef DEBUG
@@ -180,7 +172,7 @@ findruns(rle_pixel * const row,
             putc( '\n', stderr );
 #endif
         }
-	
+
         /* Search in next space */
         i++;
     }
@@ -193,319 +185,313 @@ findruns(rle_pixel * const row,
 /*****************************************************************
  * TAG( rle_putrow )
  * Write a scanline to the output file.
- * 
+ *
  * Inputs:
- *	rows:		Pointer to vector of pointers to
- *			rle_pixel arrays containing the pixel information.
- *			If NULL, rowlen scanlines are skipped.
- *	rowlen:		The number of pixels in the scanline, or the
- *			number of scanlines to skip (see above).
+ *      rows:           Pointer to vector of pointers to
+ *                      rle_pixel arrays containing the pixel information.
+ *                      If NULL, rowlen scanlines are skipped.
+ *      rowlen:         The number of pixels in the scanline, or the
+ *                      number of scanlines to skip (see above).
  * Outputs:
- * 	Run length encoded information is written to the_hdr.rle_file.
+ *      Run length encoded information is written to the_hdr.rle_file.
  * Assumptions:
- * 	I'm sure there are lots of assumptions in here.
+ *      I'm sure there are lots of assumptions in here.
  * Algorithm:
- * 	There are two parts:
- * 		1. Find all "sufficiently long" runs of background
- * 		   color.  These will not be saved at all.
- * 		2. For each run of non-background, for each color
- * 		   channel, find runs of identical pixel values
- * 		   between "data" segments (of differing pixel
- * 		   values).
- * 	For part 1, "sufficiently long" is 2 pixels, if the following
- * 	data is less than 256 pixels long, otherwise it is 4 pixels.
- * 	This is enforced by a post-process merge.
+ *      There are two parts:
+ *              1. Find all "sufficiently long" runs of background
+ *                 color.  These will not be saved at all.
+ *              2. For each run of non-background, for each color
+ *                 channel, find runs of identical pixel values
+ *                 between "data" segments (of differing pixel
+ *                 values).
+ *      For part 1, "sufficiently long" is 2 pixels, if the following
+ *      data is less than 256 pixels long, otherwise it is 4 pixels.
+ *      This is enforced by a post-process merge.
  *
- * 	Part 1 can be done in two different ways, depending on whether
- * 	FASTRUNS is defined or not.  With FASTRUNS defined, it finds
- * 	runs of the background pixel value in each channel
- * 	independently, and then merges the results.  With FASTRUNS not
- * 	defined, it scans all channels in parallel.
+ *      Part 1 can be done in two different ways, depending on whether
+ *      FASTRUNS is defined or not.  With FASTRUNS defined, it finds
+ *      runs of the background pixel value in each channel
+ *      independently, and then merges the results.  With FASTRUNS not
+ *      defined, it scans all channels in parallel.
  *
- * 	Part 2 uses a state machine.  For each run of non-background
- * 	data, it searches for sufficiently long sequences of a single
- * 	value (in each channel independently).  Sufficiently long is 4
- * 	pixels if the following data is < 256 pixels, 6 pixels
- * 	otherwise.  This is because the startup cost for the run is 2
- * 	bytes, and the startup cost for a data segment is 2 bytes if
- * 	it is < 256 pixels long, 4 bytes otherwise.  Thus a run
- * 	shorter than 4 or 6 pixels (respectively) would actually make
- * 	the output longer.  An additional pixel is required if the
- * 	preceding data is an odd number of pixels long (because a
- * 	filler byte will be output at the end of it.)
+ *      Part 2 uses a state machine.  For each run of non-background
+ *      data, it searches for sufficiently long sequences of a single
+ *      value (in each channel independently).  Sufficiently long is 4
+ *      pixels if the following data is < 256 pixels, 6 pixels
+ *      otherwise.  This is because the startup cost for the run is 2
+ *      bytes, and the startup cost for a data segment is 2 bytes if
+ *      it is < 256 pixels long, 4 bytes otherwise.  Thus a run
+ *      shorter than 4 or 6 pixels (respectively) would actually make
+ *      the output longer.  An additional pixel is required if the
+ *      preceding data is an odd number of pixels long (because a
+ *      filler byte will be output at the end of it.)
  */
 
 void
 rle_putrow(rows, rowlen, the_hdr)
-register rle_pixel *rows[];
+rle_pixel *rows[];
 int rowlen;
-register rle_hdr * the_hdr;
+rle_hdr * the_hdr;
 {
-    register int i, j;
+    int i, j;
     int nrun;
-    register rle_pixel *row;
+    rle_pixel *row;
     int mask;
     char bits[256];
-    short   state,		/* State of run-finding state machine. */
-	    dstart,		/* Starting point for current data segment. */
-    	    dend,		/* Ending point of current data segment. */
-	    rstart = 0,		/* Starting point of current run. */
-	    runval = 0;		/* Data value for current run. */
+    short   state,              /* State of run-finding state machine. */
+            dstart,             /* Starting point for current data segment. */
+            dend,               /* Ending point of current data segment. */
+            rstart = 0,         /* Starting point of current run. */
+            runval = 0;         /* Data value for current run. */
 
     if (rows == NULL)
     {
-	the_hdr->priv.put.nblank += rowlen;
-	return;
+        the_hdr->priv.put.nblank += rowlen;
+        return;
     }
-    /* 
+    /*
      * If not done already, allocate space to remember runs of
      * non-background color.  A run of bg color must be at least 2
      * bytes long to count, so there can be at most rowlen/3 of them.
      */
     if ( PBRUN == NULL )
     {
-	PBRUN = (short (*)[2])malloc(
-	    (unsigned)((rowlen/3 + 1) * 2 * sizeof(short)) );
-	if ( PBRUN == NULL )
-	{
-	    fprintf( stderr, "%s: Malloc failed in rle_putrow, writing %s\n",
-		     the_hdr->cmd, the_hdr->file_name );
-	    exit(1);
-	}
+        PBRUN = (short (*)[2])malloc(
+            (unsigned)((rowlen/3 + 1) * 2 * sizeof(short)) );
+        if ( PBRUN == NULL )
+        {
+            fprintf( stderr, "%s: Malloc failed in rle_putrow, writing %s\n",
+                     the_hdr->cmd, the_hdr->file_name );
+            exit(1);
+        }
     }
     /* Unpack bitmask in the_hdr struct */
     for ( i=0; i < the_hdr->ncolors; i++ )
-	bits[i] = RLE_BIT( *the_hdr, i );
+        bits[i] = RLE_BIT( *the_hdr, i );
     bits[255] = RLE_BIT( *the_hdr, -1 );
 
-    /* 
+    /*
      * If saving only non-background pixels, find runs of them.  Note
      * that the alpha channel is considered to be background iff it is
      * zero.
      */
-#ifdef	FASTRUNS
+#ifdef  FASTRUNS
     if ( the_hdr->background )
     {
-	/* 
-	 * Find runs in each color individually, merging them as we go.
-	 */
-	nrun = 0;		/* start out with no runs */
-	/* Alpha channel first */
-	if ( the_hdr->alpha )
-	    nrun = findruns( rows[-1], rowlen, 0, nrun, PBRUN );
-	/* Now the color channels */
-	for ( i = 0; i < the_hdr->ncolors; i++ )
-	    if ( bits[i] )
-		nrun = findruns( rows[i], rowlen, the_hdr->bg_color[i],
-				 nrun, PBRUN );
+        /*
+         * Find runs in each color individually, merging them as we go.
+         */
+        nrun = 0;               /* start out with no runs */
+        /* Alpha channel first */
+        if ( the_hdr->alpha )
+            nrun = findruns( rows[-1], rowlen, 0, nrun, PBRUN );
+        /* Now the color channels */
+        for ( i = 0; i < the_hdr->ncolors; i++ )
+            if ( bits[i] )
+                nrun = findruns( rows[i], rowlen, the_hdr->bg_color[i],
+                                 nrun, PBRUN );
     }
     else
     {
-	PBRUN[0][0] = 0;
-	PBRUN[0][1] = rowlen-1;
-	nrun = 1;
+        PBRUN[0][0] = 0;
+        PBRUN[0][1] = rowlen-1;
+        nrun = 1;
     }
-#else				/* FASTRUNS */
-    if (the_hdr->background)	/* find non-background runs */
+#else                           /* FASTRUNS */
+    if (the_hdr->background)    /* find non-background runs */
     {
-	j = 0;
-	for (i=0; i<rowlen; i++)
-	    if (!same_color( i, rows, the_hdr->bg_color,
-			     the_hdr->ncolors, bits ) ||
-		(the_hdr->alpha && rows[-1][i] != 0))
-	    {
-		if (j > 0 && i - PBRUN[j-1][1] <= 2)
-		    j--;
-		else
-		    PBRUN[j][0] = i; /* start of run */
-		for ( i++;
-		      i < rowlen && 
-			( !same_color( i, rows, the_hdr->bg_color,
-					 the_hdr->ncolors, bits ) ||
-			  (the_hdr->alpha && rows[-1][i] != 0) );
-		      i++)
-		    ;			/* find the end of this run */
-		PBRUN[j][1] = i-1;    /* last in run */
-		j++;
-	    }
-	nrun = j;
+        j = 0;
+        for (i=0; i<rowlen; i++)
+            if (!same_color( i, rows, the_hdr->bg_color,
+                             the_hdr->ncolors, bits ) ||
+                (the_hdr->alpha && rows[-1][i] != 0))
+            {
+                if (j > 0 && i - PBRUN[j-1][1] <= 2)
+                    j--;
+                else
+                    PBRUN[j][0] = i; /* start of run */
+                for ( i++;
+                      i < rowlen &&
+                        ( !same_color( i, rows, the_hdr->bg_color,
+                                         the_hdr->ncolors, bits ) ||
+                          (the_hdr->alpha && rows[-1][i] != 0) );
+                      i++)
+                    ;                   /* find the end of this run */
+                PBRUN[j][1] = i-1;    /* last in run */
+                j++;
+            }
+        nrun = j;
     }
     else
     {
-	PBRUN[0][0] = 0;
-	PBRUN[0][1] = rowlen-1;
-	nrun = 1;
+        PBRUN[0][0] = 0;
+        PBRUN[0][1] = rowlen-1;
+        nrun = 1;
     }
-#endif				/* FASTRUNS */
+#endif                          /* FASTRUNS */
     /* One final pass merges runs with fewer than 4 intervening pixels
      * if the second run is longer than 255 pixels.  This is because
      * the startup cost for such a run is 4 bytes.
      */
     if ( nrun > 1 )
     {
-	for ( i = nrun - 1; i > 0; i-- )
-	{
-	    if ( PBRUN[i][1] - PBRUN[i][0] > 255 &&
-		 PBRUN[i-1][1] + 4 > PBRUN[i][0] )
-	    {
-		PBRUN[i-1][1] = PBRUN[i][1];
-		for ( j = i; j < nrun - 1; j++ )
-		{
-		    PBRUN[j][0] = PBRUN[j+1][0];
-		    PBRUN[j][1] = PBRUN[j+1][1];
-		}
-		nrun--;
-	    }
-	}
+        for ( i = nrun - 1; i > 0; i-- )
+        {
+            if ( PBRUN[i][1] - PBRUN[i][0] > 255 &&
+                 PBRUN[i-1][1] + 4 > PBRUN[i][0] )
+            {
+                PBRUN[i-1][1] = PBRUN[i][1];
+                for ( j = i; j < nrun - 1; j++ )
+                {
+                    PBRUN[j][0] = PBRUN[j+1][0];
+                    PBRUN[j][1] = PBRUN[j+1][1];
+                }
+                nrun--;
+            }
+        }
     }
 
     if (nrun > 0)
     {
-	if (the_hdr->priv.put.nblank > 0)
-	{
-	    SkipBlankLines(the_hdr->priv.put.nblank);
-	    the_hdr->priv.put.nblank = 0;
-	}
-	for ( mask = (the_hdr->alpha ? -1 : 0);
-	      mask < the_hdr->ncolors;
-	      mask++)			/* do all colors */
-	{
-	    if ( ! bits[mask & 0xff] )
-	    {
-		continue;
-	    }
-	    row = rows[mask];
-	    SetColor(mask);
-	    if (PBRUN[0][0] > 0)
-	    {
-		SkipPixels(PBRUN[0][0], FALSE, FALSE);
-	    }
-	    for (j=0; j<nrun; j++)
-	    {
-		state = DATA;
-		dstart = PBRUN[j][0];
-		dend = PBRUN[j][1];
-		for (i=dstart; i<=dend; i++)
-		{
-		    switch(state)
-		    {
-		    case DATA:
-			if (i > dstart && runval == row[i])
-			{
-			    /* 2 in a row may be a run. */
-			    /* If odd data length, start with RUN1 */
-			    if ( ((i - dstart) % 2) == 0)
-				state = RUN1;
-			    else
-				state = RUN2;
-			}
-			else
-			{
-			    runval = row[i];	/* maybe a run starts here? */
-			    rstart = i;
-			}
-			break;
-	    
-		    case RUN4:
-			if (runval == row[i])
-			{
-			    /* If the following data might be longer
-			     * than 255 pixels then look for 8 in a
-			     * row, otherwise, 6 in a row is
-			     * sufficient.  Fake this by skipping to
-			     * state RUN5.
-			     */
-			    if ( dend - i > 255 )
-				state  = RUN5;	/* Need some more. */
-			    else
-				state = RUN7;	/* Next one makes a run. */
-			    
-			}
-			else
-			{
-			    state = DATA;	/* Nope, back to data */
-			    runval = row[i];	/* but maybe a new run here? */
-			    rstart = i;
-			}
-			break;
-
-		    case RUN1:
-		    case RUN2:
-		    case RUN3:
-		    case RUN5:
-		    case RUN6:
-			if (runval == row[i])
-			{
-			    /* Move to the next state. */
-			    state++;
-			}
-			else
-			{
-			    state = DATA;	/* Nope, back to data */
-			    runval = row[i];	/* but maybe a new run here? */
-			    rstart = i;
-			}
-			break;
-
-
-		    case RUN7:
-			if (runval == row[i])	/* enough in a row for a run */
-			{
-			    state = INRUN;
-			    putdata(row + dstart, rstart - dstart);
+        if (the_hdr->priv.put.nblank > 0)
+        {
+            SkipBlankLines(the_hdr->priv.put.nblank);
+            the_hdr->priv.put.nblank = 0;
+        }
+        for ( mask = (the_hdr->alpha ? -1 : 0);
+              mask < the_hdr->ncolors;
+              mask++)                   /* do all colors */
+        {
+            if ( ! bits[mask & 0xff] )
+            {
+                continue;
+            }
+            row = rows[mask];
+            SetColor(mask);
+            if (PBRUN[0][0] > 0)
+            {
+                SkipPixels(PBRUN[0][0], FALSE, FALSE);
+            }
+            for (j=0; j<nrun; j++)
+            {
+                state = DATA;
+                dstart = PBRUN[j][0];
+                dend = PBRUN[j][1];
+                for (i=dstart; i<=dend; i++)
+                {
+                    switch(state)
+                    {
+                    case DATA:
+                        if (i > dstart && runval == row[i])
+                        {
+                            /* 2 in a row may be a run. */
+                            /* If odd data length, start with RUN1 */
+                            if ( ((i - dstart) % 2) == 0)
+                                state = RUN1;
+                            else
+                                state = RUN2;
+                        }
+                        else
+                        {
+                            runval = row[i];    /* maybe a run starts here? */
+                            rstart = i;
+                        }
+                        break;
+
+                    case RUN4:
+                        if (runval == row[i])
+                        {
+                            /* If the following data might be longer
+                             * than 255 pixels then look for 8 in a
+                             * row, otherwise, 6 in a row is
+                             * sufficient.  Fake this by skipping to
+                             * state RUN5.
+                             */
+                            if ( dend - i > 255 )
+                                state  = RUN5;  /* Need some more. */
+                            else
+                                state = RUN7;   /* Next one makes a run. */
+
+                        }
+                        else
+                        {
+                            state = DATA;       /* Nope, back to data */
+                            runval = row[i];    /* but maybe a new run here? */
+                            rstart = i;
+                        }
+                        break;
+
+                    case RUN1:
+                    case RUN2:
+                    case RUN3:
+                    case RUN5:
+                    case RUN6:
+                        if (runval == row[i])
+                        {
+                            /* Move to the next state. */
+                            state++;
+                        }
+                        else
+                        {
+                            state = DATA;       /* Nope, back to data */
+                            runval = row[i];    /* but maybe a new run here? */
+                            rstart = i;
+                        }
+                        break;
+
+
+                    case RUN7:
+                        if (runval == row[i])   /* enough in a row for a run */
+                        {
+                            state = INRUN;
+                            putdata(row + dstart, rstart - dstart);
 #ifdef FASTRUNS
-#ifdef LOCC
-			    /* Shortcut to find end of run! */
-			    i = dend - skpc( (char *)row + i, dend + 1 - i,
-					     runval );
-#else
-			    while ( row[++i] == runval && i <= dend)
-				; /* not quite so good, but not bad */
-			    i--;
-#endif /* LOCC */
+                            while ( row[++i] == runval && i <= dend)
+                                ; /* not quite so good, but not bad */
+                            i--;
 #endif /* FASTRUNS */
-			}
-			else
-			{
-			    state = DATA;		/* not a run, */
-			    runval = row[i];	/* but may this starts one */
-			    rstart = i;
-			}
-			break;
-	    
-		    case INRUN:
-			if (runval != row[i])	/* if run out */
-			{
-			    state = DATA;
-			    putrun(runval, i - rstart, FALSE);
-			    runval = row[i];	/* who knows, might be more */
-			    rstart = i;
-			    dstart = i;	/* starting a new 'data' run */
-			}
-			break;
-		    }
-		}
-		if (state == INRUN)
-		    putrun(runval, i - rstart, TRUE);	/* last bit */
-		else
-		    putdata(row + dstart, i - dstart);
-
-		if (j < nrun-1)
-		    SkipPixels(
-			    PBRUN[j+1][0] - dend - 1,
-			    FALSE, state == INRUN);
-		else
-		{
-		    if (rowlen - dend > 0)
-			SkipPixels(
-			    rowlen - dend - 1,
-			    TRUE, state == INRUN);
-		}
-	    }
-
-	    if ( mask != the_hdr->ncolors - 1 )
-		NewScanLine(FALSE);
-	}
+                        }
+                        else
+                        {
+                            state = DATA;               /* not a run, */
+                            runval = row[i];    /* but may this starts one */
+                            rstart = i;
+                        }
+                        break;
+
+                    case INRUN:
+                        if (runval != row[i])   /* if run out */
+                        {
+                            state = DATA;
+                            putrun(runval, i - rstart, FALSE);
+                            runval = row[i];    /* who knows, might be more */
+                            rstart = i;
+                            dstart = i; /* starting a new 'data' run */
+                        }
+                        break;
+                    }
+                }
+                if (state == INRUN)
+                    putrun(runval, i - rstart, TRUE);   /* last bit */
+                else
+                    putdata(row + dstart, i - dstart);
+
+                if (j < nrun-1)
+                    SkipPixels(
+                            PBRUN[j+1][0] - dend - 1,
+                            FALSE, state == INRUN);
+                else
+                {
+                    if (rowlen - dend > 0)
+                        SkipPixels(
+                            rowlen - dend - 1,
+                            TRUE, state == INRUN);
+                }
+            }
+
+            if ( mask != the_hdr->ncolors - 1 )
+                NewScanLine(FALSE);
+        }
     }
 
     /* Increment to next scanline */
@@ -516,56 +502,32 @@ register rle_hdr * the_hdr;
 }
 
 
-/*****************************************************************
- * TAG( rle_skiprow )
- * 
- * Skip rows in RLE file.
- * Inputs:
- * 	the_hdr:    	Header struct for RLE output file.
- *  	nrow:	    	Number of rows to skip.
- * Outputs:
- * 	Increments the nblank field in the the_hdr struct, so that a Skiplines
- *  	code will be output the next time rle_putrow or rle_putraw is called.
- * Assumptions:
- * 	Only effective when called between rle_putrow or rle_putraw calls (or
- *  	some other routine that follows the same conventions.
- * Algorithm:
- *	[None]
- */
-void
-rle_skiprow( the_hdr, nrow )
-rle_hdr *the_hdr;
-int nrow;
-{
-    the_hdr->priv.put.nblank += nrow;
-}
-
 
 /*****************************************************************
  * TAG( rle_put_init )
- * 
- * Initialize the header structure for writing scanlines. 
+ *
+ * Initialize the header structure for writing scanlines.
  * Inputs:
- *	[None]
+ *      [None]
  * Outputs:
- * 	the_hdr:	Private portions initialized for output.
+ *      the_hdr:        Private portions initialized for output.
  * Assumptions:
- *	[None]
+ *      [None]
  * Algorithm:
- *	[None]
+ *      [None]
  */
 void
 rle_put_init( the_hdr )
-register rle_hdr *the_hdr;
+rle_hdr *the_hdr;
 {
     the_hdr->dispatch = RUN_DISPATCH;
 
     if ( the_hdr->is_init != RLE_INIT_MAGIC )
     {
-	the_hdr->cmd = "Urt";
-	the_hdr->file_name = "some file";
+        the_hdr->cmd = "Urt";
+        the_hdr->file_name = "some file";
     }
-    the_hdr->priv.put.nblank = 0;	/* Reinit static vars */
+    the_hdr->priv.put.nblank = 0;       /* Reinit static vars */
     /* Would like to be able to free previously allocated storage,
      * but can't count on a non-NULL value being a valid pointer.
      */
@@ -574,156 +536,100 @@ register rle_hdr *the_hdr;
 
     /* Only save alpha if alpha AND alpha channel bit are set. */
     if ( the_hdr->alpha )
-	the_hdr->alpha = (RLE_BIT( *the_hdr, -1 ) != 0);
+        the_hdr->alpha = (RLE_BIT( *the_hdr, -1 ) != 0);
     else
-	RLE_CLR_BIT( *the_hdr, -1 );
+        RLE_CLR_BIT( *the_hdr, -1 );
 }
 
+
+
 /*****************************************************************
  * TAG( rle_put_setup )
- * 
+ *
  * Initialize for writing RLE, and write header to output file.
  * Inputs:
- * 	the_hdr:	Describes output image.
+ *      the_hdr:        Describes output image.
  * Outputs:
- * 	the_hdr:	Initialized.
+ *      the_hdr:        Initialized.
  * Assumptions:
- *	Lots of them.
+ *      Lots of them.
  * Algorithm:
- *	[None]
+ *      [None]
  */
 void
 rle_put_setup( the_hdr )
-register rle_hdr * the_hdr;
+rle_hdr * the_hdr;
 {
     rle_put_init( the_hdr );
-    the_hdr->img_num++;		/* Count output images. */
+    the_hdr->img_num++;         /* Count output images. */
     Setup();
 }
 
+
+
 void
 DefaultBlockHook(rle_hdr * the_hdr)
 {
-    					/* Do nothing */
+                                        /* Do nothing */
 }
 
+
+
 /*****************************************************************
  * TAG( rle_puteof )
  * Write an EOF code into the output file.
  */
 void
 rle_puteof( the_hdr )
-register rle_hdr * the_hdr;
+rle_hdr * the_hdr;
 {
     /* Don't puteof twice. */
     if ( the_hdr->dispatch == NO_DISPATCH )
-	return;
+        return;
     PutEof();
     fflush( the_hdr->rle_file );
     /* Free storage allocated by rle_put_init. */
     if ( PBRUN != NULL )
     {
-	free( PBRUN );
-	PBRUN = NULL;
+        free( PBRUN );
+        PBRUN = NULL;
     }
     /* Signal that puteof has been called. */
     the_hdr->dispatch = NO_DISPATCH;
 }
 
+
+
 #ifndef FASTRUNS
 /*****************************************************************
  * TAG( same_color )
- * 
+ *
  * Determine if the color at the given index position in the scan rows
  * is the same as the background color.
  * Inputs:
- * 	index:	    Index to the pixel position in each row.
- *	rows:	    array of pointers to the scanlines
- *	bg_color:   the background color
- *	ncolors:    number of color elements/pixel
+ *      index:      Index to the pixel position in each row.
+ *      rows:       array of pointers to the scanlines
+ *      bg_color:   the background color
+ *      ncolors:    number of color elements/pixel
  * Outputs:
- * 	TRUE if the color at row[*][i] is the same as bg_color[*].
+ *      TRUE if the color at row[*][i] is the same as bg_color[*].
  * Assumptions:
- *	[None]
+ *      [None]
  * Algorithm:
- *	[None]
+ *      [None]
  */
 static int
 same_color( index, rows, bg_color, ncolors, bits )
-register rle_pixel *rows[];
-register int bg_color[];
+rle_pixel *rows[];
+int bg_color[];
 char *bits;
 {
-    register int i;
+    int i;
 
     for ( i = 0; i < ncolors; i++, bits++ )
-	if ( *bits &&
-	     rows[i][index] != bg_color[i] )
-	    return 0;
-    return 1;				/* all the same */
+        if ( *bits &&
+             rows[i][index] != bg_color[i] )
+            return 0;
+    return 1;                           /* all the same */
 }
 #endif /* !FASTRUNS */
-
-/*****************************************************************
- * TAG( rgb_to_bw )
- * 
- * Perform the NTSC Y transform on RGB data to get B&W data.
- * Inputs:
- * 	red_row, green_row, blue_row:	Given RGB pixel data.
- *	rowlen:	    Number of pixels in the rows.
- * Outputs:
- * 	bw_row:	    Output B&W data.  May coincide with one of the
- *		    inputs.
- * Assumptions:
- *	[None]
- * Algorithm:
- * 	BW = .30*R + .59*G + .11*B
- */
-void
-rgb_to_bw( red_row, green_row, blue_row, bw_row, rowlen )
-rle_pixel *red_row;
-rle_pixel *green_row;
-rle_pixel *blue_row;
-rle_pixel *bw_row;
-int rowlen;
-{
-    register int x, bw;
-
-    for (x=0; x<rowlen; x++)
-    {
-	/* 68000 won't store float > 127 into byte? */
-	/* HP compiler blows it */
-	bw = 0.5 + .30*red_row[x] + .59*green_row[x] + .11*blue_row[x];
-	bw_row[x] = bw;
-    }
-}
-
-#ifdef LOCC
-/*ARGSUSED*/
-locc( p, l, c )
-register char *p;
-register int l;
-register int c;
-{
-    asm( "locc	r9,r10,(r11)" );
-#ifdef lint
-    c = (int) p;		/* why doesn't ARGSUSED work? */
-    l = c;
-    return l;			/* Needs return value, at least */
-#endif
-}
-
-/*ARGSUSED*/
-skpc( p, l, c )
-register char *p;
-register int l;
-register int c;
-{
-    asm( "skpc r9,r10,(r11)" );
-#ifdef lint
-    c = (int) p;		/* why doesn't ARGSUSED work? */
-    l = c;
-    return l;			/* Needs return value, at least */
-#endif
-}
-#endif
diff --git a/urt/rle_row_alc.c b/urt/rle_row_alc.c
index 982e1c5e..4ed19880 100644
--- a/urt/rle_row_alc.c
+++ b/urt/rle_row_alc.c
@@ -1,14 +1,14 @@
 /*
  * This software is copyrighted as noted below.  It may be freely copied,
- * modified, and redistributed, provided that the copyright notice is 
+ * modified, and redistributed, provided that the copyright notice is
  * preserved on all copies.
- * 
+ *
  * There is no warranty or other guarantee of fitness for this software,
  * it is provided solely "as is".  Bug reports or fixes may be sent
  * to the author, who may or may not act on them as he desires.
  *
  * You may not include this software in a program or other software product
- * without supplying the source, or without informing the end-user that the 
+ * without supplying the source, or without informing the end-user that the
  * source is available for no extra charge.
  *
  * If you modify this software, you should include a notice giving the
@@ -18,13 +18,13 @@
  *  Modified at BRL 16-May-88 by Mike Muuss to avoid Alliant STDC desire
  *  to have all "void" functions so declared.
  */
-/* 
+/*
  * rle_row_alc.c - Allocate buffers for rle_getrow/rle_putrow.
- * 
- * Author:	Spencer W. Thomas
- * 		Computer Science Dept.
- * 		University of Utah
- * Date:	Fri Nov 14 1986
+ *
+ * Author:      Spencer W. Thomas
+ *              Computer Science Dept.
+ *              University of Utah
+ * Date:        Fri Nov 14 1986
  * Copyright (c) 1986, Spencer W. Thomas
  */
 
@@ -35,24 +35,24 @@
 
 /*****************************************************************
  * TAG( rle_row_alloc )
- * 
+ *
  * Allocate buffer space for use by rle_getrow and rle_putrow.
  * Inputs:
- * 	the_hdr:	Header structure for RLE file to be read or
- *			written.
+ *      the_hdr:        Header structure for RLE file to be read or
+ *                      written.
  * Outputs:
- *	scanp:		Pointer to pointer to created scanline buffer.
- *			This pointer is adjusted for the alpha channel,
- *			if present.
- *	Returns 0 for success, -1 if malloc failed.
+ *      scanp:          Pointer to pointer to created scanline buffer.
+ *                      This pointer is adjusted for the alpha channel,
+ *                      if present.
+ *      Returns 0 for success, -1 if malloc failed.
  * Assumptions:
- * 	No input scanline will extend beyond the declared xmax endpoint.
+ *      No input scanline will extend beyond the declared xmax endpoint.
  * Algorithm:
- *	Count number of channels actually used (check bitmap).
- * 	Allocate nchan*rowlength pixels, allocate a buffer
- *	to hold ncolors+alpha pointers, and give each channel
- *	rowlength pixels.  Rowlength is xmax + 1, to allow for rle_getrow
- *	usage.
+ *      Count number of channels actually used (check bitmap).
+ *      Allocate nchan*rowlength pixels, allocate a buffer
+ *      to hold ncolors+alpha pointers, and give each channel
+ *      rowlength pixels.  Rowlength is xmax + 1, to allow for rle_getrow
+ *      usage.
  */
 int
 rle_row_alloc( the_hdr, scanp )
@@ -64,53 +64,54 @@ rle_pixel ***scanp;
 
     rowlen = the_hdr->xmax + 1;
     if ( the_hdr->alpha && RLE_BIT( *the_hdr, RLE_ALPHA ) )
-	nchan++;
+        nchan++;
     for ( i = 0; i < the_hdr->ncolors; i++ )
-	if ( RLE_BIT( *the_hdr, i ) )
-	     nchan++;
+        if ( RLE_BIT( *the_hdr, i ) )
+             nchan++;
 
     ncol = the_hdr->ncolors + the_hdr->alpha;
 
     if ( (scanbuf = (rle_pixel **)malloc( ncol * sizeof(rle_pixel *) )) == 0 )
-	return -1;
+        return -1;
     if ( (pixbuf = (rle_pixel *)malloc( nchan * rowlen *
-				       sizeof(rle_pixel) )) == 0 )
+                                       sizeof(rle_pixel) )) == 0 )
     {
-	free( scanbuf );
-	return -1;
+        free( scanbuf );
+        return -1;
     }
 
     if ( the_hdr->alpha )
-	scanbuf++;
+        scanbuf++;
 
     for ( i = -the_hdr->alpha; i < the_hdr->ncolors; i++ )
-	if ( RLE_BIT( *the_hdr, i ) )
-	{
-	    scanbuf[i] = pixbuf;
-	    pixbuf += rowlen;
-	}
-	else
-	    scanbuf[i] = 0;
+        if ( RLE_BIT( *the_hdr, i ) )
+        {
+            scanbuf[i] = pixbuf;
+            pixbuf += rowlen;
+        }
+        else
+            scanbuf[i] = 0;
     *scanp = scanbuf;
 
     return 0;
 }
 
 
+
 /*****************************************************************
  * TAG( rle_row_free )
- * 
+ *
  * Free storage allocated by rle_row_alloc().
  * Inputs:
- * 	the_hdr:	Header structure as above.
- *	scanp:		Pointer to scanbuf above.
+ *      the_hdr:        Header structure as above.
+ *      scanp:          Pointer to scanbuf above.
  * Outputs:
- * 	Frees storage referenced by scanp and nrawp.
+ *      Frees storage referenced by scanp and nrawp.
  * Assumptions:
- * 	Storage was allocated by rle_row_alloc, or by use of same
- *	algorithm, at least.
+ *      Storage was allocated by rle_row_alloc, or by use of same
+ *      algorithm, at least.
  * Algorithm:
- * 	free scanp[0] and scanp.
+ *      free scanp[0] and scanp.
  */
 void
 rle_row_free( the_hdr, scanp )
@@ -120,12 +121,15 @@ rle_pixel **scanp;
     int i;
 
     if ( the_hdr->alpha )
-	scanp--;
+        scanp--;
     for ( i = 0; i < the_hdr->ncolors + the_hdr->alpha; i++ )
-	if ( scanp[i] != 0 )
-	{
-	    free( (char *)scanp[i] );
-	    break;
-	}
+        if ( scanp[i] != 0 )
+        {
+            free( (char *)scanp[i] );
+            break;
+        }
     free( (char *)scanp );
 }
+
+
+
diff --git a/urt/scanargs.c b/urt/scanargs.c
deleted file mode 100644
index 1dcdd235..00000000
--- a/urt/scanargs.c
+++ /dev/null
@@ -1,918 +0,0 @@
-/*
- * $Id: scanargs.c,v 3.0.1.3 1992/02/27 21:18:14 spencer Exp $
- *              Version 7 compatible
- *      Argument scanner, scans argv style argument list.
- *
- *      Some stuff is a kludge because sscanf screws up
- *
- *      Gary Newman - 10/4/1979 - Ampex Corp.
- *
- *      Modified by Spencer W. Thomas, Univ. of Utah, 5/81 to
- *      add args introduced by  a flag, add qscanargs call,
- *      allow empty flags.
- *
- *      If you make improvements we'd like to get them too.
- *      Jay Lepreau     lepreau@utah-20, decvax!harpo!utah-cs!lepreau
- *      Spencer Thomas  thomas@utah-20, decvax!harpo!utah-cs!thomas
- *
- *      (I know the code is ugly, but it just grew, you see ...)
- *
- * Modified by: Spencer W. Thomas
- *      Date:   Feb 25 1983
- * 1. Fixed scanning of optional args.  Now args introduced by a flag
- *    must follow the flag which introduces them and precede any other
- *    flag argument.  It is still possible for a flag introduced
- *    argument to be mistaken for a "bare" argument which occurs
- *    earlier in the format string.  This implies that flags may not
- *    be conditional upon other flags, and a message will be generated
- *    if this is attempted.
- *
- * 2. Usage message can be formatted by inserting newlines, tabs and
- *    spaces into the format string.  This is especially useful for
- *    long argument lists.
- *
- * 3. Added n/N types for "numeric" args.  These args are scanned
- *    using the C language conventions - a number starting 0x is
- *    hexadecimal, a number starting with 0 is octal, otherwise it is
- *    decimal.
- *
- *  Modified at BRL 16-May-88 by Mike Muuss to avoid Alliant STDC desire
- *  to have all "void" functions so declared.
- */
-
-#include <stdio.h>
-#include <ctype.h>
-#include <stdarg.h>
-
-#include "netpbm/pm_c_util.h"
-#include "netpbm/nstring.h"
-#include "rle_config.h"
-#include "rle.h"
-
-/*
- * An explicit assumption is made in this code that all pointers look
- * alike, except possible char * pointers.
- */
-typedef int *ptr;
-
-#define YES 1
-#define NO 0
-#define ERROR(msg)  {fprintf(stderr, "%s\n", msg); goto error; }
-
-/*
- * Storage allocation macros
- */
-#define NEW( type, cnt )        (type *) malloc( (cnt) * sizeof( type ) )
-#define RENEW( type, ptr, cnt ) (type *) realloc( ptr, (cnt) * sizeof( type ) )
-
-static CONST_DECL char * prformat( CONST_DECL char *, int );
-static int isnum( CONST_DECL char *, int, int );
-static int      _do_scanargs( int argc, char **argv, CONST_DECL char *format,
-                              va_list argl );
-void            scan_usage( char **, CONST_DECL char * );
-
-/*
- * Argument list is (argc, argv, format, ... )
- */
-int
-scanargs ( int argc, char **argv, CONST_DECL char *format, ... )
-{
-    va_list argl;
-    int retval;
-    va_start( argl, format );
-    retval = _do_scanargs( argc, argv, format, argl );
-    va_end( argl );
-    return retval;
-}
-
-/*
- * This routine is necessary because of a pyramid compiler botch that
- * uses parameter registers in a varargs routine.  The extra
- * subroutine call isolates the args on the register stack so they
- * don't get trashed.
- */
-
-static int
-_do_scanargs( argc, argv, format, argl )
-int     argc;                   /* Actual arguments */
-char  **argv;
-CONST_DECL char   *format;
-va_list argl;
-{
-
-    int    check;                       /* check counter to be sure all argvs
-                                           are processed */
-    register CONST_DECL char  *cp;
-    int    cnt;
-    int     optarg = 0;                 /* where optional args start */
-    int     nopt = 0;
-    char    tmpflg,                     /* temp flag */
-            typchr;                     /* type char from format string */
-    char    c;
-    bool  * arg_used;                   /* array of flags */
-    ptr     aptr = 0;                   /* pointer to return loc */
-
-    bool    required;
-    int     excnt;                      /* which flag is set */
-    unsigned int exflag;                /* How many of a set of exclusive
-                                           flags is set */
-
-    bool    list_of;                    /* set if parsing off a list of args */
-    bool    comma_list;                 /* set if AT&T style multiple args */
-    bool    no_usage;                   /* If set, don't print usage msg. */
-    bool    help = NO;                  /* If set, always print usage. */
-    int   * cnt_arg = 0;                /* where to stuff list count */
-    int     list_cnt;                   /* how many in list */
-    /* These are used to build return lists */
-    char ** strlist = 0;
-    int   * intlist = 0;
-    long  * longlist = 0;
-    float * fltlist = 0;
-    double *dbllist = 0;
-    char  * argp;                       /* Pointer to argument. */
-
-    CONST_DECL char   *ncp;             /* remember cp during flag scanning */
-    static char   cntrl[7] = "%  %1s";  /* control string for scanf's */
-    char    junk[2];                    /* junk buffer for scanf's */
-
-    /* Set up for argument counting. */
-    arg_used = NEW( bool, argc );
-    if (arg_used == NULL)
-    {
-        fprintf(stderr, "malloc failed in scanargs, exiting\n");
-        exit(-1);
-    }
-    else
-    {
-        for (cnt=0; cnt<argc; cnt++)
-            arg_used[cnt] = NO;
-    }
-    check = 0;
-
-    /* Scan for -help in arg list. */
-    for ( cnt=1; cnt<argc; cnt++ )
-        if ( strcmp( argv[cnt], "-help" ) == 0 )
-        {
-            check += cnt;
-            arg_used[cnt] = YES;
-            if ( argc == 2 )
-            {
-                scan_usage( argv, format );
-                return 0;
-            }
-            else
-                help = YES;
-        }
-
-    /* If format string ends in @, don't print a usage message. */
-    no_usage = *(format + strlen( format ) - 1) == '&';
-
-    cp = format;
-    /*
-     * Skip program name
-     */
-    while ( *cp != ' ' && *cp != '\t' && *cp != '\n' && *cp != '\0' )
-        cp++;
-
-    while (*cp)
-    {
-        required = NO;                  /* reset per-arg flags */
-        list_of = NO;
-        comma_list = NO;
-        list_cnt = 0;
-        switch (*(cp++))
-        {
-            default:                    /* all other chars */
-                break;
-            case ' ':                   /* separators */
-            case '\t':
-            case '\n':
-                optarg = 0;             /* end of optional arg string */
-                break;
-
-            case '(':                   /* Surrounds a comment. */
-            {
-                int depth = 1;          /* Count parenthesis depth. */
-                while ( *cp && depth > 0 )
-                    switch ( *(cp++) )
-                    {
-                    case '(':   depth++;                break;
-                    case ')':   depth--;                break;
-                    }
-                break;
-            }
-
-            case '!':                   /* required argument */
-                required = YES;
-            case '%':                   /* not required argument */
-reswitch:                               /* after finding '*' or ',' */
-                switch (typchr = *(cp++))
-                {
-                    case ',':           /* argument is AT&T list of things */
-                        comma_list = YES;
-                    case '*':           /* argument is list of things */
-                        list_of = YES;
-                        list_cnt = 0;   /* none yet */
-                        cnt_arg = va_arg( argl, int *); /* item count * here */
-                        goto reswitch;  /* try again */
-
-                    case '$':           /* "rest" of argument list */
-                        while ( argc > 1 && !arg_used[argc-1] )
-                            argc--;     /* find last used argument */
-                        *va_arg( argl, int * ) = argc;
-                        break;
-
-                    case '&':           /* Return unused args. */
-                        /* Count how many.  Always include argv[0]. */
-                        for ( nopt = cnt = 1; cnt < argc; cnt++ )
-                            if ( !arg_used[cnt] )
-                                nopt++;
-                        if ( nopt == 1 )
-                            nopt = 0;   /* Special case for no args. */
-                        if ( nopt > 0 )
-                        {
-                            strlist = NEW( char *, nopt + 1 );
-                            /* Copy program name, for sure. */
-                            strlist[0] = argv[0];
-                            for ( nopt = cnt = 1; cnt < argc; cnt++ )
-                                if ( !arg_used[cnt] )
-                                {
-                                    strlist[nopt++] = argv[cnt];
-                                    check += cnt;
-                                    arg_used[cnt] = 1;
-                                }
-                            strlist[nopt] = NULL;
-                        }
-                        else
-                            strlist = NULL;     /* No args, return empty. */
-
-                        /* Return count and arg list. */
-                        *va_arg( argl, int * ) = nopt;
-                        *va_arg( argl, char *** ) = strlist;
-                        break;
-
-                    case '-':           /* argument is flag */
-                        if (optarg > 0)
-                            ERROR("Format error: flag conditional on flag not allowed");
-
-                    /* go back to label */
-                        ncp = cp-1;     /* remember */
-                        cp -= 3;
-                        for (excnt = exflag = 0
-                                ; *cp != ' ' && !(*cp=='-' &&(cp[-1]=='!'||cp[-1]=='%'));
-                                (--cp, excnt++))
-                        {
-                            for (cnt = optarg+1; cnt < argc; cnt++)
-                            {
-                            /* flags all start with - */
-                                if (*argv[cnt] == '-' && !arg_used[cnt] &&
-                                        !ISDIGIT(argv[cnt][1]))
-                                    if (*(argv[cnt] + 1) == *cp)
-                                    {
-                                        if (*(argv[cnt] + 2) != 0)
-                                            ERROR ("extra flags ignored");
-                                        if (exflag)
-                                            ERROR ("more than one exclusive flag chosen");
-                                        exflag++;
-                                        required = NO;
-                                        check += cnt;
-                                        arg_used[cnt] = 1;
-                                        nopt = cnt;
-                                        *va_arg( argl, int *) |= (1 << excnt);
-                                        break;
-                                    }
-                            }
-                        }
-                        if (required)
-                            ERROR ("flag argument missing");
-                        cp = ncp;
-                        /*
-                         * If none of these flags were found, skip any
-                         * optional arguments (in the varargs list, too).
-                         */
-                        if (!exflag)
-                        {
-                            (void)va_arg( argl, int * );/* skip the arg, too */
-                            while (*++cp && ! ISSPACE(*cp))
-                                if (*cp == '!' || *cp == '%')
-                                {
-                                    if ( *++cp == '*' || *cp == ',' )
-                                    {
-                                        cp++;
-                                        (void)va_arg( argl, int * );
-                                    }
-                                    /*
-                                     * Assume that char * might be a
-                                     * different size, but that all
-                                     * other pointers are same size.
-                                     */
-                                    if ( *cp == 's' )
-                                        (void)va_arg( argl, char * );
-                                    else
-                                        (void)va_arg( argl, ptr );
-                                }
-                        }
-                        else
-                        {
-                            optarg = nopt;
-                            cp++;       /* skip over - */
-                        }
-
-                        break;
-
-                    case 's':           /* char string */
-                    case 'd':           /* decimal # */
-                    case 'o':           /* octal # */
-                    case 'x':           /* hexadecimal # */
-                    case 'n':           /* "number" in C syntax */
-                    case 'f':           /* floating # */
-                    case 'D':           /* long decimal # */
-                    case 'O':           /* long octal # */
-                    case 'X':           /* long hexadecimal # */
-                    case 'N':           /* long number in C syntax */
-                    case 'F':           /* double precision floating # */
-#if defined(sgi) && !defined(mips)
-                        /* Fix for broken SGI IRIS 2400/3000 floats */
-                        if ( typchr == 'F' ) typchr = 'f';
-#endif /* sgi */
-                        for (cnt = optarg+1; cnt < argc; cnt++)
-                        {
-                            argp = argv[cnt];
-
-                            if ( isnum( argp, typchr, comma_list ) )
-                            {
-                                ;       /* it's ok, then */
-                            }
-                            else if ( *argp == '-' && argp[1] != '\0' )
-                                if ( optarg > 0 ) /* end optional args? */
-                                {
-                                    /* Eat the arg, too, if necessary */
-                                    if ( list_cnt == 0 ) {
-                                        if ( typchr == 's' )
-                                            (void)va_arg( argl, char * );
-                                        else
-                                            (void)va_arg( argl, ptr );
-                    }
-                                    break;
-                                }
-                                else
-                                    continue;
-                            else if ( typchr != 's' )
-                                continue;       /* not number, keep looking */
-
-                            /*
-                             * Otherwise usable argument may already
-                             * be used.  (Must check this after
-                             * checking for flag, though.)
-                             */
-                            if (arg_used[cnt]) continue;
-
-                            /*
-                             * If it's a comma-and-or-space-separated
-                             * list then count how many, and separate
-                             * the list into an array of strings.
-                             */
-                            if ( comma_list )
-                            {
-                                register char * s;
-                                int pass;
-
-                                /*
-                                 * Copy the string so we remain nondestructive
-                                 */
-                                s = NEW( char, strlen(argp)+1 );
-                                strcpy( s, argp );
-                                argp = s;
-
-                                /*
-                                 * On pass 0, just count them.  On
-                                 * pass 1, null terminate each string
-                                 */
-                                for ( pass = 0; pass <= 1; pass++ )
-                                {
-                                    for ( s = argp; *s != '\0'; )
-                                    {
-                                        if ( pass )
-                                            strlist[list_cnt] = s;
-                                        while ( (c = *s) != '\0' && c != ' ' &&
-                                                c != '\t' && c != ',' )
-                                            s++;
-                                        if ( pass )
-                                            *s = '\0';
-
-                                        list_cnt++;     /* count separators */
-                                        /*
-                                         * Two commas in a row give a null
-                                         * string, but two spaces
-                                         * don't.  Also skip spaces
-                                         * after a comma.
-                                         */
-                                        if ( c != '\0' )
-                                            while ( *++s == ' ' || *s == '\t' )
-                                                ;
-                                    }
-                                    if ( pass == 0 )
-                                    {
-                                        strlist = NEW( char *, list_cnt );
-                                        list_cnt = 0;
-                                    }
-                                }
-                            }
-                            else if ( list_of )
-                                list_cnt++;   /* getting them one at a time */
-                            /*
-                             * If it's either type of list, then alloc
-                             * storage space for the returned values
-                             * (except that comma-separated string
-                             * lists already are done).
-                             */
-                            if ( list_of )
-                            {
-                                if ( list_cnt == 1 || comma_list )
-                                    switch( typchr )
-                                    {
-                                        case 's':
-                                            if ( !comma_list )
-                                                strlist = NEW( char *, 1 );
-                                            aptr = (ptr) &strlist[0];
-                                            break;
-                                        case 'n':
-                                        case 'd':
-                                        case 'o':
-                                        case 'x':
-                                            intlist = NEW( int, list_cnt );
-                                            aptr = (ptr) &intlist[0];
-                                            break;
-                                        case 'N':
-                                        case 'D':
-                                        case 'O':
-                                        case 'X':
-                                            longlist = NEW( long, list_cnt );
-                                            aptr = (ptr) &longlist[0];
-                                            break;
-                                        case 'f':
-                                            fltlist = NEW( float, list_cnt );
-                                            aptr = (ptr) &fltlist[0];
-                                            break;
-                                        case 'F':
-                                            dbllist = NEW( double, list_cnt );
-                                            aptr = (ptr) &dbllist[0];
-                                            break;
-                                    }
-                                else
-                                    switch( typchr )
-                                    {
-                                        case 's':
-                                            strlist = RENEW( char *, strlist,
-                                                             list_cnt );
-                                            aptr = (ptr) &strlist[list_cnt-1];
-                                            break;
-                                        case 'n':
-                                        case 'd':
-                                        case 'o':
-                                        case 'x':
-                                            intlist = RENEW( int, intlist,
-                                                             list_cnt );
-                                            aptr = (ptr) &intlist[list_cnt-1];
-                                            break;
-                                        case 'N':
-                                        case 'D':
-                                        case 'O':
-                                        case 'X':
-                                            longlist = RENEW( long, longlist,
-                                                              list_cnt );
-                                            aptr = (ptr) &longlist[list_cnt-1];
-                                            break;
-                                        case 'f':
-                                            fltlist = RENEW( float, fltlist,
-                                                             list_cnt );
-                                            aptr = (ptr) &fltlist[list_cnt-1];
-                                            break;
-                                        case 'F':
-                                            dbllist = RENEW( double, dbllist,
-                                                             list_cnt );
-                                            aptr = (ptr) &dbllist[list_cnt-1];
-                                            break;
-                                    }
-                            }
-                            else
-                                aptr = va_arg( argl, ptr );
-
-                            if ( typchr == 's' )
-                            {
-                                if ( ! comma_list )
-                                    *(char **)aptr = argp;
-                            }
-                            else
-                            {
-                                nopt = 0;
-                                do {
-                                    /*
-                                     * Need to update aptr if parsing
-                                     * a comma list
-                                     */
-                                    if ( comma_list && nopt > 0 )
-                                    {
-                                        argp = strlist[nopt];
-                                        switch( typchr )
-                                        {
-                                            case 'n':
-                                            case 'd':
-                                            case 'o':
-                                            case 'x':
-                                                aptr = (ptr) &intlist[nopt];
-                                                break;
-                                            case 'N':
-                                            case 'D':
-                                            case 'O':
-                                            case 'X':
-                                                aptr = (ptr) &longlist[nopt];
-                                                break;
-                                            case 'f':
-                                                aptr = (ptr) &fltlist[nopt];
-                                                break;
-                                            case 'F':
-                                                aptr = (ptr) &dbllist[nopt];
-                                                break;
-                                        }
-                                    }
-                                    /*
-                                     * Do conversion for n and N types
-                                     */
-                                    tmpflg = typchr;
-                                    if (typchr == 'n' || typchr == 'N' ) {
-                                        if (*argp != '0')
-                                            tmpflg = 'd';
-                                        else if (*(argp+1) == 'x' ||
-                                                 *(argp+1) == 'X')
-                                        {
-                                            tmpflg = 'x';
-                                            argp += 2;
-                                        }
-                                        else
-                                            tmpflg = 'o';
-                    }
-                                    if (typchr == 'N')
-                                        tmpflg = toupper( tmpflg );
-
-
-                                    /* put in conversion */
-                                    if ( isupper( tmpflg ) )
-                                    {
-                                        cntrl[1] = 'l';
-                                        cntrl[2] = tolower( tmpflg );
-                                    }
-                                    else
-                                    {
-                                        cntrl[1] = tmpflg;
-                                        cntrl[2] = ' ';
-                                    }
-                                    if (sscanf (argp, cntrl, aptr, junk) != 1)
-                                        ERROR ("Bad numeric argument");
-                                } while ( comma_list && ++nopt < list_cnt );
-                            }
-                            check += cnt;
-                            arg_used[cnt] = 1;
-                            required = NO;
-                            /*
-                             * If not looking for multiple args,
-                             * then done, otherwise, keep looking.
-                             */
-                            if ( !( list_of && !comma_list ) )
-                                break;
-                            else
-                                continue;
-                        }
-                        if (required)
-                            switch (typchr)
-                            {
-                                case 'x':
-                                case 'X':
-                                    ERROR ("missing hexadecimal argument");
-                                case 's':
-                                    ERROR ("missing string argument");
-                                case 'o':
-                                case 'O':
-                                    ERROR ("missing octal argument");
-                                case 'd':
-                                case 'D':
-                                    ERROR ("missing decimal argument");
-                                case 'f':
-                                case 'F':
-                                    ERROR ("missing floating argument");
-                                case 'n':
-                                case 'N':
-                                    ERROR ("missing numeric argument");
-                            }
-                        if ( list_cnt > 0 )
-                        {
-                            *cnt_arg = list_cnt;
-                            switch ( typchr )
-                            {
-                                case 's':
-                                    *va_arg( argl, char *** ) = strlist;
-                                    break;
-                                case 'n':
-                                case 'd':
-                                case 'o':
-                                case 'x':
-                                    *va_arg( argl, int ** ) = intlist;
-                                    break;
-                                case 'N':
-                                case 'D':
-                                case 'O':
-                                case 'X':
-                                    *va_arg( argl, long ** ) = longlist;
-                                    break;
-                                case 'f':
-                                    *va_arg( argl, float ** ) = fltlist;
-                                    break;
-                                case 'F':
-                                    *va_arg( argl, double **) = dbllist;
-                                    break;
-                            }
-                            if ( typchr != 's' && comma_list )
-                                free( (char *) strlist );
-                        }
-                        else if ( cnt >= argc )
-                        {
-                            /* Fell off end looking, so must eat the arg */
-                            if ( typchr == 's' )
-                                (void)va_arg( argl, char * );
-                            else
-                                (void)va_arg( argl, ptr );
-                        }
-                        break;
-                    default:            /* error */
-                        fprintf (stderr,
-                                 "scanargs: Corrupt or invalid format spec\n");
-                        return 0;
-                }
-        }
-    }
-
-    /*  Count up empty flags */
-    for (cnt=1; cnt<argc; cnt++)
-        if (argv[cnt][0] == '-' && argv[cnt][1] == '-' && argv[cnt][2] == 0
-            && !arg_used[cnt] )
-            check += cnt;
-
-    /* sum from 1 to N = n*(n+1)/2 used to count up checks */
-    if (check != (((argc - 1) * argc) / 2))
-        ERROR ("extra arguments not processed");
-
-    /* If -help, always print usage. */
-    if ( help )
-        scan_usage( argv, format );
-
-    free(arg_used);
-    return 1;
-
-error:
-    if ( !no_usage )
-        scan_usage( argv, format );
-    free(arg_used);
-    return 0;
-}
-
-void
-scan_usage( argv, format )
-char ** argv;
-CONST_DECL char * format;
-{
-    register CONST_DECL char * cp;
-
-    fprintf (stderr, "usage : ");
-    if (*(cp = format) != ' ')
-    {
-        if ( *cp == '%' )
-        {
-            /*
-             * This is bogus, but until everyone can agree on a name
-             * for (rindex/strrchr) ....
-             */
-            for ( cp = argv[0]; *cp != '\0'; cp++ )
-                ;                       /* find the end of the string */
-            for ( ; cp > argv[0] && *cp != '/'; cp-- )
-                ;                       /* find the last / */
-            if ( *cp == '/' )
-                cp++;
-            fprintf( stderr, "%s", cp );
-
-            cp = format + 1;            /* reset to where it should be */
-        }
-        while (putc (*cp++, stderr) != ' ');
-    }
-    else
-        fprintf (stderr, "?? ");
-    while (*cp == ' ')
-        cp++;
-    (void)prformat (cp, NO);
-}
-
-static CONST_DECL char *
-prformat (format, recurse)
-CONST_DECL char   *format;
-int     recurse;
-{
-    register CONST_DECL char  *cp;
-    bool    required, comma_list;
-    int    list_of, depth;
-
-    cp = format;
-    if (recurse)
-        putc (' ', stderr);
-
-    required = NO;
-    list_of = 0;
-    comma_list = NO;
-    while (*cp)
-    {
-        switch (*cp)
-        {
-            default:
-                cp++;
-                break;
-            case ' ':
-            case '\n':
-            case '\t':
-                /* allow annotations */
-                for ( ; format < cp; format++ )
-                    putc( *format, stderr );
-                putc(*cp, stderr);
-                format = ++cp;
-                break;
-
-            case '(':
-                /* Parentheses surround an arbitrary (parenthesis
-                 * balanced) comment.
-                 */
-                for ( ; format < cp; format++ )
-                    putc( *format, stderr );
-                for ( cp++, depth = 1; *cp && depth > 0; )
-                {
-                    /* Don't print last close paren. */
-                    if ( *cp != ')' || depth > 1 )
-                        putc( *cp, stderr );
-                    switch( *(cp++) )
-                    {
-                    case '(':   depth++;                break;
-                    case ')':   depth--;                break;
-                    }
-                }
-                format = cp;
-                break;
-
-            case '!':
-                required = YES;
-            case '%':
-reswitch:
-                switch (*++cp)
-                {
-                    case ',':
-                        comma_list = YES;
-                    case '*':
-                        list_of++;
-                        goto reswitch;
-
-                    case '$':           /* "rest" of argument list */
-                        if (!required)
-                            putc ('[', stderr);
-                        for (; format < cp - 1 - list_of; format++)
-                            putc (*format, stderr);
-                        fputs( " ...", stderr );
-                        if ( !required )
-                            putc( ']', stderr );
-                        break;
-
-                    case '-':           /* flags */
-                        if (!required)
-                            putc ('[', stderr);
-                        putc ('-', stderr);
-
-                        if (cp - format > 2 + list_of)
-                            putc ('{', stderr);
-                        cp = format;
-                        while (*cp != '%' && *cp != '!')
-                            putc (*cp++, stderr);
-                        if (cp - format > 1 + list_of)
-                            putc ('}', stderr);
-                        cp += 2;        /* skip !- or %- */
-                        if (*cp && !ISSPACE(*cp))
-                            cp = prformat (cp, YES);
-                                        /* this is a recursive call */
-
-                        cp--;   /* don't ignore next character */
-
-                        if (!required)
-                            putc (']', stderr);
-                        break;
-                    case 's':           /* char string */
-                    case 'd':           /* decimal # */
-                    case 'o':           /* octal # */
-                    case 'x':           /* hexadecimal # */
-                    case 'f':           /* floating # */
-                    case 'D':           /* long decimal # */
-                    case 'O':           /* long octal # */
-                    case 'X':           /* long hexadecimal # */
-                    case 'F':           /* double precision floating # */
-                    case 'n':           /* numeric arg (C format) */
-                    case 'N':           /* long numeric arg */
-                        if (!required)
-                            putc ('[', stderr);
-                        for (; format < cp - 1 - list_of; format++)
-                            putc (*format, stderr);
-                        if ( list_of != 0 )
-                        {
-                            if ( comma_list )
-                                putc( ',', stderr );
-                            else
-                                putc( ' ', stderr );
-                            fputs( "...", stderr );
-                        }
-                        if (!required)
-                            putc (']', stderr);
-                        break;
-                    default:
-                        break;
-                }
-                required = NO;
-                list_of = NO;
-                comma_list = NO;
-                if (*cp)                /* check for end of string */
-                    format = ++cp;
-                if (*cp && !ISSPACE(*cp))
-                    putc (' ', stderr);
-        }
-        if (recurse && ISSPACE(*cp))
-            break;
-    }
-    if (!recurse)
-    {
-        for ( ; format < cp; format++ )
-            putc( *format, stderr );
-        putc ('\n', stderr);
-    }
-    return (cp);
-}
-
-/*
- * isnum - determine whether a string MIGHT represent a number.
- * typchr indicates the type of argument we are looking for, and
- * determines the legal character set.  If comma_list is YES, then
- * space and comma are also legal characters.
- */
-static int
-isnum( str, typchr, comma_list )
-register CONST_DECL char * str;
-int typchr;
-int comma_list;
-{
-    register CONST_DECL char *allowed, *digits, *cp;
-    int hasdigit = NO;
-
-    switch( typchr )
-    {
-        case 'n':
-        case 'N':
-            allowed = " \t,+-x0123456789abcdefABCDEF";
-            break;
-        case 'd':
-        case 'D':
-            allowed = " \t,+-0123456789";
-            break;
-        case 'o':
-        case 'O':
-            allowed = " \t,01234567";
-            break;
-        case 'x':
-        case 'X':
-            allowed = " \t,0123456789abcdefABCDEF";
-            break;
-        case 'f':
-        case 'F':
-            allowed = " \t,+-eE.0123456789";
-            break;
-        case 's':                       /* only throw out decimal numbers */
-        default:
-            allowed = " \t,+-.0123456789";
-            break;
-    }
-    digits = allowed;
-    while ( *digits != '0' )
-        digits++;
-    if ( ! comma_list )
-        allowed += 3;                 /* then don't allow space, tab, comma */
-
-    while ( *str != '\0' )
-    {
-        for ( cp = allowed; *cp != '\0' && *cp != *str; cp++ )
-            ;
-        if ( *cp == '\0' )
-            return NO;               /* if not in allowed chars, not number */
-        if ( cp - digits >= 0 )
-            hasdigit = YES;
-        str++;
-    }
-    return hasdigit;
-}
diff --git a/urt/vaxshort.c b/urt/vaxshort.c
index 9a83cecb..b9c8e1ce 100644
--- a/urt/vaxshort.c
+++ b/urt/vaxshort.c
@@ -1,5 +1,5 @@
 /*
- *			V A X S H O R T
+ *                      V A X S H O R T
  *
  *  Code to manipulate 16-bit integers in VAX order in a
  *  machine independent manner.
@@ -7,46 +7,48 @@
  *  (VAX is a trademark of Digital Equipment Corporation)
  *
  *  Author -
- *	Michael John Muuss
+ *      Michael John Muuss
  *
  *  Source -
- *	SECAD/VLD Computing Consortium, Bldg 394
- *	The U. S. Army Ballistic Research Laboratory
- *	Aberdeen Proving Ground, Maryland  21005-5066
+ *      SECAD/VLD Computing Consortium, Bldg 394
+ *      The U. S. Army Ballistic Research Laboratory
+ *      Aberdeen Proving Ground, Maryland  21005-5066
  *
  *  Distribution Status -
- *	Public Domain, Distribution Unlimited.
+ *      Public Domain, Distribution Unlimited.
  */
 
 #include "vaxshort.h"
 
 /*
- *			V A X _ G S H O R T
+ *                      V A X _ G S H O R T
  *
  *  Obtain a 16-bit signed integer from two adjacent characters,
  *  stored in VAX order, regardless of word alignment.
  */
 int
-vax_gshort(char *msgp)
-{
-	register unsigned char *p = (unsigned char *) msgp;
-	register int	i;
-
-	if( (i = (p[1] << 8) | p[0]) & 0x8000 )
-		return(i | ~0xFFFF);	/* Sign extend */
-	return(i);
+vax_gshort(unsigned char * const msgp) {
+
+    int     i;
+
+    if ((i = (msgp[1] << 8) | msgp[0]) & 0x8000)
+        return i | ~0xFFFF;    /* Sign extend */
+    return(i);
 }
 
+
+
 /*
- *			V A X _ P S H O R T
+ *                      V A X _ P S H O R T
  */
-char *
-vax_pshort(char *msgp, unsigned short s)
-{
+unsigned char *
+vax_pshort(unsigned char * const msgp,
+           unsigned short  const s) {
+
+    msgp[0] = s & 0xFF;
+    msgp[1] = s >> 8;
 
-	msgp[0] = s & 0xFF;
-	msgp[1] = s >> 8;
-	return(msgp+2);
+    return msgp + 2;
 }
 
 
diff --git a/urt/vaxshort.h b/urt/vaxshort.h
index daeb856b..7a1d14ae 100644
--- a/urt/vaxshort.h
+++ b/urt/vaxshort.h
@@ -1,5 +1,5 @@
 int
-vax_gshort(char *msgp);
+vax_gshort(unsigned char *msgp);
 
-char *
-vax_pshort(char *msgp, unsigned short s);
+unsigned char *
+vax_pshort(unsigned char *msgp, unsigned short s);
diff --git a/version.mk b/version.mk
index bd596f5f..0b74eb8c 100644
--- a/version.mk
+++ b/version.mk
@@ -1,3 +1,3 @@
-NETPBM_MAJOR_RELEASE = 10
-NETPBM_MINOR_RELEASE = 93
-NETPBM_POINT_RELEASE = 0
+NETPBM_MAJOR_RELEASE = 11
+NETPBM_MINOR_RELEASE = 6
+NETPBM_POINT_RELEASE = 99